Programs & Examples On #Netnamedpipebinding

Catch an exception thrown by an async void method

The reason the exception is not caught is because the Foo() method has a void return type and so when await is called, it simply returns. As DoFoo() is not awaiting the completion of Foo, the exception handler cannot be used.

This opens up a simpler solution if you can change the method signatures - alter Foo() so that it returns type Task and then DoFoo() can await Foo(), as in this code:

public async Task Foo() {
    var x = await DoSomethingThatThrows();
}

public async void DoFoo() {
    try {
        await Foo();
    } catch (ProtocolException ex) {
        // This will catch exceptions from DoSomethingThatThrows
    }
}

How to keep keys/values in same order as declared?

From Python 3.6 onwards, the standard dict type maintains insertion order by default.

Defining

d = {'ac':33, 'gw':20, 'ap':102, 'za':321, 'bs':10}

will result in a dictionary with the keys in the order listed in the source code.

This was achieved by using a simple array with integers for the sparse hash table, where those integers index into another array that stores the key-value pairs (plus the calculated hash). That latter array just happens to store the items in insertion order, and the whole combination actually uses less memory than the implementation used in Python 3.5 and before. See the original idea post by Raymond Hettinger for details.

In 3.6 this was still considered an implementation detail; see the What's New in Python 3.6 documentation:

The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).

Python 3.7 elevates this implementation detail to a language specification, so it is now mandatory that dict preserves order in all Python implementations compatible with that version or newer. See the pronouncement by the BDFL. As of Python 3.8, dictionaries also support iteration in reverse.

You may still want to use the collections.OrderedDict() class in certain cases, as it offers some additional functionality on top of the standard dict type. Such as as being reversible (this extends to the view objects), and supporting reordering (via the move_to_end() method).

Best way to pass parameters to jQuery's .load()

In the first case, the data are passed to the script via GET, in the second via POST.

http://docs.jquery.com/Ajax/load#urldatacallback

I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.

Efficient way to do batch INSERTS with JDBC

SQLite: The above answers are all correct. For SQLite, it is a little bit different. Nothing really helps, even to put it in a batch is (sometimes) not improving performance. In that case, try to disable auto-commit and commit by hand after you are done (Warning! When multiple connections write at the same time, you can clash with these operations)

// connect(), yourList and compiledQuery you have to implement/define beforehand
try (Connection conn = connect()) {
     conn.setAutoCommit(false);
     preparedStatement pstmt = conn.prepareStatement(compiledQuery);
     for(Object o : yourList){
        pstmt.setString(o.toString());
        pstmt.executeUpdate();
        pstmt.getGeneratedKeys(); //if you need the generated keys
     }
     pstmt.close();
     conn.commit();

}

XPath: select text node

Having the following XML:

<node>Text1<subnode/>text2</node> 

How do I select either the first or the second text node via XPath?

Use:

/node/text()

This selects all text-node children of the top element (named "node") of the XML document.

/node/text()[1]

This selects the first text-node child of the top element (named "node") of the XML document.

/node/text()[2]

This selects the second text-node child of the top element (named "node") of the XML document.

/node/text()[someInteger]

This selects the someInteger-th text-node child of the top element (named "node") of the XML document. It is equivalent to the following XPath expression:

/node/text()[position() = someInteger]

How to check if a string contains text from an array of substrings in JavaScript?

building on T.J Crowder's answer

using escaped RegExp to test for "at least once" occurrence, of at least one of the substrings.

_x000D_
_x000D_
function buildSearch(substrings) {_x000D_
  return new RegExp(_x000D_
    substrings_x000D_
    .map(function (s) {return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');})_x000D_
    .join('{1,}|') + '{1,}'_x000D_
  );_x000D_
}_x000D_
_x000D_
_x000D_
var pattern = buildSearch(['hello','world']);_x000D_
_x000D_
console.log(pattern.test('hello there'));_x000D_
console.log(pattern.test('what a wonderful world'));_x000D_
console.log(pattern.test('my name is ...'));
_x000D_
_x000D_
_x000D_

How to use Object.values with typescript?

using Object.keys instead.

const data = {
  a: "first",
  b: "second",
};

const values = Object.keys(data).map(key => data[key]);

const commaJoinedValues = values.join(",");
console.log(commaJoinedValues);

wget ssl alert handshake failure

One alternative is to replace the "https" with "http" in the url that you're trying to download from to just circumvent the SSL connection. Not the most secure solution, but this worked in my case.

Datatype for storing ip address in SQL Server

I'm using varchar(15) so far everything is working for me. Insert, Update, Select. I have just started an app that has IP Addresses, though I have not done much dev work yet.

Here is the select statement:

select * From dbo.Server 
where  [IP] = ('132.46.151.181')
Go

How could I convert data from string to long in c#

long l1 = Convert.ToInt64(strValue);

That should do it.

How to get an Instagram Access Token

go to manage clinet page in :

http://www.instagram.com/developer/

set a redirect url

then :

use this code to get access token :

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>tst</title>
<script src="../jq.js"></script>
<script type="text/javascript">
       $.ajax({
            type: 'GET',
            url: 'https://api.instagram.com/oauth/authorize/?client_id=CLIENT-??ID&redirect_uri=REDI?RECT-URI&response_ty?pe=code'
            dataType: 'jsonp'}).done(function(response){
                var access = window.location.hash.substring(14);
                //you have access token in access var   
            });
</script>
</head>
<body>  
</body>
</html>

Remove stubborn underline from link

The anchor tag (link) also has pseudo-classes such as visited, hover, link and active. Make sure your style is applied to the state(s) in question and that no other styles are conflicting.

For example:

a:hover, a:visited, a:link, a:active
{
    text-decoration: none;
}

See W3.org for more information on user action pseudo-classes :hover, :active, and :focus.

Delete all rows in table

As other have said, TRUNCATE TABLE is far quicker, but it does have some restrictions (taken from here):

You cannot use TRUNCATE TABLE on tables that:

- Are referenced by a FOREIGN KEY constraint. (You can truncate a table that has a foreign key that references itself.)
- Participate in an indexed view.
- Are published by using transactional replication or merge replication.

For tables with one or more of these characteristics, use the DELETE statement instead.

The biggest drawback is that if the table you are trying to empty has foreign keys pointing to it, then the truncate call will fail.

MySQL limit from descending order

No, you shouldn't do this. Without an ORDER BY clause you shouldn't rely on the order of the results being the same from query to query. It might work nicely during testing but the order is indeterminate and could break later. Use an order by.

SELECT * FROM table1 ORDER BY id LIMIT 5

By the way, another way of getting the last 3 rows is to reverse the order and select the first three rows:

SELECT * FROM table1 ORDER BY id DESC LIMIT 3

This will always work even if the number of rows in the result set isn't always 8.

How do I pull from a Git repository through an HTTP proxy?

As this was answered by many but This is just for Winodws USER who is behind proxy with auth.

Re-Installing(first failed, Don't remove).

Goto ->
**Windows**
1. msysgit\installer-tmp\etc\gitconfig
    Under [http]
        proxy = http://user:pass@url:port

**Linux**
1. msysgit\installer-tmp\setup-msysgit.sh
      export HTTP_PROXY="http://USER:[email protected]:8080"

if you have any special char in user/pass use url_encode

ADB Driver and Windows 8.1

There is lots of stuff on this topic, each slightly different. Like many users I spent hours trying them and got nowhere. In the end, this is what worked for me - I.e. installed the driver on windows 8.1

In my extras/google/usb_driver is a file android_winusb.inf

I double clicked on this and it "ran" and installed the driver.

I can't explain why this worked.

Android file chooser

EDIT (02 Jan 2012):

I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.

You can find it at GitHub: aFileChooser.


ORIGINAL

If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser() like this:

private static final int FILE_SELECT_CODE = 0;

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("*/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", 
                Toast.LENGTH_SHORT).show();
    }
}

You would then listen for the selected file's Uri in onActivityResult() like so:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case FILE_SELECT_CODE:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file 
            Uri uri = data.getData();
            Log.d(TAG, "File Uri: " + uri.toString());
            // Get the path
            String path = FileUtils.getPath(this, uri);
            Log.d(TAG, "File Path: " + path);
            // Get the file instance
            // File file = new File(path);
            // Initiate the upload
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

The getPath() method in my FileUtils.java is:

public static String getPath(Context context, Uri uri) throws URISyntaxException {
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;

        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            // Eat it
        }
    }
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
} 

Gradle Sync failed could not find constraint-layout:1.0.0-alpha2

I updated my android gradle plugin to 2.2.0-alpha4 and constraint layout dependency to 1.0.0-alpha3 and it seems to be working now

Event when window.location.href changes

popstate event:

The popstate event is fired when the active history entry changes. [...] The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript)

So, listening to popstate event and sending a popstate event when using history.pushState() should be enough to take action on href change:

window.addEventListener('popstate', listener);

const pushUrl = (href) => {
  history.pushState({}, '', href);
  window.dispatchEvent(new Event('popstate'));
};

How to link to specific line number on github

a permalink to a code snippet is pasted into a pull request comment field

You can you use permalinks to include code snippets in issues, PRs, etc.

References:

https://help.github.com/en/articles/creating-a-permanent-link-to-a-code-snippet

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

C# compiler error: "not all code paths return a value"

The compiler doesn't get the intricate logic where you return in the last iteration of the loop, so it thinks that you could exit out of the loop and end up not returning anything at all.

Instead of returning in the last iteration, just return true after the loop:

public static bool isTwenty(int num) {
  for(int j = 1; j <= 20; j++) {
    if(num % j != 0) {
      return false;
    }
  }
  return true;
}

Side note, there is a logical error in the original code. You are checking if num == 20 in the last condition, but you should have checked if j == 20. Also checking if num % j == 0 was superflous, as that is always true when you get there.

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

A pitfall some might step into that is covered by this question but isn't addressed in the answers as it is slightly different in the code structure but returns the exact same error.

This error occurs when using bindActionCreators and not passing the dispatch function

Error Code

import someComponent from './someComponent'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { someAction } from '../../../actions/someAction'

const mapStatToProps = (state) => {
    const { someState } = state.someState

    return {
        someState
    }
};

const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({
        someAction
    });
};

export default connect(mapStatToProps, mapDispatchToProps)(someComponent)

Fixed Code

import someComponent from './someComponent'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { someAction } from '../../../actions/someAction'

const mapStatToProps = (state) => {
    const { someState } = state.someState

    return {
        someState
    }
};

const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({
        someAction
    }, dispatch);
};

export default connect(mapStatToProps, mapDispatchToProps)(someComponent)

The function dispatch was missing in the Error code

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

On Windows 7,64 bit,the above solution (Onur Turhan's) worked for me with slight changes as below

C:\Users\MyName > heroku login

Enter email/password

C:\Users\MyName >ssh-keygen -t rsa -f id_rsa

This generated two files(id_rsa and id_rsa.pub) in my c:\Users\MyName directory (Not in .ssh directory)

heroku keys:add id_rsa.pub
git clone [email protected]:some-heiku-xxxx.git -o heroku

I guess adding the correct "id_rsa.pub" file is the most important.After generating the public key using keygen just verify that you are adding correct key by looking at the time-stamp when it was created.

Confused about Service vs Factory

I had this confusion for a while and I'm trying my best to provide a simple explanation here. Hope this will help!

angular .factory and angular .service both are used to initialize a service and work in the same way.

The only difference is, how you want to initialize your service.

Both are Singletons


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


Factory

app.factory(<service name>, <function with a return value>)

If you would like to initialize your service from a function that you have with a return value, you have to use this factory method.

e.g.

function myService() {
  //return what you want
  var service = {
    myfunc: function (param) { /* do stuff */ }
  }
  return service;
}

app.factory('myService', myService);

When injecting this service (e.g. to your controller):

  • Angular will call your given function (as myService()) to return the object
  • Singleton - called only once, stored, and pass the same object.


Service

app.service(<service name>, <constructor function>)

If you would like to initialize your service from a constructor function (using this keyword), you have to use this service method.

e.g.

function myService() {
  this.myfunc: function (param) { /* do stuff */ }
}

app.service('myService', myService);

When injecting this service (e.g. to your controller):

  • Angular will newing your given function (as new myService()) to return the object
  • Singleton - called only once, stored, and pass the same object.


NOTE: If you use factory with <constructor function> or service with <function with a return value>, it will not work.


Examples - DEMOs

How can I make a "color map" plot in matlab?

I also suggest using contourf(Z). For my problem, I wanted to visualize a 3D histogram in 2D, but the contours were too smooth to represent a top view of histogram bars.

So in my case, I prefer to use jucestain's answer. The default shading faceted of pcolor() is more suitable. However, pcolor() does not use the last row and column of the plotted matrix. For this, I used the padarray() function:

pcolor(padarray(Z,[1 1],0,'post'))

Sorry if that is not really related to the original post

Cannot make file java.io.IOException: No such file or directory

i fixed my problem by this code on linux file system

if (!file.exists())
    Files.createFile(file.toPath());

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

To get the value of my drop down box on page load, I use

document.addEventListener('DOMContentLoaded',fnName);

Hope this helps some one.

Efficiently finding the last line in a text file

Seek to the end of the file minus 100 bytes or so. Do a read and search for a newline. If here is no newline, seek back another 100 bytes or so. Lather, rinse, repeat. Eventually you'll find a newline. The last line begins immediately after that newline.

Best case scenario you only do one read of 100 bytes.

Is there 'byte' data type in C++?

Yes, there is std::byte (defined in <cstddef>).

C++ 17 introduced it.

Difference between static, auto, global and local variable in the context of c and c++

static is a heavily overloaded word in C and C++. static variables in the context of a function are variables that hold their values between calls. They exist for the duration of the program.

local variables persist only for the lifetime of a function or whatever their enclosing scope is. For example:

void foo()
{
    int i, j, k;
    //initialize, do stuff
} //i, j, k fall out of scope, no longer exist

Sometimes this scoping is used on purpose with { } blocks:

{ 
   int i, j, k;
   //...
} //i, j, k now out of scope

global variables exist for the duration of the program.

auto is now different in C and C++. auto in C was a (superfluous) way of specifying a local variable. In C++11, auto is now used to automatically derive the type of a value/expression.

Jquery split function

Try this. It uses the split function which is a core part of javascript, nothing to do with jQuery.

var parts = html.split(":-"),
    i, l
;
for (i = 0, l = parts.length; i < l; i += 2) {
    $("#" + parts[i]).text(parts[i + 1]);
}

Check image width and height before upload with Javascript

You can do the steps for previewing the image without showing it which is supported on all browsers. Following js code shows you how to check the width and height :

var file = e.target.files[0];
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
    var reader = new FileReader();
    reader.addEventListener("load", function () {
        var image = new Image();
        image.src = this.result as string;
        image.addEventListener('load', function () {
            console.log(`height: ${this.height}, width: ${this.width}`);
        });
                
    }, false);
            
    reader.readAsDataURL(file);
}

Based on Mozilla docs:

The readAsDataURL method is used to read the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.

And the browser compatibility is listed too.

HTML entity for the middle dot

This can be done easily using &middot;. You can color or size the dot according to the tags you wrap it with. For example, try and run this

<h2> I &middot; love &middot; Coding </h2>

Importing a CSV file into a sqlite3 database table using Python

My 2 cents (more generic):

import csv, sqlite3
import logging

def _get_col_datatypes(fin):
    dr = csv.DictReader(fin) # comma is default delimiter
    fieldTypes = {}
    for entry in dr:
        feildslLeft = [f for f in dr.fieldnames if f not in fieldTypes.keys()]
        if not feildslLeft: break # We're done
        for field in feildslLeft:
            data = entry[field]

            # Need data to decide
            if len(data) == 0:
                continue

            if data.isdigit():
                fieldTypes[field] = "INTEGER"
            else:
                fieldTypes[field] = "TEXT"
        # TODO: Currently there's no support for DATE in sqllite

    if len(feildslLeft) > 0:
        raise Exception("Failed to find all the columns data types - Maybe some are empty?")

    return fieldTypes


def escapingGenerator(f):
    for line in f:
        yield line.encode("ascii", "xmlcharrefreplace").decode("ascii")


def csvToDb(csvFile, outputToFile = False):
    # TODO: implement output to file

    with open(csvFile,mode='r', encoding="ISO-8859-1") as fin:
        dt = _get_col_datatypes(fin)

        fin.seek(0)

        reader = csv.DictReader(fin)

        # Keep the order of the columns name just as in the CSV
        fields = reader.fieldnames
        cols = []

        # Set field and type
        for f in fields:
            cols.append("%s %s" % (f, dt[f]))

        # Generate create table statement:
        stmt = "CREATE TABLE ads (%s)" % ",".join(cols)

        con = sqlite3.connect(":memory:")
        cur = con.cursor()
        cur.execute(stmt)

        fin.seek(0)


        reader = csv.reader(escapingGenerator(fin))

        # Generate insert statement:
        stmt = "INSERT INTO ads VALUES(%s);" % ','.join('?' * len(cols))

        cur.executemany(stmt, reader)
        con.commit()

    return con

Open terminal here in Mac OS finder

If you install Big Cat Scripts (http://www.ranchero.com/bigcat/) you can add your own contextual menu (right click) items. I don't think it comes with an Open Terminal Here applescript but I use this script (which I don't honestly remember if I wrote myself, or lifted from someone else's example):


on main(filelist)
    tell application "Finder"
        try
            activate
            set frontWin to folder of front window as string
            set frontWinPath to (get POSIX path of frontWin)
            tell application "Terminal"
                activate
                do script with command "cd \"" & frontWinPath & "\""
            end tell
        on error error_message
            beep
            display dialog error_message buttons ¬
                {"OK"} default button 1
        end try
    end tell
end main

Similar scripts can also get you the complete path to a file on right-click, which is even more useful, I find.

Turning off eslint rule for a specific line

You can also disable a specific rule/rules (rather than all) by specifying them in the enable (open) and disable (close) blocks:

/* eslint-disable no-alert, no-console */

alert('foo');
console.log('bar');

/* eslint-enable no-alert */

via @goofballMagic's link above: http://eslint.org/docs/user-guide/configuring.html#configuring-rules

Stop a youtube video with jquery?

I was facing the same problem. After a lot of alternatives what I did was just reset the embed src="" with the same URL.

Code snippet:

  $("#videocontainer").fadeOut(200);<br/>
  $("#videoplayer").attr("src",videoURL);

I was able to at least stop the video from playing when I hide it.:-)

C - gettimeofday for computing time?

No. gettimeofday should NEVER be used to measure time.

This is causing bugs all over the place. Please don't add more bugs.

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

How do I run a terminal inside of Vim?

I know that I'm not directly answering the question, but I think it's a good approach. Nobody has mentioned tmux (or at least not as a standalone answer). Tmux is a terminal multiplexor like screen. Most stuff can be made in both multiplexors, but afaik tmux it's more easily to configure. Also tmux right now is being more actively developed than screen and there's quite a big ecosystem around it, like tools that help the configuration, ecc.

Also for vim, there's another plugin: ViMUX, that helps a lot in the interaction between both tools. You can call commands with:

:call VimuxRunCommand("ls")

That command creates a small horizontal split below the current pane vim is in.

It can also let you run from a prompt in case you don't want to run the whole command:

<Leader>vp :VimuxPromptCommand<CR>

As it weren't enought, there are at least 6 'platform specific plugins':

Here is a nice "use case": Tests on demand using Vimux and Turbux with Spork and Guard

Javascript event handler with parameters

Short answer:

x.addEventListener("click", function(e){myfunction(e, param1, param2)});

... 

function myfunction(e, param1, param1) {
    ... 
} 

CSS vertical-align: text-bottom;

To use vertical-align properly, you should do it on table tag. But there is a way to make other html tags to behave as a table by assigning them a css of display:table to your parent, and display:table-cell on your child. Then vertical-align:bottom will work on that child.

HTML:

??????<div class="parent">
    <div class="child">
        This text is vertically aligned to bottom.    
    </div>
</div>????????????????????????

CSS:

?.parent {
    width: 300px;
    height: 50px;
    display:? table;
    border: 1px solid red;
}
.child { 
    display: table-cell;
    vertical-align: bottom;
}?

Here is a live example: link demo

React onClick function fires on render

For those not using arrow functions but something simpler ... I encountered this when adding parentheses after my signOut function ...

replace this <a onClick={props.signOut()}>Log Out</a>

with this <a onClick={props.signOut}>Log Out</a> ... !

CSS3 opacity gradient?

You can do it in CSS, but there isn't much support in browsers other than modern versions of Chrome, Safari and Opera at the moment. Firefox currently only supports SVG masks. See the Caniuse results for more information.

CSS:

p {
    color: red;
    -webkit-mask-image: -webkit-gradient(linear, left top, left bottom, 
    from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
}

The trick is to specify a mask that is itself a gradient that ends as invisible (thru alpha value)

See a demo with a solid background, but you can change this to whatever you want.

DEMO

Notice also that all the usual image properties are available for mask-image

_x000D_
_x000D_
p  {_x000D_
  color: red;_x000D_
  font-size: 30px;_x000D_
  -webkit-mask-image: linear-gradient(to left, rgba(0,0,0,1), rgba(0,0,0,0)), linear-gradient(to right, rgba(0,0,0,1), rgba(0,0,0,0));_x000D_
  -webkit-mask-size: 100% 50%;_x000D_
  -webkit-mask-repeat: no-repeat;_x000D_
  -webkit-mask-position: left top, left bottom;_x000D_
  }_x000D_
_x000D_
div {_x000D_
    background-color: lightblue;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
_x000D_
_x000D_

Now, another approach is available, that is supported by Chrome, Firefox, Safari and Opera.

The idea is to use

mix-blend-mode: hard-light;

that gives transparency if the color is gray. Then, a grey overlay on the element creates the transparency

_x000D_
_x000D_
div {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
_x000D_
p {_x000D_
  color: red;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
  width: 200px;_x000D_
  mix-blend-mode: hard-light;_x000D_
}_x000D_
_x000D_
p::after {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
  left: 0px;_x000D_
  top: 0px;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(transparent, gray);_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
_x000D_
_x000D_

How do I insert values into a Map<K, V>?

The two errors you have in your code are very different.

The first problem is that you're initializing and populating your Map in the body of the class without a statement. You can either have a static Map and a static {//TODO manipulate Map} statement in the body of the class, or initialize and populate the Map in a method or in the class' constructor.

The second problem is that you cannot treat a Map syntactically like an array, so the statement data["John"] = "Taxi Driver"; should be replaced by data.put("John", "Taxi Driver"). If you already have a "John" key in your HashMap, its value will be replaced with "Taxi Driver".

Add a column to a table, if it does not already exist

Here's another variation that worked for me.

IF NOT EXISTS (SELECT 1
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE upper(TABLE_NAME) = 'TABLENAME'
        AND upper(COLUMN_NAME) = 'COLUMNNAME')
BEGIN
    ALTER TABLE [dbo].[Person] ADD Column
END
GO

EDIT: Note that INFORMATION_SCHEMA views may not always be updated, use SYS.COLUMNS instead:

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS....

Nested lists python

Try this setup:

a = [["a","b","c",],["d","e"],["f","g","h"]]

To print the 2nd element in the 1st list ("b"), use print a[0][1] - For the 2nd element in 3rd list ("g"): print a[2][1]

The first brackets reference which nested list you're accessing, the second pair references the item in that list.

Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic

The error Cannot find module '../lib/utils/unsupported.js' is caused by require('../lib/utils/unsupported.js') in ./lib/node_modules/npm/bin/npm-cli.js.

According to the nodejs require docs, the required module is searched relative to the file, as it starts with ../.

Thus, if we take the relative path ../lib/utils/unsupported.js starting from ./lib/node_modules/npm/bin/npm-cli.js, the required module must reside in ./lib/node_modules/npm/lib/utils/unsupported.js. If it is not there, I see two options:

  • the installation is corrupt, in which case Vincent Ducastel's answer to reinstall node might work
  • npm is no symlink to ./lib/node_modules/npm/bin/npm-cli.js. This is what caused the error in my setup. If you call npm, it will typically find it be searching it in the directories listed in the PATH env var. It might for example be located in ./bin. However, npm in a ./bin directory should only be a symlink to the aforementioned ./lib/node_modules/npm/bin/npm-cli.js. If it is not a symlink but directly contains the code, somewhere in the installation process the symlink got replaced by the file it links to. In this case, it should be sufficient to recreate the symlink: cd ./bin; rm npm; ln -s ../lib/node_modules/npm/bin/npm-cli.js npm (update: command fixed, thx @massimo)

All answers that suggest to check the NODE_PATH or the npmrc config should be ignored, as these are not considered when searching modules relatively.

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

How to inspect FormData?

  function abc(){ 
    var form = $('#form_name')[0]; 
        var formData = new FormData(form);
        for (var [key, value] of formData.entries()) { 
            console.log(key, value);
        }
        $.ajax({
            type: "POST",
            url: " ",
            data:  formData,
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function() {

            },
            success: function(data) {


            },

       });
}

JAVA_HOME is set to an invalid directory:

I found this while googling the issue with android licences when installing Flutter.

For Linux, update Your ~/.bashrc (or other shell config) file by adding this line at the end:

JAVA_HOME=/usr/local/android-studio/jre

Note: I installed Android studio by following the official installation guide for Linux (link).

For Windows, use the android studio's path to the jre directory and update the environment variable with the right value.

Then, run flutter doctor --android-licenses and press y to review the licences which are not accepted. Press y for each of the licences. It will ask Accept? (y/N): at the end of the license file. After You accept all unaccepted licences, You should see:

All SDK package licenses accepted

Forward request headers from nginx proxy server

The problem is that '_' underscores are not valid in header attribute. If removing the underscore is not an option you can add to the server block:

underscores_in_headers on;

This is basically a copy and paste from @kishorer747 comment on @Fleshgrinder answer, and solution is from: https://serverfault.com/questions/586970/nginx-is-not-forwarding-a-header-value-when-using-proxy-pass/586997#586997

I added it here as in my case the application behind nginx was working perfectly fine, but as soon ngix was between my flask app and the client, my flask app would not see the headers any longer. It was kind of time consuming to debug.

Output ("echo") a variable to a text file

Your sample code seems to be OK. Thus, the root problem needs to be dug up somehow. Let's eliminate chance for typos in the script. First off, make sure you put Set-Strictmode -Version 2.0 in the beginning of your script. This will help you to catch misspelled variable names. Like so,

# Test.ps1
set-strictmode -version 2.0 # Comment this line and no error will be reported.
$foo = "bar"
set-content -path ./test.txt -value $fo # Error! Should be "$foo"

PS C:\temp> .\test.ps1
The variable '$fo' cannot be retrieved because it has not been set.
At C:\temp\test.ps1:3 char:40
+ set-content -path ./test.txt -value $fo <<<<
    + CategoryInfo          : InvalidOperation: (fo:Token) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined

The next part about question marks sounds like you have a problem with Unicode. What's the output when you type the file with Powershell like so,

$file = "\\server\share\file.txt"
cat $file

Pinging an IP address using PHP and echoing the result

This works fine with hostname, reverse IP (for internal networks) and IP.

function pingAddress($ip) {
    $ping = exec("ping -n 2 $ip", $output, $status);
    if (strpos($output[2], 'unreachable') !== FALSE) {
        return '<span style="color:#f00;">OFFLINE</span>';
    } else {
        return '<span style="color:green;">ONLINE</span>';
    }
}

echo pingAddress($ip);

Using setTimeout to delay timing of jQuery actions

.html() only takes a string OR a function as an argument, not both. Try this:

 $("#showDiv").click(function () {
     $('#theDiv').show(1000, function () {
         setTimeout(function () {
             $('#theDiv').html(function () {
                 setTimeout(function () {
                     $('#theDiv').html('Here is some replacement text');
                 }, 0);
                 setTimeout(function () {
                     $('#theDiv').html('More replacement text goes here');
                 }, 2500);
             });
         }, 2500);
     });
 }); //click function ends

jsFiddle example

Position a div container on the right side

Is this what you wanted? - http://jsfiddle.net/jomanlk/x5vyC/3/

Floats on both sides now

#wrapper{
    background:red;
    overflow:auto;
}

#c1{
   float:left;
   background:blue;
}

#c2{
    background:green;
    float:right;
}?

<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>
</div>?

What is the '.well' equivalent class in Bootstrap 4

Looking for a one line option:

    <div class="jumbotron bg-dark"> got a team? </div>        

https://getbootstrap.com/docs/4.0/components/jumbotron/

How do I align a label and a textarea?

You need to put them both in some container element and then apply the alignment on it.

For example:

_x000D_
_x000D_
.formfield * {_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<p class="formfield">_x000D_
  <label for="textarea">Label for textarea</label>_x000D_
  <textarea id="textarea" rows="5">Textarea</textarea>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Changing fonts in ggplot2

Late to the party, but this might be of interest for people looking to add custom fonts to their ggplots inside a shiny app on shinyapps.io.

You can:

  1. Place custom font in www directory: e.g. IndieFlower.ttf from here
  2. Follow the steps from here

This leads to the following upper section inside the app.R file:

dir.create('~/.fonts')
file.copy("www/IndieFlower.ttf", "~/.fonts")
system('fc-cache -f ~/.fonts')

A full example app can be found here.

Xcode 5 and iOS 7: Architecture and Valid architectures

You do not need to limit your compiler to only armv7 and armv7s by removing arm64 setting from supported architectures. You just need to set Deployment target setting to 5.1.1

Important note: you cannot set Deployment target to 5.1.1 in Build Settings section because it is drop-down only with fixed values. But you can easily set it to 5.1.1 in General section of application settings by just typing the value in text field.

SQL Inner-join with 3 tables?

SELECT table1.col,table2.col,table3.col 
FROM table1 
INNER JOIN 
(table2 INNER JOIN table3 
ON table3.id=table2.id) 
ON table1.id(f-key)=table2.id
AND //add any additional filters HERE

How to get the week day name from a date?

SQL> SELECT TO_CHAR(date '1982-03-09', 'DAY') day FROM dual;

DAY
---------
TUESDAY

SQL> SELECT TO_CHAR(date '1982-03-09', 'DY') day FROM dual;

DAY
---
TUE

SQL> SELECT TO_CHAR(date '1982-03-09', 'Dy') day FROM dual;

DAY
---
Tue

(Note that the queries use ANSI date literals, which follow the ISO-8601 date standard and avoid date format ambiguity.)

Equivalent of Oracle's RowID in SQL Server

I have to dedupe a very big table with many columns and speed is important. Thus I use this method which works for any table:

delete T from 
(select Row_Number() Over(Partition By BINARY_CHECKSUM(*) order by %%physloc%% ) As RowNumber, * From MyTable) T
Where T.RowNumber > 1

Jquery, Clear / Empty all contents of tbody element?

Without use ID (<tbody id="tbodyid">) , it is a great way to cope with this issue

$('#table1').find("tr:gt(0)").remove();

PS:To remove specific row number as following example

$('#table1 tr').eq(1).remove();

or

$('#tr:nth-child(2)').remove();

Cannot attach the file *.mdf as database

Remove this line from the connection string that should do it ;) "AttachDbFilename=|DataDirectory|whateverurdatabasenameis-xxxxxxxxxx.mdf"

How to implement a read only property

C# 6.0 adds readonly auto properties

public object MyProperty { get; }

So when you don't need to support older compilers you can have a truly readonly property with code that's just as concise as a readonly field.


Versioning:
I think it doesn't make much difference if you are only interested in source compatibility.
Using a property is better for binary compatibility since you can replace it by a property which has a setter without breaking compiled code depending on your library.

Convention:
You are following the convention. In cases like this where the differences between the two possibilities are relatively minor following the convention is better. One case where it might come back to bite you is reflection based code. It might only accept properties and not fields, for example a property editor/viewer.

Serialization
Changing from field to property will probably break a lot of serializers. And AFAIK XmlSerializer does only serialize public properties and not public fields.

Using an Autoproperty
Another common Variation is using an autoproperty with a private setter. While this is short and a property it doesn't enforce the readonlyness. So I prefer the other ones.

Readonly field is selfdocumenting
There is one advantage of the field though:
It makes it clear at a glance at the public interface that it's actually immutable (barring reflection). Whereas in case of a property you can only see that you cannot change it, so you'd have to refer to the documentation or implementation.

But to be honest I use the first one quite often in application code since I'm lazy. In libraries I'm typically more thorough and follow the convention.

How to set the authorization header using curl

Be careful that when you using: curl -H "Authorization: token_str" http://www.example.com

token_str and Authorization must be separated by white space, otherwise server-side will not get the HTTP_AUTHORIZATION environment.

Why does "return list.sort()" return None, not the list?

Here is an email from Guido van Rossum in Python's dev list explaining why he choose not to return self on operations that affects the object and don't return a new one.

This comes from a coding style (popular in various other languages, I believe especially Lisp revels in it) where a series of side effects on a single object can be chained like this:

 x.compress().chop(y).sort(z)

which would be the same as

  x.compress()
  x.chop(y)
  x.sort(z)

I find the chaining form a threat to readability; it requires that the reader must be intimately familiar with each of the methods. The second form makes it clear that each of these calls acts on the same object, and so even if you don't know the class and its methods very well, you can understand that the second and third call are applied to x (and that all calls are made for their side-effects), and not to something else.

I'd like to reserve chaining for operations that return new values, like string processing operations:

 y = x.rstrip("\n").split(":").lower()

Generate random array of floats between a range

Why not use a list comprehension?

In Python 2

ran_floats = [random.uniform(low,high) for _ in xrange(size)]

In Python 3, range works like xrange(ref)

ran_floats = [random.uniform(low,high) for _ in range(size)]

Base 64 encode and decode example code

To anyone else who ended up here while searching for info on how to decode a string encoded with Base64.encodeBytes(), here was my solution:

// encode
String ps = "techPass";
String tmp = Base64.encodeBytes(ps.getBytes());

// decode
String ps2 = "dGVjaFBhC3M=";
byte[] tmp2 = Base64.decode(ps2); 
String val2 = new String(tmp2, "UTF-8"); 

Also, I'm supporting older versions of Android so I'm using Robert Harder's Base64 library from http://iharder.net/base64

Where does VBA Debug.Print log to?

Where do you want to see the output?

Messages being output via Debug.Print will be displayed in the immediate window which you can open by pressing Ctrl+G.

You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar

enter image description here

String concatenation in MySQL

Use concat() function instead of + like this:

select concat(firstname, lastname) as "Name" from test.student

ProgressDialog spinning circle

Try this.........

ProgressDialog pd1;
pd1=new ProgressDialog(<current context reference here>);
pd1.setMessage("Loading....");
pd1.setCancelable(false);
pd1.show();

To dismiss....

if(pd1!=null)
 pd1.dismiss(); 

Python: SyntaxError: non-keyword after keyword arg

To really get this clear, here's my for-beginners answer: You inputed the arguments in the wrong order.
A keyword argument has this style:

nullable=True, unique=False

A fixed parameter should be defined: True, False, etc. A non-keyword argument is different:

name="Ricardo", fruit="chontaduro" 

This syntax error asks you to first put name="Ricardo" and all of its kind (non-keyword) before those like nullable=True.

Two arrays in foreach loop

array_combine() worked great for me while combining $_POST multiple values from multiple form inputs in an attempt to update products quantities in a shopping cart.

Render basic HTML view?

app.get('/', function (req, res) {
res.sendfile(__dirname + '/public/index.html');
});

Converting file size in bytes to human-readable string

For those who use Angular, there's a package called angular-pipes that has a pipe for this:

File

import { BytesPipe } from 'angular-pipes';

Usage

{{ 150 | bytes }} <!-- 150 B -->
{{ 1024 | bytes }} <!-- 1 KB -->
{{ 1048576 | bytes }} <!-- 1 MB -->
{{ 1024 | bytes: 0 : 'KB' }} <!-- 1 MB -->
{{ 1073741824 | bytes }} <!-- 1 GB -->
{{ 1099511627776 | bytes }} <!-- 1 TB -->
{{ 1073741824 | bytes : 0 : 'B' : 'MB' }} <!-- 1024 MB -->

Link to the docs.

Using PHP variables inside HTML tags?

There's a shorthand-type way to do this that I have been using recently. This might need to be configured, but it should work in most mainline PHP installations. If you're storing the link in a PHP variable, you can do it in the following manner based off the OP:

<html>
  <body>
    <?php
      $link = "http://www.google.com";
    ?>
    <a href="<?= $link ?>">Click here to go to Google.</a>
  </body>
</html>

This will evaluate the variable as a string, in essence shorthand for echo $link;

mySQL convert varchar to date

As gratitude to the timely help I got from here - a minor update to above.

$query = "UPDATE `db`.`table` SET `fieldname`=  str_to_date(  fieldname, '%d/%m/%Y')";

throw checked Exceptions from mocks with Mockito

Check the Java API for List.
The get(int index) method is declared to throw only the IndexOutOfBoundException which extends RuntimeException.
You are trying to tell Mockito to throw an exception SomeException() that is not valid to be thrown by that particular method call.

To clarify further.
The List interface does not provide for a checked Exception to be thrown from the get(int index) method and that is why Mockito is failing.
When you create the mocked List, Mockito will use the definition of List.class to creates its mock.

The behavior you are specifying with the when(list.get(0)).thenThrow(new SomeException()) doesn't match the method signature in List API, because get(int index) method does not throw SomeException() so Mockito fails.

If you really want to do this, then have Mockito throw a new RuntimeException() or even better throw a new ArrayIndexOutOfBoundsException() since the API specifies that that is the only valid Exception to be thrown.

Comparing Java enum members: == or equals()?

In short, both have pros and cons.

On one hand, it has advantages to use ==, as described in the other answers.

On the other hand, if you for any reason replace the enums with a different approach (normal class instances), having used == bites you. (BTDT.)

How can I do an asc and desc sort using underscore.js?

The Array prototype's reverse method modifies the array and returns a reference to it, which means you can do this:

var sortedAsc = _.sortBy(collection, 'propertyName');
var sortedDesc = _.sortBy(collection, 'propertyName').reverse();

Also, the underscore documentation reads:

In addition, the Array prototype's methods are proxied through the chained Underscore object, so you can slip a reverse or a push into your chain, and continue to modify the array.

which means you can also use .reverse() while chaining:

var sortedDescAndFiltered = _.chain(collection)
    .sortBy('propertyName')
    .reverse()
    .filter(_.property('isGood'))
    .value();

Markdown `native` text alignment

In order to center text in md files you can use the center tag like html tag:

<center>Centered text</center>

How to remove list elements in a for loop in Python?

Probably a bit late to answer this but I just found this thread and I had created my own code for it previously...

    list = [1,2,3,4,5]
    deleteList = []
    processNo = 0
    for item in list:
        if condition:
            print item
            deleteList.insert(0, processNo)
        processNo += 1

    if len(deleteList) > 0:
        for item in deleteList:
            del list[item]

It may be a long way of doing it but seems to work well. I create a second list that only holds numbers that relate to the list item to delete. Note the "insert" inserts the list item number at position 0 and pushes the remainder along so when deleting the items, the list is deleted from the highest number back to the lowest number so the list stays in sequence.

Reporting Services permissions on SQL Server R2 SSRS

This did the trick for me. http://thecodeattic.wordpress.com/category/ssrs/. Go down to step 35 to see the error you are getting. Paraphrasing:

Once you're able to log in to YourServer/Reports as an administrator, click Home in the top-right corner, then Folder Settings and New Role Assignment. Enter your user name and check a box for each role you want to grant yourself. Finally, click OK. You should now be able to browse folders without launching your browser with elevated privileges.

Don't forget to set the security at the site level **AND ** at the folder level. I hope that helps.

Rick

Combine two ActiveRecord::Relation objects

I've been able to accomplish this, even in many odd situations, by using Rails' built-in Arel.

User.where(
  User.arel_table[:first_name].eq('Tobias').or(
    User.arel_table[:last_name].eq('Fünke')
  )
)

This merges both ActiveRecord relations by using Arel's or.


Merge, as was suggested here, didn't work for me. It dropped the 2nd set of relation objects from the results.

How do I grep recursively?

globbing **

Using grep -r works, but it may overkill, especially in large folders.

For more practical usage, here is the syntax which uses globbing syntax (**):

grep "texthere" **/*.txt

which greps only specific files with pattern selected pattern. It works for supported shells such as Bash +4 or zsh.

To activate this feature, run: shopt -s globstar.

See also: How do I find all files containing specific text on Linux?

git grep

For projects under Git version control, use:

git grep "pattern"

which is much quicker.

ripgrep

For larger projects, the quickest grepping tool is ripgrep which greps files recursively by default:

rg "pattern" .

It's built on top of Rust's regex engine which uses finite automata, SIMD and aggressive literal optimizations to make searching very fast. Check the detailed analysis here.

How do I POST form data with UTF-8 encoding by using curl?

You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.

You should use this request:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod

Disable vertical sync for glxgears

Disabling the Sync to VBlank checkbox in nvidia-settings (OpenGL Settings tab) does the trick for me.

What does PermGen actually stand for?

Permanent Generation. Details are of course implementation specific.

Briefly, it contains the Java objects associated with classes and interned strings. In Sun's client implementation with sharing on, classes.jsa is memory mapped to form the initial data, with about half read-only and half copy-on-write.

Java objects that are merely old are kept in the Tenured Generation.

Using :: in C++

look at it is informative [Qualified identifiers

A qualified id-expression is an unqualified id-expression prepended by a scope resolution operator ::, and optionally, a sequence of enumeration, (since C++11)class or namespace names or decltype expressions (since C++11) separated by scope resolution operators. For example, the expression std::string::npos is an expression that names the static member npos in the class string in namespace std. The expression ::tolower names the function tolower in the global namespace. The expression ::std::cout names the global variable cout in namespace std, which is a top-level namespace. The expression boost::signals2::connection names the type connection declared in namespace signals2, which is declared in namespace boost.

The keyword template may appear in qualified identifiers as necessary to disambiguate dependent template names]1

How to do jquery code AFTER page loading?

And if you want to run a second function after the first one finishes, see this stackoverflow answer.

How much RAM is SQL Server actually using?

Be aware that Total Server Memory is NOT how much memory SQL Server is currently using.

refer to this Microsoft article: http://msdn.microsoft.com/en-us/library/ms190924.aspx

Difference between Select Unique and Select Distinct

SELECT UNIQUE is old syntax supported by Oracle's flavor of SQL. It is synonymous with SELECT DISTINCT.

Use SELECT DISTINCT because this is standard SQL, and SELECT UNIQUE is non-standard, and in database brands other than Oracle, SELECT UNIQUE may not be recognized at all.

Convert json to a C# array?

using Newtonsoft.Json;

Install this class in package console This class works fine in all .NET Versions, for example in my project: I have DNX 4.5.1 and DNX CORE 5.0 and everything works.

Firstly before JSON deserialization, you need to declare a class to read normally and store some data somewhere This is my class:

public class ToDoItem
{
    public string text { get; set; }
    public string complete { get; set; }
    public string delete { get; set; }
    public string username { get; set; }
    public string user_password { get; set; }
    public string eventID { get; set; }
}

In HttpContent section where you requesting data by GET request for example:

HttpContent content = response.Content;
string mycontent = await content.ReadAsStringAsync();
//deserialization in items
ToDoItem[] items = JsonConvert.DeserializeObject<ToDoItem[]>(mycontent);

Switch statement for greater-than/less-than

This is another option:

     switch (true) {
         case (value > 100):
             //do stuff
             break;
         case (value <= 100)&&(value > 75):
             //do stuff
             break;
         case (value < 50):
            //do stuff
             break;
     }

Trim characters in Java

EDIT: Amended by answer to replace just the first and last '\' character.

System.err.println("\\joe\\jill\\".replaceAll("^\\\\|\\\\$", ""));

Only allow Numbers in input Tag without Javascript

Try this with the + after [0-9]:

input type="text" pattern="[0-9]+" title="number only"

List supported SSL/TLS versions for a specific OpenSSL build

This worked for me:

openssl s_client -help 2>&1  > /dev/null | egrep "\-(ssl|tls)[^a-z]"

Please let me know if this is wrong.

Installation error: INSTALL_FAILED_OLDER_SDK

If you are totally new like me, you must install the minimum SDK at first. Check the link.

This worked out perfectly for me:

Same problem other post with a good solution

Regards,

Khaled.

How to turn NaN from parseInt into 0 for an empty string?

You can have very clean code, i had similar problems and i solved it by using :

var a="bcd";
~~parseInt(a);

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

What does `return` keyword mean inside `forEach` function?

From the Mozilla Developer Network:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Early termination may be accomplished with:

The other Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.

get all the elements of a particular form

I could have sworn there used to be a convenient fields property on a form but … Must have been my imagination.

I just do this (for <form name="my_form"></form>) because I usually don't want fieldsets themselves:

let fields = Array.from(document.forms.my_form.querySelectorAll('input, select, textarea'));

AngularJS ng-repeat handle empty list case

With the newer versions of angularjs the correct answer to this question is to use ng-if:

<ul>
  <li ng-if="list.length === 0">( No items in this list yet! )</li>
  <li ng-repeat="item in list">{{ item }}</li>
</ul>

This solution will not flicker when the list is about to download either because the list has to be defined and with a length of 0 for the message to display.

Here is a plunker to show it in use: http://plnkr.co/edit/in7ha1wTlpuVgamiOblS?p=preview

Tip: You can also show a loading text or spinner:

  <li ng-if="!list">( Loading... )</li>

iOS 7 UIBarButton back button arrow color

If you are using storyboards you could set the navigation bar tint colour.

enter image description here

enter image description here

Giving UIView rounded corners

- SwiftUI

In SwiftUI, you can use cornerRadius modifier directly on any View you want. For example of this question:

Text("Signing In…")
    .padding(16)
    .background(Color.red)
    .cornerRadius(50)

Preview

Note that there is no more diamond like radius, so even if you set the cornerRadius more than half of the height, it will round smoothly.

Checkout this answer to se how to Round Specific Corners in SwiftUI

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

If you are stuck with .Net 4.0 and the target site is using TLS 1.2, you need the following line instead. ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

source: TLS 1.2 and .NET Support: How to Avoid Connection Errors

Your project path contains non-ASCII characters android studio

I meet this problem and find there are some Chinese characters in my path. After change these characters into English , the problem solved.

Access item in a list of lists

You can use itertools.cycle:

>>> from itertools import cycle
>>> lis = [[10,13,17],[3,5,1],[13,11,12]]
>>> cyc = cycle((-1, 1))
>>> 50 + sum(x*next(cyc) for x in lis[0])   # lis[0] is [10,13,17]
36

Here the generator expression inside sum would return something like this:

>>> cyc = cycle((-1, 1))
>>> [x*next(cyc) for x in lis[0]]
[-10, 13, -17]

You can also use zip here:

>>> cyc = cycle((-1, 1))
>>> [x*y for x, y  in zip(lis[0], cyc)]
[-10, 13, -17]

Remove padding from columns in Bootstrap 3

Remove/customize Bootstrap Gutter with css reference: http://arnique.net/web-design/58/a-quick-guide-to-changing-bootstraps-gutter-width/

_x000D_
_x000D_
/* remove */_x000D_
.gutter-0.row {_x000D_
  margin-right: -0px;_x000D_
  margin-left: -0px;_x000D_
}_x000D_
.gutter-0 > [class^="col-"], .gutter-0 > [class^=" col-"] {_x000D_
  padding-right: 0px;_x000D_
  padding-left: 0px;_x000D_
}_x000D_
_x000D_
/* customize */_x000D_
.gutter-6.row {_x000D_
  margin-right: -3px;_x000D_
  margin-left: -3px;_x000D_
}_x000D_
.gutter-6 > [class^="col-"], .gutter-6 > [class^=" col-"] {_x000D_
  padding-right: 3px;_x000D_
  padding-left: 3px;_x000D_
}_x000D_
    
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row gutter-6">_x000D_
  <div class="col-sm-3 col-md-3">_x000D_
    <div class="thumbnail">_x000D_
      <img width="100%" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMTcxIiBoZWlnaHQ9IjE4MCIgdmlld0JveD0iMCAwIDE3MSAxODAiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjwhLS0KU291cmNlIFVSTDogaG9sZGVyLmpzLzEwMCV4MTgwCkNyZWF0ZWQgd2l0aCBIb2xkZXIuanMgMi42LjAuCkxlYXJuIG1vcmUgYXQgaHR0cDovL2hvbGRlcmpzLmNvbQooYykgMjAxMi0yMDE1IEl2YW4gTWFsb3BpbnNreSAtIGh0dHA6Ly9pbXNreS5jbwotLT48ZGVmcz48c3R5bGUgdHlwZT0idGV4dC9jc3MiPjwhW0NEQVRBWyNob2xkZXJfMTU5MzRlYTgxN2QgdGV4dCB7IGZpbGw6I0FBQUFBQTtmb250LXdlaWdodDpib2xkO2ZvbnQtZmFtaWx5OkFyaWFsLCBIZWx2ZXRpY2EsIE9wZW4gU2Fucywgc2Fucy1zZXJpZiwgbW9ub3NwYWNlO2ZvbnQtc2l6ZToxMHB0IH0gXV0+PC9zdHlsZT48L2RlZnM+PGcgaWQ9ImhvbGRlcl8xNTkzNGVhODE3ZCI+PHJlY3Qgd2lkdGg9IjE3MSIgaGVpZ2h0PSIxODAiIGZpbGw9IiNFRUVFRUUiLz48Zz48dGV4dCB4PSI2MSIgeT0iOTQuNSI+MTcxeDE4MDwvdGV4dD48L2c+PC9nPjwvc3ZnPg==" alt="">_x000D_
      <div class="caption">_x000D_
        <h3>Thumbnail label</h3>_x000D_
        <p>more</p>_x000D_
        <p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="col-sm-3 col-md-3">_x000D_
    <div class="thumbnail">_x000D_
      <img width="100%" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMTcxIiBoZWlnaHQ9IjE4MCIgdmlld0JveD0iMCAwIDE3MSAxODAiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjwhLS0KU291cmNlIFVSTDogaG9sZGVyLmpzLzEwMCV4MTgwCkNyZWF0ZWQgd2l0aCBIb2xkZXIuanMgMi42LjAuCkxlYXJuIG1vcmUgYXQgaHR0cDovL2hvbGRlcmpzLmNvbQooYykgMjAxMi0yMDE1IEl2YW4gTWFsb3BpbnNreSAtIGh0dHA6Ly9pbXNreS5jbwotLT48ZGVmcz48c3R5bGUgdHlwZT0idGV4dC9jc3MiPjwhW0NEQVRBWyNob2xkZXJfMTU5MzRlYTgxN2QgdGV4dCB7IGZpbGw6I0FBQUFBQTtmb250LXdlaWdodDpib2xkO2ZvbnQtZmFtaWx5OkFyaWFsLCBIZWx2ZXRpY2EsIE9wZW4gU2Fucywgc2Fucy1zZXJpZiwgbW9ub3NwYWNlO2ZvbnQtc2l6ZToxMHB0IH0gXV0+PC9zdHlsZT48L2RlZnM+PGcgaWQ9ImhvbGRlcl8xNTkzNGVhODE3ZCI+PHJlY3Qgd2lkdGg9IjE3MSIgaGVpZ2h0PSIxODAiIGZpbGw9IiNFRUVFRUUiLz48Zz48dGV4dCB4PSI2MSIgeT0iOTQuNSI+MTcxeDE4MDwvdGV4dD48L2c+PC9nPjwvc3ZnPg==" alt="">_x000D_
      <div class="caption">_x000D_
        <h3>Thumbnail label</h3>_x000D_
        <p>more</p>_x000D_
        <p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="col-sm-3 col-md-3">_x000D_
    <div class="thumbnail">_x000D_
      <img width="100%" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMTcxIiBoZWlnaHQ9IjE4MCIgdmlld0JveD0iMCAwIDE3MSAxODAiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjwhLS0KU291cmNlIFVSTDogaG9sZGVyLmpzLzEwMCV4MTgwCkNyZWF0ZWQgd2l0aCBIb2xkZXIuanMgMi42LjAuCkxlYXJuIG1vcmUgYXQgaHR0cDovL2hvbGRlcmpzLmNvbQooYykgMjAxMi0yMDE1IEl2YW4gTWFsb3BpbnNreSAtIGh0dHA6Ly9pbXNreS5jbwotLT48ZGVmcz48c3R5bGUgdHlwZT0idGV4dC9jc3MiPjwhW0NEQVRBWyNob2xkZXJfMTU5MzRlYTgxN2QgdGV4dCB7IGZpbGw6I0FBQUFBQTtmb250LXdlaWdodDpib2xkO2ZvbnQtZmFtaWx5OkFyaWFsLCBIZWx2ZXRpY2EsIE9wZW4gU2Fucywgc2Fucy1zZXJpZiwgbW9ub3NwYWNlO2ZvbnQtc2l6ZToxMHB0IH0gXV0+PC9zdHlsZT48L2RlZnM+PGcgaWQ9ImhvbGRlcl8xNTkzNGVhODE3ZCI+PHJlY3Qgd2lkdGg9IjE3MSIgaGVpZ2h0PSIxODAiIGZpbGw9IiNFRUVFRUUiLz48Zz48dGV4dCB4PSI2MSIgeT0iOTQuNSI+MTcxeDE4MDwvdGV4dD48L2c+PC9nPjwvc3ZnPg==" alt="">_x000D_
      <div class="caption">_x000D_
        <h3>Thumbnail label</h3>_x000D_
        <p>more</p>_x000D_
        <p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="col-sm-3 col-md-3">_x000D_
    <div class="thumbnail">_x000D_
      <img width="100%" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iMTcxIiBoZWlnaHQ9IjE4MCIgdmlld0JveD0iMCAwIDE3MSAxODAiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjwhLS0KU291cmNlIFVSTDogaG9sZGVyLmpzLzEwMCV4MTgwCkNyZWF0ZWQgd2l0aCBIb2xkZXIuanMgMi42LjAuCkxlYXJuIG1vcmUgYXQgaHR0cDovL2hvbGRlcmpzLmNvbQooYykgMjAxMi0yMDE1IEl2YW4gTWFsb3BpbnNreSAtIGh0dHA6Ly9pbXNreS5jbwotLT48ZGVmcz48c3R5bGUgdHlwZT0idGV4dC9jc3MiPjwhW0NEQVRBWyNob2xkZXJfMTU5MzRlYTgxN2QgdGV4dCB7IGZpbGw6I0FBQUFBQTtmb250LXdlaWdodDpib2xkO2ZvbnQtZmFtaWx5OkFyaWFsLCBIZWx2ZXRpY2EsIE9wZW4gU2Fucywgc2Fucy1zZXJpZiwgbW9ub3NwYWNlO2ZvbnQtc2l6ZToxMHB0IH0gXV0+PC9zdHlsZT48L2RlZnM+PGcgaWQ9ImhvbGRlcl8xNTkzNGVhODE3ZCI+PHJlY3Qgd2lkdGg9IjE3MSIgaGVpZ2h0PSIxODAiIGZpbGw9IiNFRUVFRUUiLz48Zz48dGV4dCB4PSI2MSIgeT0iOTQuNSI+MTcxeDE4MDwvdGV4dD48L2c+PC9nPjwvc3ZnPg==" alt="">_x000D_
      <div class="caption">_x000D_
        <h3>Thumbnail label</h3>_x000D_
        <p>more</p>_x000D_
        <p><a href="#" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

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

Try again with chmod -R 755 /var/www/html/test/app/storage. Use with sudo for Operation not permitted in chmod. Use Check owner permission if still having the error.

how can I display tooltip or item information on mouse over?

The title attribute works on most HTML tags and is widely supported by modern browsers.

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

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

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

df.index = new_index

Practical uses for the "internal" keyword in C#

When you have methods, classes, etc which need to be accessible within the scope of the current assembly and never outside it.

For example, a DAL may have an ORM but the objects should not be exposed to the business layer all interaction should be done through static methods and passing in the required paramters.

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

Setting the environment variable NODE_PATH to point to your global node_modules folder.

In Windows 7 or higher the path is something like %AppData%\npm\node_modules while in UNIX could be something like /home/sg/.npm_global/lib/node_modules/ but it depends on user configuration.

The command npm config get prefix could help finding out which is the correct path.

In UNIX systems you can accomplish it with the following command:

export NODE_PATH=`npm config get prefix`/lib/node_modules/

How to install a specific JDK on Mac OS X?

For people using any LION OS X 10.7.X

They uploaded Java SE 6 version 1.6.0_26 available here

http://support.apple.com/kb/dl1421

Determine what attributes were changed in Rails after_save callback?

For those who want to know the changes just made in an after_save callback:

Rails 5.1 and greater

model.saved_changes

Rails < 5.1

model.previous_changes

Also see: http://api.rubyonrails.org/classes/ActiveModel/Dirty.html#method-i-previous_changes

How to uncheck checkbox using jQuery Uniform library

In some case you can use this:

$('.myInput').get(0).checked = true

For toggle you can use if else with function

Java: Get last element after split

You mean you don't know the sizes of the arrays at compile-time? At run-time they could be found by the value of lastone.length and lastwo.length .

c# search string in txt file

If your pair of lines will only appear once in your file, you could use

File.ReadLines(pathToTextFile)
    .SkipWhile(line => !line.Contains("CustomerEN"))
    .Skip(1) // optional
    .TakeWhile(line => !line.Contains("CustomerCh"));

If you could have multiple occurrences in one file, you're probably better off using a regular foreach loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:

List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
    if (line.Contains("CustomerEN") && current == null)
        current = new List<string>();
    else if (line.Contains("CustomerCh") && current != null)
    {
        groups.Add(current);
        current = null;
    }
    if (current != null)
        current.Add(line);
}

Bootstrap 3 - disable navbar collapse

If you're not using the less version, here is the line you need to change:

@media (max-width: 767px) { /* Change this to 0 */
  .navbar-nav .open .dropdown-menu {
    position: static;
    float: none;
    width: auto;
    margin-top: 0;
    background-color: transparent;
    border: 0;
    box-shadow: none;
  }
  .navbar-nav .open .dropdown-menu > li > a,
  .navbar-nav .open .dropdown-menu .dropdown-header {
    padding: 5px 15px 5px 25px;
  }
  .navbar-nav .open .dropdown-menu > li > a {
    line-height: 20px;
  }
  .navbar-nav .open .dropdown-menu > li > a:hover,
  .navbar-nav .open .dropdown-menu > li > a:focus {
    background-image: none;
  }
}

What primitive data type is time_t?

You could always use something like mktime to create a known time (midnight, last night) and use difftime to get a double-precision time difference between the two. For a platform-independant solution, unless you go digging into the details of your libraries, you're not going to do much better than that. According to the C spec, the definition of time_t is implementation-defined (meaning that each implementation of the library can define it however they like, as long as library functions with use it behave according to the spec.)

That being said, the size of time_t on my linux machine is 8 bytes, which suggests a long int or a double. So I did:

int main()
{
    for(;;)
    {
        printf ("%ld\n", time(NULL));
        printf ("%f\n", time(NULL));
        sleep(1);
    }
    return 0;
}

The time given by the %ld increased by one each step and the float printed 0.000 each time. If you're hell-bent on using printf to display time_ts, your best bet is to try your own such experiment and see how it work out on your platform and with your compiler.

C - determine if a number is prime

OK, so forget about C. Suppose I give you a number and ask you to determine if it's prime. How do you do it? Write down the steps clearly, then worry about translating them into code.

Once you have the algorithm determined, it will be much easier for you to figure out how to write a program, and for others to help you with it.

edit: Here's the C# code you posted:

static bool IsPrime(int number) {
    for (int i = 2; i < number; i++) {
        if (number % i == 0 && i != number) return false;
    }
    return true;
}

This is very nearly valid C as is; there's no bool type in C, and no true or false, so you need to modify it a little bit (edit: Kristopher Johnson correctly points out that C99 added the stdbool.h header). Since some people don't have access to a C99 environment (but you should use one!), let's make that very minor change:

int IsPrime(int number) {
    int i;
    for (i=2; i<number; i++) {
        if (number % i == 0 && i != number) return 0;
    }
    return 1;
}

This is a perfectly valid C program that does what you want. We can improve it a little bit without too much effort. First, note that i is always less than number, so the check that i != number always succeeds; we can get rid of it.

Also, you don't actually need to try divisors all the way up to number - 1; you can stop checking when you reach sqrt(number). Since sqrt is a floating-point operation and that brings a whole pile of subtleties, we won't actually compute sqrt(number). Instead, we can just check that i*i <= number:

int IsPrime(int number) {
    int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
}

One last thing, though; there was a small bug in your original algorithm! If number is negative, or zero, or one, this function will claim that the number is prime. You likely want to handle that properly, and you may want to make number be unsigned, since you're more likely to care about positive values only:

int IsPrime(unsigned int number) {
    if (number <= 1) return 0; // zero and one are not prime
    unsigned int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
}

This definitely isn't the fastest way to check if a number is prime, but it works, and it's pretty straightforward. We barely had to modify your code at all!

Swift - Remove " character from string

If you are getting the output Optional(5) when trying to print the value of 5 in an optional Int or String, you should unwrap the value first:

if let value = text {
    print(value)
}

Now you've got the value without the "Optional" string that Swift adds when the value is not unwrapped before.

Insert a string at a specific index

my_string          = "hello world";
my_insert          = " dear";
my_insert_location = 5;

my_string = my_string.split('');  
my_string.splice( my_insert_location , 0, my_insert );
my_string = my_string.join('');

https://jsfiddle.net/gaby_de_wilde/wz69nw9k/

Notice: Trying to get property of non-object error

The response is an array.

var_dump($pjs[0]->{'player_name'});

Twitter bootstrap scrollable modal

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

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

Source

SignalR Console app example

To build on @dyslexicanaboko's answer for dotnet core, here is a client console application:

Create a helper class:

using System;
using Microsoft.AspNetCore.SignalR.Client;

namespace com.stackoverflow.SignalRClientConsoleApp
{
    public class SignalRConnection
    {
        public async void Start()
        {
            var url = "http://signalr-server-url/hubname";

            var connection = new HubConnectionBuilder()
                .WithUrl(url)
                .WithAutomaticReconnect()
                .Build();

            // receive a message from the hub
            connection.On<string, string>("ReceiveMessage", (user, message) => OnReceiveMessage(user, message));

            var t = connection.StartAsync();

            t.Wait();

            // send a message to the hub
            await connection.InvokeAsync("SendMessage", "ConsoleApp", "Message from the console app");
        }

        private void OnReceiveMessage(string user, string message)
        {
            Console.WriteLine($"{user}: {message}");
        }

    }
}

Then implement in your console app's entry point:

using System;

namespace com.stackoverflow.SignalRClientConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var signalRConnection = new SignalRConnection();
            signalRConnection.Start();

            Console.Read();
        }
    }
}

Manipulate a url string by adding GET parameters

Example with updating existent parameters.

Also url_encode used, and possibility to don't specify parameter value

    <?
    /**
     * Add parameter to URL
     * @param string $url
     * @param string $key
     * @param string $value
     * @return string result URL
     */
    function addToUrl($url, $key, $value = null) {
        $query = parse_url($url, PHP_URL_QUERY);
        if ($query) {
            parse_str($query, $queryParams);
            $queryParams[$key] = $value;
            $url = str_replace("?$query", '?' . http_build_query($queryParams), $url);
        } else {
            $url .= '?' . urlencode($key) . '=' . urlencode($value);
        }
        return $url;
    }

T-SQL stored procedure that accepts multiple Id values

One method you might want to consider if you're going to be working with the values a lot is to write them to a temporary table first. Then you just join on it like normal.

This way, you're only parsing once.

It's easiest to use one of the 'Split' UDFs, but so many people have posted examples of those, I figured I'd go a different route ;)

This example will create a temporary table for you to join on (#tmpDept) and fill it with the department id's that you passed in. I'm assuming you're separating them with commas, but you can -- of course -- change it to whatever you want.

IF OBJECT_ID('tempdb..#tmpDept', 'U') IS NOT NULL
BEGIN
    DROP TABLE #tmpDept
END

SET @DepartmentIDs=REPLACE(@DepartmentIDs,' ','')

CREATE TABLE #tmpDept (DeptID INT)
DECLARE @DeptID INT
IF IsNumeric(@DepartmentIDs)=1
BEGIN
    SET @DeptID=@DepartmentIDs
    INSERT INTO #tmpDept (DeptID) SELECT @DeptID
END
ELSE
BEGIN
        WHILE CHARINDEX(',',@DepartmentIDs)>0
        BEGIN
            SET @DeptID=LEFT(@DepartmentIDs,CHARINDEX(',',@DepartmentIDs)-1)
            SET @DepartmentIDs=RIGHT(@DepartmentIDs,LEN(@DepartmentIDs)-CHARINDEX(',',@DepartmentIDs))
            INSERT INTO #tmpDept (DeptID) SELECT @DeptID
        END
END

This will allow you to pass in one department id, multiple id's with commas in between them, or even multiple id's with commas and spaces between them.

So if you did something like:

SELECT Dept.Name 
FROM Departments 
JOIN #tmpDept ON Departments.DepartmentID=#tmpDept.DeptID
ORDER BY Dept.Name

You would see the names of all of the department IDs that you passed in...

Again, this can be simplified by using a function to populate the temporary table... I mainly did it without one just to kill some boredom :-P

-- Kevin Fairchild

Single Form Hide on Startup

Usually you would only be doing this when you are using a tray icon or some other method to display the form later, but it will work nicely even if you never display your main form.

Create a bool in your Form class that is defaulted to false:

private bool allowshowdisplay = false;

Then override the SetVisibleCore method

protected override void SetVisibleCore(bool value)
{            
    base.SetVisibleCore(allowshowdisplay ? value : allowshowdisplay);
}

Because Application.Run() sets the forms .Visible = true after it loads the form this will intercept that and set it to false. In the above case, it will always set it to false until you enable it by setting allowshowdisplay to true.

Now that will keep the form from displaying on startup, now you need to re-enable the SetVisibleCore to function properly by setting the allowshowdisplay = true. You will want to do this on whatever user interface function that displays the form. In my example it is the left click event in my notiyicon object:

private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        this.allowshowdisplay = true;
        this.Visible = !this.Visible;                
    }
}

How to check object is nil or not in swift?

If abc is an optional, then the usual way to do this would be to attempt to unwrap it in an if statement:

if let variableName = abc { // If casting, use, eg, if let var = abc as? NSString
    // variableName will be abc, unwrapped
} else {
    // abc is nil
}

However, to answer your actual question, your problem is that you're typing the variable such that it can never be optional.

Remember that in Swift, nil is a value which can only apply to optionals.

Since you've declared your variable as:

var abc: NSString ...

it is not optional, and cannot be nil.

Try declaring it as:

var abc: NSString? ...

or alternatively letting the compiler infer the type.

What does "both" mean in <div style="clear:both">

Description of the possible values:

  • left: No floating elements allowed on the left side
  • right: No floating elements allowed on the right side
  • both: No floating elements allowed on either the left or the right side
  • none: Default. Allows floating elements on both sides
  • inherit: Specifies that the value of the clear property should be inherited from the parent element

Source: w3schools.com

How to do a scatter plot with empty circles in Python?

From the documentation for scatter:

Optional kwargs control the Collection properties; in particular:

    edgecolors:
        The string ‘none’ to plot faces with no outlines
    facecolors:
        The string ‘none’ to plot unfilled outlines

Try the following:

import matplotlib.pyplot as plt 
import numpy as np 

x = np.random.randn(60) 
y = np.random.randn(60)

plt.scatter(x, y, s=80, facecolors='none', edgecolors='r')
plt.show()

example image

Note: For other types of plots see this post on the use of markeredgecolor and markerfacecolor.

pip install returning invalid syntax

Don't enter in the python shall, Install in the command directory.

Not inside the python pip cannot be installed inside the python.

Even in the version 3.+ you don't have to write the python 3 instead just python.

which looks like

python -m pip install --upgrade pip

and then install others

python -m pip install jupyter

How to secure an ASP.NET Web API

If you want to secure your API in a server to server fashion (no redirection to website for 2 legged authentication). You can look at OAuth2 Client Credentials Grant protocol.

https://dev.twitter.com/docs/auth/application-only-auth

I have developed a library that can help you easily add this kind of support to your WebAPI. You can install it as a NuGet package:

https://nuget.org/packages/OAuth2ClientCredentialsGrant/1.0.0.0

The library targets .NET Framework 4.5.

Once you add the package to your project, it will create a readme file in the root of your project. You can look at that readme file to see how to configure/use this package.

Cheers!

How do I switch between command and insert mode in Vim?

Looks like your Vim is launched in easy mode. See :help easy.

This happens when Vim is invoked with the -y argument or as evim, or maybe you have a :set insertmode somewhere in your .vimrc configuration. Find the source and disable it; temporarily this can be also done via Ctrl + O :set noim Enter.

Warning message: In `...` : invalid factor level, NA generated

I have got similar issue which data retrieved from .xlsx file. Unfortunately, I could not find the proper answer here. I handled it on my own with dplyr as below which might help others:

#install.packages("xlsx")
library(xlsx)
extracted_df <- read.xlsx("test.xlsx", sheetName='Sheet1', stringsAsFactors=FALSE)
# Replace all NAs in a data frame with "G" character
extracted_df[is.na(extracted_df)] <- "G"

However, I could not handle it with the readxl package which does not have similar parameter to the stringsAsFactors. For the reason, I have moved to the xlsx package.

How to run a SQL query on an Excel table?

If you need to do this once just follow Charles' descriptions, but it is also possible to do this with Excel formulas and helper columns in case you want to make the filter dynamic.

Lets assume you data is on the sheet DataSheet and starts in row 2 of the following columns:

  • A: lastname
  • B: firstname
  • C: phonenumber

You need two helper columns on this sheet.

  • D2: =if(A2 = "", 1, 0), this is the filter column, corresponding to your where condition
  • E2: =if(D2 <> 1, "", sumifs(D$2:D$1048576, A$2:A$1048576, "<"&A2) + sumifs(D$2:D2, A$2:A2, A2)), this corresponds to the order by

Copy down these formulas as far as your data goes.

On the sheet which should display your result create the following columns.

  • A: A sequence of numbers starting with 1 in row 2, this limits the total number of rows you can get (kind like a limit in sequel)
  • B2: =match(A2, DataSheet!$E$2:$E$1048576, 0), this is the row of the corresponding data
  • C2: =iferror(index(DataSheet!A$2:A$1048576, $B2), ""), this is the actual data or empty if no data exists

Copy down the formulas in B2 and C2 and copy-past column C to D and E.

Determining if an Object is of primitive type

I'm late to the show, but if you're testing a field, you can use getGenericType:

import static org.junit.Assert.*;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;

import org.junit.Test;

public class PrimitiveVsObjectTest {

    private static final Collection<String> PRIMITIVE_TYPES = 
            new HashSet<>(Arrays.asList("byte", "short", "int", "long", "float", "double", "boolean", "char"));

    private static boolean isPrimitive(Type type) {
        return PRIMITIVE_TYPES.contains(type.getTypeName());
    }

    public int i1 = 34;
    public Integer i2 = 34;

    @Test
    public void primitive_type() throws NoSuchFieldException, SecurityException {
        Field i1Field = PrimitiveVsObjectTest.class.getField("i1");
        Type genericType1 = i1Field.getGenericType();
        assertEquals("int", genericType1.getTypeName());
        assertNotEquals("java.lang.Integer", genericType1.getTypeName());
        assertTrue(isPrimitive(genericType1));
    }

    @Test
    public void object_type() throws NoSuchFieldException, SecurityException {
        Field i2Field = PrimitiveVsObjectTest.class.getField("i2");
        Type genericType2 = i2Field.getGenericType();
        assertEquals("java.lang.Integer", genericType2.getTypeName());
        assertNotEquals("int", genericType2.getTypeName());
        assertFalse(isPrimitive(genericType2));
    }
}

The Oracle docs list the 8 primitive types.

could not extract ResultSet in hibernate

For MySql take in mind that it's not a good idea to write camelcase. For example if the schema is like that:

CREATE TABLE IF NOT EXISTS `task`(
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `teaching_hours` DECIMAL(5,2) DEFAULT NULL,
    `isActive` BOOLEAN DEFAULT FALSE,
    `is_validated` BOOLEAN DEFAULT FALSE,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

You must be very careful cause isActive column will translate to isactive. So in your Entity class is should be like this:

 @Basic
 @Column(name = "isactive", nullable = true)
 public boolean isActive() {
     return isActive;
 }
 public void setActive(boolean active) {
     isActive = active;
 }

That was my problem at least that got me your error

This has nothing to do with MySql which is case insensitive, but rather is a naming strategy that spring will use to translate your tables. For more refer to this post

Quickest way to convert XML to JSON in Java

I have uploaded the project you can directly open in eclipse and run that's all https://github.com/pareshmutha/XMLToJsonConverterUsingJAVA

Thank You

How can I use std::maps with user-defined types as key?

The right solution is to Specialize std::less for your class/Struct.

• Basically maps in cpp are implemented as Binary Search Trees.

  1. BSTs compare elements of nodes to determine the organization of the tree.
  2. Nodes who's element compares less than that of the parent node are placed on the left of the parent and nodes whose elements compare greater than the parent nodes element are placed on the right. i.e.

For each node, node.left.key < node.key < node.right.key

Every node in the BST contains Elements and in case of maps its KEY and a value, And keys are supposed to be ordered. More About Map implementation : The Map data Type.

In case of cpp maps , keys are the elements of the nodes and values does not take part in the organization of the tree its just a supplementary data .

So It means keys should be compatible with std::less or operator< so that they can be organized. Please check map parameters.

Else if you are using user defined data type as keys then need to give meaning full comparison semantics for that data type.

Solution : Specialize std::less:

The third parameter in map template is optional and it is std::less which will delegate to operator< ,

So create a new std::less for your user defined data type. Now this new std::less will be picked by std::map by default.

namespace std
{
    template<> struct  less<MyClass>
    {
        bool operator() (const MyClass& lhs, const MyClass& rhs) const
        {
            return lhs.anyMemen < rhs.age;
        }
    };

}

Note: You need to create specialized std::less for every user defined data type(if you want to use that data type as key for cpp maps).

Bad Solution: Overloading operator< for your user defined data type. This solution will also work but its very bad as operator < will be overloaded universally for your data type/class. which is undesirable in client scenarios.

Please check answer Pavel Minaev's answer

ORA-28001: The password has expired

I had same problem, i am trying to login database it appear a message with: "ORA-28001: The password has expired" , I have fixed the problem simple steps

1.open command prompt 2.type sqlplus 3.It will ask Enter Password, you can give old password, it will show password has expired ORA-28001 4.It will ask new password and retype password 5.It will change with new password 6.Go to the sql database and try to connect with new password, it will connect.

How to align an image dead center with bootstrap

The correct way of doing this is

<div class="row text-center">
  <img ...>
</div>

setting global sql_mode in mysql

set global sql_mode="NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLE,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

How do I link to a library with Code::Blocks?

The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)

To link with gdi32:

enter image description here

This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a has no advantage over gdi32 other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib for MSVC).

For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).

How to center-justify the last line of text in CSS?

There doesn't appear to be a way. You can fake it by using justify and then wrapping the last line of text in a span and setting just that to text align center. It works ok for small blocks of text but is not a useful approach to large quantities of text or dynamic text.

I suggest finding somebody at Adobe who's involved in their W3C work and nagging them to bring up right/left/center justification in their next meeting. If anyone's gonna be able to push for basic typography features in CSS it'd be Adobe.

How to add to the end of lines containing a pattern with sed or awk?

In bash:

while read -r line ; do
    [[ $line == all:* ]] && line+=" anotherthing"
    echo "$line"
done < filename

Build a basic Python iterator

I see some of you doing return self in __iter__. I just wanted to note that __iter__ itself can be a generator (thus removing the need for __next__ and raising StopIteration exceptions)

class range:
  def __init__(self,a,b):
    self.a = a
    self.b = b
  def __iter__(self):
    i = self.a
    while i < self.b:
      yield i
      i+=1

Of course here one might as well directly make a generator, but for more complex classes it can be useful.

Can’t delete docker image with dependent child images

Suppose we have a Dockerfile

FROM ubuntu:trusty
CMD ping localhost

We build image from that without TAG or naming

docker build .

Now we have a success report "Successfully built 57ca5ce94d04" If we see the docker images

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
<none>              <none>              57ca5ce94d04        18 seconds ago      188MB
ubuntu              trusty              8789038981bc        11 days ago         188MB

We need to first remove the docker rmi 57ca5ce94d04

Followed by

docker rmi 8789038981bc

By that image will be removed!

A forced removal of all as suggested by someone

docker rmi $(docker images -q) -f

Opening a .ipynb.txt File

What you have on your hands is an IPython Notebook file. (Now renamed to Jupyter Notebook

you can open it using the command ipython notebook filename.ipynb from the directory it is downloaded on to.

If you are on a newer machine, open the file as jupyter notebook filename.ipynb.

do not forget to remove the .txt extension.

the file has a series of python code/statements and markdown text that you can run/inspect/save/share. read more about ipython notebook from the website.

if you do not have IPython installed, you can do

pip install ipython

or check out installation instructions at the ipython website

Changing text color onclick

Do something like this:

<script>
function changeColor(id)
{
  document.getElementById(id).style.color = "#ff0000"; // forecolor
  document.getElementById(id).style.backgroundColor = "#ff0000"; // backcolor
}
</script>

<div id="myid">Hello There !!</div>

<a href="#" onclick="changeColor('myid'); return false;">Change Color</a>

Displaying Image in Java

import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

public class DisplayImage {

    public static void main(String avg[]) throws IOException
    {
        DisplayImage abc=new DisplayImage();
    }

    public DisplayImage() throws IOException
    {
        BufferedImage img=ImageIO.read(new File("f://images.jpg"));
        ImageIcon icon=new ImageIcon(img);
        JFrame frame=new JFrame();
        frame.setLayout(new FlowLayout());
        frame.setSize(200,300);
        JLabel lbl=new JLabel();
        lbl.setIcon(icon);
        frame.add(lbl);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Where is android studio building my .apk file?

In my case to get my debug build - I have to turn off Instant Run option :

File ? Settings ? Build, Execution, Deployment ? Instant Run and uncheck Enable Instant Run.

Then after run project - I found my build into Application\app\build\outputs\appDebug\apk directory

jQuery autocomplete with callback ajax json

$(document).on('keyup','#search_product',function(){
    $( "#search_product" ).autocomplete({
      source:function(request,response){
                  $.post("<?= base_url('ecommerce/autocomplete') ?>",{'name':$( "#search_product" ).val()}).done(function(data, status){

                    response(JSON.parse(data));
        });
      }
    });
});

PHP code :

public function autocomplete(){
    $name=$_POST['name'];
    $result=$this->db->select('product_name,sku_code')->like('product_name',$name)->get('product_list')->result_array();
    $names=array();
    foreach($result as $row){
        $names[]=$row['product_name'];
    }
    echo json_encode($names);
}

How to check that an element is in a std::set?

You can also check whether an element is in set or not while inserting the element. The single element version return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.

For example: Suppose the set already has 20 as an element.

 std::set<int> myset;
 std::set<int>::iterator it;
 std::pair<std::set<int>::iterator,bool> ret;

 ret=myset.insert(20);
 if(ret.second==false)
 {
     //do nothing

 }
 else
 {
    //do something
 }

 it=ret.first //points to element 20 already in set.

If the element is newly inserted than pair::first will point to the position of new element in set.

Android Use Done button on Keyboard to click button

Kotlin Solution

The base way to handle the done action in Kotlin is:

edittext.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        // Call your code here
        true
    }
    false
}

Kotlin Extension

Use this to call edittext.onDone {/*action*/} in your main code. Keeps it more readable and maintainable

edittext.onDone { submitForm() }

fun EditText.onDone(callback: () -> Unit) {
    setOnEditorActionListener { _, actionId, _ ->
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            callback.invoke()
            true
        }
        false
    }
}

Don't forget to add these options to your edittext

<EditText ...
    android:imeOptions="actionDone"
    android:inputType="text"/>

If you need inputType="textMultiLine" support, read this post

What's the regular expression that matches a square bracket?

How about using backslash \ in front of the square bracket. Normally square brackets match a character class.

NodeJS - What does "socket hang up" actually mean?

There seems to be one additional case here, which is Electron not being a fan of the "localhost" domain name. In my case I needed to change this:

const backendApiHostUrl = "http://localhost:3000";

to this:

const backendApiHostUrl = "http://127.0.0.1:3000";

After that the problem just went away.

This means that DNS resolution (local or remote) might be causing some problems too.

How do I determine whether my calculation of pi is accurate?

The Taylor series is one way to approximate pi. As noted it converges slowly.

The partial sums of the Taylor series can be shown to be within some multiplier of the next term away from the true value of pi.

Other means of approximating pi have similar ways to calculate the max error.

We know this because we can prove it mathematically.

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

What I don't understand is what to do in Df when 'OK' is pressed in order to remove fragments Df, Cf, and Bf?

Step #1: Have Df tell D "yo! we got the OK click!" via calling a method, either on the activity itself, or on an interface instance supplied by the activity.

Step #2: Have D remove the fragments via FragmentManager.

The hosting activity (D) is the one that knows what other fragments are in the activity (vs. being in other activities). Hence, in-fragment events that might affect the fragment mix should be propagated to the activity, which will make the appropriate orchestration moves.

Wait until all promises complete even if some rejected

I had the same problem and have solved it in the following way:

const fetch = (url) => {
  return node-fetch(url)
    .then(result => result.json())
    .catch((e) => {
      return new Promise((resolve) => setTimeout(() => resolve(fetch(url)), timeout));
    });
};

tasks = [fetch(url1), fetch(url2) ....];

Promise.all(tasks).then(......)

In that case Promise.all will wait for every Promise will come into resolved or rejected state.

And having this solution we are "stopping catch execution" in a non-blocking way. In fact, we're not stopping anything, we just returning back the Promise in a pending state which returns another Promise when it's resolved after the timeout.

iOS 7: UITableView shows under status bar

The following solution works well enough in code without using magic constants, and accounts for the user changing the size class, e.g. through rotations or side-by-side apps on ipads:

- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
    [super traitCollectionDidChange:previousTraitCollection];
    // Fix up content offset to ensure the tableview isn't underlapping the status bar.
    self.tableView.contentInset = UIEdgeInsetsMake(self.topLayoutGuide.length, 0.0, 0.0, 0.0);
}

Insert variable into Header Location PHP

Try using double quotes and keeping the L in location lowercase...

header("location: http://linkhere.com/HERE_I_WANT_THE_VARIABLE");

or for example

header("location: http://linkhere.com/$variable");

No need to concatenate here to insert variables.

How to convert Seconds to HH:MM:SS using T-SQL

This is what I use (typically for html table email reports)

declare @time int, @hms varchar(20)
set @time = 12345
set @hms = cast(cast((@Time)/3600 as int) as varchar(3)) 
  +':'+ right('0'+ cast(cast(((@Time)%3600)/60 as int) as varchar(2)),2) 
  +':'+ right('0'+ cast(((@Time)%3600)%60 as varchar(2)),2) +' (hh:mm:ss)'
select @hms

Django - Did you forget to register or load this tag?

{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image">

in your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE.

Process escape sequences in a string in Python

This is a bad way of doing it, but it worked for me when trying to interpret escaped octals passed in a string argument.

input_string = eval('b"' + sys.argv[1] + '"')

It's worth mentioning that there is a difference between eval and ast.literal_eval (eval being way more unsafe). See Using python's eval() vs. ast.literal_eval()?

Getting the PublicKeyToken of .Net assemblies

You can add this as an external tool to Visual Studio like so:

Title:

Get PublicKeyToken

Command:

c:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\sn.exe

(Path may differ between versions)

Arguments:

-T "$(TargetPath)"

And check the "Use Output window" option.

Change old commit message on Git

It says:

When you save and exit the editor, it will rewind you back to that last commit in that list and drop you on the command line with the following message:

$ git rebase -i HEAD~3
Stopped at 7482e0d... updated the gemspec to hopefully work better
You can amend the commit now, with

It does not mean:

type again git rebase -i HEAD~3

Try to not typing git rebase -i HEAD~3 when exiting the editor, and it should work fine.
(otherwise, in your particular situation, a git rebase -i --abort might be needed to reset everything and allow you to try again)


As Dave Vogt mentions in the comments, git rebase --continue is for going to the next task in the rebasing process, after you've amended the first commit.

Also, Gregg Lind mentions in his answer the reword command of git rebase:

By replacing the command "pick" with the command "edit", you can tell git rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.

If you just want to edit the commit message for a commit, replace the command "pick" with the command "reword", since Git1.6.6 (January 2010).

It does the same thing ‘edit’ does during an interactive rebase, except it only lets you edit the commit message without returning control to the shell. This is extremely useful.
Currently if you want to clean up your commit messages you have to:

$ git rebase -i next

Then set all the commits to ‘edit’. Then on each one:

# Change the message in your editor.
$ git commit --amend
$ git rebase --continue

Using ‘reword’ instead of ‘edit’ lets you skip the git-commit and git-rebase calls.

How to access a RowDataPacket object

you try the code which gives JSON without rowdatapacket:

var ret = [];
conn.query(SQLquery, function(err, rows, fields) {
    if (err)
        alert("...");
    else {
        ret = JSON.stringify(rows);
    }
    doStuffwithTheResult(ret);
}

Batch script loop

a completely flawless loop

set num=0
:loop
:: insert code
set num=%num%+1
if %num% neq 10 goto loop
::insert after code code

you can edit it by changing the 10 in line 5 to any number to represent how many time you want it to loop.

.Net: How do I find the .NET version?

This answer is applicable to .NET Core only!

Typing dotnet --version in your terminal of choice will print out the version of the .NET Core SDK in use.

Learn more about the dotnet command here.

Change <select>'s option and trigger events with JavaScript

It is as simple as this:

var sel = document.getElementById('sel');
var button = document.getElementById('button');

button.addEventListener('click', function (e) {
    sel.options[1].selected = true;
    sel.onchange();
});

But this way has a problem. You can't call events just like you would, with normal functions, because there may be more than one function listening for an event, and they can get set in several different ways.

Unfortunately, the 'right way' to fire an event is not so easy because you have to do it differently in Internet Explorer (using document.createEventObject) and Firefox (using document.createEvent("HTMLEvents"))

var sel = document.getElementById('sel');
var button = document.getElementById('button');

button.addEventListener('click', function (e) {
    sel.options[1].selected = true;
    fireEvent(sel,'change');

});


function fireEvent(element,event){
    if (document.createEventObject){
    // dispatch for IE
    var evt = document.createEventObject();
    return element.fireEvent('on'+event,evt)
    }
    else{
    // dispatch for firefox + others
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent(event, true, true ); // event type,bubbling,cancelable
    return !element.dispatchEvent(evt);
    }
}

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

Check to see if you have more than one file with that name in the solution.

I had this on a project that I took over from someone else. The breakpoint list was full of line numbers in Controller.cs, some active and some not. I found this question, and tried a few options, but when I double-clicked on the breakpoints, they took me to different projects within the solution. Because the files were called the same, they appear to be the same, but they aren't. The answer is of course then to ignore the warning, as they will become active if you get to load that other file.

Convert InputStream to byte array in Java

You can try Cactoos:

byte[] array = new BytesOf(stream).bytes();

Java2D: Increase the line width

You should use setStroke to set a stroke of the Graphics2D object.

The example at http://www.java2s.com gives you some code examples.

The following code produces the image below:

import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;

public class FrameTest {
    public static void main(String[] args) {
        JFrame jf = new JFrame("Demo");
        Container cp = jf.getContentPane();
        cp.add(new JComponent() {
            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setStroke(new BasicStroke(10));
                g2.draw(new Line2D.Float(30, 20, 80, 90));
            }
        });
        jf.setSize(300, 200);
        jf.setVisible(true);
    }
}

enter image description here

(Note that the setStroke method is not available in the Graphics object. You have to cast it to a Graphics2D object.)


This post has been rewritten as an article here.

Wait until page is loaded with Selenium WebDriver for Python

From selenium/webdriver/support/wait.py

driver = ...
from selenium.webdriver.support.wait import WebDriverWait
element = WebDriverWait(driver, 10).until(
    lambda x: x.find_element_by_id("someId"))

Switch with if, else if, else, and loops inside case

but i only wanted the for statement to be attached to the if statement, not the else if statements as well.

Well get rid of the else then. If the else if is not supposed to be part of the for then write it as:

           for(int i=0; i<something_in_the_array.length;i++)
                if(whatever_value==(something_in_the_array[i]))
                {
                    value=2;
                    break;
                }

           if(whatever_value==2)
           {
                value=3;
                break;  // redundant now
           }

           else if(whatever_value==3)
           {
                value=4;
                break;  // redundant now
           }

Having said that:

  • it is not at all clear what you are really trying to do here,
  • not having the else part in the loop doesn't seem to make a lot of sense here,
  • a lot of people (myself included) think it is to always use braces ... so that people don't get tripped up by incorrect indentation when reading your code. (And in this case, it might help us figure out what you are really trying to do here ...)

Finally, braces are less obtrusive if you put the opening brace on the end of the previous line; e.g.

  if (something) {
     doSomething();
  }

rather than:

  if (something) 
  {
     doSomething();
  }

Login to website, via C#

You can simplify things quite a bit by creating a class that derives from WebClient, overriding its GetWebRequest method and setting a CookieContainer object on it. If you always set the same CookieContainer instance, then cookie management will be handled automatically for you.

But the only way to get at the HttpWebRequest before it is sent is to inherit from WebClient and override that method.

public class CookieAwareWebClient : WebClient
{
    private CookieContainer cookie = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = cookie;
        }
        return request;
    }
}

var client = new CookieAwareWebClient();
client.BaseAddress = @"https://www.site.com/any/base/url/";
var loginData = new NameValueCollection();
loginData.Add("login", "YourLogin");
loginData.Add("password", "YourPassword");
client.UploadValues("login.php", "POST", loginData);

//Now you are logged in and can request pages    
string htmlSource = client.DownloadString("index.php");

What is "pom" packaging in maven?

Packaging an artifact as POM means that it has a very simple lifecycle

package -> install -> deploy

http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html

This is useful if you are deploying a pom.xml file or a project that doesn't fit with the other packaging types.

We use pom packaging for many of our projects and bind extra phases and goals as appropriate.

For example some of our applications use:

prepare-package -> test -> package -> install -> deploy

When you mvn install the application it should add it to your locally .m2 repository. To publish elsewhere you will need to set up correct distribution management information. You may also need to use the maven builder helper plugin, if artifacts aren't automatically attached to by Maven.

Absolute Positioning & Text Alignment

Try this:

http://jsfiddle.net/HRz6X/2/

You need to add left: 0 and right: 0 (not supported by IE6). Or specify a width

How can I create a Java 8 LocalDate from a long Epoch time in Milliseconds?

You can start with Instant.ofEpochMilli(long):

LocalDate date =
  Instant.ofEpochMilli(startDateLong)
  .atZone(ZoneId.systemDefault())
  .toLocalDate();

Most efficient way to find smallest of 3 numbers Java?

For those who find this topic much later:

If you have just three values to compare there is no significant difference. But if you have to find min of, say, thirty or sixty values, "min" could be easier for anyone to read in the code next year:

int smallest;

smallest = min(a1, a2);
smallest = min(smallest, a3);
smallest = min(smallest, a4);
...
smallest = min(smallest, a37);

But if you think of speed, maybe better way would be to put values into list, and then find min of that:

List<Integer> mySet = Arrays.asList(a1, a2, a3, ..., a37);

int smallest = Collections.min(mySet);

Would you agree?

jQuery - hashchange event

Note that in case of IE 7 and IE 9 if statment will give true for ("onhashchange" in windows) but the window.onhashchange will never fire, so its better to store hash and check it after every 100 millisecond whether its changed or not for all versions of IE.

    if (("onhashchange" in window) && !($.browser.msie)) { 
         window.onhashchange = function () { 
              alert(window.location.hash);             
         }            
         // Or $(window).bind( 'hashchange',function(e) {  
         //       alert(window.location.hash); 
         //   });              
    }
    else { 
        var prevHash = window.location.hash;
        window.setInterval(function () {
           if (window.location.hash != prevHash) {
              prevHash = window.location.hash;
              alert(window.location.hash);
           }
        }, 100);
    }

Why is an OPTIONS request sent and can I disable it?

What worked for me was to import "github.com/gorilla/handlers" and then use it this way:

router := mux.NewRouter()
router.HandleFunc("/config", getConfig).Methods("GET")
router.HandleFunc("/config/emcServer", createEmcServers).Methods("POST")

headersOk := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})

log.Fatal(http.ListenAndServe(":" + webServicePort, handlers.CORS(originsOk, headersOk, methodsOk)(router)))

As soon as I executed an Ajax POST request and attaching JSON data to it, Chrome would always add the Content-Type header which was not in my previous AllowedHeaders config.

Custom Authentication in ASP.Net-Core

From what I learned after several days of research, Here is the Guide for ASP .Net Core MVC 2.x Custom User Authentication

In Startup.cs :

Add below lines to ConfigureServices method :

public void ConfigureServices(IServiceCollection services)
{

services.AddAuthentication(
    CookieAuthenticationDefaults.AuthenticationScheme
).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
    options =>
    {
        options.LoginPath = "/Account/Login";
        options.LogoutPath = "/Account/Logout";
    });

    services.AddMvc();

    // authentication 
    services.AddAuthentication(options =>
    {
       options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    });

    services.AddTransient(
        m => new UserManager(
            Configuration
                .GetValue<string>(
                    DEFAULT_CONNECTIONSTRING //this is a string constant
                )
            )
        );
     services.AddDistributedMemoryCache();
}

keep in mind that in above code we said that if any unauthenticated user requests an action which is annotated with [Authorize] , they well force redirect to /Account/Login url.

Add below lines to Configure method :

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler(ERROR_URL);
    }
     app.UseStaticFiles();
     app.UseAuthentication();
     app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: DEFAULT_ROUTING);
    });
}

Create your UserManager class that will also manage login and logout. it should look like below snippet (note that i'm using dapper):

public class UserManager
{
    string _connectionString;

    public UserManager(string connectionString)
    {
        _connectionString = connectionString;
    }

    public async void SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)
    {
        using (var con = new SqlConnection(_connectionString))
        {
            var queryString = "sp_user_login";
            var dbUserData = con.Query<UserDbModel>(
                queryString,
                new
                {
                    UserEmail = user.UserEmail,
                    UserPassword = user.UserPassword,
                    UserCellphone = user.UserCellphone
                },
                commandType: CommandType.StoredProcedure
            ).FirstOrDefault();

            ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(dbUserData), CookieAuthenticationDefaults.AuthenticationScheme);
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);

            await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
        }
    }

    public async void SignOut(HttpContext httpContext)
    {
        await httpContext.SignOutAsync();
    }

    private IEnumerable<Claim> GetUserClaims(UserDbModel user)
    {
        List<Claim> claims = new List<Claim>();

        claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id().ToString()));
        claims.Add(new Claim(ClaimTypes.Name, user.UserFirstName));
        claims.Add(new Claim(ClaimTypes.Email, user.UserEmail));
        claims.AddRange(this.GetUserRoleClaims(user));
        return claims;
    }

    private IEnumerable<Claim> GetUserRoleClaims(UserDbModel user)
    {
        List<Claim> claims = new List<Claim>();

        claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id().ToString()));
        claims.Add(new Claim(ClaimTypes.Role, user.UserPermissionType.ToString()));
        return claims;
    }
}

Then maybe you have an AccountController which has a Login Action that should look like below :

public class AccountController : Controller
{
    UserManager _userManager;

    public AccountController(UserManager userManager)
    {
        _userManager = userManager;
    }

    [HttpPost]
    public IActionResult LogIn(LogInViewModel form)
    {
        if (!ModelState.IsValid)
            return View(form);
         try
        {
            //authenticate
            var user = new UserDbModel()
            {
                UserEmail = form.Email,
                UserCellphone = form.Cellphone,
                UserPassword = form.Password
            };
            _userManager.SignIn(this.HttpContext, user);
             return RedirectToAction("Search", "Home", null);
         }
         catch (Exception ex)
         {
            ModelState.AddModelError("summary", ex.Message);
            return View(form);
         }
    }
}

Now you are able to use [Authorize] annotation on any Action or Controller.

Feel free to comment any questions or bug's.

Excel telling me my blank cells aren't blank

Here's how I fixed this problem without any coding.

  1. Select the entire column that I wanted to delete the "blank" cells from.
  2. Click the Conditional Formatting tab up top.
  3. Select "New Rule".
  4. Click "Format only cells that contain".
  5. Change "between" to "equal to".
  6. Click the box next to the "equal to" box.
  7. Click one of the problem "blank" cells.
  8. Click the Format Button.
  9. Pick a random color to fill the box with.
  10. Press "OK".
  11. This should change all of the problem "blank" cells to the color that you chose. Now Right click one of the colored cells, and go to "Sort" and "Put selected cell color on top".
  12. This will put all of the problem cells at the top of the column and now all of your other cells will stay in the original order you put them in. You can now select all of the problem cells in one group and click the delete cell button on top to get rid of them.

Initialize class fields in constructor or at declaration?

Not a direct answer to your question about the best practice but an important and related refresher point is that in the case of a generic class definition, either leave it on compiler to initialize with default values or we have to use a special method to initialize fields to their default values (if that is absolute necessary for code readability).

class MyGeneric<T>
{
    T data;
    //T data = ""; // <-- ERROR
    //T data = 0; // <-- ERROR
    //T data = null; // <-- ERROR        

    public MyGeneric()
    {
        // All of the above errors would be errors here in constructor as well
    }
}

And the special method to initialize a generic field to its default value is the following:

class MyGeneric<T>
{
    T data = default(T);

    public MyGeneric()
    {           
        // The same method can be used here in constructor
    }
}

java build path problems

To configure your JRE in eclipse:

  • Window > Preferences > Java > Installed JREs...
  • Click Add
  • Find the directory of your JDK > Click OK

Simple JavaScript Checkbox Validation

You could use:

 if(!this.form.checkbox.checked)
{
    alert('You must agree to the terms first.');
    return false;
}

(demo page).

<input type="checkbox" name="checkbox" value="check"  />
<input type="submit" name="email_submit" value="submit" onclick="if(!this.form.checkbox.checked){alert('You must agree to the terms first.');return false}"  />
  • Returning false from an inline event handler will prevent the default action from taking place (in this case, submitting the form).
  • ! is the Boolean NOT operator.
  • this is the submit button because it is the element the event handler is attached to.
  • .form is the form the submit button is in.
  • .checkbox is the control named "checkbox" in that form.
  • .checked is true if the checkbox is checked and false if the checkbox is unchecked.

JQuery addclass to selected div, remove class if another div is selected

You can use a single line to add and remove class on a div. Please remove a class first to add a new class.

$('div').on('click',function(){
  $('div').removeClass('active').addClass('active');     
});

How to find the length of an array in shell?

$ a=(1 2 3 4)
$ echo ${#a[@]}
4