Programs & Examples On #Communication diagram

Error:Unknown host You may need to adjust the proxy settings in Gradle

Everyone: I Solved the problem like this. In Android Studio go to File menu and select the Invalidate Caches/Restart... I hope it will work for you. Thanks

Powershell v3 Invoke-WebRequest HTTPS error

This work-around worked for me:

Basically, in your PowerShell script:

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    public class TrustAllCertsPolicy : ICertificatePolicy {
        public bool CheckValidationResult(
            ServicePoint srvPoint, X509Certificate certificate,
            WebRequest request, int certificateProblem) {
            return true;
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

$result = Invoke-WebRequest -Uri "https://IpAddress/resource"

jQuery selector for inputs with square brackets in the name attribute

Just separate it with different quotes:

<input name="myName[1][data]" value="myValue">


var value = $('input[name="myName[1][data]"]').val();

How do I run two commands in one line in Windows CMD?

Well, you have two options: Piping, or just &:



tasklist | find "notepad.exe"

Piping (|) is more for taking the output of one command, and putting it into another. And (&) is just saying run this, and that.

How to create a new schema/new user in Oracle Database 11g?

From oracle Sql developer, execute the below in sql worksheet:

create user lctest identified by lctest;
grant dba to lctest;

then right click on "Oracle connection" -> new connection, then make everything lctest from connection name to user name password. Test connection shall pass. Then after connected you will see the schema.

List file using ls command in Linux with full path

How about:

 du -a [-b] [--max-depth=N] 

That should give you a file and directory listing, relative to your current location. You will get sizes as well (add the '-b' parameter if you want the sizes in bytes). The max-depth parameter may be necessary to "encourage" du to dive deeply enough into your file structure -- or to keep it from getting carried away.


Verify host key with pysftp

FWIR, if authentication is only username & pw, add remote server ip address to known_hosts like ssh-keyscan -H >> ~/.ssh/known_hosts for ref

Webdriver findElements By xpath

Instead of




C++ error: undefined reference to 'clock_gettime' and 'clock_settime'

I encountered the same error. My linker command did have the rt library included -lrt which is correct and it was working for a while. After re-installing Kubuntu it stopped working.

A separate forum thread suggested the -lrt needed to come after the project object files. Moving the -lrt to the end of the command fixed this problem for me although I don't know the details of why.

How to automatically update an application without ClickOnce?

This is the code to update the file but not to install This program is made through dos for copying files to the latest date and run your program automatically. may help you

open notepad and save file below with ext .bat

xcopy \\IP address\folder_share_name\*.* /s /y /d /q  
start "label" /b "youraplicationname.exe"

What is the difference between Cloud Computing and Grid Computing?

A Grid is a hardware and software infrastructure that clusters and integrates high-end computers, networks, databases, and scientific instruments from multiple sources to form a virtual supercomputer on which users can work collaboratively within virtual organisations

Grid is Mostly free used by academic research etc.

Clouds are a large pool of easily usable and accessible virtualized resources (such as hardware, development platforms and/or services). These resources can be dynamically reconfigured to adjust to a variable load (scale), allowing also for an optimum resource utilization. This pool of resources is typically exploited by a pay peruse model in which guarantees are offered by the Infrastructure Provider by customized service level agreements.

Cloud is not free. It is a service, provided by different service providers and they charge according to your work done.

Android view layout_width - how to change programmatically?

Or simply:

view.getLayoutParams().width = 400;

How to get the version of ionic framework?

ionic info

This will give you the ionic version,node, npm and os.

If you need only ionic version use ionic -v.

If your project's development ionic version and your global versions are different then check them by using the below commands.

To check the globally installed ionic version ionic -g and to check the project's ionic version use ionic -g.

To check the project's ionic version use ionic -v in your project path or else ionic info to get the details of ionic and its dependencies.

Node.js: Python not found exception due to node-sass and node-gyp

I found the same issue with Node 12.19.0 and yarn 1.22.5 on Windows 10. I fixed the problem by installing latest stable python 64-bit with adding the path to Environment Variables during python installation. After python installation, I restarted my machine for env vars.

gpg: no valid OpenPGP data found

This problem might occur if you are behind corporate proxy and corporation uses its own certificate. Just add "--no-check-certificate" in the command. e.g. wget --no-check-certificate -qO - | sudo apt-key add -

It works. If you want to see what is going on, you can use verbose command instead of quiet before adding "--no-check-certificate" option. e.g. wget -vO - | sudo apt-key add - This will tell you to use "--no-check-certificate" if you are behind proxy.

Getting a link to go to a specific section on another page

I believe the example you've posted is using HTML5, which allows you to jump to any DOM element with the matching ID attribute. To support older browsers, you'll need to change:

<div id="timeline" name="timeline" ...>

To the old format:

<a name="timeline" />

You'll then be able to navigate to /academics/page.html#timeline and jump right to that section.

Also, check out this similar question.

How to view changes made to files on a certain revision in Subversion

With this command you will see all changes in the repository path/to/repo that were committed in revision <revision>:

svn diff -c <revision> path/to/repo

The -c indicates that you would like to look at a changeset, but there are many other ways you can look at diffs and changesets. For example, if you would like to know which files were changed (but not how), you can issue

svn log -v -r <revision>

Or, if you would like to show at the changes between two revisions (and not just for one commit):

svn diff -r <revA>:<revB> path/to/repo

Pushing value of Var into an Array

Off the top of my head I think it should be done like this:

var veggies = "carrot";
var fruitvegbasket = [];

How to check if one of the following items is in a list?

Think about what the code actually says!

>>> (1 or 2)
>>> (2 or 1)

That should probably explain it. :) Python apparently implements "lazy or", which should come as no surprise. It performs it something like this:

def or(x, y):
    if x: return x
    if y: return y
    return False

In the first example, x == 1 and y == 2. In the second example, it's vice versa. That's why it returns different values depending on the order of them.

If statement in select (ORACLE)

So simple you can use case statement here.

         CASE WHEN  ISSUE_DIVISION is null then "Null Value found" //give your option
         Else 1 End
ELSE 0 END As Issue_Division_Result

How can I get argv[] as int?

You can use strtol for that:

long x;
if (argc < 2)
    /* handle error */

x = strtol(argv[1], NULL, 10);

Alternatively, if you're using C99 or better you could explore strtoimax.

password-check directive in angularjs

Creating a separate directive for this is not needed. There is already a build in Angular UI password validation tool. With this you could do:

<input name="password" required ng-model="password">
<input name="confirm_password"
       ui-validate=" '$value==password' "
       ui-validate-watch=" 'password' ">

 Passwords match? {{!!form.confirm_password.$error.validator}}

Open Sublime Text from Terminal in macOS


  • You have already installed Homebrew.
  • /usr/local/bin is in your $PATH.
  • You are on Yosemite or El Capitain.

MacOS Sierra 10.12.5 works as well confirmed by David Rawson and MacOS Sierra 10.12.6 confirmed by Alexander K.

Run the following script in Terminal to create the specific symlink.

ln -s "/Applications/Sublime" /usr/local/bin/subl


subl .

Hit Return and it should instantly open Sublime Text.

How to get absolute value from double - c-language

  //use fabs()
  double sum_primary_diagonal=0;
  double sum_secondary_diagonal=0;
  double difference = fabs(sum_primary_diagonal - sum_secondary_diagonal);

How to launch multiple Internet Explorer windows/tabs from batch file?

Of course it is an old post but just for people how will find it through search engine.

Another solution is to run it like this for IE9 and later

iexplore.exe" -noframemerging
iexplore.exe" -noframemerging

-noframemerging means run IE independently. For example it you want to run 2 browser and login as different username it will not work if you just run 2 IE. but with -noframemerging it will work. -noframemerging works for IE9 and later, for early versions like IE8 it is -nomerge

usually I create 1 but file like this run_ie.bat

"c:\Program Files (x86)\Internet Explorer\iexplore.exe" -noframemerging %1

and I create another bat file like this run_2_ie.bat

start run_ie.bat
start run_ie.bat

How to split() a delimited string to a List<String>

Try this line:

List<string> stringList = line.Split(',').ToList(); 

Why both no-cache and no-store should be used in HTTP response?

Note that Internet Explorer from version 5 up to 8 will throw an error when trying to download a file served via https and the server sending Cache-Control: no-cache or Pragma: no-cache headers.


The use of Cache-Control: no-store and Pragma: private seems to be the closest thing which still works.

Execution sequence of Group By, Having and Where clause in SQL Server?

In Oracle 12c, you can run code both in either sequence below:

Group By


Group by

String representation of an Enum

If you think about the problem we're trying to solve, it's not an enum we need at all. We need an object that allows a certain number of values to be associated with eachother; in other words, to define a class.

Jakub Šturc's type-safe enum pattern is the best option I see here.

Look at it:

  • It has a private constructor so only the class itself can define the allowed values.
  • It is a sealed class so values can't be modifed through inheritence.
  • It is type-safe, allowing your methods to require only that type.
  • There is no reflection performance hit incurred by accessing the values.
  • And lastly, it can be modified to associate more than two fields together, for example a Name, Description, and a numeric Value.

jQuery Multiple ID selectors

If you give each of these instances a class you can use


Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

Just to add to yamen's answer, which is perfect for images but not so much for text.

If you are trying to use this to scale text, like say a Word document (which is in this case in bytes from Word Interop), you will need to make a few modifications or you will get giant bars on the side.

May not be perfect but works for me!

using (MemoryStream ms = new MemoryStream(wordBytes))
    float width = 3840;
    float height = 2160;
    var brush = new SolidBrush(Color.White);

    var rawImage = Image.FromStream(ms);
    float scale = Math.Min(width / rawImage.Width, height / rawImage.Height);
    var scaleWidth  = (int)(rawImage.Width  * scale);
    var scaleHeight = (int)(rawImage.Height * scale);
    var scaledBitmap = new Bitmap(scaleWidth, scaleHeight);

    Graphics graph = Graphics.FromImage(scaledBitmap);
    graph.InterpolationMode = InterpolationMode.High;
    graph.CompositingQuality = CompositingQuality.HighQuality;
    graph.SmoothingMode = SmoothingMode.AntiAlias;
    graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
    graph.DrawImage(rawImage, new Rectangle(0, 0 , scaleWidth, scaleHeight));

    scaledBitmap.Save(fileName, ImageFormat.Png);
    return scaledBitmap;

How to replace (or strip) an extension from a filename in Python?

Handling multiple extensions

In the case where you have multiple extensions this one-liner using pathlib and str.replace works a treat:

Remove/strip extensions

>>> from pathlib import Path
>>> p = Path("/path/to/myfile.tar.gz")
>>> extensions = "".join(p.suffixes)

# any python version
>>> str(p).replace(extensions, "")

# python>=3.9
>>> str(p).removesuffix(extensions)

Replace extensions

>>> p = Path("/path/to/myfile.tar.gz")
>>> extensions = "".join(p.suffixes)
>>> new_ext = ".jpg"
>>> str(p).replace(extensions, new_ext)

If you also want a pathlib object output then you can obviously wrap the line in Path()

>>> Path(str(p).replace("".join(p.suffixes), ""))

Wrapping it all up in a function

from pathlib import Path
from typing import Union

PathLike = Union[str, Path]

def replace_ext(path: PathLike, new_ext: str = "") -> Path:
    extensions = "".join(Path(path).suffixes)
    return Path(str(p).replace(extensions, new_ext))

p = Path("/path/to/myfile.tar.gz")
new_ext = ".jpg"

assert replace_ext(p, new_ext) == Path('/path/to/myfile.jpg')
assert replace_ext(str(p), new_ext) == Path('/path/to/myfile.jpg')
assert replace_ext(p) == Path('/path/to/myfile')

Byte Array to Image object

From Database.
Blob blob = resultSet.getBlob("pictureBlob");               
byte [] data = blob.getBytes( 1, ( int ) blob.length() );
BufferedImage img = null;
try {
img = ByteArrayInputStream(data));
} catch (IOException e) {
drawPicture(img);  //  void drawPicture(Image img);

How to multiply values using SQL

Why are you grouping by? Do you mean order by?

SELECT player_name, player_salary, player_salary * 1.1 AS NewSalary
FROM players
ORDER BY player_salary, player_name;

Execute command on all files in a directory

How about this:

find /some/directory -maxdepth 1 -type f -exec cmd option {} \; > results.out
  • -maxdepth 1 argument prevents find from recursively descending into any subdirectories. (If you want such nested directories to get processed, you can omit this.)
  • -type -f specifies that only plain files will be processed.
  • -exec cmd option {} tells it to run cmd with the specified option for each file found, with the filename substituted for {}
  • \; denotes the end of the command.
  • Finally, the output from all the individual cmd executions is redirected to results.out

However, if you care about the order in which the files are processed, you might be better off writing a loop. I think find processes the files in inode order (though I could be wrong about that), which may not be what you want.

How to do logging in React Native?

console.log() is the easy way to debug your code but it need to be use with arrow function or bind() while displaying any state. You may find the link useful.

How to perform element-wise multiplication of two lists?

gahooa's answer is correct for the question as phrased in the heading, but if the lists are already numpy format or larger than ten it will be MUCH faster (3 orders of magnitude) as well as more readable, to do simple numpy multiplication as suggested by NPE. I get these timings:

0.0049ms -> N = 4, a = [i for i in range(N)], c = [a*b for a,b in zip(a, b)]
0.0075ms -> N = 4, a = [i for i in range(N)], c = a * b
0.0167ms -> N = 4, a = np.arange(N), c = [a*b for a,b in zip(a, b)]
0.0013ms -> N = 4, a = np.arange(N), c = a * b
0.0171ms -> N = 40, a = [i for i in range(N)], c = [a*b for a,b in zip(a, b)]
0.0095ms -> N = 40, a = [i for i in range(N)], c = a * b
0.1077ms -> N = 40, a = np.arange(N), c = [a*b for a,b in zip(a, b)]
0.0013ms -> N = 40, a = np.arange(N), c = a * b
0.1485ms -> N = 400, a = [i for i in range(N)], c = [a*b for a,b in zip(a, b)]
0.0397ms -> N = 400, a = [i for i in range(N)], c = a * b
1.0348ms -> N = 400, a = np.arange(N), c = [a*b for a,b in zip(a, b)]
0.0020ms -> N = 400, a = np.arange(N), c = a * b

i.e. from the following test program.

import timeit

init = ['''
import numpy as np
N = {}
a = {}
b = np.linspace(0.0, 0.5, len(a))
'''.format(i, j) for i in [4, 40, 400] 
                  for j in ['[i for i in range(N)]', 'np.arange(N)']]

func = ['''c = [a*b for a,b in zip(a, b)]''',
'''c = a * b''']

for i in init:
  for f in func:
    lines = i.split('\n')
    print('{:6.4f}ms -> {}, {}, {}'.format(
           timeit.timeit(f, setup=i, number=1000), lines[2], lines[3], f))

Regex: match word that ends with "Id"

I would use
The \b matches the beginning and end of a word i.e. space, tab or newline, or the beginning or end of a string.

The [A-Za-z] will match any letter, and the * means that 0+ get matched. Finally there is the Id.

Note that this will match words that have capital letters in the middle such as 'teStId'.

I use for regex reference

Passing arguments to require (when loading module)

Yes. In your login module, just export a single function that takes the db as its argument. For example:

module.exports = function(db) {

Assigning variables with dynamic names in Java

Dynamic Variable Names in Java
There is no such thing.

In your case you can use array:

int[] n = new int[3];
for() {
 n[i] = 5;

For more general (name, value) pairs, use Map<>

UILabel is not auto-shrinking text to fit label size

In Swift 4 (Programmatically):

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200.0, height: 200.0))
label.adjustsFontSizeToFitWidth = true
label.numberOfLines = 0

label.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."


How does Zalgo text work?

Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.

enter image description here


y + ̆ = y̆ which actually is

y + &#x0306; = y&#x0306;

Since you can stack them one atop the other you can produce the following:


which actually is:


The same goes for putting stuff underneath:


that in fact is:


In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.

More about it here

To produce a list of combining diacritical marks you can use the following script (since links keep on dying)

for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +"  "+"&#"+i+";");}

Also check em out

Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾

How to use jQuery to call an ASP.NET web service?

I have a decent example in jQuery AJAX and ASMX on using the jQuery AJAX call with asmx web services...

There is a line of code to uncommment in order to have it return JSON.

How to get the absolute path to the public_html folder?

You just need to create an offset bypass to how far you want the backwards reading to go. So, we use getcwd() to get the path and explode (split into array) to fetch the data between $root and the ending of the path.

function getRoot($root = "public_html") {
    return explode($root, getcwd())[0].$root."/";

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.


Make sure the files exist over there , else point the files to the correct path, which should be in your case


$(document).ready equivalent without jQuery

We found a quick-and-dirty cross browser implementation of ours that may do the trick for most simple cases with a minimal implementation:

window.onReady = function onReady(fn){
    document.body ? fn() : setTimeout(function(){ onReady(fn);},50);

char initial value in Java

Typically for local variables I initialize them as late as I can. It's rare that I need a "dummy" value. However, if you do, you can use any value you like - it won't make any difference, if you're sure you're going to assign a value before reading it.

If you want the char equivalent of 0, it's just Unicode 0, which can be written as

char c = '\0';

That's also the default value for an instance (or static) variable of type char.

Inserting Image Into BLOB Oracle 10g

You should do something like this:

1) create directory object what would point to server-side accessible folder

CREATE DIRECTORY image_files AS '/data/images'

2) Place your file into OS folder directory object points to

3) Give required access privileges to Oracle schema what will load data from file into table:

GRANT READ ON DIRECTORY image_files TO scott

4) Use BFILENAME, EMPTY_BLOB functions and DBMS_LOB package (example NOT tested - be care) like in below:

  l_blob BLOB; 
  v_src_loc  BFILE := BFILENAME('IMAGE_FILES', 'myimage.png');
  v_amount   INTEGER;
  INSERT INTO esignatures  
  VALUES (100, 'BOB', empty_blob()) RETURN iblob INTO l_blob; 
  v_amount := DBMS_LOB.GETLENGTH(v_src_loc);
  DBMS_LOB.LOADFROMFILE(l_blob, v_src_loc, v_amount);

After this you get the content of your file in BLOB column and can get it back using Java for example.

edit: One letter left missing: it should be LOADFROMFILE.

JavaScript: location.href to open in new window/tab?
  '_blank' // <- This is what makes it open in a new window.

How to specify multiple return types using type-hints

Python 3.10 (use |): Example for a function which takes a single argument that is either an int or str and returns either an int or str:

def func(arg: int | str) -> int | str:
              ^^^^^^^^^     ^^^^^^^^^ 
             type of arg   return type

Python 3.5 - 3.9 (use typing.Union):

from typing import Union
def func(arg: Union[int, str]) -> Union[int, str]:
              ^^^^^^^^^^^^^^^     ^^^^^^^^^^^^^^^ 
                type of arg         return type

For the special case of X | None you can use Optional[X].

Transactions in .net

It also depends on what you need. For basic SQL transactions you could try doing TSQL transactions by using BEGIN TRANS and COMMIT TRANS in your code. That is the easiest way but it does have complexity and you have to be careful to commit properly (and rollback).

I would use something like

SQLTransaction trans = null;
using(trans = new SqlTransaction)
    Do SQL stuff here passing my trans into my various SQL executers
    trans.Commit  // May not be quite right

Any failure will pop you right out of the using and the transaction will always commit or rollback (depending on what you tell it to do). The biggest problem we faced was making sure it always committed. The using ensures the scope of the transaction is limited.

converting Java bitmap to byte array

Use below functions to encode bitmap into byte[] and vice versa

public static String encodeTobase64(Bitmap image) {
    Bitmap immagex = image;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    immagex.compress(Bitmap.CompressFormat.PNG, 90, baos);
    byte[] b = baos.toByteArray();
    String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
    return imageEncoded;

public static Bitmap decodeBase64(String input) {
    byte[] decodedByte = Base64.decode(input, 0);
    return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);

HTML 5 input type="number" element for floating point numbers on Chrome

Note: If you're using AngularJS, then in addition to changing the step value, you may have to set ng-model-options="{updateOn: 'blur change'}" on the html input.

The reason for this is in order to have the validators run less often, as they are preventing the user from entering a decimal point. This way, the user can type in a decimal point and the validators go into effect after the user blurs.

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:


    echo "<p>Logged in as ".$user."</p>";
    echo "Please log in.";

How the same problem can be solved with an API centric approach by outputting JSON like this:


  user: {
      username: 'Joe', 
      securityToken: 'secret'

and in Angular you could do a get, and handle the response client side.

$"", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

Rename multiple files in cmd

This works for your specific case:

ren file?.txt "file? 1.1.txt" 

Find a row in dataGridView based on column and value

This will give you the gridview row index for the value:

String searchValue = "somestring";
int rowIndex = -1;
foreach(DataGridViewRow row in DataGridView1.Rows)
        rowIndex = row.Index;

Or a LINQ query

int rowIndex = -1;

        DataGridViewRow row = dgv.Rows
            .Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue))

        rowIndex = row.Index;

then you can do:

dataGridView1.Rows[rowIndex].Selected = true;

Can I use Class.newInstance() with constructor arguments?

You can use the getDeclaredConstructor method of Class. It expects an array of classes. Here is a tested and working example:

public static JFrame createJFrame(Class c, String name, Component parentComponent)
        JFrame frame = (JFrame)c.getDeclaredConstructor(new Class[] {String.class}).newInstance("name");
        if (parentComponent != null)
    catch (InstantiationException instantiationException)
        ExceptionHandler.handleException(instantiationException, parentComponent, Language.messages.get(Language.InstantiationExceptionKey), c.getName());
    catch(NoSuchMethodException noSuchMethodException)
        //ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.NoSuchMethodExceptionKey, "NamedConstructor");
        ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.messages.get(Language.NoSuchMethodExceptionKey), "(Constructor or a JFrame method)");
    catch (IllegalAccessException illegalAccessException)
        ExceptionHandler.handleException(illegalAccessException, parentComponent, Language.messages.get(Language.IllegalAccessExceptionKey));
    catch (InvocationTargetException invocationTargetException)
        ExceptionHandler.handleException(invocationTargetException, parentComponent, Language.messages.get(Language.InvocationTargetExceptionKey));
        return null;

How to get number of rows using SqlDataReader in C#

to complete of Pit answer and for better perfromance : get all in one query and use NextResult method.

using (var sqlCon = new SqlConnection("Server=;Database=MyDb;User Id=Me;Password=glop;"))
    var com = sqlCon.CreateCommand();
    com.CommandText = "select * from BigTable;select @@ROWCOUNT;";
    using (var reader = com.ExecuteReader())
            //iterate code
        int totalRow = 0 ;
        reader.NextResult(); // 
            totalRow = (int)reader[0];

New og:image size for Facebook share?

Tried to get the 1200x630 image working. Facebook kept complaining that it couldn't read the image, or that it was too small (it was a jpeg image ~150Kb).

Switched to a 200x200 size image, worked perfectly.

Round up value to nearest whole number in SQL UPDATE

For MS SQL CEILING(your number) will round it up. FLOOR(your number) will round it down

Split a large dataframe into a list of data frames based on common value in column

From version 0.8.0, dplyr offers a handy function called group_split():

# On sample data from @Aus_10

df %>%

# A tibble: 25 x 3
   ran_data1 ran_data2 g    
       <dbl>     <dbl> <fct>
 1     2.04      0.627 A    
 2     0.530    -0.703 A    
 3    -0.475     0.541 A    
 4     1.20     -0.565 A    
 5    -0.380    -0.126 A    
 6     1.25     -1.69  A    
 7    -0.153    -1.02  A    
 8     1.52     -0.520 A    
 9     0.905    -0.976 A    
10     0.517    -0.535 A    
# … with 15 more rows

# A tibble: 25 x 3
   ran_data1 ran_data2 g    
       <dbl>     <dbl> <fct>
 1     1.61      0.858 B    
 2     1.05     -1.25  B    
 3    -0.440    -0.506 B    
 4    -1.17      1.81  B    
 5     1.47     -1.60  B    
 6    -0.682    -0.726 B    
 7    -2.21      0.282 B    
 8    -0.499     0.591 B    
 9     0.711    -1.21  B    
10     0.705     0.960 B    
# … with 15 more rows

To not include the grouping column:

df %>%
 group_split(g, keep = FALSE)

'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository

After struggling for a couple of hours, I found that git config file was not updated when I added the entry sslVerify = false in my Eclipse.

I solved my problem by navigating to my .git directory and updating the config file to :

    sslVerify = false

Why is there no SortedList in Java?

List iterators guarantee first and foremost that you get the list's elements in the internal order of the list (aka. insertion order). More specifically it is in the order you've inserted the elements or on how you've manipulated the list. Sorting can be seen as a manipulation of the data structure, and there are several ways to sort the list.

I'll order the ways in the order of usefulness as I personally see it:

1. Consider using Set or Bag collections instead

NOTE: I put this option at the top because this is what you normally want to do anyway.

A sorted set automatically sorts the collection at insertion, meaning that it does the sorting while you add elements into the collection. It also means you don't need to manually sort it.

Furthermore if you are sure that you don't need to worry about (or have) duplicate elements then you can use the TreeSet<T> instead. It implements SortedSet and NavigableSet interfaces and works as you'd probably expect from a list:

TreeSet<String> set = new TreeSet<String>();
// automatically sorts natural order when adding

for (String s : set) {
// Prints out "cat" and "lol"

If you don't want the natural ordering you can use the constructor parameter that takes a Comparator<T>.

Alternatively, you can use Multisets (also known as Bags), that is a Set that allows duplicate elements, instead and there are third-party implementations of them. Most notably from the Guava libraries there is a TreeMultiset, that works a lot like the TreeSet.

2. Sort your list with Collections.sort()

As mentioned above, sorting of Lists is a manipulation of the data structure. So for situations where you need "one source of truth" that will be sorted in a variety of ways then sorting it manually is the way to go.

You can sort your list with the java.util.Collections.sort() method. Here is a code sample on how:

List<String> strings = new ArrayList<String>()

for (String s : strings) {
// Prints out "cat" and "lol"

Using comparators

One clear benefit is that you may use Comparator in the sort method. Java also provides some implementations for the Comparator such as the Collator which is useful for locale sensitive sorting strings. Here is one example:

Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY); // ignores casing

Collections.sort(strings, usCollator);

Sorting in concurrent environments

Do note though that using the sort method is not friendly in concurrent environments, since the collection instance will be manipulated, and you should consider using immutable collections instead. This is something Guava provides in the Ordering class and is a simple one-liner:

List<string> sorted = Ordering.natural().sortedCopy(strings);

3. Wrap your list with java.util.PriorityQueue

Though there is no sorted list in Java there is however a sorted queue which would probably work just as well for you. It is the java.util.PriorityQueue class.

Nico Haase linked in the comments to a related question that also answers this.

In a sorted collection you most likely don't want to manipulate the internal data structure which is why PriorityQueue doesn't implement the List interface (because that would give you direct access to its elements).

Caveat on the PriorityQueue iterator

The PriorityQueue class implements the Iterable<E> and Collection<E> interfaces so it can be iterated as usual. However, the iterator is not guaranteed to return elements in the sorted order. Instead (as Alderath points out in the comments) you need to poll() the queue until empty.

Note that you can convert a list to a priority queue via the constructor that takes any collection:

List<String> strings = new ArrayList<String>()

PriorityQueue<String> sortedStrings = new PriorityQueue(strings);
while(!sortedStrings.isEmpty()) {
// Prints out "cat" and "lol"

4. Write your own SortedList class

NOTE: You shouldn't have to do this.

You can write your own List class that sorts each time you add a new element. This can get rather computation heavy depending on your implementation and is pointless, unless you want to do it as an exercise, because of two main reasons:

  1. It breaks the contract that List<E> interface has because the add methods should ensure that the element will reside in the index that the user specifies.
  2. Why reinvent the wheel? You should be using the TreeSet or Multisets instead as pointed out in the first point above.

However, if you want to do it as an exercise here is a code sample to get you started, it uses the AbstractList abstract class:

public class SortedList<E> extends AbstractList<E> {

    private ArrayList<E> internalList = new ArrayList<E>();

    // Note that add(E e) in AbstractList is calling this one
    public void add(int position, E e) {
        Collections.sort(internalList, null);

    public E get(int i) {
        return internalList.get(i);

    public int size() {
        return internalList.size();


Note that if you haven't overridden the methods you need, then the default implementations from AbstractList will throw UnsupportedOperationExceptions.

Some projects cannot be imported because they already exist in the workspace error in Eclipse

New to Eclipse and Android development and this hung me up for quite a while. Here's a few things I was doing wrong that may help someone in the future:

  1. I was downloading code examples and assuming project name would be the same as the folder name and was looking for that folder name in the project explorer, not finding it, re-importing it, then getting the error message it already existed in the workspace. Yeah. Not proud of that.
  2. Didn't click on 'Copy projects into Workspace' and then searched in vain through the workspace when it didn't appear in the project explorer BECAUSE
  3. The 'Add project to working sets' option in the Import Projects tab isn't working as far as I can tell, so was not appearing in the project explorer for the active working set (refresh made no difference). Adding project to the working set had to be done after successfully importing it.

Redirect HTTP to HTTPS on default virtual host without ServerName

I have use mkcert to create infinites * subdomains & localhost with valid HTTPS/SSL certs (Windows 10 XAMPP & Linux Debian 10 Apache2)

I create the certs on Windows with mkcert v1.4.0 (execute CMD as Administrator):

mkcert -install
mkcert localhost "*"

This create in Windows 10 this files (I will install it first in Windows 10 XAMPP)


Overwrite the XAMPP default certs:

copy "localhost+1.pem" C:\xampp\apache\conf\ssl.crt\server.crt
copy "localhost+1-key.pem"  C:\xampp\apache\conf\ssl.key\server.key

Now, in Apache2 for Debian 10, activate SSL & vhost_alias

a2enmod vhosts_alias
a2enmod ssl
a2ensite default-ssl
systemctl restart apache2

For vhost_alias add this Apache2 config:

nano /etc/apache2/sites-available/999-vhosts_alias.conf

With this content:

<VirtualHost *:80>
   UseCanonicalName Off
   ServerAlias *
   VirtualDocumentRoot "/var/www/html/%0/"

Add the site:

a2ensite 999-vhosts_alias

Copy the certs to /root/mkcert by SSH and let overwrite the Debian ones:

systemctl stop apache2

mv /etc/ssl/certs/ssl-cert-snakeoil.pem /etc/ssl/certs/ssl-cert-snakeoil.pem.bak
mv /etc/ssl/private/ssl-cert-snakeoil.key /etc/ssl/private/ssl-cert-snakeoil.key.bak

cp "localhost+1.pem" /etc/ssl/certs/ssl-cert-snakeoil.pem
cp "localhost+1-key.pem" /etc/ssl/private/ssl-cert-snakeoil.key

chown root:ssl-cert /etc/ssl/private/ssl-cert-snakeoil.key
chmod 640 /etc/ssl/private/ssl-cert-snakeoil.key

systemctl start apache2

Edit the SSL config

nano /etc/apache2/sites-enabled/default-ssl.conf

At the start edit the file with this content:

<IfModule mod_ssl.c>
    <VirtualHost *:443>

            UseCanonicalName Off
            ServerAlias *
            ServerAdmin webmaster@localhost

            # DocumentRoot /var/www/html/
            VirtualDocumentRoot /var/www/html/%0/


Last restart:

systemctl restart apache2

NOTE: don´t forget to create the folders for your subdomains in /var/www/html/


Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

I'd the same problem, I checked rows of my tables and found there was some incompatibility with the value of fields that I wanted to define a foreign key. I corrected those value, tried again and the problem was solved.

How to overwrite the output directory in spark

The documentation for the parameter spark.files.overwrite says this: "Whether to overwrite files added through SparkContext.addFile() when the target file exists and its contents do not match those of the source." So it has no effect on saveAsTextFiles method.

You could do this before saving the file:

val hadoopConf = new org.apache.hadoop.conf.Configuration()
val hdfs = org.apache.hadoop.fs.FileSystem.get(new"hdfs://localhost:9000"), hadoopConf)
try { hdfs.delete(new org.apache.hadoop.fs.Path(filepath), true) } catch { case _ : Throwable => { } }

Aas explained here:

Pycharm does not show plot

In non-interactive env, we have to use

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

I can fix this by adding below code in my JSP file. Now both model and UI values are same.

<div ng-show="false">
    {{dt = (dt | date:'dd-MMMM-yyyy') }}

Android Use Done button on Keyboard to click button

And this is a Kotlin version:

editText.setOnEditorActionListener { v, actionId, event ->
  if(actionId == EditorInfo.IME_ACTION_DONE){
      //Put your action there
  } else {

If statement with String comparison fails

If you code in C++ as well as Java, it is better to remember that in C++, the string class has the == operator overloaded. But not so in Java. you need to use equals() or equalsIgnoreCase() for that.

Search and replace in bash using regular expressions

Use [[:digit:]] (note the double brackets) as the pattern:

$ hello=ho02123ware38384you443d34o3434ingtod38384day
$ echo ${hello//[[:digit:]]/}

Just wanted to summarize the answers (especially @nickl-'s

How do you sort a dictionary by value?

You'd never be able to sort a dictionary anyway. They are not actually ordered. The guarantees for a dictionary are that the key and value collections are iterable, and values can be retrieved by index or key, but there is no guarantee of any particular order. Hence you would need to get the name value pair into a list.

Convert Json string to Json object in Swift 4

The problem is that you thought your jsonString is a dictionary. It's not.

It's an array of dictionaries. In raw json strings, arrays begin with [ and dictionaries begin with {.

I used your json string with below code :

let string = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]"
let data = .utf8)!
do {
    if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
       print(jsonArray) // use the json here     
    } else {
        print("bad json")
} catch let error as NSError {

and I am getting the output :

[["form_desc": <null>, "form_name": Activity 4 with Images, "canonical_name": df_SAWERQ, "form_id": 3465]]

PostgreSQL database service

Use Services

  1. Windows -> Services
  2. check your PostgresSQL is started or in running state. ( If it's not then start your services for PostgresSQL).
  3. Close services and check again with your PostgresSQL.

This will start PostgresSQL servers as normal.

Unix command-line JSON parser?

Checkout TickTick.

It's a true Bash JSON parser.

. /path/to/

# File
DATA=`cat data.json`
# cURL

tickParse "$DATA"

echo ``pathname``
echo ``headers["user-agent"]``

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video

Why use Redux over Facebook Flux?

You might be best starting with reading this post by Dan Abramov where he discusses various implementations of Flux and their trade-offs at the time he was writing redux: The Evolution of Flux Frameworks

Secondly that motivations page you link to does not really discuss the motivations of Redux so much as the motivations behind Flux (and React). The Three Principles is more Redux specific though still does not deal with the implementation differences from the standard Flux architecture.

Basically, Flux has multiple stores that compute state change in response to UI/API interactions with components and broadcast these changes as events that components can subscribe to. In Redux, there is only one store that every component subscribes to. IMO it feels at least like Redux further simplifies and unifies the flow of data by unifying (or reducing, as Redux would say) the flow of data back to the components - whereas Flux concentrates on unifying the other side of the data flow - view to model.

JList add/remove Item

The problem is


you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.


private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       

    DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
    DefaultListModel lm1  = (DefaultListModel) listaRosa.getModel();
    if(lm2 == null)
        lm2 = new DefaultListModel();

How to create a Restful web service with input parameters?

You can try this... put parameters as :
http://localhost:8080/WebApplication11/webresources/generic/getText?arg1=hello in your browser...

package newpackage;



public class GenericResource {

    private UriInfo context;

     * Creates a new instance of GenericResource
    public GenericResource() {

     * Retrieves representation of an instance of newpackage.GenericResource

     * @return an instance of java.lang.String
    public String getText(@QueryParam("arg1")
            @DefaultValue("") String arg1) {

       return  arg1 ;  }

    public void putText(String content) {


'if' in prolog?

The best thing to do is to use the so-called cuts, which has the symbol !.

if_then_else(Condition, Action1, Action2) :- Condition, !, Action1.  
if_then_else(Condition, Action1, Action2) :- Action2.

The above is the basic structure of a condition function.

To exemplify, here's the max function:


I suggest reading more documentation on cuts, but in general they are like breakpoints. Ex.: In case the first max function returns a true value, the second function is not verified.

PS: I'm fairly new to Prolog, but this is what I've found out.

SqlException: DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null

To get the definition of the SQL codes, the easiest way is to use db2 cli!

at the unix or dos command prompt, just type

db2 "? SQL302"

this will give you the required explanation of the particular SQL code that you normally see in the java exception or your db2 sql output :)

hope this helped.

Number of days between past date and current date in Google spreadsheet

If you are using the two formulas at the same time, it will not work... Here is a simple spreadsheet with it working: If you are still getting problems I would need to know what type of erroneous result you are getting.

Today() returns a numeric integer value: Returns the current computer system date. The value is updated when your document recalculates. TODAY is a function without arguments.

What does /p mean in set /p?

For future reference, you can get help for any command by using the /? switch, which should explain what switches do what.

According to the set /? screen, the format for set /p is SET /P variable=[promptString] which would indicate that the p in /p is "prompt." It just prints in your example because <nul passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.

/L in for /L generates a List of numbers.

From ping /?:

Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
            [-r count] [-s count] [[-j host-list] | [-k host-list]]
            [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

    -t             Ping the specified host until stopped.
                   To see statistics and continue - type Control-Break;
                   To stop - type Control-C.
    -a             Resolve addresses to hostnames.
    -n count       Number of echo requests to send.
    -l size        Send buffer size.
    -f             Set Don't Fragment flag in packet (IPv4-only).
    -i TTL         Time To Live.
    -v TOS         Type Of Service (IPv4-only. This setting has been deprecated
                   and has no effect on the type of service field in the IP Header).
    -r count       Record route for count hops (IPv4-only).
    -s count       Timestamp for count hops (IPv4-only).
    -j host-list   Loose source route along host-list (IPv4-only).
    -k host-list   Strict source route along host-list (IPv4-only).
    -w timeout     Timeout in milliseconds to wait for each reply.
    -R             Use routing header to test reverse route also (IPv6-only).
    -S srcaddr     Source address to use.
    -4             Force using IPv4.
    -6             Force using IPv6.

Failed to connect to camera service

since this question was asked 4 years back..and i didn't realised that unless mentioned by the Questioner..when there were no Run time permissions support.

but hoping it useful for the users who still caught in this situation.. Have a look at Run Time Permissions ,for me it solved the problem when i added Run time permissions to grant camera access. Alternatively you can grant permissions to the app manually by going to your mobile settings=>Apps=>(select your app)=>Permissions section in the appeared window and enable/disable desired permissions. hope this will work.

What is a NullPointerException, and how do I fix it?

What is a NullPointerException?

A good place to start is the JavaDocs. They have this covered:

Thrown when an application attempts to use null in a case where an object is required. These include:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

Applications should throw instances of this class to indicate other illegal uses of the null object.

It is also the case that if you attempt to use a null reference with synchronized, that will also throw this exception, per the JLS:

    synchronized ( Expression ) Block
  • Otherwise, if the value of the Expression is null, a NullPointerException is thrown.

How do I fix it?

So you have a NullPointerException. How do you fix it? Let's take a simple example which throws a NullPointerException:

public class Printer {
    private String name;

    public void setName(String name) { = name;

    public void print() {

    private void printString(String s) {
        System.out.println(s + " (" + s.length() + ")");

    public static void main(String[] args) {
        Printer printer = new Printer();

Identify the null values

The first step is identifying exactly which values are causing the exception. For this, we need to do some debugging. It's important to learn to read a stacktrace. This will show you where the exception was thrown:

Exception in thread "main" java.lang.NullPointerException
    at Printer.printString(
    at Printer.print(
    at Printer.main(

Here, we see that the exception is thrown on line 13 (in the printString method). Look at the line and check which values are null by adding logging statements or using a debugger. We find out that s is null, and calling the length method on it throws the exception. We can see that the program stops throwing the exception when s.length() is removed from the method.

Trace where these values come from

Next check where this value comes from. By following the callers of the method, we see that s is passed in with printString(name) in the print() method, and is null.

Trace where these values should be set

Where is set? In the setName(String) method. With some more debugging, we can see that this method isn't called at all. If the method was called, make sure to check the order that these methods are called, and the set method isn't called after the print method.

This is enough to give us a solution: add a call to printer.setName() before calling printer.print().

Other fixes

The variable can have a default value (and setName can prevent it being set to null):

private String name = "";

Either the print or printString method can check for null, for example:

printString((name == null) ? "" : name);

Or you can design the class so that name always has a non-null value:

public class Printer {
    private final String name;

    public Printer(String name) { = Objects.requireNonNull(name);

    public void print() {

    private void printString(String s) {
        System.out.println(s + " (" + s.length() + ")");

    public static void main(String[] args) {
        Printer printer = new Printer("123");

See also:

I still can't find the problem

If you tried to debug the problem and still don't have a solution, you can post a question for more help, but make sure to include what you've tried so far. At a minimum, include the stacktrace in the question, and mark the important line numbers in the code. Also, try simplifying the code first (see SSCCE).

What is the difference between json.dump() and json.dumps() in python?

The functions with an s take string parameters. The others take file streams.

Behaviour of increment and decrement operators in Python

There are no post/pre increment/decrement operators in python like in languages like C.

We can see ++ or -- as multiple signs getting multiplied, like we do in maths (-1) * (-1) = (+1).



Parses as


Which translates to


Because, multiplication of - sign with - sign is +

And finally,


How to change MySQL column definition?

Syntax to change column name in MySql:

alter table table_name change old_column_name new_column_name data_type(size);


alter table test change LowSal Low_Sal integer(4);

LaTeX table positioning

Here's an easy solution, from Wikibooks:

The placeins package provides the command \FloatBarrier, which can be used to prevent floats from being moved over it.

I just put \FloatBarrier before and after every table.

PyCharm import external library

In order to reference an external library in a project File -> Settings -> Project -> Project structure -> select the folder and mark as a source

Responding with a JSON object in Node.js (converting object/array to JSON string)

var objToJson = { };
objToJson.response = response;

If you alert(JSON.stringify(objToJson)) you will get {"response":"value"}

Adding hours to JavaScript Date object?

It is probably better to make the addHours method immutable by returning a copy of the Date object rather than mutating its parameter.

Date.prototype.addHours= function(h){
    var copiedDate = new Date(this.getTime());
    return copiedDate;

This way you can chain a bunch of method calls without worrying about state.

How do you log content of a JSON object in Node.js?

function prettyJSON(obj) {
    console.log(JSON.stringify(obj, null, 2));

// obj -> value to convert to a JSON string
// null -> (do nothing)
// 2 -> 2 spaces per indent level

JSON.stringify on MDN

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

Object.entries() returns an array whose elements are arrays corresponding to the enumerable property [key, value] pairs found directly upon object. The ordering of the properties is the same as that given by looping over the property values of the object manually.


The Object.entries function returns almost the exact output you're asking for, except the keys are strings instead of numbers.

const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_

If you need the keys to be numbers, you could map the result to a new array with a callback function that replaces the key in each pair with a number coerced from it.

const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
const toNumericPairs = input => {_x000D_
    const entries = Object.entries(input);_x000D_
    return => Object.assign(entry, { 0: +entry[0] }));_x000D_

I use an arrow function and Object.assign for the map callback in the example above so that I can keep it in one instruction by leveraging the fact that Object.assign returns the object being assigned to, and a single instruction arrow function's return value is the result of the instruction.

This is equivalent to:

entry => {
    entry[0] = +entry[0];
    return entry;

As mentioned by @TravisClarke in the comments, the map function could be shortened to:

entry => [ +entry[0], entry[1] ]

However, that would create a new array for each key-value pair, instead of modifying the existing array in place, hence doubling the amount of key-value pair arrays created. While the original entries array is still accessible, it and its entries will not be garbage collected.

Now, even though using our in-place method still uses two arrays that hold the key-value pairs (the input and the output arrays), the total number of arrays only changes by one. The input and output arrays aren't actually filled with arrays, but rather references to arrays and those references take up a negligible amount of space in memory.

  • Modifying each key-value pair in-place results in a negligible amount of memory growth, but requires typing a few more characters.
  • Creating a new array for each key-value pair results in doubling the amount of memory required, but requires typing a few less characters.

You could go one step further and eliminate growth altogether by modifying the entries array in-place instead of mapping it to a new array:

const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};_x000D_
const toNumericPairs = input => {_x000D_
  const entries = Object.entries(obj);_x000D_
  entries.forEach(entry => entry[0] = +entry[0]);_x000D_
  return entries;_x000D_

YouTube API to fetch all videos on a channel

Try with like the following. It may help you.

Here author as you can specify your channel name and "q" as you can give your search key word.

How do I instantiate a Queue object in java?

Queue<String> qe=new LinkedList<String>();


Since Queue is an interface, you can't create an instance of it as you illustrated

What is the best way to repeatedly execute a function every x seconds?

Here is another solution without using any extra libaries.

def delay_until(condition_fn, interval_in_sec, timeout_in_sec):
    """Delay using a boolean callable function.

    `condition_fn` is invoked every `interval_in_sec` until `timeout_in_sec`.
    It can break early if condition is met.

        condition_fn     - a callable boolean function
        interval_in_sec  - wait time between calling `condition_fn`
        timeout_in_sec   - maximum time to run

    Returns: None
    start = last_call = time.time()
    while time.time() - start < timeout_in_sec:
        if (time.time() - last_call) > interval_in_sec:
            if condition_fn() is True:
            last_call = time.time()

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

One possibility that the above answers don't address is that you may not have an ssh access from your shell. That is, you may be in a network (some college networks do this) where ssh service is blocked.In that case you will not only be able to get github services but also any other ssh services. You can test if this is the problem by trying to use any other ssh service.This was the case with me.

How to open the command prompt and insert commands using Java?

Please, place your command in a parameter like the mentioned below.

Runtime.getRuntime().exec("cmd.exe /c start cmd /k \" parameter \"");

"Cannot instantiate the type..."

java.util.Queue is an interface so you cannot instantiate it directly. You can instantiate a concrete subclass, such as LinkedList:

Queue<T> q = new LinkedList<T>;

Best Practice to Organize Javascript Library & CSS Folder Structure

          bootstrap/--------------Libraries can have js/css/images------------
     common/--------------------common section will have application level resources             


This is how I organized my application's static resources.

How to pass values arguments to function in Bootstrap

Here's how i am calling my modal

<a data-toggle="modal" data-id="190" data-target="#modal-popup">Open</a>

Here's how i am obtaining value in the modal

$('#modal-popup').on('', function(e) {
    console.log($(e.relatedTarget).data('id')); // 190 will be printed

Ruby Arrays: select(), collect(), and map()

When dealing with a hash {}, use both the key and value to the block inside the ||. {|key,item|"" == item}

=>[false, false, true, false, false]

How to create a project from existing source in Eclipse and then find it?

This answer is going to be for the question

How to create a new eclipse project and add a folder or a new package into the project, or how to build a new project for existing java files.

  1. Create a new project from the menu File->New-> Java Project
  2. If you are going to add a new pakcage, then create the same package name here by File->New-> Package
  3. Click the name of the package in project navigator, and right click, and import... Import->General->File system (choose your file or package)

this worked for me I hope it helps others. Thank you.

IFrame: This content cannot be displayed in a frame

use <meta http-equiv="X-Frame-Options" content="allow"> in the one to show in the iframe to allow it.

Capture Signature using HTML5 and iPad

Here is a quickly hacked up version of this using SVG I just did. Works well for me on my iPhone. Also works in a desktop browser using normal mouse events.

Installing R with Homebrew

I used this tutorial to install R on my mac, and it had me install xquartz and a fortran complier (gfortran) as well.

My suggestion would be to brew untap homebrew/science and then brew tap homebrew/science and try again, also, make sure you don't have any errors when you run brew doctor

Hope this helps

What is the difference between cache and persist?

For impatient:


Without passing argument, persist() and cache() are the same, with default settings:

  • when Dataset: MEMORY_AND_DISK


Unlike cache(), persist() allows you to pass argument inside the bracket, in order to specify the level:

  • persist(MEMORY_ONLY)
  • persist(MEMORY_ONLY_SER)
  • persist(MEMORY_AND_DISK)
  • persist(MEMORY_AND_DISK_SER )
  • persist(DISK_ONLY )


MySQL Workbench: How to keep the connection alive

I was getting this error 2013 and none of the above preference changes did anything to fix the problem. I restarted mysql service and the problem went away.

Read specific columns from a csv file with csv module?

Use pandas:

import pandas as pd
my_csv = pd.read_csv(filename)
column = my_csv.column_name
# you can also use my_csv['column_name']

Discard unneeded columns at parse time:

my_filtered_csv = pd.read_csv(filename, usecols=['col1', 'col3', 'col7'])

P.S. I'm just aggregating what other's have said in a simple manner. Actual answers are taken from here and here.

Why doesn't CSS ellipsis work in table cell?

Just offering an alternative as I had this problem and none of the other answers here had the desired effect I wanted. So instead I used a list. Now semantically the information I was outputting could have been regarded as both tabular data but also listed data.

So in the end what I did was:

    <li class="group">
        <span class="title">...</span>
        <span class="description">...</span>
        <span class="mp3-player">...</span>
        <span class="download">...</span>
        <span class="shortlist">...</span>
    <!-- looped <li> -->

So basically ul is table, li is tr, and span is td.

Then in CSS I set the span elements to be display:block; and float:left; (I prefer that combination to inline-block as it'll work in older versions of IE, to clear the float effect see: and to also have the ellipses:

span {
    display: block;
    float: left;
    width: 100%;

    // truncate when long
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

Then all you do is set the max-widths of your spans and that'll give the list an appearance of a table.

Concept of void pointer in C programming

Void pointers are pointers that has no data type associated with it.A void pointer can hold address of any type and can be typcasted to any type. But, void pointer cannot be directly be dereferenced.

int x = 1;
void *p1;
p1 = &x;
cout << *p1 << endl; // this will give error
cout << (int *)(*p) << endl; // this is valid

Restrict SQL Server Login access to only one database

  1. Connect to your SQL server instance using management studio
  2. Goto Security -> Logins -> (RIGHT CLICK) New Login
  3. fill in user details
  4. Under User Mapping, select the databases you want the user to be able to access and configure


You'll also want to goto Security -> Server Roles, and for public check the permissions for TSQL Default TCP/TSQL Default VIA/TSQL Local Machine/TSQL Named Pipesand remove the connect permission

How can you flush a write using a file descriptor?

fflush() only flushes the buffering added by the stdio fopen() layer, as managed by the FILE * object. The underlying file itself, as seen by the kernel, is not buffered at this level. This means that writes that bypass the FILE * layer, using fileno() and a raw write(), are also not buffered in a way that fflush() would flush.

As others have pointed out, try not mixing the two. If you need to use "raw" I/O functions such as ioctl(), then open() the file yourself directly, without using fopen<() and friends from stdio.

How to hide Android soft keyboard on EditText

Three ways based on the same simple instruction:

a). Results as easy as locate (1):


among the configuration of any precedent element in the layout, example:

if your whole layout is composed of:





then you can write the (1) among ImageView parameters and this will grab android's attention to the ImageView instead of the EditText.

b). In case you have another precedent element than an ImageView you may need to add (2) to (1) as:


c). you can also simply create an empty element at the top of your view elements:

  android:layout_height="0px" />

This alternative until this point results as the simplest of all I've seen. Hope it helps...

Remove a git commit which has not been pushed

I just had the same problem and ended up doing:

git rebase -i HEAD~N

(N is the number of commits git will show you)

That prompts your text editor and then you can remove the commit you want by deleting the line associated with it.

UITableView - scroll to the top

If you need use Objective-C or you still in love:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [_tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];

how to fetch data from database in Hibernate

I know that it is very late to answer the question, but it may help someone like me who spent lots off time to fetch data using hql

So the thing is you just have to write a query

Query query = session.createQuery("from Employee");

it will give you all the data list but to fetch data from this you have to write this line.

List<Employee> fetchedData = query.list();

As simple as it looks.

How can I replace non-printable Unicode characters in Java?

I have redesigned the code for phone numbers +9 (987) 124124 Extract digits from a string in Java

 public static String stripNonDigitsV2( CharSequence input ) {
    if (input == null)
        return null;
    if ( input.length() == 0 )
        return "";

    char[] result = new char[input.length()];
    int cursor = 0;
    CharBuffer buffer = CharBuffer.wrap( input );
    int i=0;
    while ( i< buffer.length()  ) { //buffer.hasRemaining()
        char chr = buffer.get(i);
        if (chr=='u'){

        if ( chr > 39 && chr < 58 )
            result[cursor++] = chr;

    return new String( result, 0, cursor );

How can I concatenate strings in VBA?

The main (very interesting) difference for me is that:
"string" & Null -> "string"
"string" + Null -> Null

But that's probably more useful in database apps like Access.

How to make certain text not selectable with CSS

The CSS below stops users from being able to select text.

-webkit-user-select: none; /* Safari */        
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+/Edge */
user-select: none; /* Standard */

To target IE9 downwards the html attribute unselectable must be used instead:

<p unselectable="on">Test Text</p>

Bind TextBox on Enter-key press

A different solution (not using xaml but still quite clean I think).

class ReturnKeyTextBox : TextBox
    protected override void OnKeyUp(KeyEventArgs e)
        if (e.Key == Key.Return)

Which concurrent Queue implementation should I use in Java?

ArrayBlockingQueue has lower memory footprint, it can reuse element node, not like LinkedBlockingQueue that have to create a LinkedBlockingQueue$Node object for each new insertion.

How can I change the color of AlertDialog title and the color of the line under it

Here is another solution (based on suggested answers) that handles the styling of the dialogs in one class without needing to worry about the state of the dialog when you change the style - dialog can be already shown or just initialized.

Usage example:

AlertDialog.Builder builder = new AlertDialog.Builder(context);
AlertDialog dialog = builder.create(); //or
DialogViewDecorator.decorate(dialog, android.R.color.holo_red_light); //can also set the defaut color in the class


public class DialogViewDecorator {

private static final
@ColorRes int DEFAULT_TITLE_DIVIDER_COLOR = android.R.color.holo_orange_light;

public static void decorate(Dialog dialog) {
    decorate(dialog, DEFAULT_TITLE_DIVIDER_COLOR);

 * Sets the title divider color when the view is shown by setting DialogInterface.OnShowListener on the dialog.
 * <p/>
 * If you want to do other things onShow be sure to extend OnDecoratedDialogShownListener(call!)
 * and call {@link #decorate(Dialog, int, OnDecoratedDialogShownListener)}.
 * @param dialog
 * @param titleDividerColor
public static void decorate(Dialog dialog, final int titleDividerColor) {
    decorate(dialog, titleDividerColor, new OnDecoratedDialogShownListener(titleDividerColor));

 * Method for setting a extended implementation of OnDecoratedDialogShownListener. Don't forget to call super
 * or the titleDividerColor wont be applied!
 * @param dialog
 * @param titleDividerColor
 * @param OnShowListener
 * @param <T>
public static <T extends OnDecoratedDialogShownListener> void decorate(Dialog dialog, int titleDividerColor, T OnShowListener) {
    if (dialog == null || titleDividerColor <= 0) { return; }

    if (dialog.isShowing()) {
        setTitleDividerColor(dialog, titleDividerColor);
    } else {

private static void setTitleDividerColor(DialogInterface dialogInterface, int titleDividerColor) {
    try {
        Dialog dialog = (Dialog) dialogInterface;
        int dividerId = dialog.getContext().getResources().getIdentifier("android:id/titleDivider", null, null);
        View divider = dialog.findViewById(dividerId);
        if (divider != null) {
    } catch (Exception e) {

public static class OnDecoratedDialogShownListener implements DialogInterface.OnShowListener {
    private int titleDividerColor;

    public OnDecoratedDialogShownListener() {
        this.titleDividerColor = DEFAULT_TITLE_DIVIDER_COLOR;

    public OnDecoratedDialogShownListener(int titleDividerColor) {
        this.titleDividerColor = titleDividerColor;

    public void onShow(DialogInterface dialogInterface) {
        setTitleDividerColor(dialogInterface, titleDividerColor);

PHP: check if any posted vars are empty - form: all fields required

I did it like this:

$missing = array();
 foreach ($_POST as $key => $value) { if ($value == "") { array_push($missing, $key);}}
 if (count($missing) > 0) {
  echo "Required fields found empty: ";
  foreach ($missing as $k => $v) { echo $v." ";}
  } else {
  // do your stuff here with the $_POST

Visual Studio 2010 shortcut to find classes and methods?

Try Alt+F12 in Visual Studio 2010.

It opens up the Find Symbol dialogue which allows you to search for methods, classes, etc.

How to remove multiple indexes from a list at the same time?

remove_indices = [1,2,3]
somelist = [i for j, i in enumerate(somelist) if j not in remove_indices]


In [9]: remove_indices = [1,2,3]

In [10]: somelist = range(10)

In [11]: somelist = [i for j, i in enumerate(somelist) if j not in remove_indices]

In [12]: somelist
Out[12]: [0, 4, 5, 6, 7, 8, 9]

Div show/hide media query

I'm not sure, what you mean as the 'mobile width'. But in each case, the CSS @media can be used for hiding elements in the screen width basis. See some example:

<div id="my-content"></div>


@media screen and (min-width: 0px) and (max-width: 400px) {
  #my-content { display: block; }  /* show it on small screens */

@media screen and (min-width: 401px) and (max-width: 1024px) {
  #my-content { display: none; }   /* hide it elsewhere */

Some truly mobile detection is kind of hard programming and rather difficult. Eventually see the: or other similar sources.

How to use Git for Unity3D source control?

Only the Assets and ProjectSettings folders need to be under git version control.

You can make a gitignore like this.


# Autogenerated VS/MD solution and project files

# Mac



Auto populate columns in one sheet from another sheet

In Google Sheets you can use =ArrayFormula(Sheet1!B2:B)on the first cell and it will populate all column contents not sure if that will work in excel

Metadata file '.dll' could not be found

In my case, I have my installed directory in mistaken ways.

If your solution path is something like "My Project%2c Very Popular%2c Unit Testing%2c Software and", it cannot resolve the metadata file, perhaps we should prevent some invalid words like %2c.

Renaming the path into normal name resolved my issue.

Java ArrayList of Arrays?

ArrayList<String[]> action = new ArrayList<String[]>();

Don't need String[2];

executing a function in sql plus

  x number;
  x := myfunc(myargs);


select myfunc(myargs) from dual;

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

Can I do it dynamically?

Create view class:

public class View {
    static class Public { }
    static class ExtendedPublic extends Public { }
    static class Internal extends ExtendedPublic { }

Annotate you model

public class User {

    private String id;

    private String email;

    private String name;

    private Instant createdAt =;
    // getters/setters

Specify the view class in your controller

public class UserController {

    private final UserRepository userRepository;

    UserController(UserRepository userRepository) {
        this.userRepository = userRepository;

    @RequestMapping(method = RequestMethod.GET)
    public @ResponseBody Optional<User> get(@PathVariable String email) {
        return userRepository.findByEmail(email);


Data example:


How to fix homebrew permissions?

All of these suggestions may work. In the latest version of brew doctor, better suggestions were made though.

Firstly - fix the mess you have probably already made of /usr/local by running this in the command line:

sudo chown -R root:wheel /usr/local

Then take ownership of the paths that should be specifically for this user:

sudo chown -R $(whoami) /usr/local/lib /usr/local/sbin /usr/local/var /usr/local/Frameworks /usr/local/lib/pkgconfig /usr/local/share/locale

All of this information is available if you run sudo brew update and then read all of the warnings and errors you will run into...

How to delete only the content of file in python

You can do this:

def deleteContent(pfile): 
    return open(fn,'w')

Why is SQL Server 2008 Management Studio Intellisense not working?

When trying the accepted answer, I was getting an installation error: A failure was detected for a previous installation, patch, or repair blah, blah, blah...

To fix this, in my registry, I changed all DWORD values to 1 in the following Keys: (As always be careful modifying the registry and create a backup of the key before changing anything)

HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\100\ConfigurationState HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSAS10_50.MSSQLSERVER\ConfigurationState HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\ConfigurationState HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.SQLEXPRESS\ConfigurationState HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\ConfigurationState

See my full post about Fixing Intellisense issue in SSMS.

Cannot change column used in a foreign key constraint

You can turn off foreign key checks:




Please make sure to NOT use this on production and have a backup.

How do I view events fired on an element in Chrome DevTools?

For jQuery (at least version 1.11.2) the following procedure worked for me.

  1. Right click on the element and open 'Chrome Developer Tools'
  2. Type $._data(($0), 'events'); in the 'Console'
  3. Expand the attached objects and double click the handler: value.
  4. This shows the source code of the attached function, search for part of that using the 'Search' tab.

And it's time to stop re-inventing the wheel and start using vanilla JS events ... :)


Batch file to copy directories recursively

After reading the accepted answer's comments, I tried the robocopy command, which worked for me (using the standard command prompt from Windows 7 64 bits SP 1):

robocopy source_dir dest_dir /s /e

Executing <script> injected by innerHTML after AJAX call

Here is the script that will evaluates all script tags in the text.

function evalJSFromHtml(html) {
  var newElement = document.createElement('div');
  newElement.innerHTML = html;

  var scripts = newElement.getElementsByTagName("script");
  for (var i = 0; i < scripts.length; ++i) {
    var script = scripts[i];

Just call this function after you receive your HTML from server. Be warned: using eval can be dangerous.


How to convert string to integer in UNIX

An answer that is not limited to the OP's case

The title of the question leads people here, so I decided to answer that question for everyone else since the OP's described case was so limited.


I finally settled on writing a function.

  1. If you want 0 in case of non-int:
int(){ printf '%d' ${1:-} 2>/dev/null || :; }
  1. If you want [empty_string] in case of non-int:
int(){ expr 0 + ${1:-} 2>/dev/null||:; }
  1. If you want find the first int or [empty_string]:
int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }
  1. If you want find the first int or 0:
# This is a combination of numbers 1 and 2
int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }

If you want to get a non-zero status code on non-int, remove the ||: (aka or true) but leave the ;


# Wrapped in parens to call a subprocess and not `set` options in the main bash process
# In other words, you can literally copy-paste this code block into your shell to test
( set -eu;
    tests=( 4 "5" "6foo" "bar7" "foo8.9bar" "baz" " " "" )
    test(){ echo; type int; for test in "${tests[@]}"; do echo "got '$(int $test)' from '$test'"; done; echo "got '$(int)' with no argument"; }

    int(){ printf '%d' ${1:-} 2>/dev/null||:; };

    int(){ expr 0 + ${1:-} 2>/dev/null||:; }

    int(){ expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null||:; }

    int(){ printf '%d' $(expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null)||:; }

    # unexpected inconsistent results from `bc`
    int(){ bc<<<"${1:-}" 2>/dev/null||:; }

Test output

int is a function
int ()
    printf '%d' ${1:-} 2> /dev/null || :
got '4' from '4'
got '5' from '5'
got '0' from '6foo'
got '0' from 'bar7'
got '0' from 'foo8.9bar'
got '0' from 'baz'
got '0' from ' '
got '0' from ''
got '0' with no argument

int is a function
int ()
    expr 0 + ${1:-} 2> /dev/null || :
got '4' from '4'
got '5' from '5'
got '' from '6foo'
got '' from 'bar7'
got '' from 'foo8.9bar'
got '' from 'baz'
got '' from ' '
got '' from ''
got '' with no argument

int is a function
int ()
    expr ${1:-} : '[^0-9]*\([0-9]*\)' 2> /dev/null || :
got '4' from '4'
got '5' from '5'
got '6' from '6foo'
got '7' from 'bar7'
got '8' from 'foo8.9bar'
got '' from 'baz'
got '' from ' '
got '' from ''
got '' with no argument

int is a function
int ()
    printf '%d' $(expr ${1:-} : '[^0-9]*\([0-9]*\)' 2>/dev/null) || :
got '4' from '4'
got '5' from '5'
got '6' from '6foo'
got '7' from 'bar7'
got '8' from 'foo8.9bar'
got '0' from 'baz'
got '0' from ' '
got '0' from ''
got '0' with no argument

int is a function
int ()
    bc <<< "${1:-}" 2> /dev/null || :
got '4' from '4'
got '5' from '5'
got '' from '6foo'
got '0' from 'bar7'
got '' from 'foo8.9bar'
got '0' from 'baz'
got '' from ' '
got '' from ''
got '' with no argument


I got sent down this rabbit hole because the accepted answer is not compatible with set -o nounset (aka set -u)

# This works
$ ( number="3"; string="foo"; echo $((number)) $((string)); )
3 0

# This doesn't
$ ( set -u; number="3"; string="foo"; echo $((number)) $((string)); )
-bash: foo: unbound variable

This Handler class should be static or leaks might occur: IncomingHandler

Here is a generic example of using a weak reference and static handler class to resolve the problem (as recommended in the Lint documentation):

public class MyClass{

  //static inner class doesn't hold an implicit reference to the outer class
  private static class MyHandler extends Handler {
    //Using a weak reference means you won't prevent garbage collection
    private final WeakReference<MyClass> myClassWeakReference; 

    public MyHandler(MyClass myClassInstance) {
      myClassWeakReference = new WeakReference<MyClass>(myClassInstance);

    public void handleMessage(Message msg) {
      MyClass myClass = myClassWeakReference.get();
      if (myClass != null) { work here...

   * An example getter to provide it to some external class
   * or just use 'new MyHandler(this)' if you are using it internally.
   * If you only use it internally you might even want it as final member:
   * private final MyHandler mHandler = new MyHandler(this);
  public Handler getHandler() {
    return new MyHandler(this);

Finding blocking/locking queries in MS SQL (mssql)

Use the script: sp_blocker_pss08 or SQL Trace/Profiler and the Blocked Process Report event class.

On npm install: Unhandled rejection Error: EACCES: permission denied

Restore ownership of the user's npm related folders, to the current user, like this:

sudo chown -R $USER:$GROUP ~/.npm
sudo chown -R $USER:$GROUP ~/.config

CSS Border Not Working

The height is a 100% unsure, try putting display: block; or display: inline-block;

Securely storing passwords for use in python script

the secure way is encrypt your sensitive data by AES and the encryption key is derivation by password-based key derivation function (PBE), the master password used to encrypt/decrypt the encrypt key for AES.

master password -> secure key-> encrypt data by the key

You can use pbkdf2

from PBKDF2 import PBKDF2
from Crypto.Cipher import AES
import os
salt = os.urandom(8)    # 64-bit salt
key = PBKDF2("This passphrase is a secret.", salt).read(32) # 256-bit key
iv = os.urandom(16)     # 128-bit IV
cipher =, AES.MODE_CBC, iv)

make sure to store the salt/iv/passphrase , and decrypt using same salt/iv/passphase

Weblogic used similar approach to protect passwords in config files

How to listen for changes to a MongoDB collection?

Check out this: Change Streams

January 10, 2018 - Release 3.6

*EDIT: I wrote an article about how to do this

It's new in mongodb 3.6 2018/01/10

$ mongod --version
db version v3.6.2

In order to use changeStreams the database must be a Replication Set

More about Replication Sets:

Your Database will be a "Standalone" by default.

How to Convert a Standalone to a Replica Set:

The following example is a practical application for how you might use this.
* Specifically for Node.

/* file.js */
'use strict'

module.exports = function (
    User // Collection Name
) {
    const changeStream =;  

    // Socket Connection  
    io.on('connection', function (socket) {

        // USERS - Change
        changeStream.on('change', function(change) {
            console.log('COLLECTION CHANGED');

            User.find({}, (err, data) => {
                if (err) throw err;

                if (data) {
                    // RESEND ALL USERS
                    socket.emit('users', data);
/* END - file.js */

Useful links:

Trim whitespace from a String

Your code is fine. What you are seeing is a linker issue.

If you put your code in a single file like this:

#include <iostream>
#include <string>

using namespace std;

string trim(const string& str)
    size_t first = str.find_first_not_of(' ');
    if (string::npos == first)
        return str;
    size_t last = str.find_last_not_of(' ');
    return str.substr(first, (last - first + 1));

int main() {
    string s = "abc ";
    cout << trim(s);


then do g++ and run a.out, you will see it works.

You should check if the file that contains the trim function is included in the link stage of your compilation process.

Error: " 'dict' object has no attribute 'iteritems' "

The purpose of .iteritems() was to use less memory space by yielding one result at a time while looping. I am not sure why Python 3 version does not support iteritems()though it's been proved to be efficient than .items()

If you want to include a code that supports both the PY version 2 and 3,

except NameError:
    iteritems = items

This can help if you deploy your project in some other system and you aren't sure about the PY version.

Merge two array of objects based on a key

Well... assuming both arrays are of the same length, I would probably do something like this:

var newArr = []
for (var i = 0; i < array1.length; i++ {
    if (array1[i].id === array2[i].id) {
      newArr.push({id: array1[i].id, date: array1[i].date, name: array2[i].name});

Passing structs to functions

Passing structs to functions by reference: simply :)

#define maxn 1000

struct solotion
    int sol[maxn];
    int arry_h[maxn];
    int cat[maxn];
    int scor[maxn];


void inser(solotion &come){

void initial(solotion &come){
    for(int i=0;i<maxn;i++)

int main()
    solotion sol1;
    solotion sol2;

How to modify STYLE attribute of element with known ID using JQuery

Not sure I completely understand the question but:

$(":button.brown").click(function() {

seems to be along the lines of what you want.

I would certainly recommend using classes instead of directly setting CSS, which is problematic for several reasons (eg removing styles is non-trivial, removing classes is easy) but if you do want to go that way:

$("...").css("background", "brown");

But when you want to reverse that change, what do you set it to?

How to restrict SSH users to a predefined set of commands after login?

Why don't you write your own login-shell? It would be quite simple to use Bash for this, but you can use any language.

Example in Bash

Use your favorite editor to create the file /root/ (this can be any name or path, but should be chown root:root and chmod 700):


commands=("man" "pwd" "ls" "whoami")
timestamp(){ date +'%Y-%m-%s %H:%M:%S'; }
log(){ echo -e "$(timestamp)\t$1\t$(whoami)\t$2" > /var/log/rbash.log; }
    # Provide an option to exit the shell
    if [[ "$ln" == "exit" ]] || [[ "$ln" == "q" ]]
    # You can do exact string matching for some alias:
    elif [[ "$ln" == "help" ]]
        echo "Type exit or q to quit."
        echo "Commands you can use:"
        echo "  help"
        echo "  echo"
        echo "${commands[@]}" | tr ' ' '\n' | awk '{print "  " $0}'
    # You can use custom regular expression matching:
    elif [[ "$ln" =~ ^echo\ .*$ ]]
        echo "$ln" # Beware, these double quotes are important to prevent malicious injection
        # For example, optionally you can log this command
        log COMMAND "echo $ln"
    # Or you could even check an array of commands:
        for cmd in "${commands[@]}"
            if [[ "$cmd" == "$ln" ]]
        if $ok
            log DENIED "$cmd"

# Optionally show a friendly welcome-message with instructions since it is a custom shell
echo "$(timestamp) Welcome, $(whoami). Type 'help' for information."

# Optionally log the login
log LOGIN "$@"

# Optionally log the logout
trap "trap=\"\";log LOGOUT;exit" EXIT

# Optionally check for '-c custom_command' arguments passed directly to shell
# Then you can also use ssh user@host custom_command, which will execute /root/
if [[ "$1" == "-c" ]]
    trycmd "$@"
    while echo -n "> " && read ln
        trycmd "$ln"

All you have to do is set this executable as your login shell. For example, edit your /etc/passwd file, and replace your current login shell of that user /bin/bash with /root/

This is just a simple example, but you can make it as advanced as you want, the idea is there. Be careful to not lock yourself out by changing login shell of your own and only user. And always test weird symbols and commands to see if it is actually secure.

You can test it with: su -s /root/

Beware, make sure to match the whole command, and be careful with wildcards! Better exclude Bash-symbols such as ;, &, &&, ||, $, and backticks to be sure.

Depending on the freedom you give the user, it won't get much safer than this. I've found that often I only needed to make a user that has access to only a few relevant commands, and in that case this is really the better solution. However, do you wish to give more freedom, a jail and permissions might be more appropriate. Mistakes are easily made, and only noticed when it's already too late.

How do you do block comments in YAML?

In .gitlab-ci.yml file following works::

To comment out a block (multiline): Select the whole block section > Ctrl K C

To uncomment already commented out block (multiline): Select the whole block section > Ctrl K U

How to remove item from a JavaScript object

var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete; // or use => delete test['blue'];_x000D_

this deletes

How to preserve request url with nginx proxy_pass

In my scenario i have make this via below code in nginx vhost configuration

server {

location / {
    proxy_set_header Host $http_host;

$http_host will set URL in Header same as requested

How to get an element's top position relative to the browser's viewport?

Thanks for all the answers. It seems Prototype already has a function that does this (the page() function). By viewing the source code of the function, I found that it first calculates the element offset position relative to the page (i.e. the document top), then subtracts the scrollTop from that. See the source code of prototype for more details.

JavaFX - create custom button with image

You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.

public class ImageButton extends Parent {

    private static final Image NORMAL_IMAGE = ...;
    private static final Image PRESSED_IMAGE = ...;

    private final ImageView iv;

    public ImageButton() {
        this.iv = new ImageView(NORMAL_IMAGE);

        this.iv.setOnMousePressed(new EventHandler<MouseEvent>() {

            public void handle(MouseEvent evt) {


        // TODO other event handlers like mouse up



Using GroupBy, Count and Sum in LINQ Lambda Expressions

var boxSummary = from b in boxes
                 group b by b.Owner into g
                 let nrBoxes = g.Count()
                 let totalWeight = g.Sum(w => w.Weight)
                 let totalVolume = g.Sum(v => v.Volume)
                 select new { Owner = g.Key, Boxes = nrBoxes,
                              TotalWeight = totalWeight,
                              TotalVolume = totalVolume }

Best way to deploy Visual Studio application that can run without installing

First you need to publish the file by:

  1. BUILD -> PUBLISH or by right clicking project on Solution Explorer -> properties -> publish or select project in Solution Explorer and press Alt + Enter NOTE: if you are using Visual Studio 2013 then in properties you have to go to BUILD and then you have to disable define DEBUG constant and define TRACE constant and you are ready to go. Representation

  2. Save your file to a particular folder. Find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj). In Visual Studio they are in the Application Files folder and inside that you just need the .exe and dll files. (You have to delete ClickOnce and other files and then make this folder a zip file and distribute it.)

NOTE: The ClickOnce application does install the project to system, but it has one advantage. You DO NOT require administrative privileges here to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

How do I use Docker environment variable in ENTRYPOINT array?

You're using the exec form of ENTRYPOINT. Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, ENTRYPOINT [ "echo", "$HOME" ] will not do variable substitution on $HOME. If you want shell processing then either use the shell form or execute a shell directly, for example: ENTRYPOINT [ "sh", "-c", "echo $HOME" ].
When using the exec form and executing a shell directly, as in the case for the shell form, it is the shell that is doing the environment variable expansion, not docker.(from Dockerfile reference)

In your case, I would use shell form

ENTRYPOINT ./greeting --message "Hello, $ADDRESSEE\!"

Best way to create unique token in Rails?

To create a proper, mysql, varchar 32 GUID


Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

if you have remote server installed on you machine. give host as "localhost" and the port number. then client side , you have to give local ip- and port number. then its works

Do you know the Maven profile for

Place this in the ~/.m2/settings.xml or custom file to be run with $ mvn -s custom-settings.xml install

<settings xmlns=""

How do I clear my local working directory in Git?

You could create a commit which contains an empty working copy.

This is a generally safe, non-destructive approach because it does not involve the use of any brute-force reset mechanisms. First you hide all managed content with git checkout empty, then you are free to manually review and remove whatever unmanaged content remains.

## create a stand-alone, tagged, empty commit
true | git mktree | xargs git commit-tree | xargs git tag empty

## clear the working copy
git checkout empty

Your working copy should now be clear of any managed content. All that remains are unmanaged files and the .git folder itself.

To re-populate your working copy...

git checkout master ## or whatever branch you will be using

If you're a forward thinking individual, you might start your repository off on the right foot by basing everything on an initial empty commit...

git init
git commit --allow-empty --allow-empty-message -m ""
git tag empty

There are various uses for a tagged empty worktree. My favorite at the moment is to depopulate the root under a set of git worktree subfolders.

Bootstrap modal z-index

Well, despite of this entry being very old. I was using bootstrap's modal this week and came along this "issue". My solution was somehow a mix of everything, just posting it as it may help someone :)

First check the Z-index war to get a fix there!

The first thing you can do is deactivate the modal backdrop, I had the Stackoverflow post before but I lost it, so I wont take the credit for it, keep that in mind; but it goes like this in the HTML code:

<!-- from the bootstrap's docs -->_x000D_
<div class="modal fade" tabindex="-1" role="dialog" data-backdrop="false">_x000D_
  <!-- mind the data-backdrop="false" -->_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <!-- ... modal content -->_x000D_

The second approach was to have an event listener attached to the bootstrap's shown modal event. This is somehow not so pretty as you may think but maybe with some tricks by your own may somehow work. The advantage of this is that the element attaches the event listener and you can completely forget about it as long as you have the event listener attached :)

var element = $('selector-to-your-modal');_x000D_
// also taken from bootstrap 3 docs_x000D_
$(element).on('', function(e) {_x000D_
  // keep in mind this only works as long as Bootstrap only supports 1 modal at a time, which is the case in Bootstrap 3 so far..._x000D_
  var backDrop = $('.modal-backdrop');_x000D_

The second.1 approach is basically the same than the previous but without the event listener.

Hope it helps someone!

Jquery submit form

Since a jQuery object inherits from an array, and this array contains the selected DOM elements. Saying you're using an id and so the element should be unique within the DOM, you could perform a direct call to submit by doing :

$(".nextbutton").click(function() { 

How can I parse a string with a comma thousand separator to a number?

Yes remove the commas:

parseFloat(yournumber.replace(/,/g, ''));

How to use [DllImport("")] in C#?

You can't declare an extern local method inside of a method, or any other method with an attribute. Move your DLL import into the class:

using System.Runtime.InteropServices;

public class WindowHandling
    public static extern int SetForegroundWindow(IntPtr point);

    public void ActivateTargetApplication(string processName, List<string> barcodesList)
        Process p = Process.Start("notepad++.exe");
        IntPtr h = p.MainWindowHandle;
        IntPtr processFoundWindow = p.MainWindowHandle;

What is the main difference between PATCH and PUT request?

Differences between PUT and PATCH The main difference between PUT and PATCH requests is witnessed in the way the server processes the enclosed entity to update the resource identified by the Request-URI. When making a PUT request, the enclosed entity is viewed as the modified version of the resource saved on the original server, and the client is requesting to replace it. However, with PATCH, the enclosed entity boasts a set of instructions that describe how a resource stored on the original server should be partially modified to create a new version.

The second difference is when it comes to idempotency. HTTP PUT is said to be idempotent since it always yields the same results every after making several requests. On the other hand, HTTP PATCH is basically said to be non-idempotent. However, it can be made to be idempotent based on where it is implemented.

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

In your application context, change the bean with id from emf to entityManagerFactory:

<bean id="emf"
    <property name="packagesToScan" value="org.wahid.cse.entity" />
    <property name="dataSource" ref="dataSource" />

    <property name="jpaProperties">
            <prop key="hibernate.show_sql">true</prop>
            <prop key="">create</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>

    <property name="persistenceProvider">
        <bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>



<bean id="entityManagerFactory"
    <property name="packagesToScan" value="org.wahid.cse.entity" />
    <property name="dataSource" ref="dataSource" />

    <property name="jpaProperties">
            <prop key="hibernate.show_sql">true</prop>
            <prop key="">create</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>

    <property name="persistenceProvider">
        <bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>


Laravel back button

One of the below solve your problem




How to get a certain element in a list, given the position?

Maybe not the most efficient way. But you could convert the list into a vector.

#include <list>
#include <vector>

list<Object> myList;

vector<Object> myVector(myList.begin(), myList.end());

Then access the vector using the [x] operator.

auto x = MyVector[0];

You could put that in a helper function:

#include <memory>
#include <vector>
#include <list>

template<class T>
ListToVector(list<T> List) {
shared_ptr<vector<T>> Vector {
        new vector<string>(List.begin(), List.end()) }
return Vector;

Then use the helper funciton like this:

auto MyVector = ListToVector(Object);
auto x = MyVector[0];

How do I break a string across more than one line of code in JavaScript?

Interesting to note. Tried:

alert("Some \
    string \
    wrapped \
    across \
    mutliples lines.")

And this worked. However, on accident!, there was a space character following the final backslash (all other backslashes were at the end of the line). And this caused an error in the javascript! Removing this space fixed the error, though.

This is in ADT for Android using Cordova.

Check if a record exists in the database

Use try catch:

    SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);

    int UserExist = (int)check_User_Name.ExecuteScalar();
    // Update query
    // Insert query

JUnit 5: How to assert an exception is thrown?

Actually I think there is a error in the documentation for this particular example. The method that is intended is expectThrows

public static void assertThrows(
public static <T extends Throwable> T expectThrows(

DISTINCT clause with WHERE


Select *, (Select distinct email) from Table1

In java how to get substring from a string till a character c?

How about using regex?

String firstWord = filename.replaceAll("\\..*","")

This replaces everything from the first dot to the end with "" (ie it clears it, leaving you with what you want)

Here's a test:

System.out.println("abc.def.hij".replaceAll("\\..*", "");



sort dict by value python

In your comment in response to John, you suggest that you want the keys and values of the dictionary, not just the values.

PEP 256 suggests this for sorting a dictionary by values.

import operator
sorted(d.iteritems(), key=operator.itemgetter(1))

If you want descending order, do this

sorted(d.iteritems(), key=itemgetter(1), reverse=True)

how to make div click-able?

I suggest to use a CSS class called clickbox and activate it with jQuery:

     return false;

Now the only thing you have to do is mark your div as clickable and provide a link:

<div id="logo" class="clickbox"><a href="index.php"></a></div>

Plus a CSS style to change the mouse cursor:

.clickbox {
    cursor: pointer;

Easy, isn't it?

How to remove &quot; from my Json in javascript?

The following works for me:

function decodeHtml(html) {
    let areaElement = document.createElement("textarea");
    areaElement.innerHTML = html;

    return areaElement.value;

Try reinstalling `node-sass` on node 0.12?

For me, this issue was caused in my build system (Travis CI) by doing something kind of dumb in my .travis.yml file. In effect, I was calling npm install before nvm use 0.12, and this was causing node-sass to be built for 0.10 instead of 0.12. My solution was simply moving nvm use out of the .travis.yml file’s before_script section to before the npm install command, which was in the before_install section.

In your case, it is likely that whatever process you are starting with gulp is using a different version of node (than what you would expect).

Format in kotlin string templates

Since String.format is only an extension function (see here) which internally calls java.lang.String.format you could write your own extension function using Java's DecimalFormat if you need more flexibility:

fun Double.format(fracDigits: Int): String {
    val df = DecimalFormat()
    return df.format(this)

println(3.14159.format(2)) // 3.14

Print line numbers starting at zero using awk

If Perl is an option, you can try this:

perl -ne 'printf "%s,$_" , $.-1' file

$_ is the line
$. is the line number

How to get error message when ifstream open fails

Following on @Arne Mertz's answer, as of C++11 std::ios_base::failure inherits from system_error (see, which contains both the error code and message that strerror(errno) would return.

std::ifstream f;

// Set exceptions to be thrown on failure
f.exceptions(std::ifstream::failbit | std::ifstream::badbit);

try {;
} catch (std::system_error& e) {
    std::cerr << e.code().message() << std::endl;

This prints No such file or directory. if fileName doesn't exist.

How to trigger a build only if changes happen on particular set of files

The Git plugin has an option (excluded region) to use regexes to determine whether to skip building based on whether files in the commit match the excluded region regex.

Unfortunately, the stock Git plugin does not have a "included region" feature at this time (1.15). However, someone posted patches on GitHub that work on Jenkins and Hudson that implement the feature you want.

It is a little work to build, but it works as advertised and has been extremely useful since one of my Git trees has multiple independent projects.

Update: The Git plugin (1.16) now has the 'included' region feature.

Append text to textarea with javascript

Tray to add text with html value to textarea but it wil not works

value :

$(document).on('click', '.edit_targets_btn', function() {
            $('#targets_modal_title').text('Doel bijwerken');


                selector: '#targets_content',
                setup: function (editor) {
                    editor.on('change', function () {
                browser_spellcheck : true,
                plugins: ['advlist autolink lists image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount', 'autoresize'],
                toolbar: 'undo redo | formatselect | ' + ' bold italic backcolor | alignleft aligncenter ' + ' alignright alignjustify | bullist numlist outdent indent |' + ' removeformat | image | help',
                relative_urls : false,
                remove_script_host : false,
                image_list: [<?php $stmt = $db->query('SELECT * FROM images WHERE users_id = ' . $get_user_users_id); foreach ($stmt as $row) { ?>{title: '<?=$row['name']?>', value: '<?=$imgurl?>/image_uploads/<?=$row['src']?>'},<?php } ?>],
                min_height: 250,
                branding: false

How to change owner of PostgreSql database?

Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.


Never use REASSIGN OWNED when the original role is postgres, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)

First, connect to admin database and update DB ownership:

postgres=# REASSIGN OWNED BY old_name TO new_name;

This is a global equivalent of ALTER DATABASE command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.

The next step is to update tables ownership for each database:

psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;

This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.

Module is not available, misspelled or forgot to load (but I didn't)

I had the same error and fixed it. It turned out to be a silly reason.

This was the culprit: <script src="app.js"/>

Fix: <script src="app.js"></script>

Make sure your script tag is ended properly!

How can I replace newline or \r\n with <br/>?

You may have real characters "\" in the string (the single quote strings, as said @Robik).

If you are quite sure the '\r' or '\n' strings should be replaced as well, I'm not talking of special characters here but a sequence of two chars '\' and 'r', then escape the '\' in the replace string and it will work:


iOS - Build fails with CocoaPods cannot find header files

If none of the above worked for you and you are finding this error because you just switched to use_frameworks! in your Podfile, read on:

I tried all the solutions above and a lot more before learning that it isn't about search header paths at all in my particular case; it's that when you switch to use_frameworks! in your Podfile you no longer need to include frameworks in your bridging header, and in fact Xcode will throw the very unhelpful "unable to find header" error.

What you need to do is remove all imports from your bridging header file, and instead use the Swift import Module in your individual Swift files as needed, just like you would for Swift frameworks.

AND if you are using any of the framework headers in your Obj-C classes (in my case we have a convenience class that used the FBSDK) you need to change it from a local to global import (this means change #import "Module.h" to #import <Module/Module.h>, which should autocomplete for you when you begin to type the framework name. In my case it was <AFNetworking/AFHTTPRequestOperationManager.h>).

Edit: I've since learned that doing an @import Module uses the umbrella file which is even safer.

Task<> does not contain a definition for 'GetAwaiter'

I had this problem because I was calling a method

await myClass.myStaticMethod(myString);

but I was setting myString with

var myString = String.Format({some dynamic-type values})

which resulted in a dynamic type, not a string, thus when I tried to await on myClass.myStaticMethod(myString), the compiler thought I meant to call myClass.myStaticMethod(dynamic myString). This compiled fine because, again, in a dynamic context, it's all good until it blows up at run-time, which is what happened because there is no implementation of the dynamic version of myStaticMethod, and this error message didn't help whatsoever, and the fact that Intellisense would take me to the correct definition didn't help either.

However, by forcing the result type to string, like:

var myString = String.Format({some dynamic-type values})


string myString = String.Format({some dynamic-type values})

my call to myStaticMethod routed properly

Determining the path that a yum package installed to

yum uses RPM, so the following command will list the contents of the installed package:

$ rpm -ql package-name