Programs & Examples On #Instsrv

Running .sh scripts in Git Bash

#!/usr/bin/env sh

this is how git bash knows a file is executable. chmod a+x does nothing in gitbash. (Note: any "she-bang" will work, e.g. #!/bin/bash, etc.)

How to identify numpy types in python?

Note that the type(numpy.ndarray) is a type itself and watch out for boolean and scalar types. Don't be too discouraged if it's not intuitive or easy, it's a pain at first.

See also: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.dtypes.html - https://github.com/machinalis/mypy-data/tree/master/numpy-mypy

>>> import numpy as np
>>> np.ndarray
<class 'numpy.ndarray'>
>>> type(np.ndarray)
<class 'type'>
>>> a = np.linspace(1,25)
>>> type(a)
<class 'numpy.ndarray'>
>>> type(a) == type(np.ndarray)
False
>>> type(a) == np.ndarray
True
>>> isinstance(a, np.ndarray)
True

Fun with booleans:

>>> b = a.astype('int32') == 11
>>> b[0]
False
>>> isinstance(b[0], bool)
False
>>> isinstance(b[0], np.bool)
False
>>> isinstance(b[0], np.bool_)
True
>>> isinstance(b[0], np.bool8)
True
>>> b[0].dtype == np.bool
True
>>> b[0].dtype == bool  # python equivalent
True

More fun with scalar types, see: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.scalars.html#arrays-scalars-built-in

>>> x = np.array([1,], dtype=np.uint64)
>>> x[0].dtype
dtype('uint64')
>>> isinstance(x[0], np.uint64)
True
>>> isinstance(x[0], np.integer)
True  # generic integer
>>> isinstance(x[0], int)
False  # but not a python int in this case

# Try matching the `kind` strings, e.g.
>>> np.dtype('bool').kind                                                                                           
'b'
>>> np.dtype('int64').kind                                                                                          
'i'
>>> np.dtype('float').kind                                                                                          
'f'
>>> np.dtype('half').kind                                                                                           
'f'

# But be weary of matching dtypes
>>> np.integer
<class 'numpy.integer'>
>>> np.dtype(np.integer)
dtype('int64')
>>> x[0].dtype == np.dtype(np.integer)
False

# Down these paths there be dragons:

# the .dtype attribute returns a kind of dtype, not a specific dtype
>>> isinstance(x[0].dtype, np.dtype)
True
>>> isinstance(x[0].dtype, np.uint64)
False  
>>> isinstance(x[0].dtype, np.dtype(np.uint64))
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: isinstance() arg 2 must be a type or tuple of types
# yea, don't go there
>>> isinstance(x[0].dtype, np.int_)
False  # again, confusing the .dtype with a specific dtype


# Inequalities can be tricky, although they might
# work sometimes, try to avoid these idioms:

>>> x[0].dtype <= np.dtype(np.uint64)
True
>>> x[0].dtype <= np.dtype(np.float)
True
>>> x[0].dtype <= np.dtype(np.half)
False  # just when things were going well
>>> x[0].dtype <= np.dtype(np.float16)
False  # oh boy
>>> x[0].dtype == np.int
False  # ya, no luck here either
>>> x[0].dtype == np.int_
False  # or here
>>> x[0].dtype == np.uint64
True  # have to end on a good note!

m2eclipse not finding maven dependencies, artifacts not found

I had this issue for dependencies that were created in other projects. Downloaded thirdparty dependencies showed up fine in the build path, but not a library that I had created.

SOLUTION: In the project that is not building correctly, right-click on the project and choose Properties, and then Maven. Uncheck the box labeled "Resolve dependencies from Workspace projects", hit Apply, and then OK. Right-click again on your project and do a Maven->Update Snapshots (or Update Dependencies) and your errors should go away when your project rebuilds (automatically if you have auto-build enabled).

SOAP client in .NET - references or examples?

Here you can find a nice tutorial for calling a NuSOAP-based web-service from a .NET client application. But IMO, you should also consider the WSO2 Web Services Framework for PHP (WSO2 WSF/PHP) for servicing. See WSO2 Web Services Framework for PHP 2.0 Significantly Enhances Industry’s Only PHP Library for Creating Both SOAP and REST Services. There is also a webminar about it.

Now, in .NET world I also encourage the use of WCF, taking into account the interoperability issues. An interoperability example can be found here, but this example uses a PHP-client + WCF-service instead of the opposite. Feel free to implement the PHP-service & WFC-client.

There are some WCF's related open source projects on codeplex.com that I found very productive. These projects are very useful to design & implement Win Forms and Windows Presentation Foundation applications: Smart Client, Web Client and Mobile Client. They can be used in combination with WCF to wisely call any kind of Web services.

Generally speaking, the patterns & practices team summarize good practices & designs in various open source projects that dealing with the .NET platform, specially for the web. So I think it's a good starting point for any design decision related to .NET clients.

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

React / JSX Dynamic Component Name

Suspose we wish to access various views with dynamic component loading.The following code gives a working example of how to accomplish this by using a string parsed from the search string of a url.

Lets assume we want to access a page 'snozberrys' with two unique views using these url paths:

'http://localhost:3000/snozberrys?aComponent'

and

'http://localhost:3000/snozberrys?bComponent'

we define our view's controller like this:

import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom'
import AComponent from './AComponent.js';
import CoBComponent sole from './BComponent.js';

const views = {
  aComponent: <AComponent />,
  console: <BComponent />
}

const View = (props) => {
  let name = props.location.search.substr(1);
  let view = views[name];
  if(view == null) throw "View '" + name + "' is undefined";
  return view;
}

class ViewManager extends Component {
  render() {
    return (
      <Router>
        <div>
          <Route path='/' component={View}/>
        </div>
      </Router>
    );
  }
}

export default ViewManager

ReactDOM.render(<ViewManager />, document.getElementById('root'));

callback to handle completion of pipe

Here's a solution that handles errors in requests and calls a callback after the file is written:

request(opts)
    .on('error', function(err){ return callback(err)})
    .pipe(fs.createWriteStream(filename))
    .on('finish', function (err) {
        return callback(err);
    });

Install Qt on Ubuntu

In Ubuntu 18.04 the QtCreator examples and API docs missing, This is my way to solve this problem, should apply to almost every Ubuntu release.

For QtCreator and Examples and API Docs:

sudo apt install `apt-cache search 5-examples | grep qt | grep example | awk '{print $1 }' | xargs `

sudo apt install `apt-cache search 5-doc | grep "Qt 5 " | awk '{print $1}' | xargs`

sudo apt-get install build-essential qtcreator qt5-default

If something is also missing, then:

sudo apt install `apt-cache search qt | grep 5- | grep ^qt | awk '{print $1}' | xargs `

Hope to be helpful.

Also posted in Ask Ubuntu: https://askubuntu.com/questions/450983/ubuntu-14-04-qtcreator-qt5-examples-missing

Combining two lists and removing duplicates, without removing duplicates in original list

resulting_list = first_list + [i for i in second_list if i not in first_list]

How to set java.net.preferIPv4Stack=true at runtime?

System.setProperty is not working for applets. Because JVM already running before applet start. In this case we use applet parameters like this:

    deployJava.runApplet({
        id: 'MyApplet',
        code: 'com.mkysoft.myapplet.SomeClass',
        archive: 'com.mkysoft.myapplet.jar'
    }, {
        java_version: "1.6*", // Target version
        cache_option: "no",
        cache_archive: "",
        codebase_lookup: true,
        java_arguments: "-Djava.net.preferIPv4Stack=true"
    },
       "1.6" // Minimum version
    );

You can find deployJava.js at https://www.java.com/js/deployJava.js

Difference between Subquery and Correlated Subquery

when it comes to subquery and co-related query both have inner query and outer query the only difference is in subquery the inner query doesn't depend on outer query, whereas in co-related inner query depends on outer.

How to generate unique IDs for form labels in React?

The id should be placed inside of componentWillMount (update for 2018) constructor, not render. Putting it in render will re-generate new ids unnecessarily.

If you're using underscore or lodash, there is a uniqueId function, so your resulting code should be something like:

constructor(props) {
    super(props);
    this.id = _.uniqueId("prefix-");
}

render() { 
  const id = this.id;
  return (
    <div>
        <input id={id} type="checkbox" />
        <label htmlFor={id}>label</label>
    </div>
  );
}

2019 Hooks update:

import React, { useState } from 'react';
import _uniqueId from 'lodash/uniqueId';

const MyComponent = (props) => {
  // id will be set once when the component initially renders, but never again
  // (unless you assigned and called the second argument of the tuple)
  const [id] = useState(_uniqueId('prefix-'));
  return (
    <div>
      <input id={id} type="checkbox" />
      <label htmlFor={id}>label</label>
    </div>
  );
}

Can I hide/show asp:Menu items based on role?

This is best done in the MenuItemDataBound.

protected void NavigationMenu_MenuItemDataBound(object sender, MenuEventArgs e)
{
    if (!Page.User.IsInRole("Admin"))
    {
        if (e.Item.NavigateUrl.Equals("/admin"))
        {
            if (e.Item.Parent != null)
            {
                MenuItem menu = e.Item.Parent;

                menu.ChildItems.Remove(e.Item);
            }
            else
            {
                Menu menu = (Menu)sender;

                menu.Items.Remove(e.Item);
            }               
        }
    }
}

Because the example used the NavigateUrl it is not language specific and works on sites with localized site maps.

how to change background image of button when clicked/focused?

You just need to set background and give previous.xml file in background of button in your layout file.

<Button
 android:id="@+id/button1"
 android:background="@drawable/previous"
 android:layout_width="200dp"
 android:layout_height="126dp"
 android:text="Hello" />

and done.Edit Following is previous.xml file in drawable directory

<?xml version="1.0" encoding="utf-8"?>

<item android:drawable="@drawable/onclick" android:state_selected="true"></item>
<item android:drawable="@drawable/onclick" android:state_pressed="true"></item>
<item android:drawable="@drawable/normal"></item>

Is it possible to use if...else... statement in React render function?

You can also use conditional (ternary) operator inside conditional operator in case you have 2 different dependencies.

{
(launch_success)
  ?
  <span className="bg-green-100">
    Success
  </span>
  :
  (upcoming)
    ?
    <span className="bg-teal-100">
      Upcoming
    </span>
    :
    <span className="bg-red-100">
      Failed
    </span>
}

How do I use a char as the case in a switch-case?

public class SwitCase {
    public static void main (String[] args){
        String hello = JOptionPane.showInputDialog("Input a letter: ");
        char hi = hello.charAt(0); //get the first char.
        switch(hi){
            case 'a': System.out.println("a");
        }
    }   
}

Arrays in cookies PHP

Try serialize(). It converts an array into a string format, you can then use unserialize() to convert it back to an array. Scripts like WordPress use this to save multiple values to a single database field.

You can also use json_encode() as Rob said, which maybe useful if you want to read the cookie in javascript.

Get all files that have been modified in git branch

For some reason no one mentioned git-tree. See https://stackoverflow.com/a/424142/1657819

git-tree is preferred because it's a plumbing command; meant to be programmatic (and, presumably, faster)

(assuming base branch is master)

git diff-tree --no-commit-id --name-only -r master..branch-name

However this will show you all files which were affected in the branch, if you want to see explicitly modified files only, you can use --diff-filter:

git diff-tree --no-commit-id --name-only -r master..branch-name --diff-filter=M

Also one can use --name-status instead of --name-only to see the status of the files (A/M/D and so on)

Pandas split column of lists into multiple columns

The above solutions didn't work for me since I have nan observations in my dataframe. In my case df2[['team1','team2']] = pd.DataFrame(df2.teams.values.tolist(), index= df2.index) yields:

object of type 'float' has no len()

I solve this using list comprehension. Here the replicable example:

import pandas as pd
import numpy as np
d1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],
            ['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]}
df2 = pd.DataFrame(d1)
df2.loc[2,'teams'] = np.nan
df2.loc[4,'teams'] = np.nan
df2

output:

        teams
0   [SF, NYG]
1   [SF, NYG]
2   NaN
3   [SF, NYG]
4   NaN
5   [SF, NYG]
6   [SF, NYG]

df2['team1']=np.nan
df2['team2']=np.nan

solving with list comprehension:

for i in [0,1]:
    df2['team{}'.format(str(i+1))]=[k[i] if isinstance(k,list) else k for k in df2['teams']]

df2

yields:

    teams   team1   team2
0   [SF, NYG]   SF  NYG
1   [SF, NYG]   SF  NYG
2   NaN        NaN  NaN
3   [SF, NYG]   SF  NYG
4   NaN        NaN  NaN
5   [SF, NYG]   SF  NYG
6   [SF, NYG]   SF  NYG

Does reading an entire file leave the file handle open?

The answer to that question depends somewhat on the particular Python implementation.

To understand what this is all about, pay particular attention to the actual file object. In your code, that object is mentioned only once, in an expression, and becomes inaccessible immediately after the read() call returns.

This means that the file object is garbage. The only remaining question is "When will the garbage collector collect the file object?".

in CPython, which uses a reference counter, this kind of garbage is noticed immediately, and so it will be collected immediately. This is not generally true of other python implementations.

A better solution, to make sure that the file is closed, is this pattern:

with open('Path/to/file', 'r') as content_file:
    content = content_file.read()

which will always close the file immediately after the block ends; even if an exception occurs.

Edit: To put a finer point on it:

Other than file.__exit__(), which is "automatically" called in a with context manager setting, the only other way that file.close() is automatically called (that is, other than explicitly calling it yourself,) is via file.__del__(). This leads us to the question of when does __del__() get called?

A correctly-written program cannot assume that finalizers will ever run at any point prior to program termination.

-- https://devblogs.microsoft.com/oldnewthing/20100809-00/?p=13203

In particular:

Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable.

[...]

CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references.

-- https://docs.python.org/3.5/reference/datamodel.html#objects-values-and-types

(Emphasis mine)

but as it suggests, other implementations may have other behavior. As an example, PyPy has 6 different garbage collection implementations!

Storing sex (gender) in database

I'd call the column "gender".

Data Type   Bytes Taken          Number/Range of Values
------------------------------------------------
TinyINT     1                    255 (zero to 255)
INT         4            -       2,147,483,648 to 2,147,483,647
BIT         1 (2 if 9+ columns)  2 (0 and 1)
CHAR(1)     1                    26 if case insensitive, 52 otherwise

The BIT data type can be ruled out because it only supports two possible genders which is inadequate. While INT supports more than two options, it takes 4 bytes -- performance will be better with a smaller/more narrow data type.

CHAR(1) has the edge over TinyINT - both take the same number of bytes, but CHAR provides a more narrow number of values. Using CHAR(1) would make using "m", "f",etc natural keys, vs the use of numeric data which are referred to as surrogate/artificial keys. CHAR(1) is also supported on any database, should there be a need to port.

Conclusion

I would use Option 2: CHAR(1).

Addendum

An index on the gender column likely would not help because there's no value in an index on a low cardinality column. Meaning, there's not enough variety in the values for the index to provide any value.

Get time difference between two dates in seconds

time difference between now and 10 minutes later using momentjs

let start_time = moment().format('YYYY-MM-DD HH:mm:ss');
let next_time = moment().add(10, 'm').format('YYYY-MM-DD HH:mm:ss');

let diff_milliseconds = Date.parse(next_time) - Date.parse(star_time);
let diff_seconds = diff_milliseconds * 1000;

How to force child div to be 100% of parent div's height without specifying parent's height?

I know it's been a looong time since the question was made, but I found an easy solution and thought someone could use it (sorry about the poor english). Here it goes:

CSS

.main, .sidebar {
    float: none;
    padding: 20px;
    vertical-align: top;
}
.container {
    display: table;
}
.main {
    width: 400px;
    background-color: LightSlateGrey;
    display: table-cell;
}
.sidebar {
    width: 200px;
    display: table-cell;
    background-color: Tomato;
}

HTML

<div class="container clearfix">
    <div class="sidebar">
        simple text here
    </div>
    <div class="main">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam congue, tortor in mattis mattis, arcu erat pharetra orci, at vestibulum lorem ante a felis. Integer sit amet est ac elit vulputate lobortis. Vestibulum in ipsum nulla. Aenean erat elit, lacinia sit amet adipiscing quis, aliquet at erat. Vivamus massa sem, cursus vel semper non, dictum vitae mi. Donec sed bibendum ante.
    </div>
</div>

Simple example. Note that you can turn into responsiveness.

Cannot find name 'require' after upgrading to Angular4

As for me, using VSCode and Angular 5, only had to add "node" to types in tsconfig.app.json. Save, and restart the server.

_x000D_
_x000D_
{_x000D_
    "compilerOptions": {_x000D_
    .._x000D_
    "types": [_x000D_
      "node"_x000D_
    ]_x000D_
  }_x000D_
  .._x000D_
}
_x000D_
_x000D_
_x000D_

One curious thing, is that this problem "cannot find require (", does not happen when excuting with ts-node

PHP PDO returning single row

$DBH = new PDO( "connection string goes here" );
$STH - $DBH -> prepare( "select figure from table1 ORDER BY x LIMIT 1" );

$STH -> execute();
$result = $STH -> fetch();
echo $result ["figure"];

$DBH = null;

You can use fetch and LIMIT together. LIMIT has the effect that the database returns only one entry so PHP has to handle very less data. With fetch you get the first (and only) result entry from the database reponse.

You can do more optimizing by setting the fetching type, see http://www.php.net/manual/de/pdostatement.fetch.php. If you access it only via column names you need to numbered array.

Be aware of the ORDER clause. Use ORDER or WHERE to get the needed row. Otherwise you will get the first row in the table alle the time.

GDB: break if variable equal value

You can use a watchpoint for this (A breakpoint on data instead of code).

You can start by using watch i.
Then set a condition for it using condition <breakpoint num> i == 5

You can get the breakpoint number by using info watch

How to list all users in a Linux group?

lid -g groupname | cut -f1 -d'(' 

Cannot open new Jupyter Notebook [Permission Denied]

Seems like the problem is in the last release, so

pip install notebook==5.6.0

must solve the problem!

How to add elements of a string array to a string array list?

Arrays.asList is bridge between Array and collection framework and it returns a fixed size List backed by Array.

species = Arrays.asList(speciesArr);

How to create a HTML Cancel button that redirects to a URL

With Jquery:

$(".cancel-button").click(function (e) {
  e.preventDefault();
});

How to spawn a process and capture its STDOUT in .NET?

You need to call p.Start() to actually run the process after you set the StartInfo. As it is, your function is probably hanging on the WaitForExit() call because the process was never actually started.

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

String dateStr = "2016-09-17T08:14:03+00:00";
String s = dateStr.replace("Z", "+00:00");
s = s.substring(0, 22) + s.substring(23);
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s);
Timestamp createdOn = new Timestamp(date.getTime());
mcList.setCreated_on(createdOn);

Java 7 added support for time zone descriptors according to ISO 8601. This can be use in Java 7.

How to save RecyclerView's scroll position using RecyclerView.State?

I had the same problem with a minor difference, I was using Databinding, and I was setting recyclerView adapter and the layoutManager in the binding methods.

The problem was that data-binding was happening after onResume so it was resetting my layoutManager after onResume and that means it was scrolling back to original place every time. So when I stopped setting layoutManager in Databinding adaptor methods, it works fine again.

The real difference between "int" and "unsigned int"

Hehe. You have an implicit cast here, because you're telling printf what type to expect.

Try this on for size instead:

unsigned int x = 0xFFFFFFFF;
int y = 0xFFFFFFFF;

if (x < 0)
    printf("one\n");
else
    printf("two\n");
if (y < 0)
    printf("three\n");
else
    printf("four\n");

How can I get a user's media from Instagram without authenticating as a user?

If you bypass Oauth you probably wouldn't know which instagram user they are. That being said there are a few ways to get instagram images without authentication.

  1. Instagram's API allows you to view a user's most popular images without authenticating. Using the following endpoint: Here is link

  2. Instagram provides rss feeds for tags at this.

  3. Instagram user pages are public, so you can use PHP with CURL to get their page and a DOM parser to search the html for the image tags you want.

libxml install error using pip

error: command 'gcc' failed with exit status 1

yum remove audit
yum install gcc
yum install libxslt-devel libxml2-devel

cd lxml-x.x.x
python setup.py build
python setup.py install

iReport not starting using JRE 8

I have installed IReport 5.6 with Java 7: not working

I tried to install Java 6 and added the path to "ireport.conf" file like the attached screenshot and it worked fine :Denter image description here

So the steps is :

 Install IReport 5.6
 Install JDK 6
 Edit "ireport.conf" file like the below image and Enjoy ;)

How to use (install) dblink in PostgreSQL?

# or even faster copy paste answer if you have sudo on the host 
sudo su - postgres  -c "psql template1 -c 'CREATE EXTENSION IF NOT EXISTS \"dblink\";'"

How-to turn off all SSL checks for postman for a specific site

enter image description here

click here in settings, one pop up window will get open. There we have switcher to make SSL verification certificate (Off)

What is deserialize and serialize in JSON?

In the context of data storage, serialization (or serialisation) is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted (for example, across a network connection link) and reconstructed later. [...]
The opposite operation, extracting a data structure from a series of bytes, is deserialization. From Wikipedia

In Python "serialization" does nothing else than just converting the given data structure (e.g. a dict) into its valid JSON pendant (object).

  • Python's True will be converted to JSONs true and the dictionary itself will then be encapsulated in quotes.
  • You can easily spot the difference between a Python dictionary and JSON by their Boolean values:
    • Python: True / False,
    • JSON: true / false
  • Python builtin module json is the standard way to do serialization:

Code example:

data = {
    "president": {
        "name": "Zaphod Beeblebrox",
        "species": "Betelgeusian",
        "male": True,
    }
}

import json
json_data = json.dumps(data, indent=2) # serialize
restored_data = json.loads(json_data) # deserialize

# serialized json_data now looks like:
# {
#   "president": {
#     "name": "Zaphod Beeblebrox",
#     "species": "Betelgeusian",
#     "male": true
#   }
# }

Source: realpython.com

How can I open a Shell inside a Vim Window?

I am currently using tmux.

Installation: sudo apt-get install tmux Run it: tmux

Ctrl + b followed by Ctr + % : it splits your terminal window in two vertical halves.

Ctrl + "arrow left | arrow right" : moves between terminals.

What are the rules for calling the superclass constructor?

If you simply want to pass all constructor arguments to the base-class (=parent), here is a minimal example.

This uses templates to forward every constructor call with 1, 2 or 3 arguments to the parent class std::string.

Code

Live-Version

#include <iostream>
#include <string>

class ChildString: public std::string
{
    public:
        template<typename... Args>
        ChildString(Args... args): std::string(args...)
        {
            std::cout 
                << "\tConstructor call ChildString(nArgs="
                << sizeof...(Args) << "): " << *this
                << std::endl;
        }

};

int main()
{
    std::cout << "Check out:" << std::endl;
    std::cout << "\thttp://www.cplusplus.com/reference/string/string/string/" << std::endl;
    std::cout << "for available string constructors" << std::endl;

    std::cout << std::endl;
    std::cout << "Initialization:" << std::endl;
    ChildString cs1 ("copy (2)");

    char char_arr[] = "from c-string (4)";
    ChildString cs2 (char_arr);

    std::string str = "substring (3)";
    ChildString cs3 (str, 0, str.length());

    std::cout << std::endl;
    std::cout << "Usage:" << std::endl;
    std::cout << "\tcs1: " << cs1 << std::endl;
    std::cout << "\tcs2: " << cs2 << std::endl;
    std::cout << "\tcs3: " << cs3 << std::endl;

    return 0;
}

Output

Check out:
    http://www.cplusplus.com/reference/string/string/string/
for available string constructors

Initialization:
    Constructor call ChildString(nArgs=1): copy (2)
    Constructor call ChildString(nArgs=1): from c-string (4)
    Constructor call ChildString(nArgs=3): substring (3)

Usage:
    cs1: copy (2)
    cs2: from c-string (4)
    cs3: substring (3)

Update: Using Variadic Templates

To generalize to n arguments and simplify

        template <class C>
        ChildString(C arg): std::string(arg)
        {
            std::cout << "\tConstructor call ChildString(C arg): " << *this << std::endl;
        }
        template <class C1, class C2>
        ChildString(C1 arg1, C2 arg2): std::string(arg1, arg2)
        {
            std::cout << "\tConstructor call ChildString(C1 arg1, C2 arg2, C3 arg3): " << *this << std::endl;
        }
        template <class C1, class C2, class C3>
        ChildString(C1 arg1, C2 arg2, C3 arg3): std::string(arg1, arg2, arg3)
        {
            std::cout << "\tConstructor call ChildString(C1 arg1, C2 arg2, C3 arg3): " << *this << std::endl;
        }

to

template<typename... Args>
        ChildString(Args... args): std::string(args...)
        {
            std::cout 
                << "\tConstructor call ChildString(nArgs="
                << sizeof...(Args) << "): " << *this
                << std::endl;
        }

What is the difference between "::" "." and "->" in c++

-> is for pointers to a class instance

. is for class instances

:: is for classnames - for example when using a static member

How do I export html table data as .csv file?

I was able to use the answer outlined here: Export to CSV using jQuery and html and added in a modification to make it work in IE and another modification mentioned in the comments to grab the thead from the table.

function exportTableToCSV($table, filename) {

    var $rows = $table.find('tr:has(td),tr:has(th)'),

        // Temporary delimiter characters unlikely to be typed by keyboard
        // This is to avoid accidentally splitting the actual contents
        tmpColDelim = String.fromCharCode(11), // vertical tab character
        tmpRowDelim = String.fromCharCode(0), // null character

        // actual delimiter characters for CSV format
        colDelim = '","',
        rowDelim = '"\r\n"',

        // Grab text from table into CSV formatted string
        csv = '"' + $rows.map(function (i, row) {
            var $row = $(row), $cols = $row.find('td,th');

            return $cols.map(function (j, col) {
                var $col = $(col), text = $col.text();

                return text.replace(/"/g, '""'); // escape double quotes

            }).get().join(tmpColDelim);

        }).get().join(tmpRowDelim)
            .split(tmpRowDelim).join(rowDelim)
            .split(tmpColDelim).join(colDelim) + '"',



        // Data URI
        csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

        console.log(csv);

        if (window.navigator.msSaveBlob) { // IE 10+
            //alert('IE' + csv);
            window.navigator.msSaveOrOpenBlob(new Blob([csv], {type: "text/plain;charset=utf-8;"}), "csvname.csv")
        } 
        else {
            $(this).attr({ 'download': filename, 'href': csvData, 'target': '_blank' }); 
        }
}

// This must be a hyperlink
$("#xx").on('click', function (event) {

    exportTableToCSV.apply(this, [$('#projectSpreadsheet'), 'export.csv']);

    // IF CSV, don't do event.preventDefault() or return false
    // We actually need this to be a typical hyperlink
});

With my link looking like this...

<a href="#" id="xx" style="text-decoration:none;color:#000;background-color:#ddd;border:1px solid #ccc;padding:8px;">Export Table data into Excel</a>

JsFiddle: https://jsfiddle.net/mnsinger/65hqxygo/

How to get an IFrame to be responsive in iOS Safari?

I am working with ionic2 and system config is as below-


******************************************************

Your system information:

Cordova CLI: 6.4.0 
Ionic Framework Version: 2.0.0-beta.10
Ionic CLI Version: 2.1.8
Ionic App Lib Version: 2.1.4
ios-deploy version: Not installed
ios-sim version: 5.0.8 
OS: OS X Yosemite
Node Version: v6.2.2
Xcode version: Xcode 7.2 Build version 7C68



******************************************************

For me this issue got resolved with this code-
for html iframe tag-

<div class="iframe_container">
      <iframe class= "animated fadeInUp" id="iframe1" [src]='page' frameborder="0" >
        <!--  <img src="img/video-icon.png"> -->
      </iframe><br>
   </div>

See css of the same as-


.iframe_container {
  overflow: auto; 
  position: relative; 
  -webkit-overflow-scrolling: touch;
  height: 75%;
}

iframe {
  position:relative;
  top: 2%;
  left: 5%;
  border: 0 !important;
  width: 90%;
}

Position property play a vital role here in my case.
position:relative;

It may help you too!!!

How to retrieve records for last 30 minutes in MS SQL?

Remember that CURRENT_TIMESTAMP - (number) works fine, but that you need to understand what number it is looking for - it is floating-point number of days. So CURRENT_TIMESTAMP-1.0 is 1 day ago, CURRENT_TIMESTAMP-0.5 is 1/2 day ago. For 30 minutes, that is 1.0/48.0 (use radix so result is a floating point number) or 0.0208333333333333, so your query will work if re-written as

select * from
[Janus999DB].[dbo].[tblCustomerPlay]
where DatePlayed < CURRENT_TIMESTAMP
and DatePlayed >
CURRENT_TIMESTAMP-1.0/48.0

You could also use 1.0/24.0/2.0 if that looks more like 1/2 hour to you.

Generate a UUID on iOS from Swift

For Swift 3, many Foundation types have dropped the 'NS' prefix, so you'd access it by UUID().uuidString.

Fastest way to set all values of an array?

Arrays.fill(myArray, 'c');

Arrays.fill

Although it is quite possible that this is doing the loop in the background and is therefore not any more efficient than what you have (other than the lines of code savings). If you really care about efficiency, try the following in comparison to the above:

int size = 50;
char[] array = new char[size];
for (int i=0; i<size; i++){
  array[i] = 'c';
}

Notice that the above doesn't call array.size() for each iteration.

How do I drop a foreign key in SQL Server?

Are you trying to drop the FK constraint or the column itself?

To drop the constraint:

alter table company drop constraint Company_CountryID_FK

You won't be able to drop the column until you drop the constraint.

How to grey out a button?

I used this code for that:

ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
profilePicture.setColorFilter(filter);

How to extract the substring between two markers?

text = 'I want to find a string between two substrings'
left = 'find a '
right = 'between two'

print(text[text.index(left)+len(left):text.index(right)])

Gives

string

SQL Last 6 Months

For MS SQL Server, you can use:

where datetime_column >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6,
current_timestamp)), 0)

How do I iterate over an NSArray?

Add each method in your NSArray category, you gonna need it a lot

Code taken from ObjectiveSugar

- (void)each:(void (^)(id object))block {
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        block(obj);
    }];
}

AngularJS - pass function to directive

I had to use the "=" binding instead of "&" because that was not working. Strange behavior.

What is causing this error - "Fatal error: Unable to find local grunt"

Install Grunt in node_modules rather than globally

Unable to find local Grunt likely means that you have installed Grunt globally.

The Grunt CLI insists that you install grunt in your local node_modules directory, so Grunt is local to your project.

This will fail:

npm install -g grunt

Do this instead:

npm install grunt --save-dev

How can I insert data into a MySQL database?

Here is OOP:

import MySQLdb


class Database:

    host = 'localhost'
    user = 'root'
    password = '123'
    db = 'test'

    def __init__(self):
        self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
        self.cursor = self.connection.cursor()

    def insert(self, query):
        try:
            self.cursor.execute(query)
            self.connection.commit()
        except:
            self.connection.rollback()



    def query(self, query):
        cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
        cursor.execute(query)

        return cursor.fetchall()

    def __del__(self):
        self.connection.close()


if __name__ == "__main__":

    db = Database()

    #CleanUp Operation
    del_query = "DELETE FROM basic_python_database"
    db.insert(del_query)

    # Data Insert into the table
    query = """
        INSERT INTO basic_python_database
        (`name`, `age`)
        VALUES
        ('Mike', 21),
        ('Michael', 21),
        ('Imran', 21)
        """

    # db.query(query)
    db.insert(query)

    # Data retrieved from the table
    select_query = """
        SELECT * FROM basic_python_database
        WHERE age = 21
        """

    people = db.query(select_query)

    for person in people:
        print "Found %s " % person['name']

HTML how to clear input using javascript?

instead of clearing the name text use placeholder attribute it is good practice

<input type="text" placeholder="name"  name="name">

Checkbox for nullable boolean

For me the solution was to change the view model. Consider you are searching for invoices. These invoices can be paid or not. So your search has three options: Paid, Unpaid, or "I don't Care".

I had this originally set as a bool? field:

public bool? PaidInvoices { get; set; }

This made me stumble onto this question. I ended up created an Enum type and I handled this as follows:

@Html.RadioButtonFor(m => m.PaidInvoices, PaidStatus.NotSpecified, new { @checked = true })
@Html.RadioButtonFor(m => m.PaidInvoices, PaidStatus.Yes) 
@Html.RadioButtonFor(m => m.PaidInvoices, PaidStatus.No)

Of course I had them wrapped in labels and had text specified, I just mean here's another option to consider.

How to use phpexcel to read data and insert into database?

Using the PHPExcel library, the following code will do.

require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';    
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true); //optional

$objPHPExcel = $objReader->load(__DIR__.'/YourExcelFile.xlsx');
$objWorksheet = $objPHPExcel->getActiveSheet();

$i=1;
foreach ($objWorksheet->getRowIterator() as $row) {

    $column_A_Value = $objPHPExcel->getActiveSheet()->getCell("A$i")->getValue();//column A
    //you can add your own columns B, C, D etc.

    //inset $column_A_Value value in DB query here

    $i++;
}

Updating a date in Oracle SQL table

This is based on the assumption that you're getting an error about the date format, such as an invalid month value or non-numeric character when numeric expected.

Dates stored in the database do not have formats. When you query the date your client is formatting the date for display, as 4/16/2011. Normally the same date format is used for selecting and updating dates, but in this case they appear to be different - so your client is apparently doing something more complicated that SQL*Plus, for example.

When you try to update it it's using a default date format model. Because of how it's displayed you're assuming that is MM/DD/YYYY, but it seems not to be. You could find out what it is, but it's better not to rely on the default or any implicit format models at all.

Whether that is the problem or not, you should always specify the date model:

UPDATE PASOFDATE SET ASOFDATE = TO_DATE('11/21/2012', 'MM/DD/YYYY');

Since you aren't specifying a time component - all Oracle DATE columns include a time, even if it's midnight - you could also use a date literal:

UPDATE PASOFDATE SET ASOFDATE = DATE '2012-11-21';

You should maybe check that the current value doesn't include a time, though the column name suggests it doesn't.

Why does range(start, end) not include end?

It's just more convenient to reason about in many cases.

Basically, we could think of a range as an interval between start and end. If start <= end, the length of the interval between them is end - start. If len was actually defined as the length, you'd have:

len(range(start, end)) == start - end

However, we count the integers included in the range instead of measuring the length of the interval. To keep the above property true, we should include one of the endpoints and exclude the other.

Adding the step parameter is like introducing a unit of length. In that case, you'd expect

len(range(start, end, step)) == (start - end) / step

for length. To get the count, you just use integer division.

How to define an empty object in PHP

php.net said it is best:

$new_empty_object = new stdClass();

The difference between fork(), vfork(), exec() and clone()

in fork(), either child or parent process will execute based on cpu selection.. But in vfork(), surely child will execute first. after child terminated, parent will execute.

Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

check for network issues, to bypass the exception case code

In my case, I was using a custom index, that index had no route and such would trigger the exception case code. The exception case bug still exists and still masks the real issue, however I was able to work around this by testing the connectivity with other tools such as nc -vzw1 myindex.example.org 443 and retrying when the network was up.

How to push object into an array using AngularJS

Please check this - http://plnkr.co/edit/5Sx4k8tbWaO1qsdMEWYI?p=preview

Controller-

var app= angular.module('app', []);

app.controller('TestController', function($scope) {
    this.arrayText = [{text:'Hello',},{text: 'world'}];

    this.addText = function(text) {

      if(text) {
        var obj = {
          text: text
        };
          this.arrayText.push(obj);
          this.myText = '';
          console.log(this.arrayText);
        }
      } 
 });

HTML

<form ng-controller="TestController as testCtrl" ng-submit="testCtrl.addText(testCtrl.myText)">
        <input type="text" ng-model="testCtrl.myText" value="Lets go">
        <button type="submit">Add</button>
        <div ng-repeat="item in testCtrl.arrayText">
            <span>{{item}}</span>
        </div>
</form>

Set the Value of a Hidden field using JQuery

If you have a hidden field like this

  <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("VertragNr") %>'/>

Now you can use your value like this

$(this).parent().find('input[type=hidden]').val()

Excel VBA - How to Redim a 2D array?

I stumbled across this question while hitting this road block myself. I ended up writing a piece of code real quick to handle this ReDim Preserve on a new sized array (first or last dimension). Maybe it will help others who face the same issue.

So for the usage, lets say you have your array originally set as MyArray(3,5), and you want to make the dimensions (first too!) larger, lets just say to MyArray(10,20). You would be used to doing something like this right?

 ReDim Preserve MyArray(10,20) '<-- Returns Error

But unfortunately that returns an error because you tried to change the size of the first dimension. So with my function, you would just do something like this instead:

 MyArray = ReDimPreserve(MyArray,10,20)

Now the array is larger, and the data is preserved. Your ReDim Preserve for a Multi-Dimension array is complete. :)

And last but not least, the miraculous function: ReDimPreserve()

'redim preserve both dimensions for a multidimension array *ONLY
Public Function ReDimPreserve(aArrayToPreserve,nNewFirstUBound,nNewLastUBound)
    ReDimPreserve = False
    'check if its in array first
    If IsArray(aArrayToPreserve) Then       
        'create new array
        ReDim aPreservedArray(nNewFirstUBound,nNewLastUBound)
        'get old lBound/uBound
        nOldFirstUBound = uBound(aArrayToPreserve,1)
        nOldLastUBound = uBound(aArrayToPreserve,2)         
        'loop through first
        For nFirst = lBound(aArrayToPreserve,1) to nNewFirstUBound
            For nLast = lBound(aArrayToPreserve,2) to nNewLastUBound
                'if its in range, then append to new array the same way
                If nOldFirstUBound >= nFirst And nOldLastUBound >= nLast Then
                    aPreservedArray(nFirst,nLast) = aArrayToPreserve(nFirst,nLast)
                End If
            Next
        Next            
        'return the array redimmed
        If IsArray(aPreservedArray) Then ReDimPreserve = aPreservedArray
    End If
End Function

I wrote this in like 20 minutes, so there's no guarantees. But if you would like to use or extend it, feel free. I would've thought that someone would've had some code like this up here already, well apparently not. So here ya go fellow gearheads.

Set disable attribute based on a condition for Html.TextBoxFor

if you dont want to use Html Helpers take look it my solution

disabled="@(your Expression that returns true or false")"

that it

@{
    bool isManager = (Session["User"] as User).IsManager;
}
<textarea rows="4" name="LetterManagerNotes" disabled="@(!isManager)"></textarea>

and I think the better way to do it is to do that check in the controller and save it within a variable that is accessible inside the view(Razor engine) in order to make the view free from business logic

XDocument or XmlDocument

As mentioned elsewhere, undoubtedly, Linq to Xml makes creation and alteration of xml documents a breeze in comparison to XmlDocument, and the XNamespace ns + "elementName" syntax makes for pleasurable reading when dealing with namespaces.

One thing worth mentioning for xsl and xpath die hards to note is that it IS possible to still execute arbitrary xpath 1.0 expressions on Linq 2 Xml XNodes by including:

using System.Xml.XPath;

and then we can navigate and project data using xpath via these extension methods:

For instance, given the Xml document:

<xml>
    <foo>
        <baz id="1">10</baz>
        <bar id="2" special="1">baa baa</bar>
        <baz id="3">20</baz>
        <bar id="4" />
        <bar id="5" />
    </foo>
    <foo id="123">Text 1<moo />Text 2
    </foo>
</xml>

We can evaluate:

var node = xele.XPathSelectElement("/xml/foo[@id='123']");
var nodes = xele.XPathSelectElements(
"//moo/ancestor::xml/descendant::baz[@id='1']/following-sibling::bar[not(@special='1')]");
var sum = xele.XPathEvaluate("sum(//foo[not(moo)]/baz)");

what is .subscribe in angular?

In Angular (currently on Angular-6) .subscribe() is a method on the Observable type. The Observable type is a utility that asynchronously or synchronously streams data to a variety of components or services that have subscribed to the observable.

The observable is an implementation/abstraction over the promise chain and will be a part of ES7 as a proposed and very supported feature. In Angular it is used internally due to rxjs being a development dependency.

An observable itself can be thought of as a stream of data coming from a source, in Angular this source is an API-endpoint, a service, a database or another observable. But the power it has is that it's not expecting a single response. It can have one or many values that are returned.

Link to rxjs for observable/subscribe docs here: https://rxjs-dev.firebaseapp.com/api/index/class/Observable#subscribe-

Subscribe takes 3 methods as parameters each are functions:

  • next: For each item being emitted by the observable perform this function
  • error: If somewhere in the stream an error is found, do this method
  • complete: Once all items are complete from the stream, do this method

Within each of these, there is the potentional to pipe (or chain) other utilities called operators onto the results to change the form or perform some layered logic.

In the simple example above:

.subscribe(hero => this.hero = hero); basically says on this observable take the hero being emitted and set it to this.hero.

Adding this answer to give more context to Observables based off the documentation and my understanding.

Multiple lines of input in <input type="text" />

If you need textarea with auto height, Use follows with pure javascript,

_x000D_
_x000D_
function auto_height(elem) {  /* javascript */_x000D_
    elem.style.height = "1px";_x000D_
    elem.style.height = (elem.scrollHeight)+"px";_x000D_
}
_x000D_
.auto_height { /* CSS */_x000D_
  width: 100%;_x000D_
}
_x000D_
<textarea rows="1" class="auto_height" oninput="auto_height(this)"></textarea>
_x000D_
_x000D_
_x000D_

Getting the client's time zone (and offset) in JavaScript

function getLocalTimeZone() {
    var dd = new Date();
    var ddStr = dd.toString();
    var ddArr = ddStr.split(' ');
    var tmznSTr = ddArr[5];
    tmznSTr = tmznSTr.substring(3, tmznSTr.length);
    return tmznSTr;
}

Example : Thu Jun 21 2018 18:12:50 GMT+0530 (India Standard Time)

O/P : +0530

How can I programmatically determine if my app is running in the iphone simulator?

Already asked, but with a very different title.

What #defines are set up by Xcode when compiling for iPhone

I'll repeat my answer from there:

It's in the SDK docs under "Compiling source code conditionally"

The relevant definition is TARGET_OS_SIMULATOR, which is defined in /usr/include/TargetConditionals.h within the iOS framework. On earlier versions of the toolchain, you had to write:

#include "TargetConditionals.h"

but this is no longer necessary on the current (Xcode 6/iOS8) toolchain.

So, for example, if you want to check that you are running on device, you should do

#if TARGET_OS_SIMULATOR
    // Simulator-specific code
#else
    // Device-specific code
#endif

depending on which is appropriate for your use-case.

Correct way of looping through C++ arrays

sizeof(texts) on my system evaluated to 96: the number of bytes required for the array and its string instances.

As mentioned elsewhere, the sizeof(texts)/sizeof(texts[0]) would give the value of 3 you were expecting.

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

Probably this information will help. I was on Ubuntu 18.04 and when I tried to install Krita, using the ppa method, I got this error:

This application failed to start because it could not find or load the Qt platform plugin "xcb" in "".

Available platform plugins are: linuxfb, minimal, minimalegl, offscreen, wayland-egl, wayland, xcb.

Reinstalling the application may fix this problem.

Aborted

I tried all the solutions that I found in this thread and other webs without any success.

Finally, I found a post where the author mention that is possible to activate the debugging tool of qt5 using this simple command:

export QT_DEBUG_PLUGINS=1

After adding this command I run again krita I got the same error, however this time I knew the cause of that error.

libxcb-xinerama.so.0: cannot open shared object file: No such file or directory.

This error prevents to the "xcb" to load properly. So, the solution will be install the `libxcb-xinerama.so.0" right? However, when I run the command:

sudo apt install libxcb-xinerama

The lib was already installed. Now what Teo? Well, then I used an old trick :) Yeah, that one --reinstall

sudo apt install --reinstall libxcb-xinerama

TLDR: This last command solved my problem.

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

I use this:

interface IObjectKeys {
  [key: string]: string | number;
}

interface IDevice extends IObjectKeys {
  id: number;
  room_id: number;
  name: string;
  type: string;
  description: string;
}

If you use the optional property in your object:

interface IDevice extends IObjectKeys {
  id: number;
  room_id?: number;
  name?: string;
  type?: string;
  description?: string;
}

... you should add 'undefined' value into the IObjectKeys interface:

interface IObjectKeys {
  [key: string]: string | number | undefined;
}

How to upload a file and JSON data in Postman?

The Missing Visual Guide

You must first find the nearly-invisible pale-grey-on-white dropdown for File which is the magic key that unlocks the Choose Files button.

After you choose POST, then choose Body->form-data, then find the File dropdown, and then choose 'File', only then will the 'Choose Files' button magically appear:

Postman POST file setup - (Text,File) dropdown highlighted

How to replicate vector in c?

A lot of C projects end up implementing a vector-like API. Dynamic arrays are such a common need, that it's nice to abstract away the memory management as much as possible. A typical C implementation might look something like:

typedef struct dynamic_array_struct
{
  int* data;
  size_t capacity; /* total capacity */
  size_t size; /* number of elements in vector */
} vector;

Then they would have various API function calls which operate on the vector:

int vector_init(vector* v, size_t init_capacity)
{
  v->data = malloc(init_capacity * sizeof(int));
  if (!v->data) return -1;

  v->size = 0;
  v->capacity = init_capacity;

  return 0; /* success */
}

Then of course, you need functions for push_back, insert, resize, etc, which would call realloc if size exceeds capacity.

vector_resize(vector* v, size_t new_size);

vector_push_back(vector* v, int element);

Usually, when a reallocation is needed, capacity is doubled to avoid reallocating all the time. This is usually the same strategy employed internally by std::vector, except typically std::vector won't call realloc because of C++ object construction/destruction. Rather, std::vector might allocate a new buffer, and then copy construct/move construct the objects (using placement new) into the new buffer.

An actual vector implementation in C might use void* pointers as elements rather than int, so the code is more generic. Anyway, this sort of thing is implemented in a lot of C projects. See http://codingrecipes.com/implementation-of-a-vector-data-structure-in-c for an example vector implementation in C.

mysql datetime comparison

I know its pretty old but I just encounter the problem and there is what I saw in the SQL doc :

[For best results when using BETWEEN with date or time values,] use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.

I assume it's better to use STR_TO_DATE since they took the time to make a function just for that and also the fact that i found this in the BETWEEN doc...

How to add Python to Windows registry

I installed ArcGIS Pro 1.4 and it didn't register the Python 3.5.2 it installed which prevented me from installing any add-ons. I resolved this by using the "reg" command in an Administrator PowerShell session to manually create and populate the necessary registry keys/values (where Python is installed in C:\Python35):

reg add "HKLM\Software\Python\PythonCore\3.5\Help\Main Python Documentation" /reg:64 /ve /t REG_SZ /d "C:\Python35\Doc\Python352.chm"
reg add "HKLM\Software\Python\PythonCore\3.5\InstallPath" /reg:64 /ve /t REG_SZ /d "C:\Python35\"
reg add "HKLM\Software\Python\PythonCore\3.5\InstallPath\InstallGroup" /reg:64 /ve /t REG_SZ /d "Python 3.5"
reg add "HKLM\Software\Python\PythonCore\3.5\PythonPath" /reg:64 /ve /t REG_SZ /d "C:\Python35\Lib;C:\Python35\DLLs;C:\Python35\Lib\lib-tk"

I find this easier than using Registry Editor but that's solely a personal preference.

The same commands can be executed in CMD.EXE session if you prefer; just make sure you run it as Administrator.

How to install MySQLi on MacOS

Here is the link for installation details: http://php.net/manual/en/mysqli.installation.php

If you are using Windows or Linux:
- The MySQLi extension is automatically installed in most cases, when PHP & MySQL package is installed.

Hiding a button in Javascript

visibility=hidden

is very useful, but it will still take up space on the page. You can also use

display=none

because that will not only hide the object, but make it so that it doesn't take up space until it is displayed. (Also keep in mind that display's opposite is "block," not "visible")

How to apply Hovering on html area tag?

What I did was to create a canvas element that I then position in front of the image map. Then, whenever an area is moused-over, I call a func that gets the coord string for that shape and the shape-type. If it's a poly I use the coords to draw an outline on the canvas. If it's a rect I draw a rect outline. You could easily add code to deal with circles.

You could also set the opacity of the canvas to less than 100% before filling the poly/rect/circle. You could also change the reliance on a global for the canvas's context - this would mean you could deal with more than 1 image-map on the same page.

<!DOCTYPE html>
<html>
<head>
<script>

// stores the device context of the canvas we use to draw the outlines
// initialized in myInit, used in myHover and myLeave
var hdc;

// shorthand func
function byId(e){return document.getElementById(e);}

// takes a string that contains coords eg - "227,307,261,309, 339,354, 328,371, 240,331"
// draws a line from each co-ord pair to the next - assumes starting point needs to be repeated as ending point.
function drawPoly(coOrdStr)
{
    var mCoords = coOrdStr.split(',');
    var i, n;
    n = mCoords.length;

    hdc.beginPath();
    hdc.moveTo(mCoords[0], mCoords[1]);
    for (i=2; i<n; i+=2)
    {
        hdc.lineTo(mCoords[i], mCoords[i+1]);
    }
    hdc.lineTo(mCoords[0], mCoords[1]);
    hdc.stroke();
}

function drawRect(coOrdStr)
{
    var mCoords = coOrdStr.split(',');
    var top, left, bot, right;
    left = mCoords[0];
    top = mCoords[1];
    right = mCoords[2];
    bot = mCoords[3];
    hdc.strokeRect(left,top,right-left,bot-top); 
}

function myHover(element)
{
    var hoveredElement = element;
    var coordStr = element.getAttribute('coords');
    var areaType = element.getAttribute('shape');

    switch (areaType)
    {
        case 'polygon':
        case 'poly':
            drawPoly(coordStr);
            break;

        case 'rect':
            drawRect(coordStr);
    }
}

function myLeave()
{
    var canvas = byId('myCanvas');
    hdc.clearRect(0, 0, canvas.width, canvas.height);
}

function myInit()
{
    // get the target image
    var img = byId('img-imgmap201293016112');

    var x,y, w,h;

    // get it's position and width+height
    x = img.offsetLeft;
    y = img.offsetTop;
    w = img.clientWidth;
    h = img.clientHeight;

    // move the canvas, so it's contained by the same parent as the image
    var imgParent = img.parentNode;
    var can = byId('myCanvas');
    imgParent.appendChild(can);

    // place the canvas in front of the image
    can.style.zIndex = 1;

    // position it over the image
    can.style.left = x+'px';
    can.style.top = y+'px';

    // make same size as the image
    can.setAttribute('width', w+'px');
    can.setAttribute('height', h+'px');

    // get it's context
    hdc = can.getContext('2d');

    // set the 'default' values for the colour/width of fill/stroke operations
    hdc.fillStyle = 'red';
    hdc.strokeStyle = 'red';
    hdc.lineWidth = 2;
}
</script>

<style>
body
{
    background-color: gray;
}
canvas
{
    pointer-events: none;       /* make the canvas transparent to the mouse - needed since canvas is position infront of image */
    position: absolute;
}
</style>

<title></title>
</head>
<body onload='myInit()'>
    <canvas id='myCanvas'></canvas>     <!-- gets re-positioned in myInit(); -->
<center>
<img src='http://dailyaeen.com.pk/epaper/wp-content/uploads/2012/09/27+Sep+2012-1.jpg?1349003469874' usemap='#imgmap_css_container_imgmap201293016112' class='imgmap_css_container' title='imgmap201293016112' alt='imgmap201293016112' id='img-imgmap201293016112' />
<map id='imgmap201293016112' name='imgmap_css_container_imgmap201293016112'>
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="2,0,604,-3,611,-3,611,166,346,165,345,130,-2,130,-2,124,1,128,1,126" href="" alt="imgmap201293016112-0" title="imgmap201293016112-0" class="imgmap201293016112-area" id="imgmap201293016112-area-0" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,131,341,213" href="" alt="imgmap201293016112-1" title="imgmap201293016112-1" class="imgmap201293016112-area" id="imgmap201293016112-area-1" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,166,614,241" href="" alt="imgmap201293016112-2" title="imgmap201293016112-2" class="imgmap201293016112-area" id="imgmap201293016112-area-2" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="917,242,344,239,345,496,574,495,575,435,917,433" href="" alt="imgmap201293016112-3" title="imgmap201293016112-3" class="imgmap201293016112-area" id="imgmap201293016112-area-3" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,416,341,494" href="" alt="imgmap201293016112-4" title="imgmap201293016112-4" class="imgmap201293016112-area" id="imgmap201293016112-area-4" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,215,341,410" href="" alt="imgmap201293016112-5" title="imgmap201293016112-5" class="imgmap201293016112-area" id="imgmap201293016112-area-5" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="916,533,916,436,578,436,576,495,806,496,807,535" href="" alt="imgmap201293016112-6" title="imgmap201293016112-6" class="imgmap201293016112-area" id="imgmap201293016112-area-6" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="805,536,918,614" href="" alt="imgmap201293016112-7" title="imgmap201293016112-7" class="imgmap201293016112-area" id="imgmap201293016112-area-7" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="461,494,803,616" href="" alt="imgmap201293016112-8" title="imgmap201293016112-8" class="imgmap201293016112-area" id="imgmap201293016112-area-8" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,497,223,616" href="" alt="imgmap201293016112-9" title="imgmap201293016112-9" class="imgmap201293016112-area" id="imgmap201293016112-area-9" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,494,456,614" href="" alt="imgmap201293016112-10" title="imgmap201293016112-10" class="imgmap201293016112-area" id="imgmap201293016112-area-10" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="345,935,572,1082" href="" alt="imgmap201293016112-11" title="imgmap201293016112-11" class="imgmap201293016112-area" id="imgmap201293016112-area-11" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="1,617,457,760" href="" alt="imgmap201293016112-12" title="imgmap201293016112-12" class="imgmap201293016112-area" id="imgmap201293016112-area-12" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="345,760,577,847" href="" alt="imgmap201293016112-13" title="imgmap201293016112-13" class="imgmap201293016112-area" id="imgmap201293016112-area-13" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,759,344,906" href="" alt="imgmap201293016112-14" title="imgmap201293016112-14" class="imgmap201293016112-area" id="imgmap201293016112-area-14" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,850,571,935" href="" alt="imgmap201293016112-15" title="imgmap201293016112-15" class="imgmap201293016112-area" id="imgmap201293016112-area-15" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="578,761,915,865" href="" alt="imgmap201293016112-16" title="imgmap201293016112-16" class="imgmap201293016112-area" id="imgmap201293016112-area-16" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1017,226,1085" href="" alt="imgmap201293016112-17" title="imgmap201293016112-17" class="imgmap201293016112-area" id="imgmap201293016112-area-17" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,908,342,1017" href="" alt="imgmap201293016112-18" title="imgmap201293016112-18" class="imgmap201293016112-area" id="imgmap201293016112-area-18" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="229,1010,342,1084" href="" alt="imgmap201293016112-19" title="imgmap201293016112-19" class="imgmap201293016112-area" id="imgmap201293016112-area-19" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1086,340,1206" href="" alt="imgmap201293016112-20" title="imgmap201293016112-20" class="imgmap201293016112-area" id="imgmap201293016112-area-20" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1209,224,1290" href="" alt="imgmap201293016112-21" title="imgmap201293016112-21" class="imgmap201293016112-area" id="imgmap201293016112-area-21" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1290,225,1432" href="" alt="imgmap201293016112-22" title="imgmap201293016112-22" class="imgmap201293016112-area" id="imgmap201293016112-area-22" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="0,1432,340,1517" href="" alt="imgmap201293016112-23" title="imgmap201293016112-23" class="imgmap201293016112-area" id="imgmap201293016112-area-23" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="346,1432,686,1517" href="" alt="imgmap201293016112-24" title="imgmap201293016112-24" class="imgmap201293016112-area" id="imgmap201293016112-area-24" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="461,1266,686,1429" href="" alt="imgmap201293016112-25" title="imgmap201293016112-25" class="imgmap201293016112-area" id="imgmap201293016112-area-25" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,1365,455,1430" href="" alt="imgmap201293016112-26" title="imgmap201293016112-26" class="imgmap201293016112-area" id="imgmap201293016112-area-26" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="231,1291,457,1360" href="" alt="imgmap201293016112-27" title="imgmap201293016112-27" class="imgmap201293016112-area" id="imgmap201293016112-area-27" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="230,1210,342,1289" href="" alt="imgmap201293016112-28" title="imgmap201293016112-28" class="imgmap201293016112-area" id="imgmap201293016112-area-28" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="692,928,916,1016" href="" alt="imgmap201293016112-29" title="imgmap201293016112-29" class="imgmap201293016112-area" id="imgmap201293016112-area-29" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="460,616,916,759" href="" alt="imgmap201293016112-30" title="imgmap201293016112-30" class="imgmap201293016112-area" id="imgmap201293016112-area-30" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="693,1316,917,1518" href="" alt="imgmap201293016112-31" title="imgmap201293016112-31" class="imgmap201293016112-area" id="imgmap201293016112-area-31" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="344,1150,572,1219" href="" alt="imgmap201293016112-32" title="imgmap201293016112-32" class="imgmap201293016112-area" id="imgmap201293016112-area-32" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="693,1015,916,1171" href="" alt="imgmap201293016112-33" title="imgmap201293016112-33" class="imgmap201293016112-area" id="imgmap201293016112-area-33" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="577,955,686,1032" href="" alt="imgmap201293016112-34" title="imgmap201293016112-34" class="imgmap201293016112-area" id="imgmap201293016112-area-34" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="577,1036,687,1101" href="" alt="imgmap201293016112-35" title="imgmap201293016112-35" class="imgmap201293016112-area" id="imgmap201293016112-area-35" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="576,1104,689,1172" href="" alt="imgmap201293016112-36" title="imgmap201293016112-36" class="imgmap201293016112-area" id="imgmap201293016112-area-36" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="691,1232,918,1313" href="" alt="imgmap201293016112-37" title="imgmap201293016112-37" class="imgmap201293016112-area" id="imgmap201293016112-area-37" />
    <area shape="rect" onmouseover='myHover(this);' onmouseout='myLeave();' coords="341,1085,573,1151" href="" alt="imgmap201293016112-38" title="imgmap201293016112-38" class="imgmap201293016112-area" id="imgmap201293016112-area-38" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="917,868,917,925,688,927,688,955,576,955,574,867,572,864" href="" alt="imgmap201293016112-39" title="imgmap201293016112-39" class="imgmap201293016112-area" id="imgmap201293016112-area-39" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="919,1173,917,1231,688,1231,688,1266,574,1267,576,1175,576,1175" href="" alt="imgmap201293016112-40" title="imgmap201293016112-40" class="imgmap201293016112-area" id="imgmap201293016112-area-40" />
    <area shape="poly" onmouseover='myHover(this);' onmouseout='myLeave();' coords="572,1222,572,1265,459,1265,458,1289,339,1290,344,1225" href="" alt="imgmap201293016112-41" title="imgmap201293016112-41" class="imgmap201293016112-area" id="imgmap201293016112-area-41" />
</map>
</center>

</body>
</html>

Get Absolute URL from Relative path (refactored method)

The final version taking care of all previous complaints (ports, logical url, relative url, existing absolute url...etc.) considering the current handler is the page:

public static string ConvertToAbsoluteUrl(string url)
{
    if (!IsAbsoluteUrl(url))
    {
        if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Handler is System.Web.UI.Page)
        {
            var originalUrl = HttpContext.Current.Request.Url;
            return string.Format("{0}://{1}{2}{3}", originalUrl.Scheme, originalUrl.Host, !originalUrl.IsDefaultPort ? (":" + originalUrl.Port) : string.Empty, ((System.Web.UI.Page)HttpContext.Current.Handler).ResolveUrl(url));
        }
        throw new Exception("Invalid context!");
    }
    else
        return url;
}

private static bool IsAbsoluteUrl(string url)
{
    Uri result;
    return Uri.TryCreate(url, UriKind.Absolute, out result);
}

How to pass ArrayList of Objects from one to another activity using Intent in android?

I do one of two things in this scenario

  1. Implement a serialize/deserialize system for my objects and pass them as Strings (in JSON format usually, but you can serialize them any way you'd like)

  2. Implement a container that lives outside of the activities so that all my activities can read and write to this container. You can make this container static or use some kind of dependency injection to retrieve the same instance in each activity.

Parcelable works just fine, but I always found it to be an ugly looking pattern and doesn't really add any value that isn't there if you write your own serialization code outside of the model.

How do I initialize an empty array in C#?

string[] a = new string[0];

or short notation:

string[] a = { };

The preferred way now is:

var a = Array.Empty<string>();

I have written a short regular expression that you can use in Visual Studio if you want to replace zero-length allocations e.g. new string[0]. Use Find (search) in Visual Studio with Regular Expression option turned on:

new[ ][a-zA-Z0-9]+\[0\]

Now Find All or F3 (Find Next) and replace all with Array.Empty<…>() !

How do I read a specified line in a text file?

Late Answer but worth it .

You need to load the lines in array or list object where each line will be assign to an index ,then simply call any range of lines by their index in for loop .

Solution is pretty Good ,but there is a memory consumption in between .

give it try ...Its worth it

SQL Server, division returns zero

Because it's an integer. You need to declare them as floating point numbers or decimals, or cast to such in the calculation.

Display Image On Text Link Hover CSS Only

It is not possible to do this with just CSS alone, you will need to use Javascript.

<img src="default_image.jpg" id="image" width="100" height="100" alt="" />


<a href="page.html" onmouseover="document.images['image'].src='mouseover.jpg';" onmouseout="document.images['image'].src='default_image.jpg';"/>Text</a>

Invoke-customs are only supported starting with android 0 --min-api 26

After hours of struggling, I solved it by including the following within app/build.gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

https://github.com/mapbox/mapbox-gl-native/issues/11378

How to Import 1GB .sql file to WAMP/phpmyadmin

I also face the same problem and strangely changing the values in php.ini did not worked for me. So I found out one more solution which worked for me.

  • Click your Wamp server icon -> MySql -> MySql console
  • Once mysql console is open. Enter your mysql password. and give these commands.

    1. use user_database_name
    2. source c:/your/sql/path/filename.sql

If you still have problems watch this video.

define() vs. const

To add on NikiC's answer. const can be used within classes in the following manner:

class Foo {
    const BAR = 1;

    public function myMethod() {
        return self::BAR;
    }
}

You can not do this with define().

"git rm --cached x" vs "git reset head --? x"?

There are three places where a file, say, can be - the (committed) tree, the index and the working copy. When you just add a file to a folder, you are adding it to the working copy.

When you do something like git add file you add it to the index. And when you commit it, you add it to the tree as well.

It will probably help you to know the three more common flags in git reset:

git reset [--<mode>] [<commit>]

This form resets the current branch head to <commit> and possibly updates the index (resetting it to the tree of <commit>) and the working tree depending on <mode>, which must be one of the following:
--soft

Does not touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

--mixed

Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated. This is the default action.

--hard

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

Now, when you do something like git reset HEAD, what you are actually doing is git reset HEAD --mixed and it will "reset" the index to the state it was before you started adding files / adding modifications to the index (via git add). In this case, no matter what the state of the working copy was, you didn't change it a single bit, but you changed the index in such a way that is now in sync with the HEAD of the tree. Whether git add was used to stage a previously committed but changed file, or to add a new (previously untracked) file, git reset HEAD is the exact opposite of git add.

git rm, on the other hand, removes a file from the working directory and the index, and when you commit, the file is removed from the tree as well. git rm --cached, however, removes the file from the index alone and keeps it in your working copy. In this case, if the file was previously committed, then you made the index to be different from the HEAD of the tree and the working copy, so that the HEAD now has the previously committed version of the file, the index has no file at all, and the working copy has the last modification of it. A commit now will sync the index and the tree, and the file will be removed from the tree (leaving it untracked in the working copy). When git add was used to add a new (previously untracked) file, then git rm --cached is the exact opposite of git add (and is pretty much identical to git reset HEAD).

Git 2.25 introduced a new command for these cases, git restore, but as of Git 2.28 it is described as “experimental” in the man page, in the sense that the behavior may change.

How do I convert a org.w3c.dom.Document object to a String?

This worked for me, as documented on this page:

TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
StringWriter sw = new StringWriter();
trans.transform(new DOMSource(document), new StreamResult(sw));
return sw.toString();

Why is textarea filled with mysterious white spaces?

Look closely at your code. In it, there are already three line breaks, and a ton of white space before </textarea>. Remove those first so that there are no line breaks in between the tags any more. It might already do the trick.

Setting up an MS-Access DB for multi-user access

The first thing to do (if not already done) is to split your database into a front end (with all the forms/reports etc) and a back end(with all the data). The second thing is to setup version control on the front end.

The way I have done that in a lot of my databases is to have the users run a small “jumper” database to open the main database. This jumper does the following things

• Checks to see if the user has the database on their C drive

• If they do not then install and run

• If they do then check what version they have

• If the version numbers do not match then copy down the latest version

• Open the database

This whole checking process normally takes under half a second. Using this model you can do all your development on a separate database then when you are ready to “release” you just put the new mde up onto the network share and the next time the user opens the jumper the latest version is copied down.

There are also other things to think about in multiuser database and it might be worth checking for the common mistakes such as binding a form to a whole table etc

How to subtract 2 hours from user's local time?

According to Javascript Date Documentation, you can easily do this way:

var twoHoursBefore = new Date();
twoHoursBefore.setHours(twoHoursBefore.getHours() - 2);

And don't worry about if hours you set will be out of 0..23 range. Date() object will update the date accordingly.

Passing parameters to a JDBC PreparedStatement

If you are using prepared statement, you should use it like this:

"SELECT * from employee WHERE userID = ?"

Then use:

statement.setString(1, userID);

? will be replaced in your query with the user ID passed into setString method.

Take a look here how to use PreparedStatement.

How to set default value to all keys of a dict object in python?

You can use the following class. Just change zero to any default value you like. The solution was tested in Python 2.7.

class cDefaultDict(dict):
    # dictionary that returns zero for missing keys
    # keys with zero values are not stored

    def __missing__(self,key):
        return 0

    def __setitem__(self, key, value):
        if value==0:
            if key in self:  # returns zero anyway, so no need to store it
                del self[key]
        else:
            dict.__setitem__(self, key, value)

Putty: Getting Server refused our key Error

Steps to fix Root mount (That i followed as i changed permission with ec2-user folder and the authorization key file) This process will be similar to detach and attach a pen-drive

Below are some other scenarios you may encounter -

  1. You're using an SSH private key but the corresponding public key is not in the authorized_keys file.
  2. You don't have permissions for your authorized_keys file.
  3. You don't have permissions for the .ssh folder.
  4. Your authorized_keys file or .ssh folder isn't named correctly.
  5. Your authorized_keys file or .ssh folder was deleted.

Steps to fix them

  • Stop the problematic Ec2 instance
  • Detach the root volume (/dev/sda1)
  • Create an ec2 instance or use an running one
  • Mount the detached volume (/dev/sdvf) to new ec2 instance

Now after you login to new ec2 run below steps

  • Lsblk command - list all available mounts
  • Pick the mount value that you unmount from the problematic instance
  • As ec2-user run “sudo mount /dev/mapper/rootvg-home /mnt” sudo mount /dev/mapper/rootvg-home /mnt
  • Then change directory to /mnt
  • Make all necessary changes

Now we have fixed our volume with the issue that we faced. Mostly it could be user permission issue - Umount /mnt to unmounts it - Now go to the console and point to the volume attached to new instance and detach it - After detached, attached it to your new volume as /dev/sda1

With that said you should be able to login successfully

How to configure postgresql for the first time?

The other answers were not completely satisfying to me. Here's what worked for postgresql-9.1 on Xubuntu 12.04.1 LTS.

  1. Connect to the default database with user postgres:

    sudo -u postgres psql template1

  2. Set the password for user postgres, then exit psql (Ctrl-D):

    ALTER USER postgres with encrypted password 'xxxxxxx';

  3. Edit the pg_hba.conf file:

    sudo vim /etc/postgresql/9.1/main/pg_hba.conf

    and change "peer" to "md5" on the line concerning postgres:

    local      all     postgres     peer md5

    To know what version of postgresql you are running, look for the version folder under /etc/postgresql. Also, you can use Nano or other editor instead of VIM.

  4. Restart the database :

    sudo /etc/init.d/postgresql restart

    (Here you can check if it worked with psql -U postgres).

  5. Create a user having the same name as you (to find it, you can type whoami):

    sudo createuser -U postgres -d -e -E -l -P -r -s <my_name>

    The options tell postgresql to create a user that can login, create databases, create new roles, is a superuser, and will have an encrypted password. The really important ones are -P -E, so that you're asked to type the password that will be encrypted, and -d so that you can do a createdb.

    Beware of passwords: it will first ask you twice the new password (for the new user), repeated, and then once the postgres password (the one specified on step 2).

  6. Again, edit the pg_hba.conf file (see step 3 above), and change "peer" to "md5" on the line concerning "all" other users:

    local      all     all     peer md5

  7. Restart (like in step 4), and check that you can login without -U postgres:

    psql template1

    Note that if you do a mere psql, it will fail since it will try to connect you to a default database having the same name as you (i.e. whoami). template1 is the admin database that is here from the start.

  8. Now createdb <dbname> should work.

Platform.runLater and Task in JavaFX

Use Platform.runLater(...) for quick and simple operations and Task for complex and big operations .

Example: Why Can't we use Platform.runLater(...) for long calculations (Taken from below reference).

Problem: Background thread which just counts from 0 to 1 million and update progress bar in UI.

Code using Platform.runLater(...):

final ProgressBar bar = new ProgressBar();
new Thread(new Runnable() {
    @Override public void run() {
    for (int i = 1; i <= 1000000; i++) {
        final int counter = i;
        Platform.runLater(new Runnable() {
            @Override public void run() {
                bar.setProgress(counter / 1000000.0);
            }
        });
    }
}).start();

This is a hideous hunk of code, a crime against nature (and programming in general). First, you’ll lose brain cells just looking at this double nesting of Runnables. Second, it is going to swamp the event queue with little Runnables — a million of them in fact. Clearly, we needed some API to make it easier to write background workers which then communicate back with the UI.

Code using Task :

Task task = new Task<Void>() {
    @Override public Void call() {
        static final int max = 1000000;
        for (int i = 1; i <= max; i++) {
            updateProgress(i, max);
        }
        return null;
    }
};

ProgressBar bar = new ProgressBar();
bar.progressProperty().bind(task.progressProperty());
new Thread(task).start();

it suffers from none of the flaws exhibited in the previous code

Reference : Worker Threading in JavaFX 2.0

Why doesn't catching Exception catch RuntimeException?

catch (Exception ex) { ... }

WILL catch RuntimeException.

Whatever you put in catch block will be caught as well as the subclasses of it.

What is the difference between ( for... in ) and ( for... of ) statements?

I found the following explanation from https://javascript.info/array very helpful:

One of the oldest ways to cycle array items is the for loop over indexes:

let arr = ["Apple", "Orange", "Pear"];

for (let i = 0; i < arr.length; i++) { alert( arr[i] ); } But for arrays there is another form of loop, for..of:

let fruits = ["Apple", "Orange", "Plum"];

// iterates over array elements for (let fruit of fruits) { alert( fruit ); } The for..of doesn’t give access to the number of the current element, just its value, but in most cases that’s enough. And it’s shorter.

Technically, because arrays are objects, it is also possible to use for..in:

let arr = ["Apple", "Orange", "Pear"];

for (let key in arr) { alert( arr[key] ); // Apple, Orange, Pear } But that’s actually a bad idea. There are potential problems with it:

The loop for..in iterates over all properties, not only the numeric ones.

There are so-called “array-like” objects in the browser and in other environments, that look like arrays. That is, they have length and indexes properties, but they may also have other non-numeric properties and methods, which we usually don’t need. The for..in loop will list them though. So if we need to work with array-like objects, then these “extra” properties can become a problem.

The for..in loop is optimized for generic objects, not arrays, and thus is 10-100 times slower. Of course, it’s still very fast. The speedup may only matter in bottlenecks. But still we should be aware of the difference.

Generally, we shouldn’t use for..in for arrays.

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_

in_array() and multidimensional array

if your array like this

$array = array(
              array("name" => "Robert", "Age" => "22", "Place" => "TN"), 
              array("name" => "Henry", "Age" => "21", "Place" => "TVL")
         );

Use this

function in_multiarray($elem, $array,$field)
{
    $top = sizeof($array) - 1;
    $bottom = 0;
    while($bottom <= $top)
    {
        if($array[$bottom][$field] == $elem)
            return true;
        else 
            if(is_array($array[$bottom][$field]))
                if(in_multiarray($elem, ($array[$bottom][$field])))
                    return true;

        $bottom++;
    }        
    return false;
}

example : echo in_multiarray("22", $array,"Age");

Apache: "AuthType not set!" 500 Error

You can try sudo a2enmod rewrite if you use it in your config.

Controlling fps with requestAnimationFrame?

The simplest way


const FPS = 30;
let lastTimestamp = 0;


function update(timestamp) {
  requestAnimationFrame(update);
  if (timestamp - lastTimestamp < 1000 / FPS) return;
  
  
   /* <<< PUT YOUR CODE HERE >>>  */

 
  lastTimestamp = timestamp;
}


update();

How exactly to use Notification.Builder

I was having a problem building notifications (only developing for Android 4.0+). This link showed me exactly what I was doing wrong and says the following:

Required notification contents

A Notification object must contain the following:

A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()

Basically I was missing one of these. Just as a basis for troubleshooting with this, make sure you have all of these at the very least. Hopefully this will save someone else a headache.

Creating a byte array from a stream

It really depends on whether or not you can trust s.Length. For many streams, you just don't know how much data there will be. In such cases - and before .NET 4 - I'd use code like this:

public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16*1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

With .NET 4 and above, I'd use Stream.CopyTo, which is basically equivalent to the loop in my code - create the MemoryStream, call stream.CopyTo(ms) and then return ms.ToArray(). Job done.

I should perhaps explain why my answer is longer than the others. Stream.Read doesn't guarantee that it will read everything it's asked for. If you're reading from a network stream, for example, it may read one packet's worth and then return, even if there will be more data soon. BinaryReader.Read will keep going until the end of the stream or your specified size, but you still have to know the size to start with.

The above method will keep reading (and copying into a MemoryStream) until it runs out of data. It then asks the MemoryStream to return a copy of the data in an array. If you know the size to start with - or think you know the size, without being sure - you can construct the MemoryStream to be that size to start with. Likewise you can put a check at the end, and if the length of the stream is the same size as the buffer (returned by MemoryStream.GetBuffer) then you can just return the buffer. So the above code isn't quite optimised, but will at least be correct. It doesn't assume any responsibility for closing the stream - the caller should do that.

See this article for more info (and an alternative implementation).

How to I say Is Not Null in VBA

Use Not IsNull(Fields!W_O_Count.Value)

HTML5 Canvas Resize (Downscale) Image High Quality?

Not the right answer for people who really need to resize the image itself, but just to shrink the file size.

I had a problem with "directly from the camera" pictures, that my customers often uploaded in "uncompressed" JPEG.

Not so well known is, that the canvas supports (in most browsers 2017) to change the quality of JPEG

data=canvas.toDataURL('image/jpeg', .85) # [1..0] default 0.92

With this trick I could reduce 4k x 3k pics with >10Mb to 1 or 2Mb, sure it depends on your needs.

look here

Peak detection in a 2D array

Just wanna tell you guys there is a nice option to find local maxima in images with python:

from skimage.feature import peak_local_max

or for skimage 0.8.0:

from skimage.feature.peak import peak_local_max

http://scikit-image.org/docs/0.8.0/api/skimage.feature.peak.html

Curl error: Operation timed out

I got same problem lot of time. Check your request url, if you are requesting on local server like 127.1.1/api or 192.168...., try to change it, make sure you are hitting cloud.

assign function return value to some variable using javascript

Or just...

var response = (function() {
    var a;
    // calculate a
    return a;
})();  

In this case, the response variable receives the return value of the function. The function executes immediately.

You can use this construct if you want to populate a variable with a value that needs to be calculated. Note that all calculation happens inside the anonymous function, so you don't pollute the global namespace.

Difference between del, remove, and pop on lists

The remove operation on a list is given a value to remove. It searches the list to find an item with that value and deletes the first matching item it finds. It is an error if there is no matching item, raises a ValueError.

>>> x = [1, 0, 0, 0, 3, 4, 5]
>>> x.remove(4)
>>> x
[1, 0, 0, 0, 3, 5]
>>> del x[7]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    del x[7]
IndexError: list assignment index out of range

The del statement can be used to delete an entire list. If you have a specific list item as your argument to del (e.g. listname[7] to specifically reference the 8th item in the list), it'll just delete that item. It is even possible to delete a "slice" from a list. It is an error if there index out of range, raises a IndexError.

>>> x = [1, 2, 3, 4]
>>> del x[3]
>>> x
[1, 2, 3]
>>> del x[4]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    del x[4]
IndexError: list assignment index out of range

The usual use of pop is to delete the last item from a list as you use the list as a stack. Unlike del, pop returns the value that it popped off the list. You can optionally give an index value to pop and pop from other than the end of the list (e.g listname.pop(0) will delete the first item from the list and return that first item as its result). You can use this to make the list behave like a queue, but there are library routines available that can provide queue operations with better performance than pop(0) does. It is an error if there index out of range, raises a IndexError.

>>> x = [1, 2, 3] 
>>> x.pop(2) 
3 
>>> x 
[1, 2]
>>> x.pop(4)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    x.pop(4)
IndexError: pop index out of range

See collections.deque for more details.

How to call controller from the button click in asp.net MVC 4

You are mixing razor and aspx syntax,if your view engine is razor just do this:

<button class="btn btn-info" type="button" id="addressSearch"   
          onclick="location.href='@Url.Action("List", "Search")'">

What is the difference between a function expression vs declaration in JavaScript?

Function Declaration

function foo() { ... }

Because of function hoisting, the function declared this way can be called both after and before the definition.

Function Expression

  1. Named Function Expression

    var foo = function bar() { ... }
    
  2. Anonymous Function Expression

    var foo = function() { ... }
    

foo() can be called only after creation.

Immediately-Invoked Function Expression (IIFE)

(function() { ... }());

Conclusion

Crockford recommends to use function expression because it makes it clear that foo is a variable containing a function value. Well, personally, I prefer to use Declaration unless there is a reason for Expression.

How to change btn color in Bootstrap

Just create your own button on:

Cheers

How to declare and display a variable in Oracle

Did you recently switch from MySQL and are now longing for the logical equivalents of its more simple commands in Oracle? Because that is the case for me and I had the very same question. This code will give you a quick and dirty print which I think is what you're looking for:

Variable n number
begin
    :n := 1;
end;
print n

The middle section is a PL/SQL bit that binds the variable. The output from print n is in column form, and will not just give the value of n, I'm afraid. When I ran it in Toad 11 it returned like this

        n
---------
        1

I hope that helps

Returning data from Axios API

I know this post is old. But i have seen several attempts of guys trying to answer using async and await but getting it wrong. This should clear it up for any new references

async function axiosTest() {
      try {
        const {data:response} = await axios.get(url) //use data destructuring to get data from the promise object
        return response
      }

      catch (error) {
        console.log(error);
      }
    }

DELETE ... FROM ... WHERE ... IN

The canonical T-SQL (SqlServer) answer is to use a DELETE with JOIN as such

DELETE o
FROM Orders o
INNER JOIN Customers c
    ON o.CustomerId = c.CustomerId
WHERE c.FirstName = 'sklivvz'

This will delete all orders which have a customer with first name Sklivvz.

async await return Task

async methods are different than normal methods. Whatever you return from async methods are wrapped in a Task.

If you return no value(void) it will be wrapped in Task, If you return int it will be wrapped in Task<int> and so on.

If your async method needs to return int you'd mark the return type of the method as Task<int> and you'll return plain int not the Task<int>. Compiler will convert the int to Task<int> for you.

private async Task<int> MethodName()
{
    await SomethingAsync();
    return 42;//Note we return int not Task<int> and that compiles
}

Sameway, When you return Task<object> your method's return type should be Task<Task<object>>

public async Task<Task<object>> MethodName()
{
     return Task.FromResult<object>(null);//This will compile
}

Since your method is returning Task, it shouldn't return any value. Otherwise it won't compile.

public async Task MethodName()
{
     return;//This should work but return is redundant and also method is useless.
}

Keep in mind that async method without an await statement is not async.

Twitter Bootstrap Responsive Background-Image inside Div

Try this (apply to a class you image is in (not img itself), e.g.

.myimage {
  background: transparent url("yourimage.png") no-repeat top center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: 100%;
  height: 500px;
}

Android: ScrollView force to bottom

When the view is not loaded yet, you cannot scroll. You can do it 'later' with a post or sleep call as above, but this is not very elegant.

It is better to plan the scroll and do it on the next onLayout(). Example code here:

https://stackoverflow.com/a/10209457/1310343

How to get last inserted row ID from WordPress database?

I needed to get the last id way after inserting it, so

$lastid = $wpdb->insert_id;

Was not an option.

Did the follow:

global $wpdb;
$id = $wpdb->get_var( 'SELECT id FROM ' . $wpdb->prefix . 'table' . ' ORDER BY id DESC LIMIT 1');

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

I've encountered a very similar issue. I spent almost half a day to understand why everything works correctly in Firefox and fails in Chrome. In my case it was because of duplicated (or maybe mistyped) fields in my request header.

Error: class X is public should be declared in a file named X.java

The name of the public class within a file has to be the same as the name of that file.

So if your file declares class WeatherArray, it needs to be named WeatherArray.java

NULL or BLANK fields (ORACLE)

DROP TABLE TEST;  -- COMMENT THIS OUT FOR THE FIRST RUN

CREATE TABLE TEST
(
    COL_NAME,
    TEST_NAME
) AS
(
    SELECT      NULL,         'ACTUAL NULL'  FROM DUAL
    UNION ALL
    SELECT      '',           'NULL STRING'  FROM DUAL
    UNION ALL
    SELECT      ' ',          'SINGLE SPACE' FROM DUAL
    UNION ALL
    SELECT      '  ',         'DOUBLE SPACE' FROM DUAL
    UNION ALL
    SELECT      '          ', 'TEN SPACES'   FROM DUAL
    UNION ALL   
    SELECT      'NONSPACE',   'NONSPACES'    FROM DUAL
)
;

SELECT LENGTH(COL_NAME) NUM_OF_SPACES, TEST_NAME
FROM TEST
WHERE LENGTH(COL_NAME) > 0         -- THERE IS SOMETHING IN THE FIELD
  AND TRIM(COL_NAME) IS NULL;      -- WHICH EQUATES TO NULL

table TEST dropped.
table TEST created.
NUM_OF_SPACES TEST_NAME


         1 SINGLE SPACE 
         2 DOUBLE SPACE 
        10 TEN SPACES

Once you have identified the columns that contain blanks, wrap that query in a count. If you actually need to identify the fields for some kind of update, consider selecting the ROWID as well.

checking memory_limit in PHP

Checking on command line:

php -i | grep "memory_limit"

What do the python file extensions, .pyc .pyd .pyo stand for?

  1. .py: This is normally the input source code that you've written.
  2. .pyc: This is the compiled bytecode. If you import a module, python will build a *.pyc file that contains the bytecode to make importing it again later easier (and faster).
  3. .pyo: This was a file format used before Python 3.5 for *.pyc files that were created with optimizations (-O) flag. (see the note below)
  4. .pyd: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll

Also for some further discussion on .pyc vs .pyo, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)

  • When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
  • Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only __doc__ strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.
  • A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
  • When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.

Note:

On 2015-09-15 the Python 3.5 release implemented PEP-488 and eliminated .pyo files. This means that .pyc files represent both unoptimized and optimized bytecode.

How to confirm RedHat Enterprise Linux version?

I assume that you've run yum upgrade. That will in general update you to the newest minor release.

Your main resources for determining the version are /etc/redhat_release and lsb_release -a

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

What's the best way to check if a file exists in C?

Usually when you want to check if a file exists, it's because you want to create that file if it doesn't. Graeme Perrow's answer is good if you don't want to create that file, but it's vulnerable to a race condition if you do: another process could create the file in between you checking if it exists, and you actually opening it to write to it. (Don't laugh... this could have bad security implications if the file created was a symlink!)

If you want to check for existence and create the file if it doesn't exist, atomically so that there are no race conditions, then use this:

#include <fcntl.h>
#include <errno.h>

fd = open(pathname, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);
if (fd < 0) {
  /* failure */
  if (errno == EEXIST) {
    /* the file already existed */
    ...
  }
} else {
  /* now you can use the file */
}

How to compile and run C files from within Notepad++ using NppExec plugin?

You can actually compile and run C code even without the use of nppexec plugins. If you use MingW32 C compiler, use g++ for C++ language and gcc for C language.

Paste this code into the notepad++ run section

cmd /k cd $(CURRENT_DIRECTORY) && gcc $(FILE_NAME) -o $(NAME_PART).exe  && $(NAME_PART).exe && pause

It will compile your C code into exe and run it immediately. It's like a build and run feature in CodeBlock. All these are done with some cmd knowledge.

Explanation:

  1. cmd /k is used for testing.
  2. cd $(CURRENT_DIRECTORY)
    • change directory to where file is located
  3. && operators
    • to chain your commands in a single line
  4. gcc $(FILE_NAME)
    • use GCC to compile File with its file extension.
  5. -o $(NAME_PART).exe
    • this flag allow you to choose your output filename. $(NAME_PART) does not include file extension.
  6. $(NAME_PART).exe
    • this alone runs your program
  7. pause
    • this command is used to keep your console open after file has been executed.

For more info on notepad++ commands, go to

http://docs.notepad-plus-plus.org/index.php/External_Programs

htaccess redirect if URL contains a certain string

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/foobar/i$ index.php [NE,L]

Deprecated: mysql_connect()

<?php 
$link = mysqli_connect('localhost','root',''); 
if (!$link) { 
    die('Could not connect to MySQL: ' . mysqli_error()); 
} 
echo 'Connection OK'; mysqli_close($link); 
?>

This will solve your problem.

wait process until all subprocess finish?

subprocess.call

Automatically waits , you can also use:

p1.wait()

How to create separate AngularJS controller files?

For brevity, here's an ES2015 sample that doesn't rely on global variables

// controllers/example-controller.js

export const ExampleControllerName = "ExampleController"
export const ExampleController = ($scope) => {
  // something... 
}

// controllers/another-controller.js

export const AnotherControllerName = "AnotherController"
export const AnotherController = ($scope) => {
  // functionality... 
}

// app.js

import angular from "angular";

import {
  ExampleControllerName,
  ExampleController
} = "./controllers/example-controller";

import {
  AnotherControllerName,
  AnotherController
} = "./controllers/another-controller";

angular.module("myApp", [/* deps */])
  .controller(ExampleControllerName, ExampleController)
  .controller(AnotherControllerName, AnotherController)

How to fix corrupted git repository?

Here's a script (bash) to automate the first solution by @CodeGnome to restore from a backup (run from the top level of the corrupted repo). The backup doesn't need to be complete, it only needs to have the missing objects.

git fsck 2>&1 | grep -e missing -e invalid | awk '{print $NF}' | sort -u |
    while read entry; do
        mkdir -p .git/objects/${entry:0:2}
        cp ${BACKUP}/objects/${entry:0:2}/${entry:2} .git/objects/${entry:0:2}/${entry:2}
    done

Meaning of *& and **& in C++

Typically, you can read the declaration of the variable from right to left. Therefore in the case of int *ptr; , it means that you have a Pointer * to an Integer variable int. Also when it's declared int **ptr2;, it is a Pointer variable * to a Pointer variable * pointing to an Integer variable int , which is the same as "(int *)* ptr2;"

Now, following the syntax by declaring int*& rPtr;, we say it's a Reference & to a Pointer * that points to a variable of type int. Finally, you can apply again this approach also for int**& rPtr2; concluding that it signifies a Reference & to a Pointer * to a Pointer * to an Integer int.

what is Segmentation fault (core dumped)?

"Segmentation fault" means that you tried to access memory that you do not have access to.

The first problem is with your arguments of main. The main function should be int main(int argc, char *argv[]), and you should check that argc is at least 2 before accessing argv[1].

Also, since you're passing in a float to printf (which, by the way, gets converted to a double when passing to printf), you should use the %f format specifier. The %s format specifier is for strings ('\0'-terminated character arrays).

Programmatically set TextBlock Foreground Color

Foreground needs a Brush, so you can use

textBlock.Foreground = Brushes.Navy;

If you want to use the color from RGB or ARGB then

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 125, 35)); 

or

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(Colors.Navy); 

To get the Color from Hex

textBlock.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFDFD991")); 

How do I start an activity from within a Fragment?

Use the Base Context of the Activity in which your fragment resides to start an Intent.

Intent j = new Intent(fBaseCtx, NewactivityName.class);         
startActivity(j);

where fBaseCtx is BaseContext of your current activity. You can get it as fBaseCtx = getBaseContext();

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I've had a similar issue, and I've resolved it by statically linking libstdc++ into the program I was compiling, like so:

$ LIBS=-lstdc++ ./configure ... etc.

instead of the usual

$ ./configure ... etc.

There might be problems with this solution to do with loading shared libraries at runtime, but I haven't looked into the issue deeply enough to comment.

Install python 2.6 in CentOS

You could also use the EPEL-repository, and then do sudo yum install python26 to install python 2.6

How can I escape a single quote?

You could try using: &#145;

WPF: simple TextBox data binding

Name2 is a field. WPF binds only to properties. Change it to:

public string Name2 { get; set; }

Be warned that with this minimal implementation, your TextBox won't respond to programmatic changes to Name2. So for your timer update scenario, you'll need to implement INotifyPropertyChanged:

partial class Window1 : Window, INotifyPropertyChanged
{
  public event PropertyChangedEventHandler PropertyChanged;

  protected void OnPropertyChanged(string propertyName)
  {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
  }

  private string _name2;

  public string Name2
  {
    get { return _name2; }
    set
    {
      if (value != _name2)
      {
         _name2 = value;
         OnPropertyChanged("Name2");
      }
    }
  }
}

You should consider moving this to a separate data object rather than on your Window class.

How to get parameter on Angular2 route in Angular way?

Update: Sep 2019

As a few people have mentioned, the parameters in paramMap should be accessed using the common MapAPI:

To get a snapshot of the params, when you don't care that they may change:

this.bankName = this.route.snapshot.paramMap.get('bank');

To subscribe and be alerted to changes in the parameter values (typically as a result of the router's navigation)

this.route.paramMap.subscribe( paramMap => {
    this.bankName = paramMap.get('bank');
})

Update: Aug 2017

Since Angular 4, params have been deprecated in favor of the new interface paramMap. The code for the problem above should work if you simply substitute one for the other.

Original Answer

If you inject ActivatedRoute in your component, you'll be able to extract the route parameters

    import {ActivatedRoute} from '@angular/router';
    ...
    
    constructor(private route:ActivatedRoute){}
    bankName:string;
    
    ngOnInit(){
        // 'bank' is the name of the route parameter
        this.bankName = this.route.snapshot.params['bank'];
    }

If you expect users to navigate from bank to bank directly, without navigating to another component first, you ought to access the parameter through an observable:

    ngOnInit(){
        this.route.params.subscribe( params =>
            this.bankName = params['bank'];
        )
    }

For the docs, including the differences between the two check out this link and search for "activatedroute"

JavaScript variable number of arguments to function

Be aware that passing an Object with named properties as Ken suggested adds the cost of allocating and releasing the temporary object to every call. Passing normal arguments by value or reference will generally be the most efficient. For many applications though the performance is not critical but for some it can be.

Unable to resolve host "<URL here>" No address associated with host name

Some times on the emulator, I have to launch the browser before my app can access the Internet.

Java command not found on Linux

You can add one of the Java path to PATH variable using the following command.

export PATH=$PATH:/usr/java/jre1.6.0_24/bin/

You can add this line to .bashrc file in your home directory. Adding this to .bashrc will ensure everytime you open bash it will be PATH variable is updated.

Best practice when adding whitespace in JSX

Because &nbsp causes you to have non-breaking spaces, you should only use it where necessary. In most cases, this will have unintended side effects.

Older versions of React, I believe all those before v14, would automatically insert <span> </span> when you had a newline inside of a tag.

While they no longer do this, that's a safe way to handle this in your own code. Unless you have styling that specifically targets span (bad practice in general), then this is the safest route.

Per your example, you can put them on a single line together as it's pretty short. In longer-line scenarios, this is how you should probably do it:

  <div className="top-element-formatting">
    Hello <span className="second-word-formatting">World!</span>
    <span> </span>
    So much more text in this box that it really needs to be on another line.
  </div>

This method is also safe against auto-trimming text editors.

The other method is using {' '} which doesn't insert random HTML tags. This could be more useful when styling, highlighting elements, and removes clutter from the DOM. If you don't need backwards compatibility with React v14 or earlier, this should be your preferred method.

  <div className="top-element-formatting">
    Hello <span className="second-word-formatting">World!</span>
    {' '}
    So much more text in this box that it really needs to be on another line.
  </div>

How to work with string fields in a C struct?

While Richard's is what you want if you do want to go with a typedef, I'd suggest that it's probably not a particularly good idea in this instance, as you lose sight of it being a pointer, while not gaining anything.

If you were treating it a a counted string, or something with additional functionality, that might be different, but I'd really recommend that in this instance, you just get familiar with the 'standard' C string implementation being a 'char *'...

Laravel 5 call a model function in a blade view

want to use model in view as:

{{ Product::find($id) }}

you can use in view:

<?php
$tmp = \App\Product::find($id);
?>
{{ $tmp->name }}

Hope this will help you

How to open every file in a folder

The code below reads for any text files available in the directory which contains the script we are running. Then it opens every text file and stores the words of the text line into a list. After store the words we print each word line by line

import os, fnmatch

listOfFiles = os.listdir('.')
pattern = "*.txt"
store = []
for entry in listOfFiles:
    if fnmatch.fnmatch(entry, pattern):
        _fileName = open(entry,"r")
        if _fileName.mode == "r":
            content = _fileName.read()
            contentList = content.split(" ")
            for i in contentList:
                if i != '\n' and i != "\r\n":
                    store.append(i)

for i in store:
    print(i)

How do I quickly rename a MySQL database (change schema name)?

I posted this How do I change the database name using MySQL? today after days of head scratching and hair pulling. The solution is quite simple export a schema to a .sql file and open the file and change the database/schema name in the sql CREAT TABLE section at the top. There are three instances or more and may not be at the top of the page if multible schemas are saved to the file. It is posible to edit the entire database this way but I expect that in large databases it could be quite a pain following all instances of a table property or index.

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

I solved this a completely different route (because I was in a hurry and didn't want to implement a new HtmlHelper):

I wrapped my Partial View in a big if-else statement:

@if ((bool)ViewData["ShouldRenderScripts"] == true){
// Scripts
}else{
// Html
}

Then, I called the Partial twice with a custom ViewData:

@Html.Partial("MyPartialView", Model, 
    new ViewDataDictionary { { "ShouldRenderScripts", false } })

@section scripts{
    @Html.Partial("MyPartialView", Model, 
        new ViewDataDictionary { { "ShouldRenderScripts", true } })
}

How to use ClassLoader.getResources() correctly?

The Spring Framework has a class which allows to recursively search through the classpath:

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.getResources("classpath*:some/package/name/**/*.xml");

What is the benefit of using "SET XACT_ABORT ON" in a stored procedure?

Regarding client timeouts and the use of XACT_ABORT to handle them, in my opinion there is at least one very good reason to have timeouts in client APIs like SqlClient, and that is to guard the client application code from deadlocks occurring in SQL server code. In this case the client code has no fault, but has to protect it self from blocking forever waiting for the command to complete on the server. So conversely, if client timeouts have to exist to protect client code, so does XACT_ABORT ON has to protect server code from client aborts, in case the server code takes longer to execute than the client is willing to wait for.

Returning value from called function in a shell script

In case you have some parameters to pass to a function and want a value in return. Here I am passing "12345" as an argument to a function and after processing returning variable XYZ which will be assigned to VALUE

#!/bin/bash
getValue()
{
    ABC=$1
    XYZ="something"$ABC
    echo $XYZ
}


VALUE=$( getValue "12345" )
echo $VALUE

Output:

something12345

Pass path with spaces as parameter to bat file

Interesting one. I love collecting quotes about quotes handling in cmd/command.

Your particular scripts gets fixed by using %1 instead of "%1" !!!

By adding an 'echo on' ( or getting rid of an echo off ), you could have easily found that out.

How to show current time in JavaScript in the format HH:MM:SS?

You can do this in Javascript.

var time = new Date();
console.log(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());

At present it returns 15:5:18. Note that if any of the values are less than 10, they will display using only one digit, not two.

Check this in JSFiddle

Updates:
For prefixed 0's try

var time = new Date();
console.log(
    ("0" + time.getHours()).slice(-2)   + ":" + 
    ("0" + time.getMinutes()).slice(-2) + ":" + 
    ("0" + time.getSeconds()).slice(-2));

Cocoa: What's the difference between the frame and the bounds?

The frame is the rectangle that defines the UIView with respect to its superview.

The bounds rect is the range of values that define that NSView's coordinate system.

i.e. anything in this rectangle will actually display in the UIView.

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

You can use case in update and SWAP as many as you want

update Table SET column=(case when is_row_1 then value_2 else value_1 end) where rule_to_match_swap_columns

Write a file in UTF-8 using FileWriter (Java)?

OK it's 2019 now, and from Java 11 you have a constructor with Charset:

FileWriter?(String fileName, Charset charset)

Unfortunately, we still cannot modify the byte buffer size, and it's set to 8192. (https://www.baeldung.com/java-filewriter)

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

I believe some of the respondents of this question have missed the broader implication of the fold function as an abstract tool. Yes, sum can do the same thing for a list of integers, but this is a trivial case. fold is more generic. It is useful when you have a sequence of data structures of varying shape and want to cleanly express an aggregation. So instead of having to build up a for loop with an aggregate variable and manually recompute it each time, a fold function (or the Python version, which reduce appears to correspond to) allows the programmer to express the intent of the aggregation much more plainly by simply providing two things:

  • A default starting or "seed" value for the aggregation.
  • A function that takes the current value of the aggregation (starting with the "seed") and the next element in the list, and returns the next aggregation value.

Download a div in a HTML page as pdf using javascript

Content inside a <div class='html-content'>....</div> can be downloaded as pdf with styles using jspdf & html2canvas.

You need to refer both js libraries,

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>

Then call below function,

//Create PDf from HTML...
function CreatePDFfromHTML() {
    var HTML_Width = $(".html-content").width();
    var HTML_Height = $(".html-content").height();
    var top_left_margin = 15;
    var PDF_Width = HTML_Width + (top_left_margin * 2);
    var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
    var canvas_image_width = HTML_Width;
    var canvas_image_height = HTML_Height;

    var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;

    html2canvas($(".html-content")[0]).then(function (canvas) {
        var imgData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
        for (var i = 1; i <= totalPDFPages; i++) { 
            pdf.addPage(PDF_Width, PDF_Height);
            pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
        }
        pdf.save("Your_PDF_Name.pdf");
        $(".html-content").hide();
    });
}

Ref: pdf genration from html canvas and jspdf.

May be this will help someone.

"use database_name" command in PostgreSQL

When you get a connection to PostgreSQL it is always to a particular database. To access a different database, you must get a new connection.

Using \c in psql closes the old connection and acquires a new one, using the specified database and/or credentials. You get a whole new back-end process and everything.

How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

Demi Magus answer worked for me until Rails 5.

On Apache2/Passenger/Ruby (2.4)/Rails (5.1.6), I had to put

export SECRET_KEY_BASE=GENERATED_CODE

from Demi Magus answer in /etc/apache2/envvars, cause /etc/profile seems to be ignored.

Source: https://www.phusionpassenger.com/library/indepth/environment_variables.html#apache

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

A more "generic" version(?), allowing none English letters as special characters.

^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,}$

_x000D_
_x000D_
var pwdList = [_x000D_
    '@@V4-\3Z`zTzM{>k',_x000D_
    '12qw!"QW12',_x000D_
    '123qweASD!"#',_x000D_
    '1qA!"#$%&',_x000D_
    'Günther32',_x000D_
    '123456789',_x000D_
    'qweASD123',_x000D_
    'qweqQWEQWEqw',_x000D_
    '12qwAS!'_x000D_
  ],_x000D_
  re = /^(?=\S*[a-z])(?=\S*[A-Z])(?=\S*\d)(?=\S*[^\w\s])\S{8,}$/;_x000D_
  _x000D_
  pwdList.forEach(function (pw) {_x000D_
    document.write('<span style="color:'+ (re.test(pw) ? 'green':'red') + '">' + pw + '</span><br/>');_x000D_
  });
_x000D_
_x000D_
_x000D_

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

Or simply use

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

See updated solution here:

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

How can I develop for iPhone using a Windows development machine?

Interesting that no one has mentioned the cross-platform wxWidgets option.

It's less than an optimal solution, though.

IMHO, the business-wisest way to go is to invest the money in Apple's endorsed framework. That way, if you find yourself stuck with some mind-boggling problem, you have a much larger community of developers to consult with.

How do I fix a merge conflict due to removal of a file in a branch?

I normally just run git mergetool and it will prompt me if I want to keep the modified file or keep it deleted. This is the quickest way IMHO since it's one command instead of several per file.

If you have a bunch of deleted files in a specific subdirectory and you want all of them to be resolved by deleting the files, you can do this:

yes d | git mergetool -- the/subdirectory

The d is provided to choose deleting each file. You can also use m to keep the modified file. Taken from the prompt you see when you run mergetool:

Use (m)odified or (d)eleted file, or (a)bort?

In C#, what is the difference between public, private, protected, and having no access modifier?

Public - If you can see the class, then you can see the method

Private - If you are part of the class, then you can see the method, otherwise not.

Protected - Same as Private, plus all descendants can also see the method.

Static (class) - Remember the distinction between "Class" and "Object" ? Forget all that. They are the same with "static"... the class is the one-and-only instance of itself.

Static (method) - Whenever you use this method, it will have a frame of reference independent of the actual instance of the class it is part of.

Ruby: How to post a file via HTTP as multipart/form-data?

I can't say enough good things about Nick Sieger's multipart-post library.

It adds support for multipart posting directly to Net::HTTP, removing your need to manually worry about boundaries or big libraries that may have different goals than your own.

Here is a little example on how to use it from the README:

require 'net/http/post/multipart'

url = URI.parse('http://www.example.com/upload')
File.open("./image.jpg") do |jpg|
  req = Net::HTTP::Post::Multipart.new url.path,
    "file" => UploadIO.new(jpg, "image/jpeg", "image.jpg")
  res = Net::HTTP.start(url.host, url.port) do |http|
    http.request(req)
  end
end

You can check out the library here: http://github.com/nicksieger/multipart-post

or install it with:

$ sudo gem install multipart-post

If you're connecting via SSL you need to start the connection like this:

n = Net::HTTP.new(url.host, url.port) 
n.use_ssl = true
# for debugging dev server
#n.verify_mode = OpenSSL::SSL::VERIFY_NONE
res = n.start do |http|

set pythonpath before import statements

As also noted in the docs here.
Go to Python X.X/Lib and add these lines to the site.py there,

import sys
sys.path.append("yourpathstring")

This changes your sys.path so that on every load, it will have that value in it..

As stated here about site.py,

This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.

For other possible methods of adding some path to sys.path see these docs

creating a new list with subset of list using index in python

The following definition might be more efficient than the first solution proposed

def new_list_from_intervals(original_list, *intervals):
    n = sum(j - i for i, j in intervals)
    new_list = [None] * n
    index = 0
    for i, j in intervals :
        for k in range(i, j) :
            new_list[index] = original_list[k]
            index += 1

    return new_list

then you can use it like below

new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))

Datatable to html Table

The first answer is correct, but if you have a large amount of data (in my project I had 8.000 rows * 8 columns) is tragically slow.... Having a string that becomes that large in c# is why that solution is forbiden

Instead using a large string I used a string array that I join at the end in order to return the string of the html table. Moreover, I used a linq expression ((from o in row.ItemArray select o.ToString()).ToArray()) in order to join each DataRow of the table, instead of looping again, in order to save as much time as possible.

This is my sample code:

private string MakeHtmlTable(DataTable data)
{
            string[] table = new string[data.Rows.Count] ;
            long counter = 1;
            foreach (DataRow row in data.Rows)
            {
                table[counter-1] = "<tr><td>" + String.Join("</td><td>", (from o in row.ItemArray select o.ToString()).ToArray()) + "</td></tr>";

                counter+=1;
            }

            return "</br><table>" + String.Join("", table) + "</table>";
}

RecyclerView expand/collapse items

Do the following after you set the onClick listener to the ViewHolder class:

@Override
    public void onClick(View v) {
        final int originalHeight = yourLinearLayout.getHeight();
        animationDown(YourLinearLayout, originalHeight);//here put the name of you layout that have the options to expand.
    }

    //Animation for devices with kitkat and below
    public void animationDown(LinearLayout billChoices, int originalHeight){

        // Declare a ValueAnimator object
        ValueAnimator valueAnimator;
        if (!billChoices.isShown()) {
            billChoices.setVisibility(View.VISIBLE);
            billChoices.setEnabled(true);
            valueAnimator = ValueAnimator.ofInt(0, originalHeight+originalHeight); // These values in this method can be changed to expand however much you like
        } else {
            valueAnimator = ValueAnimator.ofInt(originalHeight+originalHeight, 0);

            Animation a = new AlphaAnimation(1.00f, 0.00f); // Fade out

            a.setDuration(200);
            // Set a listener to the animation and configure onAnimationEnd
            a.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    billChoices.setVisibility(View.INVISIBLE);
                    billChoices.setEnabled(false);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            // Set the animation on the custom view
            billChoices.startAnimation(a);
        }
        valueAnimator.setDuration(200);
        valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            public void onAnimationUpdate(ValueAnimator animation) {
                Integer value = (Integer) animation.getAnimatedValue();
                billChoices.getLayoutParams().height = value.intValue();
                billChoices.requestLayout();
            }
        });


        valueAnimator.start();
    }
}

I think that should help, that's how I implemented and does the same google does in the recent call view.

Detect merged cells in VBA Excel with MergeArea

There are several helpful bits of code for this.

Place your cursor in a merged cell and ask these questions in the Immidiate Window:

Is the activecell a merged cell?

? Activecell.Mergecells
 True

How many cells are merged?

? Activecell.MergeArea.Cells.Count
 2

How many columns are merged?

? Activecell.MergeArea.Columns.Count
 2

How many rows are merged?

? Activecell.MergeArea.Rows.Count
  1

What's the merged range address?

? activecell.MergeArea.Address
  $F$2:$F$3

Is there a way to define a min and max value for EditText in Android?

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    try {
        String prefix = dest.toString().substring(0, dstart);
        String insert = source.toString();
        String suffix = dest.toString().substring(dend);
        String input_string = prefix + insert + suffix;
        int input = Integer.parseInt(input_string);

        if (isInRange(min, max, input) || input_string.length() < String.valueOf(min).length())
            return null;
    } catch (NumberFormatException nfe) { }
    return "";
}

private boolean isInRange(int a, int b, int c) {
    return b > a ? c >= a && c <= b : c >= b && c <= a;
}

extracting days from a numpy.timedelta64 value

Use dt.days to obtain the days attribute as integers.

For eg:

In [14]: s = pd.Series(pd.timedelta_range(start='1 days', end='12 days', freq='3000T'))

In [15]: s
Out[15]: 
0    1 days 00:00:00
1    3 days 02:00:00
2    5 days 04:00:00
3    7 days 06:00:00
4    9 days 08:00:00
5   11 days 10:00:00
dtype: timedelta64[ns]

In [16]: s.dt.days
Out[16]: 
0     1
1     3
2     5
3     7
4     9
5    11
dtype: int64

More generally - You can use the .components property to access a reduced form of timedelta.

In [17]: s.dt.components
Out[17]: 
   days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
0     1      0        0        0             0             0            0
1     3      2        0        0             0             0            0
2     5      4        0        0             0             0            0
3     7      6        0        0             0             0            0
4     9      8        0        0             0             0            0
5    11     10        0        0             0             0            0

Now, to get the hours attribute:

In [23]: s.dt.components.hours
Out[23]: 
0     0
1     2
2     4
3     6
4     8
5    10
Name: hours, dtype: int64

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

SELECT RTRIM(' Author ') AS Name;

Output will be without any trailing spaces.

Name —————— ‘ Author’

How to change options of <select> with jQuery?

For some odd reason this part

$el.empty(); // remove old options

from CMS solution didn't work for me, so instead of that I've simply used this

el.html(' ');

And it's works. So my working code now looks like that:

var newOptions = {
    "Option 1":"option-1",
    "Option 2":"option-2"
};

var $el = $('.selectClass');
$el.html(' ');
$.each(newOptions, function(key, value) {
    $el.append($("<option></option>")
    .attr("value", value).text(key));
});

SyntaxError: "can't assign to function call"

You are assigning to a function call:

invest(initial_amount,top_company(5,year,year+1)) = subsequent_amount

which is illegal in Python. The question is, what do you want to do? What does invest() do? I suppose it returns a value, namely what you're trying to use as subsequent_amount, right?

If so, then something like this should work:

amount = invest(amount,top_company(5,year,year+1),year)

Call Activity method from adapter

if (parent.getContext() instanceof yourActivity) {
  //execute code
}

this condition will enable you to execute something if the Activity which has the GroupView that requesting views from the getView() method of your adapter is yourActivity

NOTE : parent is that GroupView

Disable html5 video autoplay

_x000D_
_x000D_
<video class="embed-responsive-item"  controls>_x000D_
   <source src="http://example.com/video.mp4" autostart="false">_x000D_
   Your browser does not support the video tag._x000D_
</video>
_x000D_
_x000D_
_x000D_

How to use Servlets and Ajax?

$.ajax({
type: "POST",
url: "url to hit on servelet",
data:   JSON.stringify(json),
dataType: "json",
success: function(response){
    // we have the response
    if(response.status == "SUCCESS"){
        $('#info').html("Info  has been added to the list successfully.<br>"+
        "The  Details are as follws : <br> Name : ");

    }else{
        $('#info').html("Sorry, there is some thing wrong with the data provided.");
    }
},
 error: function(e){
   alert('Error: ' + e);
 }
});

Error:Execution failed for task ':app:processDebugResources'. > java.io.IOException: Could not delete folder "" in android studio

Fix This issue by this command

In Windows Platform

cd android && gradlew clean && cd..

In Mac Platform

cd android && ./gradlew clean && cd ..

Jquery href click - how can I fire up an event?

If you own the HTML code then it might be wise to assign an id to this href. Then your code would look like this:

<a id="sign_up" class="sign_new">Sign up</a>

And jQuery:

$(document).ready(function(){
    $('#sign_up').click(function(){
        alert('Sign new href executed.');
    });
});

If you do not own the HTML then you'd need to change $('#sign_up') to $('a.sign_new'). You might also fire event.stopPropagation() if you have a href in anchor and do not want it handled (AFAIR return false might work as well).

$(document).ready(function(){
    $('#sign_up').click(function(event){
        alert('Sign new href executed.');
        event.stopPropagation();
    });
});

How can I get date in application run by node.js?

Node.js is a server side JS platform build on V8 which is chrome java-script runtime.

It leverages the use of java-script on servers too.

You can use JS Date() function or Date class.

“tag already exists in the remote" error after recreating the git tag

In Windows SourceTree, untick Push all tags to remotes.

enter image description here

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

In Visual Studio 2017 or 2015:

Go to the Solution right click on solution then select Properties-> select all the Configuration-> Debug then click OK. After that Rebuild and Run,this solution worked for me.

SQL search multiple values in same field

This has been partially answered here: MySQL Like multiple values

I advise against

$search = explode( ' ', $search );

and input them directly into the SQL query as this makes prone to SQL inject via the search bar. You will have to escape the characters first in case they try something funny like: "--; DROP TABLE name;

$search = str_replace('"', "''", search );

But even that is not completely safe. You must try to use SQL prepared statements to be safer. Using the regular expression is much easier to build a function to prepare and create what you want.

function makeSQL_search_pattern($search) {
    search_pattern = false;
    //escape the special regex chars
    $search = str_replace('"', "''", $search);
    $search = str_replace('^', "\\^", $search);
    $search = str_replace('$', "\\$", $search);
    $search = str_replace('.', "\\.", $search);
    $search = str_replace('[', "\\[", $search);
    $search = str_replace(']', "\\]", $search);
    $search = str_replace('|', "\\|", $search);
    $search = str_replace('*', "\\*", $search);
    $search = str_replace('+', "\\+", $search);
    $search = str_replace('{', "\\{", $search);
    $search = str_replace('}', "\\}", $search);
    $search = explode(" ", $search);
    for ($i = 0; $i < count($search); $i++) {
        if ($i > 0 && $i < count($search) ) {
           $search_pattern .= "|";
        }
        $search_pattern .= $search[$i];
    }
    return search_pattern;
}

$search_pattern = makeSQL_search_pattern($search);
$sql_query = "SELECT name FROM Products WHERE name REGEXP :search LIMIT 6"
$stmt = pdo->prepare($sql_query);
$stmt->bindParam(":search", $search_pattern, PDO::PARAM_STR);
$stmt->execute();

I have not tested this code, but this is what I would do in your case. I hope this helps.

JAVA How to remove trailing zeros from a double

You should use DecimalFormat("0.#")


For 4.3000

Double price = 4.3000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

output is:

4.3

In case of 5.000 we have

Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

And the output is:

5

Calling @Html.Partial to display a partial view belonging to a different controller

That's no problem.

@Html.Partial("../Controller/View", model)

or

@Html.Partial("~/Views/Controller/View.cshtml", model)

Should do the trick.

If you want to pass through the (other) controller, you can use:

@Html.Action("action", "controller", parameters)

or any of the other overloads