Programs & Examples On #Zipfile

For issues relating to creating and/or utilizing zip files.

How to create a zip archive of a directory in Python?

For anyone else delving into this question and trying to archive the very same directory their program is in and is getting both very deep tree structures and ending up with recursion due to the zip file zipping itself, try this.

It's a combination of Mark's answer and some extra checks to ensure that there's no recursive zipping of the zipfile itself, and no unnecessarily deep folder structures.

import os
import zipfile

def zipdir(path, ziph, ignored_directories, ignored_files):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
      for file in files:
        if not any(ignored_dir in root for ignored_dir in ignored_directories):
          if not any(ignored_fname in file for ignored_fname in ignored_files):
            ziph.write(os.path.join(root, file))

# current working directory
this_dir = os.path.dirname(os.path.abspath(__file__))

# the directory within the working directory the zip will be created in (build/archives).
zip_dest_dir = os.path.join('build', 'archives')

# verify zip_dest_dir exists: if not, create it
if not os.path.isdir(zip_dest_dir):
    os.makedirs(zip_dest_dir, exist_ok=True)

# leave zip_dest_dir blank (or set dist_dir = this_dir) if you want the zip file in the working directory (same directory as the script)
dest_dir = os.path.join(this_dir, zip_dest_dir)

# name the zip file: remember the file extension
zip_filename = 'zipped_directory.zip'

# zip file's path
zip_path = os.path.join(dest_dir, zip_filename)

# create the zipfile handle: you can change ZIP_STORED to any other compression algorithm of your choice, like ZIP_DEFLATED, if you need actual compression
zipf = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_STORED)

# ignored files and directories: I personally wanted to ignore the "build" directory, alongside with "node_modules", so those would be listed here.
ignored_dirs = []

# ignore any specific files: in my case, I was ignoring the script itself, so I'd include 'deploy.py' here
ignored_files = [zip_filename]

# zip directory contents
zipdir('.', zipf, ignored_dirs, ignored_files)
zipf.close()

The resulting zip file should only include directories starting from the working directory: so no Users/user/Desktop/code/.../working_directory/.../etc. kind of file structure.

Unzipping files in Python

You can also import only ZipFile:

from zipfile import ZipFile
zf = ZipFile('path_to_file/file.zip', 'r')
zf.extractall('path_to_extract_folder')
zf.close()

Works in Python 2 and Python 3.

Python: Open file in zip without temporarily extracting it

Vincent Povirk's answer won't work completely;

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...

You have to change it in:

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...

For details read the ZipFile docs here.

Extract Google Drive zip from Google colab notebook

TO unzip a file to a directory:

!unzip path_to_file.zip -d path_to_directory

Node.js heap out of memory

Here are some flag values to add some additional info on how to allow more memory when you start up your node server.

1GB - 8GB

#increase to 1gb
node --max-old-space-size=1024 index.js

#increase to 2gb
node --max-old-space-size=2048 index.js 

#increase to 3gb
node --max-old-space-size=3072 index.js

#increase to 4gb
node --max-old-space-size=4096 index.js

#increase to 5gb
node --max-old-space-size=5120 index.js

#increase to 6gb
node --max-old-space-size=6144 index.js

#increase to 7gb
node --max-old-space-size=7168 index.js

#increase to 8gb 
node --max-old-space-size=8192 index.js 

How do I change db schema to dbo

ms-help://MS.SQLCC.v9/MS.SQLSVR.v9.en/tsqlref9/html/0a760138-460e-410a-a3c1-d60af03bf2ed.htm

ALTER SCHEMA schema_name TRANSFER securable_name

How to parse a JSON file in swift?

Here is a code to make the conversions between JSON and NSData in Swift 2.0

// Convert from NSData to json object
func nsdataToJSON(data: NSData) -> AnyObject? {
    do {
        return try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
    } catch let myJSONError {
        print(myJSONError)
    }
    return nil
}

// Convert from JSON to nsdata
func jsonToNSData(json: AnyObject) -> NSData?{
    do {
        return try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
    } catch let myJSONError {
        print(myJSONError)
    }
    return nil;
}

How to call two methods on button's onclick method in HTML or JavaScript?

  1. Try this:

    <input type="button" onclick="function1();function2();" value="Call2Functions" />
    
  2. Or, call second function at the end of first function:

       function func1(){
         //--- some logic
         func2();
       }
    
       function func2(){
        //--- some logic
       }
    

    ...and call func1() onclick of button:

    <input type="button" onclick="func1();" value="Call2Functions" />
    

How to update maven repository in Eclipse?

If Maven update snapshot doesn't work and if you have Spring Tooling, one interesting way is to remove

  • Right-click on your project then Maven > Disable Maven Nature
  • Right-click on your project then Spring Tools > Update Maven Dependencies
  • After "BUILD SUCCESS", Right-click on your project then Configure > Convert Maven Project

Note: Maven update snapshot sometimes stops working if you use anything else i.e. eclipse:eclipse or Spring Tooling

Correct way to work with vector of arrays

You cannot store arrays in a vector or any other container. The type of the elements to be stored in a container (called the container's value type) must be both copy constructible and assignable. Arrays are neither.

You can, however, use an array class template, like the one provided by Boost, TR1, and C++0x:

std::vector<std::array<double, 4> >

(You'll want to replace std::array with std::tr1::array to use the template included in C++ TR1, or boost::array to use the template from the Boost libraries. Alternatively, you can write your own; it's quite straightforward.)

Is there a C# case insensitive equals operator?

Others answer are totally valid here, but somehow it takes some time to type StringComparison.OrdinalIgnoreCase and also using String.Compare.

I've coded simple String extension method, where you could specify if comparison is case sensitive or case senseless with boolean - see following answer:

https://stackoverflow.com/a/49208128/2338477

How can I get the name of an object in Python?

Based on what it looks like you're trying to do you could use this approach.

In your case, your functions would all live in the module foo. Then you could:

import foo

func_name = parse_commandline()
method_to_call = getattr(foo, func_name)
result = method_to_call()

Or more succinctly:

import foo

result = getattr(foo, parse_commandline())()

How to check if "Radiobutton" is checked?

This worked for me:

   Espresso.onView(ViewMatchers.withId(R.id.radiobutton)).check(ViewAssertions.matches(isChecked()))

Scroll to bottom of div?

A very simple method to this is to set the scroll to to the height of the div.

var myDiv = document.getElementById("myDiv");
window.scrollTo(0, myDiv.innerHeight);

ImportError: DLL load failed: %1 is not a valid Win32 application

When I had this error, it went away after I my computer crashed and restarted. Try closing and reopening your IDE, if that doesn't work, try restarting your computer. I had just installed the libraries at that point without restarting pycharm when I got this error.

Never closed PyCharm first to test because my blasted computer keeps crashing randomly... working on that one, but it at least solved this problem.. little victories.. :).

Properly escape a double quote in CSV

Use 2 quotes:

"Samsung U600 24"""

dlib installation on Windows 10

After spending a lot of time, this comment gave me the right result.

https://github.com/ageitgey/face_recognition/issues/802#issuecomment-544232494

  1. Download Python 3.6.8 and install, make sure you add it to PATH.

  2. Install NumPy, scipy, matplotlib and pandas in your pc/laptop with this command in command prompt:-

    pip install numpy

    pip install scipy

    pip install matplotlib

    pip install pandas

  3. Go to https://pypi.org/project/wheel/#files and right click on filename wheel-0.33.6-py2.py3-none-any.whl (21.6 kB) and copy link address. Then go to your pc/laptop, open command prompt and write this command "python -m pip install" after this command space first then paste the link copied. After install successful go to next step.

  4. Then go this link, https://pypi.org/simple/dlib/ and right click on filename "dlib-19.8.1-cp36-cp36m-win_amd64.whl" then copy link address. Then open command prompt and do the same as step 2 which is, write this command "python -m pip install" after this command space first then paste the link copied. then the dlib will be installed successfully.

  5. After that, type python and enter, then type import dlib to check dlib is installed perfectly. the you can proceed to install face recognition.py which suite for python 3.6.

How to add text to an existing div with jquery

You need to define the button text and have valid HTML for the button. I would also suggest using .on for the click handler of the button

_x000D_
_x000D_
$(function () {_x000D_
  $('#Add').on('click', function () {_x000D_
    $('<p>Text</p>').appendTo('#Content');_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="Content">_x000D_
    <button id="Add">Add Text</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Also I would make sure the jquery is at the bottom of the page just before the closing </body> tag. Doing so will make it so you do not have to have the whole thing wrapped in $(function but I would still do that. Having your javascript load at the end of the page makes it so the rest of the page loads incase there is a slow down in your javascript somewhere.

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

The octothorpe/number-sign/hashmark has a special significance in an URL, it normally identifies the name of a section of a document. The precise term is that the text following the hash is the anchor portion of an URL. If you use Wikipedia, you will see that most pages have a table of contents and you can jump to sections within the document with an anchor, such as:

https://en.wikipedia.org/wiki/Alan_Turing#Early_computers_and_the_Turing_test

https://en.wikipedia.org/wiki/Alan_Turing identifies the page and Early_computers_and_the_Turing_test is the anchor. The reason that Facebook and other Javascript-driven applications (like my own Wood & Stones) use anchors is that they want to make pages bookmarkable (as suggested by a comment on that answer) or support the back button without reloading the entire page from the server.

In order to support bookmarking and the back button, you need to change the URL. However, if you change the page portion (with something like window.location = 'http://raganwald.com';) to a different URL or without specifying an anchor, the browser will load the entire page from the URL. Try this in Firebug or Safari's Javascript console. Load http://minimal-github.gilesb.com/raganwald. Now in the Javascript console, type:

window.location = 'http://minimal-github.gilesb.com/raganwald';

You will see the page refresh from the server. Now type:

window.location = 'http://minimal-github.gilesb.com/raganwald#try_this';

Aha! No page refresh! Type:

window.location = 'http://minimal-github.gilesb.com/raganwald#and_this';

Still no refresh. Use the back button to see that these URLs are in the browser history. The browser notices that we are on the same page but just changing the anchor, so it doesn't reload. Thanks to this behaviour, we can have a single Javascript application that appears to the browser to be on one 'page' but to have many bookmarkable sections that respect the back button. The application must change the anchor when a user enters different 'states', and likewise if a user uses the back button or a bookmark or a link to load the application with an anchor included, the application must restore the appropriate state.

So there you have it: Anchors provide Javascript programmers with a mechanism for making bookmarkable, indexable, and back-button-friendly applications. This technique has a name: It is a Single Page Interface.

p.s. There is a fourth benefit to this technique: Loading page content through AJAX and then injecting it into the current DOM can be much faster than loading a new page. In addition to the speed increase, further tricks like loading certain portions in the background can be performed under the programmer's control.

p.p.s. Given all of that, the 'bang' or exclamation mark is a further hint to Google's web crawler that the exact same page can be loaded from the server at a slightly different URL. See Ajax Crawling. Another technique is to make each link point to a server-accessible URL and then use unobtrusive Javascript to change it into an SPI with an anchor.

Here's the key link again: The Single Page Interface Manifesto

How do I change select2 box height

On 4.0.6, below is the solution that worked for me. Had to include select2-selection__rendered and select2-selection__arrow to vertically align the dropdown label and the arrow icon:

.select2-container .select2-selection, 
.select2-selection__rendered, 
.select2-selection__arrow {
    height: 48px !important;
    line-height: 48px !important;
}

How to check if a class inherits another class without instantiating it?

Try this

typeof(IFoo).IsAssignableFrom(typeof(BarClass));

This will tell you whether BarClass(Derived) implements IFoo(SomeType) or not

How do I add a user when I'm using Alpine as a base image?

The commands are adduser and addgroup.

Here's a template for Docker you can use in busybox environments (alpine) as well as Debian-based environments (Ubuntu, etc.):

ENV USER=docker
ENV UID=12345
ENV GID=23456

RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "$(pwd)" \
    --ingroup "$USER" \
    --no-create-home \
    --uid "$UID" \
    "$USER"

Note the following:

  • --disabled-password prevents prompt for a password
  • --gecos "" circumvents the prompt for "Full Name" etc. on Debian-based systems
  • --home "$(pwd)" sets the user's home to the WORKDIR. You may not want this.
  • --no-create-home prevents cruft getting copied into the directory from /etc/skel

The usage description for these applications is missing the long flags present in the code for adduser and addgroup.

The following long-form flags should work both in alpine as well as debian-derivatives:

adduser

BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.

Usage: adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

        --home DIR           Home directory
        --gecos GECOS        GECOS field
        --shell SHELL        Login shell
        --ingroup GRP        Group (by name)
        --system             Create a system user
        --disabled-password  Don't assign a password
        --no-create-home     Don't create home directory
        --uid UID            User id

One thing to note is that if --ingroup isn't set then the GID is assigned to match the UID. If the GID corresponding to the provided UID already exists adduser will fail.

addgroup

BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.

Usage: addgroup [-g GID] [-S] [USER] GROUP

Add a group or add a user to a group

        --gid GID  Group id
        --system   Create a system group

I discovered all of this while trying to write my own alternative to the fixuid project for running containers as the hosts UID/GID.

My entrypoint helper script can be found on GitHub.

The intent is to prepend that script as the first argument to ENTRYPOINT which should cause Docker to infer UID and GID from a relevant bind mount.

An environment variable "TEMPLATE" may be required to determine where the permissions should be inferred from.

(At the time of writing I don't have documentation for my script. It's still on the todo list!!)

Accidentally committed .idea directory files into git

Add .idea directory to the list of ignored files

First, add it to .gitignore, so it is not accidentally committed by you (or someone else) again:

.idea

Remove it from repository

Second, remove the directory only from the repository, but do not delete it locally. To achieve that, do what is listed here:

Remove a file from a Git repository without deleting it from the local filesystem

Send the change to others

Third, commit the .gitignore file and the removal of .idea from the repository. After that push it to the remote(s).

Summary

The full process would look like this:

$ echo '.idea' >> .gitignore
$ git rm -r --cached .idea
$ git add .gitignore
$ git commit -m '(some message stating you added .idea to ignored entries)'
$ git push

(optionally you can replace last line with git push some_remote, where some_remote is the name of the remote you want to push to)

Reading file contents on the client-side in javascript in various browsers

In order to read a file chosen by the user, using a file open dialog, you can use the <input type="file"> tag. You can find information on it from MSDN. When the file is chosen you can use the FileReader API to read the contents.

_x000D_
_x000D_
function onFileLoad(elementId, event) {_x000D_
    document.getElementById(elementId).innerText = event.target.result;_x000D_
}_x000D_
_x000D_
function onChooseFile(event, onLoadFileHandler) {_x000D_
    if (typeof window.FileReader !== 'function')_x000D_
        throw ("The file API isn't supported on this browser.");_x000D_
    let input = event.target;_x000D_
    if (!input)_x000D_
        throw ("The browser does not properly implement the event object");_x000D_
    if (!input.files)_x000D_
        throw ("This browser does not support the `files` property of the file input.");_x000D_
    if (!input.files[0])_x000D_
        return undefined;_x000D_
    let file = input.files[0];_x000D_
    let fr = new FileReader();_x000D_
    fr.onload = onLoadFileHandler;_x000D_
    fr.readAsText(file);_x000D_
}
_x000D_
<input type='file' onchange='onChooseFile(event, onFileLoad.bind(this, "contents"))' />_x000D_
<p id="contents"></p>
_x000D_
_x000D_
_x000D_

How to play .mp4 video in videoview in android?

Check the format of the video you are rendering. Rendering of mp4 format started from API level 11 and the format must be mp4(H.264)

I encountered the same problem, I had to convert my video to many formats before I hit the format: Use total video converter to convert the video to mp4. It works like a charm.

How do I remove version tracking from a project cloned from git?

You can also remove all the git related stuff using one command. The .gitignore file will also be deleted with this one.

rm -rf .git*

How do I read text from the clipboard?

Use Pythons library Clipboard

Its simply used like this:

import clipboard
clipboard.copy("this text is now in the clipboard")
print clipboard.paste()  

Best way to access a control on another form in Windows Forms?

Step 1:

string regno, exm, brd, cleg, strm, mrks, inyear;

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    string url;
    regno = GridView1.Rows[e.NewEditIndex].Cells[1].Text;
    exm = GridView1.Rows[e.NewEditIndex].Cells[2].Text;
    brd = GridView1.Rows[e.NewEditIndex].Cells[3].Text;
    cleg = GridView1.Rows[e.NewEditIndex].Cells[4].Text;
    strm = GridView1.Rows[e.NewEditIndex].Cells[5].Text;
    mrks = GridView1.Rows[e.NewEditIndex].Cells[6].Text;
    inyear = GridView1.Rows[e.NewEditIndex].Cells[7].Text;

    url = "academicinfo.aspx?regno=" + regno + ", " + exm + ", " + brd + ", " +
          cleg + ", " + strm + ", " + mrks + ", " + inyear;
    Response.Redirect(url);
}

Step 2:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string prm_string = Convert.ToString(Request.QueryString["regno"]);

        if (prm_string != null)
        {
            string[] words = prm_string.Split(',');
            txt_regno.Text = words[0];
            txt_board.Text = words[2];
            txt_college.Text = words[3];
        }
    }
}

Java array reflection: isArray vs. instanceof

If you ever have a choice between a reflective solution and a non-reflective solution, never pick the reflective one (involving Class objects). It's not that it's "Wrong" or anything, but anything involving reflection is generally less obvious and less clear.

How can I add a .npmrc file?

There are a few different points here:

  1. Where is the .npmrc file created.
  2. How can you download private packages

Running npm config ls -l will show you all the implicit settings for npm, including what it thinks is the right place to put the .npmrc. But if you have never logged in (using npm login) it will be empty. Simply log in to create it.

Another thing is #2. You can actually do that by putting a .npmrc file in the NPM package's root. It will then be used by NPM when authenticating. It also supports variable interpolation from your shell so you could do stuff like this:

; Get the auth token to use for fetching private packages from our private scope
; see http://blog.npmjs.org/post/118393368555/deploying-with-npm-private-modules
; and also https://docs.npmjs.com/files/npmrc
//registry.npmjs.org/:_authToken=${NPM_TOKEN}

Pointers

What is a void pointer in C++?

A void* can point to anything (it's a raw pointer without any type info).

MessageBox Buttons?

Check this:

                     if (
 MessageBox.Show(@"Are you Alright?", @"My Message Box",MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        //YES ---> Ok IM ALRIGHHT
                    }
                    else
                   {
                   //NO --->NO IM STUCK
                    }

Regards

Create an array with random values

Quirk single-line solutions on every day.

Values in arrays is total random, so when you will be use this snippets, it will different.

An array (length 10) with random chars in lowercase

Array.apply(null, Array(10)).map(function() { return String.fromCharCode(Math.floor(Math.random() * (123 - 97) + 97)); })

[ 'k', 'a', 'x', 'y', 'n', 'w', 'm', 'q', 'b', 'j' ]

An array (length 10) with random integer numbers from 0 to 99

Array.apply(null, Array(10)).map(function() { return Math.floor(Math.random() * 100 % 100); })

[ 86, 77, 83, 27, 79, 96, 67, 75, 52, 21 ]

An array random dates (from 10 years to ago to now)

Array.apply(null, Array(10)).map(function() { return new Date((new Date()).getFullYear() - Math.floor(Math.random() * 10), Math.floor(Math.random() * 12), Math.floor(Math.random() * 29) )})

[ 2008-08-22T21:00:00.000Z, 2007-07-17T21:00:00.000Z,
2015-05-05T21:00:00.000Z, 2011-06-14T21:00:00.000Z,
2009-07-23T21:00:00.000Z, 2009-11-13T22:00:00.000Z,
2010-05-09T21:00:00.000Z, 2008-01-05T22:00:00.000Z,
2016-05-06T21:00:00.000Z, 2014-08-06T21:00:00.000Z ]

An array (length 10) random strings

Array.apply(null, Array(10)).map(function() { return Array.apply(null, Array(Math.floor(Math.random() * 10  + 3))).map(function() { return String.fromCharCode(Math.floor(Math.random() * (123 - 97) + 97)); }).join('') });

[ 'cubjjhaph', 'bmwy', 'alhobd', 'ceud', 'tnyullyn', 'vpkdflarhnf', 'hvg', 'arazuln', 'jzz', 'cyx' ]

Other useful things you may found here https://github.com/setivolkylany/nodejs-utils/blob/master/utils/faker.js

How to solve PHP error 'Notice: Array to string conversion in...'

Array to string conversion in latest versions of php 7.x is error, rather than notice, and prevents further code execution.

Using print, echo on array is not an option anymore.

Suppressing errors and notices is not a good practice, especially when in development environment and still debugging code.

Use var_dump,print_r, iterate through input value using foreach or for to output input data for names that are declared as input arrays ('name[]')

Most common practice to catch errors is using try/catch blocks, that helps us prevent interruption of code execution that might cause possible errors wrapped within try block.

  try{  //wrap around possible cause of error or notice
    
    if(!empty($_POST['C'])){
        echo $_POST['C'];
    }

  }catch(Exception $e){

    //handle the error message $e->getMessage();
  }

How do I get the directory that a program is running from?

I know it is very late at the day to throw an answer at this one but I found that none of the answers were as useful to me as my own solution. A very simple way to get the path from your CWD to your bin folder is like this:

int main(int argc, char* argv[])
{
    std::string argv_str(argv[0]);
    std::string base = argv_str.substr(0, argv_str.find_last_of("/"));
}

You can now just use this as a base for your relative path. So for example I have this directory structure:

main
  ----> test
  ----> src
  ----> bin

and I want to compile my source code to bin and write a log to test I can just add this line to my code.

std::string pathToWrite = base + "/../test/test.log";

I have tried this approach on Linux using full path, alias etc. and it works just fine.

NOTE:

If you are on windows you should use a '\' as the file separator not '/'. You will have to escape this too for example:

std::string base = argv[0].substr(0, argv[0].find_last_of("\\"));

I think this should work but haven't tested, so comment would be appreciated if it works or a fix if not.

MySQL Error #1133 - Can't find any matching row in the user table

To expound on Stephane's answer.

I got this error when I tried to grant remote connections privileges of a particular database to a root user on MySQL server by running the command:

USE database_name;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';

This gave an error:

ERROR 1133 (42000): Can't find any matching row in the user table

Here's how I fixed it:

First, confirm that your MySQL server allows for remote connections. Use your preferred text editor to open the MySQL server configuration file:

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

Scroll down to the bind-address line and ensure that is either commented out or replaced with 0.0.0.0 (to allow all remote connections) or replaced with Ip-Addresses that you want remote connections from.

Once you make the necessary changes, save and exit the configuration file. Apply the changes made to the MySQL config file by restarting the MySQL service:

sudo systemctl restart mysql

Next, log into the MySQL server console on the server it was installed:

mysql -u root -p

Enter your mysql user password

Check the hosts that the user you want has access to already. In my case the user is root:

SELECT host FROM mysql.user WHERE user = "root";

This gave me this output:

+-----------+
| host      |
+-----------+
| localhost |
+-----------+

Next, I ran the command below which is similar to the previous one that was throwing errors, but notice that I added a password to it this time:

USE database_name;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'my-password';

Note: % grants a user remote access from all hosts on a network. You can specify the Ip-Address of the individual hosts that you want to grant the user access from using the command - GRANT ALL PRIVILEGES ON *.* TO 'root'@'Ip-Address' IDENTIFIED BY 'my-password';

Afterwhich I checked the hosts that the user now has access to. In my case the user is root:

SELECT host FROM mysql.user WHERE user = "root";

This gave me this output:

+-----------+
| host      |
+-----------+
| %         |
| localhost |
+-----------+

Finally, you can try connecting to the MySQL server from another server using the command:

mysql -u username -h mysql-server-ip-address -p

Where u represents user, h represents mysql-server-ip-address and p represents password. So in my case it was:

mysql -u root -h 34.69.261.158 -p

Enter your mysql user password

You should get this output depending on your MySQL server version:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.31 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

Resources: How to Allow Remote Connections to MySQL

That's all.

I hope this helps

Populate nested array in mongoose

Remove docs reference

if (err) {
    return res.json(500);
}
Project.populate(docs, options, function (err, projects) {
    res.json(projects);
});

This worked for me.

if (err) {
    return res.json(500);
}
Project.populate(options, function (err, projects) {
    res.json(projects);
});

How to convert uint8 Array to base64 Encoded String?

npm install google-closure-library --save

require("google-closure-library");
goog.require('goog.crypt.base64');

var result =goog.crypt.base64.encodeByteArray(Uint8Array.of(1,83,27,99,102,66));
console.log(result);

$node index.js would write AVMbY2Y= to the console.

How to pass ArrayList<CustomeObject> from one activity to another?

you need implements Parcelable in your ContactBean class, I put one example for you:

public class ContactClass implements Parcelable {

private String id;
private String photo;
private String firstname;
private String lastname;

public ContactClass()
{

}

private ContactClass(Parcel in) {
    firstname = in.readString();
    lastname = in.readString();
    photo = in.readString();
    id = in.readString();

}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {

    dest.writeString(firstname);
    dest.writeString(lastname);
    dest.writeString(photo);
    dest.writeString(id);

}

 public static final Parcelable.Creator<ContactClass> CREATOR = new Parcelable.Creator<ContactClass>() {
        public ContactClass createFromParcel(Parcel in) {
            return new ContactClass(in);
        }

        public ContactClass[] newArray(int size) {
            return new ContactClass[size];

        }
    };

   // all get , set method 
 }

and this get and set for your code:

Intent intent = new Intent(this,DisplayContact.class);
intent.putExtra("Contact_list", ContactLis);
startActivity(intent);

second class:

ArrayList<ContactClass> myList = getIntent().getParcelableExtra("Contact_list");

Set android shape color programmatically

Try this:

 public void setGradientColors(int bottomColor, int topColor) {
 GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[]  
 {bottomColor, topColor});
 gradient.setShape(GradientDrawable.RECTANGLE);
 gradient.setCornerRadius(10.f);
 this.setBackgroundDrawable(gradient);
 }

for more detail check this link this

hope help.

Logical Operators, || or OR?

I know it's an old topic but still. I've just met the problem in the code I am debugging at work and maybe somebody may have similar issue...

Let's say the code looks like this:

$positions = $this->positions() || [];

You would expect (as you are used to from e.g. javascript) that when $this->positions() returns false or null, $positions is empty array. But it isn't. The value is TRUE or FALSE depends on what $this->positions() returns.

If you need to get value of $this->positions() or empty array, you have to use:

$positions = $this->positions() or [];

EDIT:

The above example doesn't work as intended but the truth is that || and or is not the same... Try this:

<?php

function returnEmpty()
{
  //return "string";
  //return [1];
  return null;
}

$first = returnEmpty() || [];
$second = returnEmpty() or [];
$third = returnEmpty() ?: [];

var_dump($first);
var_dump($second);
var_dump($third);
echo "\n";

This is the result:

bool(false)
NULL
array(0) {
}

So, actually the third option ?: is the correct solution when you want to set returned value or empty array.

$positions = $this->positions() ?: [];

Tested with PHP 7.2.1

How to define a variable in a Dockerfile?

You can use ARG - see https://docs.docker.com/engine/reference/builder/#arg

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs an error.

access denied for user @ 'localhost' to database ''

You are most likely not using the correct credentials for the MySQL server. You also need to ensure the user you are connecting as has the correct privileges to view databases/tables, and that you can connect from your current location in network topographic terms (localhost).

Why can't I define a static method in a Java interface?

Static methods aren't virtual like instance methods so I suppose the Java designers decided they didn't want them in interfaces.

But you can put classes containing static methods inside interfaces. You could try that!

public interface Test {
    static class Inner {
        public static Object get() {
            return 0;
        }
    }
}

what exactly is device pixel ratio?

Boris Smus's article High DPI Images for Variable Pixel Densities has a more accurate definition of device pixel ratio: the number of device pixels per CSS pixel is a good approximation, but not the whole story.

Note that you can get the DPR used by a device with window.devicePixelRatio.

Replace CRLF using powershell

This is a state-of-the-union answer as of Windows PowerShell v5.1 / PowerShell Core v6.2.0:

  • Andrew Savinykh's ill-fated answer, despite being the accepted one, is, as of this writing, fundamentally flawed (I do hope it gets fixed - there's enough information in the comments - and in the edit history - to do so).

  • Ansgar Wiecher's helpful answer works well, but requires direct use of the .NET Framework (and reads the entire file into memory, though that could be changed). Direct use of the .NET Framework is not a problem per se, but is harder to master for novices and hard to remember in general.

  • A future version of PowerShell Core will have a
    Convert-TextFile cmdlet with a -LineEnding parameter to allow in-place updating of text files with a specific newline style, as being discussed on GitHub.

In PSv5+, PowerShell-native solutions are now possible, because Set-Content now supports the -NoNewline switch, which prevents undesired appending of a platform-native newline[1] :

# Convert CRLFs to LFs only.
# Note:
#  * (...) around Get-Content ensures that $file is read *in full*
#    up front, so that it is possible to write back the transformed content
#    to the same file.
#  * + "`n" ensures that the file has a *trailing LF*, which Unix platforms
#     expect.
((Get-Content $file) -join "`n") + "`n" | Set-Content -NoNewline $file

The above relies on Get-Content's ability to read a text file that uses any combination of CR-only, CRLF, and LF-only newlines line by line.

Caveats:

  • You need to specify the output encoding to match the input file's in order to recreate it with the same encoding. The command above does NOT specify an output encoding; to do so, use -Encoding; without -Encoding:

    • In Windows PowerShell, you'll get "ANSI" encoding, your system's single-byte, 8-bit legacy encoding, such as Windows-1252 on US-English systems.
    • In PowerShell Core, you'll get UTF-8 encoding without a BOM.
  • The input file's content as well as its transformed copy must fit into memory as a whole, which can be problematic with large input files.

  • There's a risk of file corruption, if the process of writing back to the input file gets interrupted.


[1] In fact, if there are multiple strings to write, -NoNewline also doesn't place a newline between them; in the case at hand, however, this is irrelevant, because only one string is written.

What's with the dollar sign ($"string")

String Interpolation

is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):

It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.

A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.

Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.

{<interpolatedExpression>[,<alignment>][:<formatString>]}  

Where:

  • interpolatedExpression - The expression that produces a result to be formatted
  • alignment - The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolated expression. If positive, the string representation is right-aligned; if negative, it's left-aligned.
  • formatString - A format string that is supported by the type of the expression result.

The following code example concatenates a string where an object, author as a part of the string interpolation.

string author = "Mohit";  
string hello = $"Hello {author} !";  
Console.WriteLine(hello);  // Hello Mohit !

Read more on C#/.NET Little Wonders: String Interpolation in C# 6

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Same Problem I had... I was writing all the script in a seperate file and was adding it through tag into the end of the HTML file after body tag. After moving the the tag inside the body tag it works fine. before :

</body>
<script>require('../script/viewLog.js')</script>

after :

<script>require('../script/viewLog.js')</script>
</body>

How to select specific columns in laravel eloquent

To get the result of specific column from table,we have to specify the column name.

Use following code : -

   $result = DB::Table('table_name')->select('column1','column2')->where('id',1)->get();  

for example -

$result = DB::Table('Student')->select('subject','class')->where('id',1)->get();  

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

Is there an "if -then - else " statement in XPath?

Unfortunately the previous answers were no option for me so i researched for a while and found this solution:

http://blog.alessio.marchetti.name/post/2011/02/12/the-Oliver-Becker-s-XPath-method

I use it to output text if a certain Node exists. 4 is the length of the text foo. So i guess a more elegant solution would be the use of a variable.

substring('foo',number(not(normalize-space(/elements/the/element/)))*4)

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Problem solved, I've not added the index.html. Which is point out in the web.xml

enter image description here

Note: a project may have more than one web.xml file.

if there are another web.xml in

src/main/webapp/WEB-INF

Then you might need to add another index (this time index.jsp) to

src/main/webapp/WEB-INF/pages/

(grep) Regex to match non-ASCII characters?

No, [^\x20-\x7E] is not ASCII.

This is real ASCII:

 [^\x00-\x7F]

Otherwise, it will trim out newlines and other special characters that are part of the ASCII table!

Microsoft.Office.Core Reference Missing

I faced the same problem when i tried to open my old c# project into visual studio 2017 version. This problem arises typically when you try to open a project that you made with previous version of VS and open it with latest version. what i did is,i opened my project and delete the reference from my project,then added Microsoft outlook 12.0 object library and Microsoft office 12.0 object libraryMicrosoft outlook 12.0 object library

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

I had that same problem when I tried to add the firebase-database implementation, if I commented that line it works, so after a few tries I went to https://firebase.google.com/docs/android/setup

There I checked the versions of the available libraries and my firebase-core was at 16.0.1 (current version is 16.0.4) so I manually changed it and it worked just fine, build and sync were successful.

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

My guess is that $_.Name does not exist.

If I were you, I'd bring the script into the ISE and run it line for line till you get there then take a look at the value of $_

How to open local files in Swagger-UI

I had that issue and here is much simpler solution:

  • Make a dir (eg: swagger-ui) in your public dir (static path: no route is required) and copy dist from swagger-ui into that directory and open localhost/swagger-ui
  • You will see swagger-ui with default petstore example
  • Replace default petstore url in dist/index.html with your localhost/api-docs or to make it more generalized, replace with this:

    location.protocol+'//' + location.hostname+(location.port ? ':' + location.port: '') + "/api-docs";

  • Hit again localhost/swagger-ui

Voila! You local swagger implementation is ready

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

I could not understand those 3 rules in the specs too well -- hope to have something that is more plain English -- but here is what I gathered from JavaScript: The Definitive Guide, 6th Edition, David Flanagan, O'Reilly, 2011:

Quote:

JavaScript does not treat every line break as a semicolon: it usually treats line breaks as semicolons only if it can’t parse the code without the semicolons.

Another quote: for the code

var a
a
=
3 console.log(a)

JavaScript does not treat the second line break as a semicolon because it can continue parsing the longer statement a = 3;

and:

two exceptions to the general rule that JavaScript interprets line breaks as semicolons when it cannot parse the second line as a continuation of the statement on the first line. The first exception involves the return, break, and continue statements

... If a line break appears after any of these words ... JavaScript will always interpret that line break as a semicolon.

... The second exception involves the ++ and -- operators ... If you want to use either of these operators as postfix operators, they must appear on the same line as the expression they apply to. Otherwise, the line break will be treated as a semicolon, and the ++ or -- will be parsed as a prefix operator applied to the code that follows. Consider this code, for example:

x 
++ 
y

It is parsed as x; ++y;, not as x++; y

So I think to simplify it, that means:

In general, JavaScript will treat it as continuation of code as long as it makes sense -- except 2 cases: (1) after some keywords like return, break, continue, and (2) if it sees ++ or -- on a new line, then it will add the ; at the end of the previous line.

The part about "treat it as continuation of code as long as it makes sense" makes it feel like regular expression's greedy matching.

With the above said, that means for return with a line break, the JavaScript interpreter will insert a ;

(quoted again: If a line break appears after any of these words [such as return] ... JavaScript will always interpret that line break as a semicolon)

and due to this reason, the classic example of

return
{ 
  foo: 1
}

will not work as expected, because the JavaScript interpreter will treat it as:

return;   // returning nothing
{
  foo: 1
}

There has to be no line-break immediately after the return:

return { 
  foo: 1
}

for it to work properly. And you may insert a ; yourself if you were to follow the rule of using a ; after any statement:

return { 
  foo: 1
};

Convert image from PIL to openCV format

use this:

pil_image = PIL.Image.open('Image.jpg').convert('RGB') 
open_cv_image = numpy.array(pil_image) 
# Convert RGB to BGR 
open_cv_image = open_cv_image[:, :, ::-1].copy() 

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

We have now posted an official response to the bug opened on Connect. The workarounds we recommend are as follows:

This error is due to Entity Framework creating an implicit transaction during the SaveChanges() call. The best way to work around the error is to use a different pattern (i.e., not saving while in the midst of reading) or by explicitly declaring a transaction. Here are three possible solutions:

// 1: Save after iteration (recommended approach in most cases)
using (var context = new MyContext())
{
    foreach (var person in context.People)
    {
        // Change to person
    }
    context.SaveChanges();
}

// 2: Declare an explicit transaction
using (var transaction = new TransactionScope())
{
    using (var context = new MyContext())
    {
        foreach (var person in context.People)
        {
            // Change to person
            context.SaveChanges();
        }
    }
    transaction.Complete();
}

// 3: Read rows ahead (Dangerous!)
using (var context = new MyContext())
{
    var people = context.People.ToList(); // Note that this forces the database
                                          // to evaluate the query immediately
                                          // and could be very bad for large tables.

    foreach (var person in people)
    {
        // Change to person
        context.SaveChanges();
    }
} 

Pick any kind of file via an Intent in Android

This gives me the best result:

    Intent intent;
    if (android.os.Build.MANUFACTURER.equalsIgnoreCase("samsung")) {
        intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
        intent.putExtra("CONTENT_TYPE", "*/*");
        intent.addCategory(Intent.CATEGORY_DEFAULT);
    } else {

        String[] mimeTypes =
                {"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
                        "application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
                        "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
                        "text/plain",
                        "application/pdf",
                        "application/zip", "application/vnd.android.package-archive"};

        intent = new Intent(Intent.ACTION_GET_CONTENT); // or ACTION_OPEN_DOCUMENT
        intent.setType("*/*");
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
    }

How do I split a string with multiple separators in JavaScript?

My refactor of @Brian answer

_x000D_
_x000D_
var string = 'and this is some kind of information and another text and simple and some egample or red or text';_x000D_
var separators = ['and', 'or'];_x000D_
_x000D_
function splitMulti(str, separators){_x000D_
            var tempChar = 't3mp'; //prevent short text separator in split down_x000D_
            _x000D_
            //split by regex e.g. \b(or|and)\b_x000D_
            var re = new RegExp('\\b(' + separators.join('|') + ')\\b' , "g");_x000D_
            str = str.replace(re, tempChar).split(tempChar);_x000D_
            _x000D_
            // trim & remove empty_x000D_
            return str.map(el => el.trim()).filter(el => el.length > 0);_x000D_
}_x000D_
_x000D_
console.log(splitMulti(string, separators))
_x000D_
_x000D_
_x000D_

XML string to XML document

Depending on what document type you want you can use XmlDocument.LoadXml or XDocument.Load.

How to activate "Share" button in android app?

Create a button with an id share and add the following code snippet.

share.setOnClickListener(new View.OnClickListener() {             
    @Override
    public void onClick(View v) {

        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        String shareBody = "Your body here";
        String shareSub = "Your subject here";
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        startActivity(Intent.createChooser(sharingIntent, "Share using"));
    }
});

The above code snippet will open the share chooser on share button click action. However, note...The share code snippet might not output very good results using emulator. For actual results, run the code snippet on android device to get the real results.

How to break out of jQuery each Loop

According to the documentation return false; should do the job.

We can break the $.each() loop [..] by making the callback function return false.

Return false in the callback:

function callback(indexInArray, valueOfElement) {
  var booleanKeepGoing;

  this; // == valueOfElement (casted to Object)

  return booleanKeepGoing; // optional, unless false 
                           // and want to stop looping
}

BTW, continue works like this:

Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

What do these three dots in React do?

Spread Attributes used to Pass the multiple Properties in a Simple Way

{ ... this.props } is Holding the property of this.props

Use of the { ... } Spread Operator with below props

this.props = 
 { 
    firstName: 'Dan', 
    lastName: 'Abramov', 
    city: 'New York',
    country: 'USA' 
}

Without { ... } Spread

<Child 
  firstName={this.props.firstName}
  lastName={this.props.lastName}
  city={this.props.city}
  country={this.props.country}

> 

With { ... } Spread

<Child { ...this.props } />

Dan Abramov's Tweet about Spread operator (Creator of Redux)

How to add elements to a list in R (loop)

The following adds elements to a list in a loop.

l<-c()
i=1

while(i<100) {

    b<-i
    l<-c(l,b)
    i=i+1
}

What does the 'standalone' directive mean in XML?

standalone describes if the current XML document depends on an external markup declaration.

W3C describes its purpose in "Extensible Markup Language (XML) 1.0 (Fifth Edition)":

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

Here is the solution step-by-step:

  1. Open up httpd-ssl.conf in path2xampp\apache\conf\extra
  2. Look for the line Listen 443
  3. Change port number to anything you want. I use 4430. ex. Listen 4430.
  4. Replace every 443 string in that file with 4430.
  5. Save the file.

HTML5 Canvas: Zooming

If you have a source image or canvas element and your 400x400 canvas you want to draw into you can use the drawImage method to achieve zooming.

So for example, the full view might be like this

ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);

And a zoomed view might be like this

ctx.drawImage(img, img.width / 4, img.height / 4, img.width / 2, img.height / 2, 0, 0, canvas.width, canvas.height);

The first parameter to drawImage is the image element or canvas element to draw, the next 4 are the x, y, width and height to sample from the source and the last 4 parameters are the x, y, width and height of the region to draw in the canvas. It will then handle the scaling for you.

You would just need to pick the width and height for the source sample based on the zoom level and the x and y based on where the mouse is clicked minus half the calculated width and height (but you will need to ensure the rectangle isn't out of bounds).

How to find and return a duplicate value in array

  1. Let's create duplication method that take array of elements as input
  2. In the method body, let's create 2 new array objects one is seen and another one is duplicate
  3. finally lets iterate through each object in given array and for every iteration lets find that object existed in seen array.
  4. if object existed in the seen_array, then it is considered as duplicate object and push that object into duplication_array
  5. if object not-existed in the seen, then it is considered as unique object and push that object into seen_array

let's demonstrate in Code Implementation

def duplication given_array
  seen_objects = []
  duplication_objects = []

  given_array.each do |element|
    duplication_objects << element if seen_objects.include?(element)
    seen_objects << element
  end

  duplication_objects
end

Now call duplication method and output return result -

dup_elements = duplication [1,2,3,4,4,5,6,6]
puts dup_elements.inspect

Debugging in Maven?

If you don't want to be IDE dependent and want to work directly with the command line, you can use 'jdb' (Java Debugger)

As mentioned by Samuel with small modification (set suspend=y instead of suspend=n, y means yes which suspends the program and not run it so you that can set breakpoints to debug it, if suspend=n means it may run the program to completion before you can even debug it)

On the directory which contains your pom.xml, execute:

mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=1044 com.mycompany.app.App"

Then, open up a new terminal and execute:

jdb -attach 1044

You can then use jdb to debug your program!=)

Sources: Java jdb remote debugging command line tool

onClick function of an input type="button" not working

You have to change the ID of the button to be different from the function name JSFiddle

_x000D_
_x000D_
var counter = 0;_x000D_
_x000D_
_x000D_
function moreFields() {_x000D_
  counter++;_x000D_
  var newFields = document.getElementById('readroot').cloneNode(true);_x000D_
  newFields.id = '';_x000D_
  newFields.style.display = 'block';_x000D_
  var newField = newFields.childNodes;_x000D_
  for (var i = 0; i < newField.length; i++) {_x000D_
    var theName = newField[i].name_x000D_
    if (theName) newField[i].name = theName + counter;_x000D_
  }_x000D_
  var insertHere = document.getElementById('writeroot');_x000D_
  insertHere.parentNode.insertBefore(newFields, insertHere);_x000D_
}_x000D_
_x000D_
window.onload = moreFields();
_x000D_
<div id="readroot" style="display: none">_x000D_
  <input type="button" value="Remove review" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />_x000D_
  <br />_x000D_
  <br />_x000D_
  <input name="cd" value="title" />_x000D_
  <select name="rankingsel">_x000D_
    <option>Rating</option>_x000D_
    <option value="excellent">Excellent</option>_x000D_
    <option value="good">Good</option>_x000D_
    <option value="ok">OK</option>_x000D_
    <option value="poor">Poor</option>_x000D_
    <option value="bad">Bad</option>_x000D_
  </select>_x000D_
  <br />_x000D_
  <br />_x000D_
  <textarea rows="5" cols="20" name="review">Short review</textarea>_x000D_
  <br />Radio buttons included to test them in Explorer:_x000D_
  <br />_x000D_
  <input type="radio" name="something" value="test1" />Test 1_x000D_
  <br />_x000D_
  <input type="radio" name="something" value="test2" />Test 2</div>_x000D_
<form method="post" action="index1.php"> <span id="writeroot"></span>_x000D_
_x000D_
  <input type="button" onclick="moreFields();" id="moreFieldsButton" value="Give me more fields!" />_x000D_
  <input type="submit" value="Send form" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Merge / convert multiple PDF files into one PDF

pdfunite is fine to merge entire PDFs. If you want, for example, pages 2-7 from file1.pdf and pages 1,3,4 from file2.pdf, you have to use pdfseparate to split the files into separate PDFs for each page to give to pdfunite.

At that point you probably want a program with more options. qpdf is the best utility I've found for manipulating PDFs. pdftk is bigger and slower and Red Hat/Fedora don't package it because of its dependency on gcj. Other PDF utilities have Mono or Python dependencies. I found qpdf produced a much smaller output file than using pdfseparate and pdfunite to assemble pages into a 30-page output PDF, 970kB vs. 1,6450 kB. Because it offers many more options, qpdf's command line is not as simple; the original request to merge file1 and file2 can be performed with

qpdf --empty --pages file1.pdf file2.pdf -- merged.pdf

How to check if android checkbox is checked within its onClick method (declared in XML)?

try this one :

public void itemClicked(View v) {
  //code to check if this checkbox is checked!
  CheckBox checkBox = (CheckBox)v;
  if(checkBox.isChecked()){

  }
}

Bind a function to Twitter Bootstrap Modal Close

if you want to fire a function on every modal close, you can use this method,

$(document).ready(function (){
    $('.modal').each(function (){
        $(this).on('hidden.bs.modal', function () {
            //fires when evey popup close. Ex. resetModal();
        });
    });
});

So you don't need to specify modal ids every time.

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

You can also create a public method on the page then call that from the code-in-front.

e.g. if using C#:

public string ProcessMyDataItem(object myValue)
{
  if (myValue == null)
  {
     return "0 value";
  }

  return myValue.ToString();
}

Then the label in the code-in-front will be something like:

<asp:Label ID="Label18" Text='<%# ProcessMyDataItem(Eval("item")) %>' runat="server"></asp:Label>

Sorry, haven't tested this code so can't guarantee I got the syntax of "<%# ProcessMyDataItem(Eval("item")) %>" entirely correct.

Get cookie by name

If you use jQuery I recommend you to use this plugin:

https://github.com/carhartl/jquery-cookie
https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js

<script type="text/javascript"
 src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js">

So you can read cookie like this:

var value = $.cookie("obligations");

Also you can write cookie:

$.cookie('obligations', 'new_value');
$.cookie('obligations', 'new_value', { expires: 14, path: '/' });

Delete cookie:

$.removeCookie('obligations');

how to load url into div tag

Try the load() function.

$('#content').load("http://vnexpress.net");

Please not that for this to work, the URL to be loaded must either be on the same domain as the page that's calling it, or enable cross-origin HTTP requests ("Cross-Origin Resource Sharing", short CORS) on the server. This involves sending an additional HTTP header, in its most basic form:

Access-Control-Allow-Origin:*

to allow requests from everywhere.

How do I make an attributed string using Swift?

Swift 5 and above

   let attributedString = NSAttributedString(string:"targetString",
                                   attributes:[NSAttributedString.Key.foregroundColor: UIColor.lightGray,
                                               NSAttributedString.Key.font: UIFont(name: "Arial", size: 18.0) as Any])

Apache VirtualHost and localhost

For someone doing everything described here and still can't access:

XAMPP with Apache HTTP Server 2.4:

In file httpd-vhost.conf:

<VirtualHost *>
    DocumentRoot "D:/xampp/htdocs/dir"
    ServerName something.dev
   <Directory "D:/xampp/htdocs/dir">
    Require all granted #apache v 2.4.4 uses just this
   </Directory>
</VirtualHost>

There isn't any need for a port, or an IP address here. Apache configures it on its own files. There isn't any need for NameVirtualHost *:80; it's deprecated. You can use it, but it doesn't make any difference.

Then to edit hosts, you must run Notepad as administrator (described bellow). If you were editing the file without doing this, you are editing a pseudo file, not the original (yes, it saves, etc., but it's not the real file)

In Windows:

Find the Notepad icon, right click, run as administrator, open file, go to C:/WINDOWS/system32/driver/etc/hosts, check "See all files", and open hosts.

If you where editing it before, probably you will see it's not the file you were previously editing when not running as administrator.

Then to check if Apache is reading your httpd-vhost.conf, go to folder xampFolder/apache/bin, Shift + right click, open a terminal command here, open XAMPP (as you usually do), start Apache, and then on the command line, type httpd -S. You will see a list of the virtual hosts. Just check if your something.dev is there.

jQuery using append with effects

Another way when working with incoming data (like from an ajax call):

var new_div = $(data).hide();
$('#old_div').append(new_div);
new_div.slideDown();

Last segment of URL in jquery

Also,

var url = $(this).attr("href");
var part = url.substring(url.lastIndexOf('/') + 1);

How to make code wait while calling asynchronous calls like Ajax

Why didn't it work for you using Deferred Objects? Unless I misunderstood something this may work for you.

/* AJAX success handler */
var echo = function() {
    console.log('Pass1');
};

var pass = function() {
  $.when(
    /* AJAX requests */
    $.post("/echo/json/", { delay: 1 }, echo),
    $.post("/echo/json/", { delay: 2 }, echo),
    $.post("/echo/json/", { delay: 3 }, echo)
  ).then(function() {
    /* Run after all AJAX */
    console.log('Pass2');
  });
};?

See it here.


UPDATE

Based on your input it seems what your quickest alternative is to use synchronous requests. You can set the property async to false in your $.ajax requests to make them blocking. This will hang your browser until the request is finished though.

Notice I don't recommend this and I still consider you should fix your code in an event-based workflow to not depend on it.

Joining Spark dataframes on the key

From https://spark.apache.org/docs/1.5.1/api/java/org/apache/spark/sql/DataFrame.html, use join:

Inner equi-join with another DataFrame using the given column.

PersonDf.join(ProfileDf,$"personId")

OR

PersonDf.join(ProfileDf,PersonDf("personId") === ProfileDf("personId"))

Update:

You can also save the DFs as temp table using df.registerTempTable("tableName") and you can write sql queries using sqlContext.

How do I make CMake output into a 'bin' dir?

cat CMakeLists.txt
project (hello)
set(CMAKE_BINARY_DIR "/bin")
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR})
add_executable (hello hello.c)

How to remove item from list in C#?

You don't specify what kind of list, but the generic List can use either the RemoveAt(index) method, or the Remove(obj) method:

// Remove(obj)
var item = resultList.Single(x => x.Id == 2);
resultList.Remove(item);

// RemoveAt(index)
resultList.RemoveAt(1);

Steps to upload an iPhone application to the AppStore

Check that your singing identity IN YOUR TARGET properties is correct. This one over-rides what you have in your project properties.

Also: I dunno if this is true - but I wasn't getting emails detailing my binary rejections when I did the "ready for binary upload" from a PC - but I DID get an email when I did this on the MAC

How to drop all tables from a database with one SQL query?

If you don't want to type, you can create the statements with this:

USE Databasename

SELECT  'DROP TABLE [' + name + '];'
FROM    sys.tables

Then copy and paste into a new SSMS window to run it.

How can I create download link in HTML?

This answer is outdated. We now have the download attribute. (see also this link to MDN)

If by "the download link" you mean a link to a file to download, use

  <a href="http://example.com/files/myfile.pdf" target="_blank">Download</a>

the target=_blank will make a new browser window appear before the download starts. That window will usually be closed when the browser discovers that the resource is a file download.

Note that file types known to the browser (e.g. JPG or GIF images) will usually be opened within the browser.

You can try sending the right headers to force a download like outlined e.g. here. (server side scripting or access to the server settings is required for that.)

Defined Edges With CSS3 Filter Blur

Having tackled this same problem myself today, I'd like to present a solution that (currently) works on the major browsers. Some of the other answers on this page did work once, but recent updates, whether it be browser or OS, have voided most/all of these answers.

The key is to place the image in a container, and to transform:scale that container out of it's overflow:hidden parent. Then, the blur gets applied to the img inside the container, instead of on the container itself.

Working Fiddle: https://jsfiddle.net/x2c6txk2/

HTML

<div class="container">
    <div class="img-holder">
        <img src="https://unsplash.it/500/300/?random">
    </div>
</div>

CSS

.container {
    width    : 90%;
    height   : 400px;
    margin   : 50px 5%;
    overflow : hidden;
    position : relative;
}

.img-holder {
    position  : absolute;
    left      : 0;
    top       : 0;
    bottom    : 0;
    right     : 0;
    transform : scale(1.2, 1.2);
}

.img-holder img {
    width          : 100%;
    height         : 100%;
    -webkit-filter : blur(15px);
    -moz-filter    : blur(15px);
    filter         : blur(15px);
}

How to correctly use the ASP.NET FileUpload control

Adding a FileUpload control from the code behind should work just fine, where the HasFile property should be available (for instance in your Click event).

If the properties don't appear to be available (either as a compiler error or via intellisense), you probably are referencing a different variable than you think you are.

Force update of an Android app when a new version is available

you can do this by doing a match between a version number that is kept on app in a variable and similarly the current app version is kept on server side and each time user opens the app the first request should be send to check that if it founds matching do nothing simply let the user use your app otherwise fire an intent to the google playstore or open a webview window to your app(window.open("https://play.google.com/store/apps/details?id=package_name", '_system', 'location=yes');) and there they will automatically have the button asking for update that's what google playstore does for you if you dont have automatic updates on.

How to SSH into Docker?

I guess it is possible. You just need to install a SSH server in each container and expose a port on the host. The main annoyance would be maintaining/remembering the mapping of port to container.

However, I have to question why you'd want to do this. SSH'ng into containers should be rare enough that it's not a hassle to ssh to the host then use docker exec to get into the container.

How to make pylab.savefig() save image for 'maximized' window instead of default size

You can look in a saved figure it's size, like 1920x983 px (size when i saved a maximized window), then I set the dpi as 100 and the size as 19.20x9.83 and it worked fine. Saved exactly equal to the maximized figure.

import numpy as np
import matplotlib.pyplot as plt
x, y = np.genfromtxt('fname.dat', usecols=(0,1), unpack=True)
a = plt.figure(figsize=(19.20,9.83))
a = plt.plot(x, y, '-')
plt.savefig('file.png',format='png',dpi=100)

Javascript geocoding from address to latitude and longitude numbers not working

The script tag to the api has changed recently. Use something like this to query the Geocoding API and get the JSON object back

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/geocode/json?address=THE_ADDRESS_YOU_WANT_TO_GEOCODE&key=YOUR_API_KEY"></script>

The address could be something like

1600+Amphitheatre+Parkway,+Mountain+View,+CA (URI Encoded; you should Google it. Very useful)

or simply

1600 Amphitheatre Parkway, Mountain View, CA

By entering this address https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY inside the browser, along with my API Key, I get back a JSON object which contains the Latitude & Longitude for the city of Moutain view, CA.

{"results" : [
  {
     "address_components" : [
        {
           "long_name" : "1600",
           "short_name" : "1600",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Amphitheatre Parkway",
           "short_name" : "Amphitheatre Pkwy",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Mountain View",
           "short_name" : "Mountain View",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Santa Clara County",
           "short_name" : "Santa Clara County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "California",
           "short_name" : "CA",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "94043",
           "short_name" : "94043",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
     "geometry" : {
        "location" : {
           "lat" : 37.4222556,
           "lng" : -122.0838589
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 37.4236045802915,
              "lng" : -122.0825099197085
           },
           "southwest" : {
              "lat" : 37.4209066197085,
              "lng" : -122.0852078802915
           }
        }
     },
     "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
     "types" : [ "street_address" ]
  }],"status" : "OK"}

Web Frameworks such like AngularJS allow us to perform these queries with ease.

A Generic error occurred in GDI+ in Bitmap.Save method

For me it was a permission problem. Somebody removed write permissions on the folder for the user account under which the application was running.

Android device is not connected to USB for debugging (Android studio)

Windows, many times it will not recognize the device fully and because of driver issues, the device won't show up.

  • 1).go to settings

    2).control panel

    3).hardware and sound

    4).device manager

enter image description here

What is the difference between Swing and AWT?

The base difference that which already everyone mentioned is that one is heavy weight and other is light weight. Let me explain, basically what the term heavy weight means is that when you're using the awt components the native code used for getting the view component is generated by the Operating System, thats why it the look and feel changes from OS to OS. Where as in swing components its the responsibility of JVM to generate the view for the components. Another statement which i saw is that swing is MVC based and awt is not.

file_put_contents(meta/services.json): failed to open stream: Permission denied

This issue actually caused by different users who wants to write/read file but denied cause different ownership. maybe you as 'root' installed laravel before then you login into your site as 'laravel' user where 'laravel' the default ownership, so this is the actually real issue here. So when user 'laravel' want to read/write all file in disk as default, to be denied, cause that file has ownership by 'root'.

To solving this problem you can follow like this:

sudo chown -hR your-user-name /root /nameforlder

or in my case

sudo chown -hR igmcoid /root /sublaravel

Footnote:

  1. root as name first ownership who installed before
  2. your-user-name as the default ownership who actually write/read in site.
  3. namefolder as name folder that want you change the ownership.

Using new line(\n) in string and rendering the same in HTML

Set your css in the table cell to

white-space:pre-wrap;

_x000D_
_x000D_
document.body.innerHTML = 'First line\nSecond line\nThird line';
_x000D_
body{ white-space:pre-wrap; }
_x000D_
_x000D_
_x000D_

How to drop rows of Pandas DataFrame whose value in a certain column is NaN

You could use dataframe method notnull or inverse of isnull, or numpy.isnan:

In [332]: df[df.EPS.notnull()]
Out[332]:
   STK_ID  RPT_Date  STK_ID.1  EPS  cash
2  600016  20111231    600016  4.3   NaN
4  601939  20111231    601939  2.5   NaN


In [334]: df[~df.EPS.isnull()]
Out[334]:
   STK_ID  RPT_Date  STK_ID.1  EPS  cash
2  600016  20111231    600016  4.3   NaN
4  601939  20111231    601939  2.5   NaN


In [347]: df[~np.isnan(df.EPS)]
Out[347]:
   STK_ID  RPT_Date  STK_ID.1  EPS  cash
2  600016  20111231    600016  4.3   NaN
4  601939  20111231    601939  2.5   NaN

Why can't static methods be abstract in Java?

A static method, by definition, doesn't need to know this. Thus, it cannot be a virtual method (that is overloaded according to dynamic subclass information available through this); instead, a static method overload is solely based on info available at compile time (this means: once you refer a static method of superclass, you call namely the superclass method, but never a subclass method).

According to this, abstract static methods would be quite useless because you will never have its reference substituted by some defined body.

Insert null/empty value in sql datetime column by default

Ozi, when you create a new datetime object as in datetime foo = new datetime(); foo is constructed with the time datetime.minvalue() in building a parameterized query, you could check to see if the values entered are equal to datetime.minvalue()

-Just a side thought. seems you have things working.

Parsing JSON in Java without knowing JSON format

To get JSON quickly into Java objects (Maps) that you can then 'drill' and work with, you can use json-io (https://github.com/jdereg/json-io). This library will let you read in a JSON String, and get back a 'Map of Maps' representation.

If you have the corresponding Java classes in your JVM, you can read the JSON in and it will parse it directly into instances of the Java classes.

JsonReader.jsonToMaps(String json)

where json is the String containing the JSON to be read. The return value is a Map where the keys will contain the JSON fields, and the values will contain the associated values.

JsonReader.jsonToJava(String json) 

will read the same JSON string in, and the return value will be the Java instance that was serialized into the JSON. Use this API if you have the classes in your JVM that were written by

JsonWriter.objectToJson(MyClass foo).

Sort an array in Java

If you want to build the Quick sort algorithm yourself and have more understanding of how it works check the below code :

1- Create sort class

class QuickSort {
    private int input[];
    private int length;

    public void sort(int[] numbers) {
        if (numbers == null || numbers.length == 0) {
            return;
        }
        this.input = numbers;
        length = numbers.length;
        quickSort(0, length - 1);
    }
    /*
     * This method implements in-place quicksort algorithm recursively.
     */

    private void quickSort(int low, int high) {
        int i = low;
        int j = high;

        // pivot is middle index
        int pivot = input[low + (high - low) / 2];

        // Divide into two arrays
        while (i <= j) {
            /**
             * As shown in above image, In each iteration, we will identify a
             * number from left side which is greater then the pivot value, and
             * a number from right side which is less then the pivot value. Once
             * search is complete, we can swap both numbers.
             */
            while (input[i] < pivot) {
                i++;
            }
            while (input[j] > pivot) {
                j--;
            }
            if (i <= j) {
                swap(i, j);
                // move index to next position on both sides
                i++;
                j--;
            }
        }

        // calls quickSort() method recursively
        if (low < j) {
            quickSort(low, j);
        }

        if (i < high) {
            quickSort(i, high);
        }
    }

    private void swap(int i, int j) {
        int temp = input[i];
        input[i] = input[j];
        input[j] = temp;
    }
}

2- Send your unsorted array to Quicksort class

import java.util.Arrays;


public class QuickSortDemo {

    public static void main(String args[]) {
        // unsorted integer array
        int[] unsorted = {6, 5, 3, 1, 8, 7, 2, 4};
        System.out.println("Unsorted array :" + Arrays.toString(unsorted));
        QuickSort algorithm = new QuickSort();
        // sorting integer array using quicksort algorithm
        algorithm.sort(unsorted);
        // printing sorted array
        System.out.println("Sorted array :" + Arrays.toString(unsorted));
    }
}

3- Output

Unsorted array :[6, 5, 3, 1, 8, 7, 2, 4] 
Sorted array :[1, 2, 3, 4, 5, 6, 7, 8]

What is event bubbling and capturing?

I have found this tutorial at javascript.info to be very clear in explaining this topic. And its 3-points summary at the end is really talking to the crucial points. I quote it here:

  1. Events first are captured down to deepest target, then bubble up. In IE<9 they only bubble.
  2. All handlers work on bubbling stage excepts addEventListener with last argument true, which is the only way to catch the event on capturing stage.
  3. Bubbling/capturing can be stopped by event.cancelBubble=true (IE) or event.stopPropagation() for other browsers.

How to make connection to Postgres via Node.js

Connection String

The connection string is a string of the form:

postgres://[user[:password]@][host][:port][/dbname]

(where the parts in [...] can optionally be included or excluded)

Some examples of valid connection strings include:

postgres://localhost
postgres://localhost:5432
postgres://localhost/mydb
postgres://user@localhost
postgres://user:secret_password@localhost

If you've just started a database on your local machine, the connection string postgres://localhost will typically work, as that uses the default port number, username, and no password. If the database was started with a specific account, you might find you need to use postgres://pg@localhost or postgres://postgres@localhost

If none of these work, and you have installed docker, another option is to run npx @databases/pg-test start. This will start a postgres server in a docker container and then print out the connection string for you. The pg-test databases are only intended for testing though, so you will loose all your data if your computer restarts.

Connecting in node.js

You can connect to the database and issue queries using @databases/pg:

const createPool = require('@databases/pg');
const {sql} = require('@databases/pg');

// If you're using TypeScript or Babel, you can swap
// the two `require` calls for this import statement:

// import createPool, {sql} from '@databases/pg';

// create a "pool" of connections, you can think of this as a single
// connection, the pool is just used behind the scenes to improve
// performance
const db = createPool('postgres://localhost');

// wrap code in an `async` function so we can use `await`
async function run() {

  // we can run sql by tagging it as "sql" and then passing it to db.query
  await db.query(sql`
    CREATE TABLE IF NOT EXISTS beatles (
      name TEXT NOT NULL,
      height INT NOT NULL,
      birthday DATE NOT NULL
    );
  `);

  const beatle = {
    name: 'George',
    height: 70,
    birthday: new Date(1946, 02, 14),
  };

  // If we need to pass values, we can use ${...} and they will
  // be safely & securely escaped for us
  await db.query(sql`
    INSERT INTO beatles (name, height, birthday)
    VALUES (${beatle.name}, ${beatle.height}, ${beatle.birthday});
  `);

  console.log(
    await db.query(sql`SELECT * FROM beatles;`)
  );
}

run().catch(ex => {
  // It's a good idea to always report errors using
  // `console.error` and set the process.exitCode if
  // you're calling an async function at the top level
  console.error(ex);
  process.exitCode = 1;
}).then(() => {
  // For this little demonstration, we'll dispose of the
  // connection pool when we're done, so that the process
  // exists. If you're building a web server/backend API
  // you probably never need to call this.
  return db.dispose();
});

You can find a more complete guide to querying Postgres using node.js at https://www.atdatabases.org/docs/pg

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

With only this line you can get if a path is a directory or a file:

File.GetAttributes(data.Path).HasFlag(FileAttributes.Directory)

How do I read a large csv file with pandas?

Chunking shouldn't always be the first port of call for this problem.

  1. Is the file large due to repeated non-numeric data or unwanted columns?

    If so, you can sometimes see massive memory savings by reading in columns as categories and selecting required columns via pd.read_csv usecols parameter.

  2. Does your workflow require slicing, manipulating, exporting?

    If so, you can use dask.dataframe to slice, perform your calculations and export iteratively. Chunking is performed silently by dask, which also supports a subset of pandas API.

  3. If all else fails, read line by line via chunks.

    Chunk via pandas or via csv library as a last resort.

Disable Input fields in reactive form

Pay attention

If you are creating a form using a variable for condition and trying to change it later it will not work, i.e. the form will not change.

For example

this.isDisabled = true;
    
this.cardForm = this.fb.group({
    number: [{value: null, disabled: this.isDisabled},
});

and if you change the variable

this.isDisabled = false;

the form will not change. You should use

this.cardForm.get('number').disable();

BTW.

You should use patchValue method for changing value:

this.cardForm.patchValue({
    number: '1703'
});

Fetching data from MySQL database using PHP, Displaying it in a form for editing

<form action="Delegate_update.php" method="post">
  Name
  <input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
  Username
  <input type="text" name= "Username" value= "<?php echo $row['Username']; ?> "size=10>
  Password
  <input type="text" name= "Password" value= "<?php echo $row['Password']; ?>" size=17>
  <input type="submit" name= "submit" value="Update">
</form>

look into this

Jupyter notebook not running code. Stuck on In [*]

It's just the incorrect lines of code you were trying to execute..

  1. You need to turn off your antivirus (if have).
  2. Restart Jupyter Notebook.
  3. Copy your code then delete the cell you were working on.
  4. Rewrite code and make sure you are not doing any mistakes.
  5. Find the missed/wrong lines of code specially increment operators and correct them.

hope it help..

Cannot read property 'map' of undefined

First of all, set more safe initial data:

getInitialState : function() {
    return {data: {comments:[]}};
},

And ensure your ajax data.

It should work if you follow above two instructions like Demo.

Updated: you can just wrap the .map block with conditional statement.

if (this.props.data) {
  var commentNodes = this.props.data.map(function (comment){
      return (
        <div>
          <h1>{comment.author}</h1>
        </div>
      );
  });
}

Format date as dd/MM/yyyy using pipes

If anyone can looking to display date with time in AM or PM in angular 6 then this is for you.

{{date | date: 'dd/MM/yyyy hh:mm a'}}

Output

enter image description here

Pre-defined format options

Examples are given in en-US locale.

'short': equivalent to 'M/d/yy, h:mm a' (6/15/15, 9:03 AM).
'medium': equivalent to 'MMM d, y, h:mm:ss a' (Jun 15, 2015, 9:03:01 AM).
'long': equivalent to 'MMMM d, y, h:mm:ss a z' (June 15, 2015 at 9:03:01 AM GMT+1).
'full': equivalent to 'EEEE, MMMM d, y, h:mm:ss a zzzz' (Monday, June 15, 2015 at 9:03:01 AM GMT+01:00).
'shortDate': equivalent to 'M/d/yy' (6/15/15).
'mediumDate': equivalent to 'MMM d, y' (Jun 15, 2015).
'longDate': equivalent to 'MMMM d, y' (June 15, 2015).
'fullDate': equivalent to 'EEEE, MMMM d, y' (Monday, June 15, 2015).
'shortTime': equivalent to 'h:mm a' (9:03 AM).
'mediumTime': equivalent to 'h:mm:ss a' (9:03:01 AM).
'longTime': equivalent to 'h:mm:ss a z' (9:03:01 AM GMT+1).
'fullTime': equivalent to 'h:mm:ss a zzzz' (9:03:01 AM GMT+01:00).

Reference Link

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

how i solve it in Eclipse

  1. go to the properties of the project enter image description here

  2. go to Java compiler enter image description here

  3. change in the Compiler complicated level to java that my project work with (java 11 in my project) you can see that it your java that you work when the last message disappear

  4. Apply enter image description here

How to use terminal commands with Github?

To add all file at a time, use git add -A

To check git whole status, use git log

Setting Action Bar title and subtitle

The title for the actionbar could be in the AndroidManifest, here:

<activity 
    . . .
          android:label="string resource" 
    . . .
</activity>

android:label A user-readable label for the activity. The label is displayed on-screen when the activity must be represented to the user. It's often displayed along with the activity icon. If this attribute is not set, the label set for the application as a whole is used instead (see the element's label attribute). The activity's label — whether set here or by the element — is also the default label for all the activity's intent filters (see the element's label attribute). The label should be set as a reference to a string resource, so that it can be localized like other strings in the user interface. However, as a convenience while you're developing the application, it can also be set as a raw string.

How to get HTTP response code for a URL in Java?

you can use java http/https url connection to get the response code from the website and other information as well here is a sample code.

 try {

            url = new URL("https://www.google.com"); // create url object for the given string  
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            if(https_url.startsWith("https")){
                 connection = (HttpsURLConnection) url.openConnection();
            }

            ((HttpURLConnection) connection).setRequestMethod("HEAD");
            connection.setConnectTimeout(50000); //set the timeout
            connection.connect(); //connect
            String responseMessage = connection.getResponseMessage(); //here you get the response message
             responseCode = connection.getResponseCode(); //this is http response code
            System.out.println(obj.getUrl()+" is up. Response Code : " + responseMessage);
            connection.disconnect();`
}catch(Exception e){
e.printStackTrace();
}

How do you make a LinearLayout scrollable?

 <LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
                <---------Content Here --------------->
            </LinearLayout>
       </ScrollView>
    </LinearLayout>

How to keep two folders automatically synchronized?

You can take advantage of fschange. It’s a Linux filesystem change notification. The source code is downloadable from the above link, you can compile it yourself. fschange can be used to keep track of file changes by reading data from a proc file (/proc/fschange). When data is written to a file, fschange reports the exact interval that has been modified instead of just saying that the file has been changed. If you are looking for the more advanced solution, I would suggest checking Resilio Connect. It is cross-platform, provides extended options for use and monitoring. Since it’s BitTorrent-based, it is faster than any other existing sync tool. It was written on their behalf.

Static way to get 'Context' in Android?

If you don't want to modify the manifest file, you can manually store the context in a static variable in your initial activity:

public class App {
    private static Context context;

    public static void setContext(Context cntxt) {
        context = cntxt;
    }

    public static Context getContext() {
        return context;
    }
}

And just set the context when your activity (or activities) start:

// MainActivity

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

    // Set Context
    App.setContext(getApplicationContext());

    // Other stuff
}

Note: Like all other answers, this is a potential memory leak.

Add views in UIStackView programmatically

It is really not recommended to set a height constraint... If you can, never, never, never set a height! You need to check all the constraints of the views inside your UIStackView and be sure that there is constraints for bottom, top, leading and trailing. Someone said to me: it is like a guy pushing on walls. If he don't push on 4 sides, one of the wall will fall on him.

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

This solved my problem: Kotlin Code:

val fragmentTransaction = activity.supportFragmentManager.beginTransaction()
fragmentTransaction.add(dialogFragment, tag)
fragmentTransaction.commitAllowingStateLoss()

How is commitAllowingStateLoss() is different than commit() ?

As per documentation:

Like commit() but allows the commit to be executed after an activity's state is saved. https://developer.android.com/reference/android/app/FragmentTransaction#commitAllowingStateLoss()

P.S: you can show Fragment Dialogs or can load fragments by this method. Applicable for both.

What are the git concepts of HEAD, master, origin?

While this doesn't directly answer the question, there is great book available for free which will help you learn the basics called ProGit. If you would prefer the dead-wood version to a collection of bits you can purchase it from Amazon.

jQuery if statement, syntax

It depends on what you mean by stop. If it's in a function that can return void then:

if(a && b) {
    // do something
}else{
    // "stop"
    return;
}

What good are SQL Server schemas?

At an ORACLE shop I worked at for many years, schemas were used to encapsulate procedures (and packages) that applied to different front-end applications. A different 'API' schema for each application often made sense as the use cases, users, and system requirements were quite different. For example, one 'API' schema was for a development/configuration application only to be used by developers. Another 'API' schema was for accessing the client data via views and procedures (searches). Another 'API' schema encapsulated code that was used for synchronizing development/configuration and client data with an application that had it's own database. Some of these 'API' schemas, under the covers, would still share common procedures and functions with eachother (via other 'COMMON' schemas) where it made sense.

I will say that not having a schema is probably not the end of the world, though it can be very helpful. Really, it is the lack of packages in SQL Server that really creates problems in my mind... but that is a different topic.

VSCode Change Default Terminal

I just type following keywords in the opened terminal;

  1. powershell
  2. bash
  3. cmd
  4. node
  5. python (or python3)

See details in the below image. (VSCode version 1.19.1 - windows 10 OS) enter image description here

It works on VS Code Mac as well. I tried it with VSCode (Version 1.20.1)

Postgresql tables exists, but getting "relation does not exist" when querying

I hit this error and it turned out my connection string was pointing to another database, obviously the table didn't exist there.

I spent a few hours on this and no one else has mentioned to double check your connection string.

How to import other Python files?

One very unknown feature of Python is the ability to import zip files:

library.zip
|-library
|--__init__.py

The file __init__.py of the package contains the following:

def dummy():
    print 'Testing things out...'

We can write another script which can import a package from the zip archive. It is only necessary to add the zip file to the sys.path.

import sys
sys.path.append(r'library.zip')

import library

def run():
    library.dummy()

run()

How to show full height background image?

 html, body {
    height:100%;
}

body { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

How to amend a commit without changing commit message (reusing the previous one)?

just to add some clarity, you need to stage changes with git add, then amend last commit:

git add /path/to/modified/files
git commit --amend --no-edit

This is especially useful for if you forgot to add some changes in last commit or when you want to add more changes without creating new commits by reusing the last commit.

Codeigniter how to create PDF

I have used mpdf in my project. In Codeigniter-3, putted mpdf files under application/third_party and then used in this way:

 /**
 * This function is used to display data in PDF file.
 * function is using mpdf api to generate pdf.
 * @param number $id : This is unique id of table.
 */
function generatePDF($id){
    require APPPATH . '/third_party/mpdf/vendor/autoload.php';
    //$mpdf=new mPDF();
    $mpdf = new mPDF('utf-8', 'Letter', 0, '', 0, 0, 7, 0, 0, 0);

    $checkRecords =  $this->user_model->getCheckInfo($id);      
    foreach ($checkRecords as $key => $value) {
        $data['info'] = $value;
        $filename = $this->load->view(CHEQUE_VIEWS.'index',$data,TRUE);
        $mpdf->WriteHTML($filename); 
    }

    $mpdf->Output(); //output pdf document.
    //$content = $mpdf->Output('', 'S'); //get pdf document content's as variable. 

}

CSS styling in Django forms

You could use this library: https://pypi.python.org/pypi/django-widget-tweaks

It allows you to do the following:

{% load widget_tweaks %}
<!-- add 2 extra css classes to field element -->
{{ form.title|add_class:"css_class_1 css_class_2" }}

How to send multiple data fields via Ajax?

According to http://api.jquery.com/jquery.ajax/

$.ajax({
  method: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
  alert( "Data Saved: " + msg );
});

Regular Expression usage with ls

You are confusing regular expression with shell globbing. If you want to use regular expression to match file names you could do:

$ ls | egrep '.+\..+'

How do I lowercase a string in C?

Looping the pointer to gain better performance:

#include <ctype.h>

char* toLower(char* s) {
  for(char *p=s; *p; p++) *p=tolower(*p);
  return s;
}
char* toUpper(char* s) {
  for(char *p=s; *p; p++) *p=toupper(*p);
  return s;
}

How can I set the value of a DropDownList using jQuery?

$("#mydropdownlist").val("thevalue");

just make sure the value in the options tags matches the value in the val method.

How do I change file permissions in Ubuntu

Add -R for recursive:

sudo chmod -R 666 /var/www

Android. Fragment getActivity() sometimes returns null

The best to get rid of this is to keep activity reference when onAttach is called and use the activity reference wherever needed, for e.g.

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mContext = context;
}

@Override
public void onDetach() {
    super.onDetach();
    mContext = null;
}

Edited, since onAttach(Activity) is depreciated & now onAttach(Context) is being used

div inside php echo

You can do the following:

echo '<div class="my_class">';
echo ($cart->count_product > 0) ? $cart->count_product : '';
echo '</div>';

If you want to have it inside your statement, do this:

if($cart->count_product > 0) 
{
    echo '<div class="my_class">'.$cart->count_product.'</div>';
}

You don't need the else statement, since you're only going to output the above when it's truthy anyway.

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

Conditional Logic on Pandas DataFrame

In [1]: df
Out[1]:
   data
0     1
1     2
2     3
3     4

You want to apply a function that conditionally returns a value based on the selected dataframe column.

In [2]: df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')
Out[2]:
0     true
1     true
2    false
3    false
Name: data

You can then assign that returned column to a new column in your dataframe:

In [3]: df['desired_output'] = df['data'].apply(lambda x: 'true' if x <= 2.5 else 'false')

In [4]: df
Out[4]:
   data desired_output
0     1           true
1     2           true
2     3          false
3     4          false

Remove padding or margins from Google Charts

I am quite late but any user searching for this can get help from it. Inside the options you can pass a new parameter called chartArea.

        var options = {
        chartArea:{left:10,top:20,width:"100%",height:"100%"}
    };

Left and top options will define the amount of padding from left and top. Hope this will help.

How can I truncate a datetime in SQL Server?

CONVERT(DATE, <yourdatetime>) or CONVERT(DATE, GetDate()) or CONVERT(DATE, CURRENT_TIMESTAMP)

Disable Enable Trigger SQL server for a table

I wanted to share something that helped me out. Idea credit goes to @Siavash and @Shahab Naseer.

I needed something where I could script disable and re enable of triggers for a particular table. I normally try and stay away from tiggers, but sometimes they could be good to use.

I took the script above and added a join to the sysobjects so I could filter by table name. This script will disable a trigger or triggers for a table.

select 'alter table '+ (select Schema_name(schema_id) from sys.objects o 
where o.object_id = parent_id) + '.'+object_name(parent_id) + ' ENABLE TRIGGER '+ t.Name as EnableScript,*
from sys.triggers t 
INNER JOIN dbo.sysobjects DS ON DS.id = t.parent_id 
where is_disabled = 0 AND DS.name = 'tblSubContact'

Clone an image in cv2 python

Using python 3 and opencv-python version 4.4.0, the following code should work:

img_src = cv2.imread('image.png')
img_clone = img_src.copy()

Java NIO FileChannel versus FileOutputstream performance / usefulness

I tested the performance of FileInputStream vs. FileChannel for decoding base64 encoded files. In my experients I tested rather large file and traditional io was alway a bit faster than nio.

FileChannel might have had an advantage in prior versions of the jvm because of synchonization overhead in several io related classes, but modern jvm are pretty good at removing unneeded locks.

Server returned HTTP response code: 401 for URL: https

Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package

import sun.misc.BASE64Encoder;

import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;

and then,

String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );

 public String getAuthantication(String username, String password) {
   String auth = new String(Base64.encode(username + ":" + password));
   return auth;
 }

How do I find out where login scripts live?

In addition from the command prompt run SET.

This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).

Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.

Proper way to use **kwargs in Python

Another simple solution for processing unknown or multiple arguments can be:

class ExampleClass(object):

    def __init__(self, x, y, **kwargs):
      self.x = x
      self.y = y
      self.attributes = kwargs

    def SomeFunction(self):
      if 'something' in self.attributes:
        dosomething()

Adding an assets folder in Android Studio

To specify any additional asset folder I've used this with my Gradle. This adds moreAssets, a folder in the project root, to the assets.

android {
    sourceSets {
        main.assets.srcDirs += '../moreAssets'
    }
}

Difference between string and char[] types in C++

One of the difference is Null termination (\0).

In C and C++, char* or char[] will take a pointer to a single char as a parameter and will track along the memory until a 0 memory value is reached (often called the null terminator).

C++ strings can contain embedded \0 characters, know their length without counting.

#include<stdio.h>
#include<string.h>
#include<iostream>

using namespace std;

void NullTerminatedString(string str){
   int NUll_term = 3;
   str[NUll_term] = '\0';       // specific character is kept as NULL in string
   cout << str << endl <<endl <<endl;
}

void NullTerminatedChar(char *str){
   int NUll_term = 3;
   str[NUll_term] = 0;     // from specific, all the character are removed 
   cout << str << endl;
}

int main(){
  string str = "Feels Happy";
  printf("string = %s\n", str.c_str());
  printf("strlen = %d\n", strlen(str.c_str()));  
  printf("size = %d\n", str.size());  
  printf("sizeof = %d\n", sizeof(str)); // sizeof std::string class  and compiler dependent
  NullTerminatedString(str);


  char str1[12] = "Feels Happy";
  printf("char[] = %s\n", str1);
  printf("strlen = %d\n", strlen(str1));
  printf("sizeof = %d\n", sizeof(str1));    // sizeof char array
  NullTerminatedChar(str1);
  return 0;
}

Output:

strlen = 11
size = 11
sizeof = 32  
Fee s Happy


strlen = 11
sizeof = 12
Fee

Boolean Field in Oracle

The best option is 0 and 1 (as numbers - another answer suggests 0 and 1 as CHAR for space-efficiency but that's a bit too twisted for me), using NOT NULL and a check constraint to limit contents to those values. (If you need the column to be nullable, then it's not a boolean you're dealing with but an enumeration with three values...)

Advantages of 0/1:

  • Language independent. 'Y' and 'N' would be fine if everyone used it. But they don't. In France they use 'O' and 'N' (I have seen this with my own eyes). I haven't programmed in Finland to see whether they use 'E' and 'K' there - no doubt they're smarter than that, but you can't be sure.
  • Congruent with practice in widely-used programming languages (C, C++, Perl, Javascript)
  • Plays better with the application layer e.g. Hibernate
  • Leads to more succinct SQL, for example, to find out how many bananas are ready to eat select sum(is_ripe) from bananas instead of select count(*) from bananas where is_ripe = 'Y' or even (yuk) select sum(case is_ripe when 'Y' then 1 else 0) from bananas

Advantages of 'Y'/'N':

  • Takes up less space than 0/1
  • It's what Oracle suggests, so might be what some people are more used to

Another poster suggested 'Y'/null for performance gains. If you've proven that you need the performance, then fair enough, but otherwise avoid since it makes querying less natural (some_column is null instead of some_column = 0) and in a left join you'll conflate falseness with nonexistent records.

T-SQL - function with default parameters

One way around this problem is to use stored procedures with an output parameter.

exec sp_mysprocname @returnvalue output, @firstparam = 1, @secondparam=2

values you do not pass in default to the defaults set in the stored procedure itself. And you can get the results from your output variable.

How to convert a string to lower case in Bash?

For a standard shell (without bashisms) using only builtins:

uppers=ABCDEFGHIJKLMNOPQRSTUVWXYZ
lowers=abcdefghijklmnopqrstuvwxyz

lc(){ #usage: lc "SOME STRING" -> "some string"
    i=0
    while ([ $i -lt ${#1} ]) do
        CUR=${1:$i:1}
        case $uppers in
            *$CUR*)CUR=${uppers%$CUR*};OUTPUT="${OUTPUT}${lowers:${#CUR}:1}";;
            *)OUTPUT="${OUTPUT}$CUR";;
        esac
        i=$((i+1))
    done
    echo "${OUTPUT}"
}

And for upper case:

uc(){ #usage: uc "some string" -> "SOME STRING"
    i=0
    while ([ $i -lt ${#1} ]) do
        CUR=${1:$i:1}
        case $lowers in
            *$CUR*)CUR=${lowers%$CUR*};OUTPUT="${OUTPUT}${uppers:${#CUR}:1}";;
            *)OUTPUT="${OUTPUT}$CUR";;
        esac
        i=$((i+1))
    done
    echo "${OUTPUT}"
}

Java String to JSON conversion

You are getting NullPointerException as the "output" is null when the while loop ends. You can collect the output in some buffer and then use it, something like this-

    StringBuilder buffer = new StringBuilder();
    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
        buffer.append(output);
    }
    output = buffer.toString(); // now you have the output
    conn.disconnect();

I have never set any passwords to my keystore and alias, so how are they created?

Keystore name: "debug.keystore"

Keystore password: "android"

Key alias: "androiddebugkey"

Key password: "android"

I use this information and successfully generate Signed APK.

Centering a background image, using CSS

Had the same problem. Used display and margin properties and it worked.

.background-image {
  background: url('yourimage.jpg') no-repeat;
  display: block;
  margin-left: auto;
  margin-right: auto;
  height: whateveryouwantpx;
  width: whateveryouwantpx;
}

Why does .NET foreach loop throw NullRefException when collection is null?

I think the explanation of why exception is thrown is very clear with the answers provided here. I just wish to complement with the way I usually work with these collections. Because, some times, I use the collection more then once and have to test if null every time. To avoid that, I do the following:

    var returnArray = DoSomething() ?? Enumerable.Empty<int>();

    foreach (int i in returnArray)
    {
        // do some more stuff
    }

This way we can use the collection as much as we want without fear the exception and we don't polute the code with excessive conditional statements.

Using the null check operator ?. is also a great approach. But, in case of arrays (like the example in the question), it should be transformed into List before:

    int[] returnArray = DoSomething();

    returnArray?.ToList().ForEach((i) =>
    {
        // do some more stuff
    });

How to compile .c file with OpenSSL includes?

If the OpenSSL headers are in the openssl sub-directory of the current directory, use:

gcc -I. -o Opentest Opentest.c -lcrypto

The pre-processor looks to create a name such as "./openssl/ssl.h" from the "." in the -I option and the name specified in angle brackets. If you had specified the names in double quotes (#include "openssl/ssl.h"), you might never have needed to ask the question; the compiler on Unix usually searches for headers enclosed in double quotes in the current directory automatically, but it does not do so for headers enclosed in angle brackets (#include <openssl/ssl.h>). It is implementation defined behaviour.

You don't say where the OpenSSL libraries are - you might need to add an appropriate option and argument to specify that, such as '-L /opt/openssl/lib'.

WSDL/SOAP Test With soapui

I faced the same exception while trying to test my web-services deployed to WSO2 ESB.

WSO2 generated both wsdl and wsdl2. I tried to pass a wsdl2 URL and got the above exception. Quick googling showed me, that one of differences between wsdl1.1 and wsdl2.0 is replacing 'definitions' element with 'description'. Also, I found out, that SoapUI does not support wsdl2.

Therefore, for me the solution was to use wsdl1 url instead of wsdl2.

How to disable a particular checkstyle rule for a particular line of code?

In case if you are using checkstyle from qulice mvn plugin (https://github.com/teamed/qulice) you may use the following suppresion:

// @checkstyle <Rulename> (N lines)
... code with violation(s)

or


/**
 * ...
 * @checkstyle <Rulename> (N lines)
 * ...
 */
 ... code with violation(s)

How to get First and Last record from a sql query?

First record:

SELECT <some columns> FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date ASC
LIMIT 1

Last record:

SELECT <some columns> FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date DESC
LIMIT 1

SimpleXML - I/O warning : failed to load external entity

You can also load the content with cURL, if file_get_contents insn't enabled on your server.

Example:

$ch = curl_init();  

curl_setopt($ch,CURLOPT_URL,"http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=int");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

$output = curl_exec($ch);

curl_close($ch);

$items = simplexml_load_string($output);

how to use "AND", "OR" for RewriteCond on Apache?

Having trouble wrapping my head around this.

Have a rewrite rule with four conditions.
The first three conditions A, B, C are to be AND which is then OR with D

RewriteCond A       true
RewriteCond B       false
RewriteCond C [OR]  true
RewriteCond D       true
RewriteRule ...

But that seems to be an expression of A and B and (C or D) = false (don't rewrite)

How can I get to the desired expression? (A and B and C) or D = true (rewrite)

Preferably without using the additional steps of setting environment variables.

HELP!!!

jQuery animated number counter from zero to value

Here is my solution and it's also working, when element shows into the viewport


You can see the code in action by clicking jfiddle

var counterTeaserL = $('.go-counterTeaser');
var winHeight = $(window).height();
if (counterTeaserL.length) {
    var firEvent = false,
        objectPosTop = $('.go-counterTeaser').offset().top;

        //when element shows at bottom
        var elementViewInBottom = objectPosTop - winHeight;
    $(window).on('scroll', function() {
        var currentPosition = $(document).scrollTop();
        //when element position starting in viewport
      if (currentPosition > elementViewInBottom && firEvent === false) {
        firEvent = true;
        animationCounter();
      }   
    });
}

//counter function will animate by using external js also add seprator "."
 function animationCounter(){
        $('.numberBlock h2').each(function () {
            var comma_separator_number_step =           $.animateNumber.numberStepFactories.separator('.');
            var counterValv = $(this).text();
            $(this).animateNumber(
                {
                  number: counterValv,
                  numberStep: comma_separator_number_step
                }
            );
        });
    }


https://jsfiddle.net/uosahmed/frLoxm34/9/

How to delete a row from GridView?

Delete the row from the table dtPrf_Mstr rather than from the grid view.

How to form tuple column from two columns in Pandas

I'd like to add df.values.tolist(). (as long as you don't mind to get a column of lists rather than tuples)

import pandas as pd
import numpy as np

size = int(1e+07)
df = pd.DataFrame({'a': np.random.rand(size), 'b': np.random.rand(size)}) 

%timeit df.values.tolist()
1.47 s ± 38.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit list(zip(df.a,df.b))
1.92 s ± 131 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

Response you are getting is in object form i.e.

{ 
  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 
}

Replace below line of code :

List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))

with

Post post = gson.fromJson(reader, Post.class);

How do I write output in same place on the console?

#kinda like the one above but better :P

from __future__ import print_function
from time import sleep

for i in range(101):
  str1="Downloading File FooFile.txt [{}%]".format(i)
  back="\b"*len(str1)
  print(str1, end="")
  sleep(0.1)
  print(back, end="")

Write and read a list from file

As long as your file has consistent formatting (i.e. line-breaks), this is easy with just basic file IO and string operations:

with open('my_file.txt', 'rU') as in_file:
    data = in_file.read().split('\n')

That will store your data file as a list of items, one per line. To then put it into a file, you would do the opposite:

with open('new_file.txt', 'w') as out_file:
    out_file.write('\n'.join(data)) # This will create a string with all of the items in data separated by new-line characters

Hopefully that fits what you're looking for.

Convert NaN to 0 in javascript

Write your own method, and use it everywhere you want a number value:

function getNum(val) {
   if (isNaN(val)) {
     return 0;
   }
   return val;
}

How does Tomcat find the HOME PAGE of my Web App?

I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping> 

AngularJS does not send hidden field value

Here I would like to share my working code :

_x000D_
_x000D_
<input type="text" name="someData" ng-model="data" ng-init="data=2" style="display: none;"/>_x000D_
OR_x000D_
<input type="hidden" name="someData" ng-model="data" ng-init="data=2"/>_x000D_
OR_x000D_
<input type="hidden" name="someData" ng-init="data=2"/>
_x000D_
_x000D_
_x000D_

How to echo in PHP, HTML tags

<?php

echo '<div>
 <h3><a href="#">First</a></h3>
 <div>Lorem ipsum dolor sit amet.</div>
</div>
<div>';

?>

Just put it in single quotes.

What is the equivalent of ngShow and ngHide in Angular 2+?

For anybody else stumbling across this issue, this is how I accomplished it.

import {Directive, ElementRef, Input, OnChanges, Renderer2} from "@angular/core";

@Directive({
  selector: '[hide]'
})
export class HideDirective implements OnChanges {
  @Input() hide: boolean;

  constructor(private renderer: Renderer2, private elRef: ElementRef) {}

  ngOnChanges() {
    if (this.hide) {
      this.renderer.setStyle(this.elRef.nativeElement, 'visibility', 'hidden');
    } else {
      this.renderer.setStyle(this.elRef.nativeElement, 'visibility', 'visible');
    }
  }
}

I used 'visibility' because I wanted to preserve the space occupied by the element. If you did not wish to do so, you could just use 'display' and set it to 'none';

You can bind it to your html element, dynamically or not.

<span hide="true"></span>

or

<span [hide]="anyBooleanExpression"></span>

vbscript output to console

There are five ways to output text to the console:

Dim StdOut : Set StdOut = CreateObject("Scripting.FileSystemObject").GetStandardStream(1)

WScript.Echo "Hello"
WScript.StdOut.Write "Hello"
WScript.StdOut.WriteLine "Hello"
Stdout.WriteLine "Hello"
Stdout.Write "Hello"

WScript.Echo will output to console but only if the script is started using cscript.exe. It will output to message boxes if started using wscript.exe.

WScript.StdOut.Write and WScript.StdOut.WriteLine will always output to console.

StdOut.Write and StdOut.WriteLine will also always output to console. It requires extra object creation but it is about 10% faster than WScript.Echo.

iOS download and save image inside app

You can download image without blocking UI with using NSURLSessionDataTask.

+(void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
 {
 NSURLSessionDataTask*  _sessionTask = [[NSURLSession sharedSession] dataTaskWithRequest:[NSURLRequest requestWithURL:url]
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error != nil)
        {
          if ([error code] == NSURLErrorAppTransportSecurityRequiresSecureConnection)
                {
                    completionBlock(NO,nil);
                }
         }
    else
     {
      [[NSOperationQueue mainQueue] addOperationWithBlock: ^{
                        dispatch_async(dispatch_get_main_queue(), ^{
                        UIImage *image = [[UIImage alloc] initWithData:data];
                        completionBlock(YES,image);

                        });

      }];

     }

                                            }];
    [_sessionTask resume];
}

Remove credentials from Git

  1. Go to C:\Users\<current-user>
  2. check for .git-credentials file
  3. Delete content or modify as per your requirement
  4. Restart your terminal

shell-script headers (#!/bin/sh vs #!/bin/csh)

This defines what shell (command interpreter) you are using for interpreting/running your script. Each shell is slightly different in the way it interacts with the user and executes scripts (programs).

When you type in a command at the Unix prompt, you are interacting with the shell.

E.g., #!/bin/csh refers to the C-shell, /bin/tcsh the t-shell, /bin/bash the bash shell, etc.

You can tell which interactive shell you are using the

 echo $SHELL

command, or alternatively

 env | grep -i shell

You can change your command shell with the chsh command.

Each has a slightly different command set and way of assigning variables and its own set of programming constructs. For instance the if-else statement with bash looks different that the one in the C-shell.

This page might be of interest as it "translates" between bash and tcsh commands/syntax.

Using the directive in the shell script allows you to run programs using a different shell. For instance I use the tcsh shell interactively, but often run bash scripts using /bin/bash in the script file.

Aside:

This concept extends to other scripts too. For instance if you program in Python you'd put

 #!/usr/bin/python

at the top of your Python program

How to SUM parts of a column which have same text value in different column in the same row

If your data has the names grouped as shown then you can use this formula in D2 copied down to get a total against the last entry for each name

=IF((A2=A3)*(B2=B3),"",SUM(C$2:C2)-SUM(D$1:D1))

See screenshot

enter image description here

How to pass form input value to php function

you must have read about function call . here i give you example of it.

<?php
 funtion pr($n)
{
echo $n;
 }
?>
<form action="<?php $f=$_POST['input'];pr($f);?>" method="POST">
<input name=input type=text></input>
</form>

Modulo operator with negative values

a % b

in c++ default:

(-7/3) => -2
-2 * 3 => -6
so a%b => -1

(7/-3) => -2
-2 * -3 => 6
so a%b => 1

in python:

-7 % 3 => 2
7 % -3 => -2

in c++ to python:

(b + (a%b)) % b

How to remove new line characters from data rows in mysql?

UPDATE mytable SET title=TRIM(REPLACE(REPLACE(title, "\n", ""), "\t", ""));

Pass a javascript variable value into input type hidden value

if you already have that hidden input :

function product(a, b) {
   return a * b;
}
function setInputValue(input_id, val) {
    document.getElementById(input_id).setAttribute('value', val);
}

if not, you can create one, add it to the body and then set it's value :

function addInput(val) {
    var input = document.createElement('input');
    input.setAttribute('type', 'hidden');
    input.setAttribute('value', val);
    document.body.appendChild(input);
}

And then you can use(depending on the case) :

addInput(product(2, 3)); // if you want to create the input
// or
setInputValue('input_id', product(2, 3)); 

How to add an item to an ArrayList in Kotlin?

For people just migrating from java, In Kotlin List is by default immutable and mutable version of Lists is called MutableList.

Hence if you have something like :

val list: List<String> = ArrayList()

In this case you will not get an add() method as list is immutable. Hence you will have to declare a MutableList as shown below :

val list: MutableList<String> = ArrayList()

Now you will see an add() method and you can add elements to any list.

What is a good way to handle exceptions when trying to read a file in python?

Here is a read/write example. The with statements insure the close() statement will be called by the file object regardless of whether an exception is thrown. http://effbot.org/zone/python-with-statement.htm

import sys

fIn = 'symbolsIn.csv'
fOut = 'symbolsOut.csv'

try:
   with open(fIn, 'r') as f:
      file_content = f.read()
      print "read file " + fIn
   if not file_content:
      print "no data in file " + fIn
      file_content = "name,phone,address\n"
   with open(fOut, 'w') as dest:
      dest.write(file_content)
      print "wrote file " + fOut
except IOError as e:
   print "I/O error({0}): {1}".format(e.errno, e.strerror)
except: #handle other exceptions such as attribute errors
   print "Unexpected error:", sys.exc_info()[0]
print "done"

Print a string as hex bytes?

Print a string as hex bytes?

The accepted answer gives:

s = "Hello world !!"
":".join("{:02x}".format(ord(c)) for c in s)

returns:

'48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21'

The accepted answer works only so long as you use bytes (mostly ascii characters). But if you use unicode, e.g.:

a_string = u"?????? ???!!" # "Prevyet mir", or "Hello World" in Russian.

You need to convert to bytes somehow.

If your terminal doesn't accept these characters, you can decode from UTF-8 or use the names (so you can paste and run the code along with me):

a_string = (
    "\N{CYRILLIC CAPITAL LETTER PE}"
    "\N{CYRILLIC SMALL LETTER ER}"
    "\N{CYRILLIC SMALL LETTER I}"
    "\N{CYRILLIC SMALL LETTER VE}"
    "\N{CYRILLIC SMALL LETTER IE}"
    "\N{CYRILLIC SMALL LETTER TE}"
    "\N{SPACE}"
    "\N{CYRILLIC SMALL LETTER EM}"
    "\N{CYRILLIC SMALL LETTER I}"
    "\N{CYRILLIC SMALL LETTER ER}"
    "\N{EXCLAMATION MARK}"
    "\N{EXCLAMATION MARK}"
)

So we see that:

":".join("{:02x}".format(ord(c)) for c in a_string)

returns

'41f:440:438:432:435:442:20:43c:438:440:21:21'

a poor/unexpected result - these are the code points that combine to make the graphemes we see in Unicode, from the Unicode Consortium - representing languages all over the world. This is not how we actually store this information so it can be interpreted by other sources, though.

To allow another source to use this data, we would usually need to convert to UTF-8 encoding, for example, to save this string in bytes to disk or to publish to html. So we need that encoding to convert the code points to the code units of UTF-8 - in Python 3, ord is not needed because bytes are iterables of integers:

>>> ":".join("{:02x}".format(c) for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

Or perhaps more elegantly, using the new f-strings (only available in Python 3):

>>> ":".join(f'{c:02x}' for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

In Python 2, pass c to ord first, i.e. ord(c) - more examples:

>>> ":".join("{:02x}".format(ord(c)) for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'
>>> ":".join(format(ord(c), '02x') for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

How do I pass a URL with multiple parameters into a URL?

In jQuery, you can use:

let myObject = {first:1, second:12, third:5};
jQuery.param(myObject);

Doc: http://api.jquery.com/jquery.param/ The output: first=1&second=12&third=5 This will format it, whatever your object contain.

GROUP BY without aggregate function

Use sub query e.g:

SELECT field1,field2,(SELECT distinct field3 FROM tbl2 WHERE criteria) AS field3
FROM tbl1 GROUP BY field1,field2

OR

SELECT DISTINCT field1,field2,(SELECT distinct field3 FROM tbl2 WHERE criteria) AS field3
FROM tbl1

Copy table to a different database on a different SQL Server

SQL Server(2012) provides another way to generate script for the SQL Server databases with its objects and data. This script can be used to copy the tables’ schema and data from the source database to the destination one in our case.

  1. Using the SQL Server Management Studio, right-click on the source database from the object explorer, then from Tasks choose Generate Scripts. enter image description here
  2. In the Choose objects window, choose Select Specific Database Objects to specify the tables that you will generate script for, then choose the tables by ticking beside each one of it. Click Next. enter image description here
  3. In the Set Scripting Options window, specify the path where you will save the generated script file, and click Advanced. enter image description here
  4. From the appeared Advanced Scripting Options window, specify Schema and Data as Types of Data to Script. You can decide from here if you want to script the indexes and keys in your tables. Click OK. enter image description here Getting back to the Advanced Scripting Options window, click Next.
  5. Review the Summary window and click Next. enter image description here
  6. You can monitor the progress from the Save or Publish Scripts window. If there is no error click Finish and you will find the script file in the specified path. enter image description here

SQL Scripting method is useful to generate one single script for the tables’ schema and data, including the indexes and keys. But again this method doesn’t generate the tables’ creation script in the correct order if there are relations between the tables.

How do I set the default locale in the JVM?

You can do this:

enter image description here

enter image description here

And to capture locale. You can do this:

private static final String LOCALE = LocaleContextHolder.getLocale().getLanguage()
            + "-" + LocaleContextHolder.getLocale().getCountry();

starting file download with JavaScript

Reading the answers - including the accepted one I'd like to point out the security implications of passing a path directly to readfile via GET.

It may seem obvious to some but some may simply copy/paste this code:

<?php 
   header("Content-Type: application/octet-stream");
   header("Content-Disposition: attachment; filename=".$_GET['path']);
   readfile($_GET['path']);
?>

So what happens if I pass something like '/path/to/fileWithSecrets' to this script? The given script will happily send any file the webserver-user has access to.

Please refer to this discussion for information how to prevent this: How do I make sure a file path is within a given subdirectory?

Conversion from 12 hours time to 24 hours time in java

java.time

In Java 8 and later it could be done in one line using class java.time.LocalTime.

In the formatting pattern, lowercase hh means 12-hour clock while uppercase HH means 24-hour clock.

Code example:

String result =                                       // Text representing the value of our date-time object.
    LocalTime.parse(                                  // Class representing a time-of-day value without a date and without a time zone.
        "03:30 PM" ,                                  // Your `String` input text.
        DateTimeFormatter.ofPattern(                  // Define a formatting pattern to match your input text.
            "hh:mm a" ,
            Locale.US                                 // `Locale` determines the human language and cultural norms used in localization. Needed here to translate the `AM` & `PM` value.
        )                                             // Returns a `DateTimeFormatter` object.
    )                                                 // Return a `LocalTime` object.
    .format( DateTimeFormatter.ofPattern("HH:mm") )   // Generate text in a specific format. Returns a `String` object.
;

See this code run live at IdeOne.com.

15:30

See Oracle Tutorial.

How to get element by classname or id

You don't have to add a . in getElementsByClassName, i.e.

var multibutton = angular.element(element.getElementsByClassName("multi-files"));

However, when using angular.element, you do have to use jquery style selectors:

angular.element('.multi-files');

should do the trick.

Also, from this documentation "If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite.""

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

This UnsupportedOperationException comes when you try to perform some operation on collection where its not allowed and in your case, When you call Arrays.asList it does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayList which is an immutable list. You cannot add to it and you cannot remove from it.

How to build a RESTful API?

As simon marc said, the process is much the same as it is for you or I browsing a website. If you are comfortable with using the Zend framework, there are some easy to follow tutorials to that make life quite easy to set things up. The hardest part of building a restful api is the design of the it, and making it truly restful, think CRUD in database terms.

It could be that you really want an xmlrpc interface or something else similar. What do you want this interface to allow you to do?

--EDIT

Here is where I got started with restful api and Zend Framework. Zend Framework Example

In short don't use Zend rest server, it's obsolete.

Unable to Install Any Package in Visual Studio 2015

Open the packages folder. Check if files with extension .deleteme exists, example Newtonsoft.Json.9.0.1.deleteme. Delete all the packages which have a .deleteme file manually. Delete the .deleteme files. Close and open the Nuget Explorer.

How to access private data members outside the class without making "friend"s?

friend is your friend.

class A{
    friend void foo(A arg);
    int iData;
};

void foo(A arg){
     // can access a.iData here
}

If you're doing this regularly you should probably reconsider your design though.

MySQL Error: #1142 - SELECT command denied to user

This is th privileges issue in your database users. first check and grant permission to user 'marco' in localhost