Programs & Examples On #Growl

Growl is a global notification system for the Mac OS X and Windows operating systems.

How to manually install a pypi module without pip/easy_install?

  1. Download the package
  2. unzip it if it is zipped
  3. cd into the directory containing setup.py
  4. If there are any installation instructions contained in documentation contianed herein, read and follow the instructions OTHERWISE
  5. type in python setup.py install

You may need administrator privileges for step 5. What you do here thus depends on your operating system. For example in Ubuntu you would say sudo python setup.py install

EDIT- thanks to kwatford (see first comment)

To bypass the need for administrator privileges during step 5 above you may be able to make use of the --user flag. In this way you can install the package only for the current user.

The docs say:

Files will be installed into subdirectories of site.USER_BASE (written as userbase hereafter). This scheme installs pure Python modules and extension modules in the same location (also known as site.USER_SITE). Here are the values for UNIX, including Mac OS X:

More details can be found here: http://docs.python.org/2.7/install/index.html

Static link of shared library function in gcc

A bit late but ... I found a link that I saved a couple of years ago and I thought it might be useful for you guys:

CDE: Automatically create portable Linux applications

http://www.pgbovine.net/cde.html

  • Just download the program
  • Execute the binary passing as a argument the name of the binary you want make portable, for example: nmap

    ./cde_2011-08-15_64bit nmap

The program will read all of libs linked to nmap and its dependencias and it will save all of them in a folder called cde-package/ (in the same directory that you are).

  • Finally, you can compress the folder and deploy the portable binary in whatever system.

Remember, to launch the portable program you have to exec the binary located in cde-package/nmap.cde

Best regards

Add views below toolbar in CoordinatorLayout

To use collapsing top ToolBar or using ScrollFlags of your own choice we can do this way:From Material Design get rid of FrameLayout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleGravity="top"
            app:layout_scrollFlags="scroll|enterAlways">


        <androidx.appcompat.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin">

            <ImageView
                android:id="@+id/ic_back"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_arrow_back" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="back"
                android:textSize="16sp"
                android:textStyle="bold" />

        </androidx.appcompat.widget.Toolbar>


        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/post_details_recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="5dp"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Want to show/hide div based on dropdown box selection

You need to either put your code at the end of the page or wrap it in a document ready call, otherwise you're trying to execute code on elements that don't yet exist. Also, you can reduce your code to:

$('#purpose').on('change', function () {
    $("#business").css('display', (this.value == '1') ? 'block' : 'none');
});

jsFiddle example

How to resolve the C:\fakepath?

If you really need to send the full path of the uploded file, then you'd probably have to use something like a signed java applet as there isn't any way to get this information if the browser doesn't send it.

How to call base.base.method()?

public class A
{
    public int i = 0;
    internal virtual void test()
    {
        Console.WriteLine("A test");
    }
}

public class B : A
{
    public new int i = 1;
    public new void test()
    {
        Console.WriteLine("B test");
    }
}

public class C : B
{
    public new int i = 2;
    public new void test()
    {
        Console.WriteLine("C test - ");
        (this as A).test(); 
    }
}

An explicit value for the identity column in table can only be specified when a column list is used and IDENTITY_INSERT is ON SQL Server

SET IDENTITY_INSERT tableA ON

You have to make a column list for your INSERT statement:

INSERT Into tableA ([id], [c2], [c3], [c4], [c5] ) 
SELECT [id], [c2], [c3], [c4], [c5] FROM tableB

not like "INSERT Into tableA SELECT ........"

SET IDENTITY_INSERT tableA OFF

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

Note that both pcolor and "surf + view(2)" do not show the last row and the last column of your 2D data.

On the other hand, using imagesc, you have to be careful with the axes. The surf and the imagesc examples in gevang's answer only (almost -- apart from the last row and column) correspond to each other because the 2D sinc function is symmetric.

To illustrate these 2 points, I produced the figure below with the following code:

[x, y] = meshgrid(1:10,1:5);
z      = x.^3 + y.^3;

subplot(3,1,1)
imagesc(flipud(z)), axis equal tight, colorbar
set(gca, 'YTick', 1:5, 'YTickLabel', 5:-1:1);
title('imagesc')

subplot(3,1,2)
surf(x,y,z,'EdgeColor','None'), view(2), axis equal tight, colorbar
title('surf with view(2)')

subplot(3,1,3)
imagesc(flipud(z)), axis equal tight, colorbar
axis([0.5 9.5 1.5 5.5])
set(gca, 'YTick', 1:5, 'YTickLabel', 5:-1:1);
title('imagesc cropped')

colormap jet

surf vs imagesc

As you can see the 10th row and 5th column are missing in the surf plot. (You can also see this in images in the other answers.)

Note how you can use the "set(gca, 'YTick'..." (and Xtick) command to set the x and y tick labels properly if x and y are not 1:1:N.

Also note that imagesc only makes sense if your z data correspond to xs and ys are (each) equally spaced. If not you can use surf (and possibly duplicate the last column and row and one more "(end,end)" value -- although that's a kind of a dirty approach).

AngularJS ui router passing data between states without URL

The params object is included in $stateParams, but won't be part of the url.

1) In the route configuration:

$stateProvider.state('edit_user', {
    url: '/users/:user_id/edit',
    templateUrl: 'views/editUser.html',
    controller: 'editUserCtrl',
    params: {
        paramOne: { objectProperty: "defaultValueOne" },  //default value
        paramTwo: "defaultValueTwo"
    }
});

2) In the controller:

.controller('editUserCtrl', function ($stateParams, $scope) {       
    $scope.paramOne = $stateParams.paramOne;
    $scope.paramTwo = $stateParams.paramTwo;
});

3A) Changing the State from a controller

$state.go("edit_user", {
    user_id: 1,                
    paramOne: { objectProperty: "test_not_default1" },
    paramTwo: "from controller"
});

3B) Changing the State in html

<div ui-sref="edit_user({ user_id: 3, paramOne: { objectProperty: 'from_html1' }, paramTwo: 'fromhtml2' })"></div>

Example Plunker

Easiest way to toggle 2 classes in jQuery

The easiest solution is to toggleClass() both classes individually.

Let's say you have an icon:

    <i id="target" class="fa fa-angle-down"></i>

To toggle between fa-angle-down and fa-angle-up do the following:

    $('.sometrigger').click(function(){
        $('#target').toggleClass('fa-angle-down');
        $('#target').toggleClass('fa-angle-up');
    });

Since we had fa-angle-down at the beginning without fa-angle-up each time you toggle both, one leaves for the other to appear.

Reactjs: Unexpected token '<' Error

Here is a working example from your jsbin:

HTML:

<!DOCTYPE html>
<html>
<head>
<script src="//fb.me/react-with-addons-0.9.0.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <div id="main-content"></div>
</body>
</html>

jsx:

<script type="text/jsx">
/** @jsx React.DOM */
var LikeOrNot = React.createClass({
    render: function () {
      return (
        <p>Like</p>
      );
    }
});

React.renderComponent(<LikeOrNot />, document.getElementById('main-content'));
</script>

Run this code from a single file and your it should work.

NULL value for int in Update statement

Assuming the column is set to support NULL as a value:

UPDATE YOUR_TABLE
   SET column = NULL

Be aware of the database NULL handling - by default in SQL Server, NULL is an INT. So if the column is a different data type you need to CAST/CONVERT NULL to the proper data type:

UPDATE YOUR_TABLE
   SET column = CAST(NULL AS DATETIME)

...assuming column is a DATETIME data type in the example above.

How to search for file names in Visual Studio?

With Visual Studio 2017, It now comes with a much better version, named “Go To All” and is bound to the keyboard shortcut CTRL + T as well as CTRL +, and includes inline filtering and “fuzzy search”

CTRL + T

CTRL + ,

Embed HTML5 YouTube video without iframe?

Yes, but it depends on what you mean by 'embed'; as far as I can tell after reading through the docs, it seems like you have a couple of options if you want to get around using the iframe API. You can use the javascript and flash API's (https://developers.google.com/youtube/player_parameters) to embed a player, but that involves creating Flash objects in your code (something I personally avoid, but not necessarily something that you have to). Below are some helpful sections from the dev docs for the Youtube API.

If you really want to get around all these methods and include video without any sort of iframe, then your best bet might be creating an HTML5 video player/app that can connect to the Youtube Data API (https://developers.google.com/youtube/v3/). I'm not sure what the extent of your needs are, but this would be the way to go if you really want to get around using any iframes or flash objects.

Hope this helps!


Useful:

(https://developers.google.com/youtube/player_parameters)

IFrame embeds using the IFrame Player API

Follow the IFrame Player API instructions to insert a video player in your web page or application after the Player API's JavaScript code has loaded. The second parameter in the constructor for the video player is an object that specifies player options. Within that object, the playerVars property identifies player parameters.

The HTML and JavaScript code below shows a simple example that inserts a YouTube player into the page element that has an id value of ytplayer. The onYouTubePlayerAPIReady() function specified here is called automatically when the IFrame Player API code has loaded. This code does not define any player parameters and also does not define other event handlers.

...

IFrame embeds using tags

Define an tag in your application in which the src URL specifies the content that the player will load as well as any other player parameters you want to set. The tag's height and width parameters specify the dimensions of the player.

If you are creating the element yourself (rather than using the IFrame Player API to create it), you can append player parameters directly to the end of the URL. The URL has the following format:

...

AS3 object embeds

Object embeds use an tag to specify the player's dimensions and parameters. The sample code below demonstrates how to use an object embed to load an AS3 player that automatically plays the same video as the previous two examples.

Get ALL User Friends Using Facebook Graph API - Android

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

The /me/friendlists endpoint and user_friendlists permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.

If you want to access a list of non-app-using friends, there are two options:

  1. If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.

  2. If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.

In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission).

For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.

How do you calculate program run time in python?

Quick alternative

import timeit

start = timeit.default_timer()

#Your statements here

stop = timeit.default_timer()

print('Time: ', stop - start)  

Spring: @Component versus @Bean

Let's consider I want specific implementation depending on some dynamic state. @Bean is perfect for that case.

@Bean
@Scope("prototype")
public SomeService someService() {
    switch (state) {
    case 1:
        return new Impl1();
    case 2:
        return new Impl2();
    case 3:
        return new Impl3();
    default:
        return new Impl();
    }
}

However there is no way to do that with @Component.

Xcode variables

Here's a list of the environment variables. I think you might want CURRENT_VARIANT. See also BUILD_VARIANTS.

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

To resolve this issue, I had to do the following:

  1. Launch the Visual Studio Installer with administrative privileges
  2. If it prompts you to install updates to Visual Studio, do so before continuing
  3. When prompted, click the button to Modify the existing installation
  4. Click on the "Individual components" tab / header along the top
  5. Scroll down to the "Debugging and testing" section
  6. Check the box next to "Web performance and load testing tools"
  7. Click the Modify button on the bottom right corner of the dialog to install the missing DLLs

Once the DLLs are installed, you can add references to them using the method that Agent007 indicated in his answer.

What do the return values of Comparable.compareTo mean in Java?

Official Definition

From the reference docs of Comparable.compareTo(T):

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)

The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.

Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."

In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.

My Version

In short:

this.compareTo(that)

returns

  • a negative int if this < that
  • 0 if this == that
  • a positive int if this > that

where the implementation of this method determines the actual semantics of < > and == (I don't mean == in the sense of java's object identity operator)

Examples

"abc".compareTo("def")

will yield something smaller than 0 as abc is alphabetically before def.

Integer.valueOf(2).compareTo(Integer.valueOf(1))

will yield something larger than 0 because 2 is larger than 1.

Some additional points

Note: It is good practice for a class that implements Comparable to declare the semantics of it's compareTo() method in the javadocs.

Note: you should read at least one of the following:

Warning: you should never rely on the return values of compareTo being -1, 0 and 1. You should always test for x < 0, x == 0, x > 0, respectively.

Is there any native DLL export functions viewer?

you can use Dependency Walker to view the function name. you can see the function's parameters only if it's decorated. read the following from the FAQ:

How do I view the parameter and return types of a function? For most functions, this information is simply not present in the module. The Windows' module file format only provides a single text string to identify each function. There is no structured way to list the number of parameters, the parameter types, or the return type. However, some languages do something called function "decoration" or "mangling", which is the process of encoding information into the text string. For example, a function like int Foo(int, int) encoded with simple decoration might be exported as _Foo@8. The 8 refers to the number of bytes used by the parameters. If C++ decoration is used, the function would be exported as ?Foo@@YGHHH@Z, which can be directly decoded back to the function's original prototype: int Foo(int, int). Dependency Walker supports C++ undecoration by using the Undecorate C++ Functions Command.

How to use timer in C?

Here's a solution I used (it needs #include <time.h>):

int msec = 0, trigger = 10; /* 10ms */
clock_t before = clock();

do {
  /*
   * Do something to busy the CPU just here while you drink a coffee
   * Be sure this code will not take more than `trigger` ms
   */

  clock_t difference = clock() - before;
  msec = difference * 1000 / CLOCKS_PER_SEC;
  iterations++;
} while ( msec < trigger );

printf("Time taken %d seconds %d milliseconds (%d iterations)\n",
  msec/1000, msec%1000, iterations);

Getting cursor position in Python

Using pyautogui

To install

pip install pyautogui

and to find the location of the mouse pointer

import pyautogui
print(pyautogui.position())

This will give the pixel location to which mouse pointer is at.

JavaScript open in a new window, not tab

OK, after making a lot of test, here my concluson:

When you perform:

     window.open('www.yourdomain.tld','_blank');
     window.open('www.yourdomain.tld','myWindow');

or whatever you put in the destination field, this will change nothing: the new page will be opened in a new tab (so depend on user preference)

If you want the page to be opened in a new "real" window, you must put extra parameter. Like:

window.open('www.yourdomain.tld', 'mywindow','location=1,status=1,scrollbars=1, resizable=1, directories=1, toolbar=1, titlebar=1');

After testing, it seems the extra parameter you use, dont' really matter: this is not the fact you put "this parameter" or "this other one" which create the new "real window" but the fact there is new parameter(s).

But something is confused and may explain a lot of wrong answers:

This:

 win1 = window.open('myurl1', 'ID_WIN');
 win2 = window.open('myurl2', 'ID_WIN', 'location=1,status=1,scrollbars=1');

And this:

 win2 = window.open('myurl2', 'ID_WIN', 'location=1,status=1,scrollbars=1');
 win1 = window.open('myurl1', 'ID_WIN');

will NOT give the same result.

In the first case, as you first open a page without extra parameter, it will open in a new tab. And in this case, the second call will be also opened in this tab because of the name you give.

In second case, as your first call is made with extra parameter, the page will be opened in a new "real window". And in that case, even if the second call is made without the extra parameter, it will also be opened in this new "real window"... but same tab!

This mean the first call is important as it decided where to put the page.

failed to open stream: HTTP wrapper does not support writeable connections

it is because of using web address, You can not use http to write data. don't use : http:// or https:// in your location for upload files or save data or somting like that. instead of of using $_SERVER["HTTP_REFERER"] use $_SERVER["DOCUMENT_ROOT"]. for example :

wrong :

move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["HTTP_REFERER"].'/uploads/images/1.jpg')

correct:

move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["DOCUMENT_ROOT"].'/uploads/images/1.jpg')

How can I create an error 404 in PHP?

Did you remember to die() after sending the header? The 404 header doesn't automatically stop processing, so it may appear not to have done anything if there is further processing happening.

It's not good to REDIRECT to your 404 page, but you can INCLUDE the content from it with no problem. That way, you have a page that properly sends a 404 status from the correct URL, but it also has your "what are you looking for?" page for the human reader.

open program minimized via command prompt

The answer is simple. Just look at the image.

enter image description here

Custom exception type

In short:

Option 1: use babel-plugin-transform-builtin-extend

Option 2: do it yourself (inspired from that same library)

    function CustomError(...args) {
      const instance = Reflect.construct(Error, args);
      Reflect.setPrototypeOf(instance, Reflect.getPrototypeOf(this));
      return instance;
    }
    CustomError.prototype = Object.create(Error.prototype, {
      constructor: {
        value: Error,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    Reflect.setPrototypeOf(CustomError, Error);
  • If you are using pure ES5:

    function CustomError(message, fileName, lineNumber) {
      const instance = new Error(message, fileName, lineNumber);
      Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
      return instance;
    }
    CustomError.prototype = Object.create(Error.prototype, {
      constructor: {
        value: Error,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
    if (Object.setPrototypeOf){
        Object.setPrototypeOf(CustomError, Error);
    } else {
        CustomError.__proto__ = Error;
    }
    
  • Alternative: use Classtrophobic framework

Explanation:

Why extending the Error class using ES6 and Babel is a problem?

Because an instance of CustomError is not anymore recognized as such.

class CustomError extends Error {}
console.log(new CustomError('test') instanceof Error);// true
console.log(new CustomError('test') instanceof CustomError);// false

In fact, from the official documentation of Babel, you cannot extend any built-in JavaScript classes such as Date, Array, DOM or Error.

The issue is described here:

What about the other SO answers?

All the given answers fix the instanceof issue but you lose the regular error console.log:

console.log(new CustomError('test'));
// output:
// CustomError {name: "MyError", message: "test", stack: "Error?    at CustomError (<anonymous>:4:19)?    at <anonymous>:1:5"}

Whereas using the method mentioned above, not only you fix the instanceof issue but you also keep the regular error console.log:

console.log(new CustomError('test'));
// output:
// Error: test
//     at CustomError (<anonymous>:2:32)
//     at <anonymous>:1:5

Present and dismiss modal view controller

Swift

Updated for Swift 3

enter image description here

Storyboard

Create two View Controllers with a button on each. For the second view controller, set the class name to SecondViewController and the storyboard ID to secondVC.

Code

ViewController.swift

import UIKit
class ViewController: UIViewController {

    @IBAction func presentButtonTapped(_ sender: UIButton) {
        
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let myModalViewController = storyboard.instantiateViewController(withIdentifier: "secondVC")
        myModalViewController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
        myModalViewController.modalTransitionStyle = UIModalTransitionStyle.coverVertical
        self.present(myModalViewController, animated: true, completion: nil)
    }
}

SecondViewController.swift

import UIKit
class SecondViewController: UIViewController {
    
    @IBAction func dismissButtonTapped(_ sender: UIButton) {
        self.dismiss(animated: true, completion: nil)
    }
}

Source:

IN vs ANY operator in PostgreSQL

(Neither IN nor ANY is an "operator". A "construct" or "syntax element".)

Logically, quoting the manual:

IN is equivalent to = ANY.

But there are two syntax variants of IN and two variants of ANY. Details:

IN taking a set is equivalent to = ANY taking a set, as demonstrated here:

But the second variant of each is not equivalent to the other. The second variant of the ANY construct takes an array (must be an actual array type), while the second variant of IN takes a comma-separated list of values. This leads to different restrictions in passing values and can also lead to different query plans in special cases:

ANY is more versatile

The ANY construct is far more versatile, as it can be combined with various operators, not just =. Example:

SELECT 'foo' LIKE ANY('{FOO,bar,%oo%}');

For a big number of values, providing a set scales better for each:

Related:

Inversion / opposite / exclusion

"Find rows where id is in the given array":

SELECT * FROM tbl WHERE id = ANY (ARRAY[1, 2]);

Inversion: "Find rows where id is not in the array":

SELECT * FROM tbl WHERE id <> ALL (ARRAY[1, 2]);
SELECT * FROM tbl WHERE id <> ALL ('{1, 2}');  -- equivalent array literal
SELECT * FROM tbl WHERE NOT (id = ANY ('{1, 2}'));

All three equivalent. The first with array constructor, the other two with array literal. The data type can be derived from context unambiguously. Else, an explicit cast may be required, like '{1,2}'::int[].

Rows with id IS NULL do not pass either of these expressions. To include NULL values additionally:

SELECT * FROM tbl WHERE (id = ANY ('{1, 2}')) IS NOT TRUE;

Sort Java Collection

A lot of correct answers, but I haven't found this one: Collections cannot be sorted, you can only iterate through them.

Now you can iterate over them and create a new sorted something. Follow the answers here for that.

How to get element by class name?

Another option is to use querySelector('.foo') or querySelectorAll('.foo') which have broader browser support than getElementsByClassName.

http://caniuse.com/#feat=queryselector

http://caniuse.com/#feat=getelementsbyclassname

Ignore invalid self-signed ssl certificate in node.js with https.request?

Adding to @Armand answer:

Add the following environment variable:

NODE_TLS_REJECT_UNAUTHORIZED=0 e.g. with export:

export NODE_TLS_REJECT_UNAUTHORIZED=0 (with great thanks to Juanra)

If you on windows usage:

set NODE_TLS_REJECT_UNAUTHORIZED=0

Thanks to: @weagle08

How do I convert an object to an array?

//My Function is worked. Hope help full for you :)
      $input = [
            '1' => (object) [1,2,3],
            '2' => (object) [4,5,6,
                (object) [6,7,8,
                [9, 10, 11,
                    (object) [12, 13, 14]]]
            ],
            '3' =>[15, 16, (object)[17, 18]]
        ];

        echo "<pre>";
        var_dump($input);
        var_dump(toAnArray($input));

      public function toAnArray(&$input) {

        if (is_object($input)) {
            $input = get_object_vars($input);
        }
        foreach ($input as &$item) {
            if (is_object($item) || is_array($item)) {
                if (is_object($item)) {
                    $item = get_object_vars($item);
                }
                self::toAnArray($item);
            }
        }
    }

Returning a promise in an async function in TypeScript

When you do new Promise((resolve)... the type inferred was Promise<{}> because you should have used new Promise<number>((resolve).

It is interesting that this issue was only highlighted when the async keyword was added. I would recommend reporting this issue to the TS team on GitHub.

There are many ways you can get around this issue. All the following functions have the same behavior:

const whatever1 = () => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever2 = async () => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever3 = async () => {
    return await new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever4 = async () => {
    return Promise.resolve(4);
};

const whatever5 = async () => {
    return await Promise.resolve(4);
};

const whatever6 = async () => Promise.resolve(4);

const whatever7 = async () => await Promise.resolve(4);

In your IDE you will be able to see that the inferred type for all these functions is () => Promise<number>.

How to make zsh run as a login shell on Mac OS X (in iTerm)?

chsh -s $(which zsh)

You'll be prompted for your password, but once you update your settings any new iTerm/Terminal sessions you start on that machine will default to zsh.

How to check for null in a single statement in scala?

Option(getObject) foreach (QueueManager add)

SQLAlchemy create_all() does not create tables

If someone is having issues with creating tables by using files dedicated to each model, be aware of running the "create_all" function from a file different from the one where that function is declared. So, if the filesystem is like this:

Root  
--app.py     <-- file from which app will be run
--models
----user.py      <-- file with "User" model
----order.py    <-- file with "Order" model
----database.py <-- file with database and "create_all" function declaration

Be careful about calling the "create_all" function from app.py.

This concept is explained better by the answer to this thread posted by @SuperShoot

Undefined symbols for architecture arm64

If the architecture and linker settings look good, check your h files. My issue was the same error, but I had restructured the h files and I removed an extern statement. Other m files were using that variable, causing the linker error.

Passing multiple parameters with $.ajax url

why not just pass an data an object with your key/value pairs then you don't have to worry about encoding

$.ajax({
    type: "Post",
    url: "getdata.php",
    data:{
       timestamp: timestamp,
       uid: id,
       uname: name
    },
    async: true,
    cache: false,
    success: function(data) {


    };
}?);?

How can I tell Moq to return a Task?

Now you can also use Talentsoft.Moq.SetupAsync package https://github.com/TalentSoft/Moq.SetupAsync

Which on the base on the answers found here and ideas proposed to Moq but still not yet implemented here: https://github.com/moq/moq4/issues/384, greatly simplify setup of async methods

Few examples found in previous responses done with SetupAsync extension:

mock.SetupAsync(arg=>arg.DoSomethingAsync());
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Callback(() => { <my code here> });
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Throws(new InvalidOperationException());

Check if a file exists with wildcard in shell script

Update: For bash scripts, the most direct and performant approach is:

if compgen -G "${PROJECT_DIR}/*.png" > /dev/null; then
    echo "pattern exists!"
fi

This will work very speedily even in directories with millions of files and does not involve a new subshell.

Source


The simplest should be to rely on ls return value (it returns non-zero when the files do not exist):

if ls /path/to/your/files* 1> /dev/null 2>&1; then
    echo "files do exist"
else
    echo "files do not exist"
fi

I redirected the ls output to make it completely silent.


EDIT: Since this answer has got a bit of attention (and very useful critic remarks as comments), here is an optimization that also relies on glob expansion, but avoids the use of ls:

for f in /path/to/your/files*; do

    ## Check if the glob gets expanded to existing files.
    ## If not, f here will be exactly the pattern above
    ## and the exists test will evaluate to false.
    [ -e "$f" ] && echo "files do exist" || echo "files do not exist"

    ## This is all we needed to know, so we can break after the first iteration
    break
done

This is very similar to @grok12's answer, but it avoids the unnecessary iteration through the whole list.

Adding a slide effect to bootstrap dropdown

Here is a nice simple solution using jQuery that works nicely:

$('.dropdown-toggle').click(function () {
    $(this).next('.dropdown-menu').slideToggle(300);
});

$('.dropdown-toggle').focusout(function () {
    $(this).next('.dropdown-menu').slideUp(300);
})

The slide animation toggle occurs on clicking and it always slides back up on losing focus.

Alter the 300 value to anything you want, the lower the number the faster the animation.

Edit:

This solution will only work for desktop views. It will need some further modification in order to display nicely for mobile.

The term 'ng' is not recognized as the name of a cmdlet

After changing the path you have to restart powershell. You do not need to restart your computer.

How do I put the image on the right side of the text in a UIButton?

After trying multiple solutions from around the internet, I was not achieving the exact requirement. So I ended up writing custom utility code. Posting to help someone in future. Tested on swift 4.2

// This function should be called in/after viewDidAppear to let view render
    func addArrowImageToButton(button: UIButton, arrowImage:UIImage = #imageLiteral(resourceName: "my_image_name") ) {
        let btnSize:CGFloat = 32
        let imageView = UIImageView(image: arrowImage)
        let btnFrame = button.frame
        imageView.frame = CGRect(x: btnFrame.width-btnSize-8, y: btnFrame.height/2 - btnSize/2, width: btnSize, height: btnSize)
        button.addSubview(imageView)
        //Imageview on Top of View
        button.bringSubviewToFront(imageView)
    }

parent & child with position fixed, parent overflow:hidden bug

If you want to hide overflow on fixed-position elements, the simplest approach I've found is to place the element inside a container element, and apply position:fixed and overflow:hidden to that element instead of the contained element (you must remove position:fixed from the contained element for this to work). The content of the fixed container should then be clipped as expected.

In my case I was having trouble with using object-fit:cover on a fixed-position element (it was spilling outside the bounds of the page body, regardless of overflow:hidden). Placing it inside a fixed container with overflow:hidden on the container fixed the issue.

Excel "External table is not in the expected format."

ACE has Superceded JET

Ace Supports all Previous versions of Office

This Code works well!

        OleDbConnection MyConnection;
        DataSet DtSet;
        OleDbDataAdapter MyCommand;
        
        MyConnection = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\\Book.xlsx;Extended Properties=Excel 12.0;");
        MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
        DtSet = new System.Data.DataSet();
        
        MyCommand.Fill(DtSet);
        dataGridView1.DataSource = DtSet.Tables[0];
        MyConnection.Close();

Get size of an Iterable in Java

java 8 and above

StreamSupport.stream(data.spliterator(), false).count();

Detect network connection type on Android

Detect the what type of network and getting the boolean value of isconnected or not use below snippet

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
public class NetworkManagerUtils {

/**
 * Get the network info
 * @param context
 * @return
 */
public static NetworkInfo getNetworkInfo(Context context){
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo();
}

/**
 * Check if there is any connectivity
 * @param context
 * @return
 */
public static boolean isConnected(Context context){
    NetworkInfo info = NetworkManagerUtils.getNetworkInfo(context);
    return (info != null && info.isConnected());
}

/**
 * Check if there is any connectivity to a Wifi network
 * @param context.
 * @param type
 * @return
 */
public static boolean isConnectedWifi(Context context){
    NetworkInfo info = NetworkManagerUtils.getNetworkInfo(context);
    return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}

/**
 * Check if there is any connectivity to a mobile network
 * @param context
 * @param type
 * @return
 */
public static boolean isConnectedMobile(Context context){
    NetworkInfo info = NetworkManagerUtils.getNetworkInfo(context);
    return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
}

/**
 * Check if there is fast connectivity
 * @param context
 * @return
 */
public static boolean isConnectedFast(Context context){
    NetworkInfo info = NetworkManagerUtils.getNetworkInfo(context);
    return (info != null && info.isConnected() && NetworkManagerUtils.isConnectionFast(info.getType(),info.getSubtype()));
}

/**
 * Check if the connection is fast
 * @param type
 * @param subType
 * @return
 */
public static boolean isConnectionFast(int type, int subType){
    if(type== ConnectivityManager.TYPE_WIFI){
        return true;
    }else if(type==ConnectivityManager.TYPE_MOBILE){
        switch(subType){
            case TelephonyManager.NETWORK_TYPE_1xRTT:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_CDMA:
                return false; // ~ 14-64 kbps
            case TelephonyManager.NETWORK_TYPE_EDGE:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
                return true; // ~ 400-1000 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
                return true; // ~ 600-1400 kbps
            case TelephonyManager.NETWORK_TYPE_GPRS:
                return false; // ~ 100 kbps
            case TelephonyManager.NETWORK_TYPE_HSDPA:
                return true; // ~ 2-14 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPA:
                return true; // ~ 700-1700 kbps
            case TelephonyManager.NETWORK_TYPE_HSUPA:
                return true; // ~ 1-23 Mbps
            case TelephonyManager.NETWORK_TYPE_UMTS:
                return true; // ~ 400-7000 kbps
            /*
             * Above API level 7, make sure to set android:targetSdkVersion
             * to appropriate level to use these
             */
            case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11
                return true; // ~ 1-2 Mbps
            case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9
                return true; // ~ 5 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13
                return true; // ~ 10-20 Mbps
            case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8
                return false; // ~25 kbps
            case TelephonyManager.NETWORK_TYPE_LTE: // API level 11
                return true; // ~ 10+ Mbps
            // Unknown
            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
            default:
                return false;
        }
    }else{
        return false;
    }
}
public static String getNetworkClass(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info == null || !info.isConnected())
        return "-"; // not connected
    if (info.getType() == ConnectivityManager.TYPE_WIFI)
        return "WIFI";
    if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
        int networkType = info.getSubtype();
        switch (networkType) {
            case TelephonyManager.NETWORK_TYPE_GPRS:
            case TelephonyManager.NETWORK_TYPE_EDGE:
            case TelephonyManager.NETWORK_TYPE_CDMA:
            case TelephonyManager.NETWORK_TYPE_1xRTT:
            case TelephonyManager.NETWORK_TYPE_IDEN:     // api< 8: replace by 11
            case TelephonyManager.NETWORK_TYPE_GSM:      // api<25: replace by 16
                return "2G";
            case TelephonyManager.NETWORK_TYPE_UMTS:
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
            case TelephonyManager.NETWORK_TYPE_HSDPA:
            case TelephonyManager.NETWORK_TYPE_HSUPA:
            case TelephonyManager.NETWORK_TYPE_HSPA:
            case TelephonyManager.NETWORK_TYPE_EVDO_B:   // api< 9: replace by 12
            case TelephonyManager.NETWORK_TYPE_EHRPD:    // api<11: replace by 14
            case TelephonyManager.NETWORK_TYPE_HSPAP:    // api<13: replace by 15
            case TelephonyManager.NETWORK_TYPE_TD_SCDMA: // api<25: replace by 17
                return "3G";
            case TelephonyManager.NETWORK_TYPE_LTE:      // api<11: replace by 13
            case TelephonyManager.NETWORK_TYPE_IWLAN:    // api<25: replace by 18
            case 19: // LTE_CA
                return "4G";
            default:
                return "?";
        }
    }
    return "?";
}
}

use this following the class pass the context you will the get network status like network type,fast network,etc.

How to remove symbols from a string with Python?

Sometimes it takes longer to figure out the regex than to just write it out in python:

import string
s = "how much for the maple syrup? $20.99? That's ricidulous!!!"
for char in string.punctuation:
    s = s.replace(char, ' ')

If you need other characters you can change it to use a white-list or extend your black-list.

Sample white-list:

whitelist = string.letters + string.digits + ' '
new_s = ''
for char in s:
    if char in whitelist:
        new_s += char
    else:
        new_s += ' '

Sample white-list using a generator-expression:

whitelist = string.letters + string.digits + ' '
new_s = ''.join(c for c in s if c in whitelist)

How do I create a MessageBox in C#?

This is some of the things you can put into a message box. Enjoy
MessageBox.Show("Enter the text for the message box",
"Enter the name of the message box",
(Enter the button names e.g. MessageBoxButtons.YesNo),
(Enter the icon e.g. MessageBoxIcon.Question),
(Enter the default button e.g. MessageBoxDefaultButton.Button1)

More information can be found here

What is the difference between pip and conda?

For WINDOWS users

"standard" packaging tools situation is improving recently:

  • on pypi itself, there are now 48% of wheel packages as of sept. 11th 2015 (up from 38% in may 2015 , 24% in sept. 2014),

  • the wheel format is now supported out-of-the-box per latest python 2.7.9,

"standard"+"tweaks" packaging tools situation is improving also:

  • you can find nearly all scientific packages on wheel format at http://www.lfd.uci.edu/~gohlke/pythonlibs,

  • the mingwpy project may bring one day a 'compilation' package to windows users, allowing to install everything from source when needed.

"Conda" packaging remains better for the market it serves, and highlights areas where the "standard" should improve.

(also, the dependency specification multiple-effort, in standard wheel system and in conda system, or buildout, is not very pythonic, it would be nice if all these packaging 'core' techniques could converge, via a sort of PEP)

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations

Then you can do things like:

var day = moment("12-25-1995", "MM-DD-YYYY");

or

var day = moment("25/12/1995", "DD/MM/YYYY");

then operate on the date

day.add('days', 7)

and to get the native javascript date

day.toDate();

How to cin to a vector

The initial size() of V will be 0, while int n contains any random value because you don't initialize it.

V.size() < n is probably false.

Silly me missed the "Enter the amount of numbers you want to evaluate: "

If you enter a n that's smaller than V.size() at that time, the loop will terminate.

Why should I prefer to use member initialization lists?

For POD class members, it makes no difference, it's just a matter of style. For class members which are classes, then it avoids an unnecessary call to a default constructor. Consider:

class A
{
public:
    A() { x = 0; }
    A(int x_) { x = x_; }
    int x;
};

class B
{
public:
    B()
    {
        a.x = 3;
    }
private:
    A a;
};

In this case, the constructor for B will call the default constructor for A, and then initialize a.x to 3. A better way would be for B's constructor to directly call A's constructor in the initializer list:

B()
  : a(3)
{
}

This would only call A's A(int) constructor and not its default constructor. In this example, the difference is negligible, but imagine if you will that A's default constructor did more, such as allocating memory or opening files. You wouldn't want to do that unnecessarily.

Furthermore, if a class doesn't have a default constructor, or you have a const member variable, you must use an initializer list:

class A
{
public:
    A(int x_) { x = x_; }
    int x;
};

class B
{
public:
    B() : a(3), y(2)  // 'a' and 'y' MUST be initialized in an initializer list;
    {                 // it is an error not to do so
    }
private:
    A a;
    const int y;
};

Redirect all output to file using Bash on Linux?

you can use this syntax to redirect all output stderr and stdout to stdout.txt

<cmd> <args> > allout.txt 2>&1 

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

Simple: In Visual Studio Report designer
1. Open the report in design mode and delete the dataset from the RDLC File
2. Open solution Explorer and delete the actual (corrupted) XSD file
3. Add the dataset back to the RDLC file.
4. The above procedure will create the new XSD file.
5. More detailed is below.

In Visual Studio, Open your RDLC file Report in Design mode. Click on the report and then Select View and then Report Data from the top line menu. Select Datasets and then Right Click and delete the dataset from the report. Next Open Solution Explorer, if it is not already open in your Visual Studio. Locate the XSD file (It should be the same name as the dataset you just deleted from the report). Now go back and right click again on the report data Datasets, and select Add Dataset . This will create a new XSD file and write the dataset properties to the report. Now your error message will be gone and any missing data will now appear in your reports.

Is the order of elements in a JSON list preserved?

The order of elements in an array ([]) is maintained. The order of elements (name:value pairs) in an "object" ({}) is not, and it's usual for them to be "jumbled", if not by the JSON formatter/parser itself then by the language-specific objects (Dictionary, NSDictionary, Hashtable, etc) that are used as an internal representation.

Fastest way to get the first object from a queryset in django?

It can be like this

obj = model.objects.filter(id=emp_id)[0]

or

obj = model.objects.latest('id')

Refresh Part of Page (div)

Usefetch and innerHTML to load div content

_x000D_
_x000D_
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"

async function refresh() {
  btn.disabled = true;
  dynamicPart.innerHTML = "Loading..."
  dynamicPart.innerHTML = await(await fetch(url)).text();
  setTimeout(refresh,2000);
}
_x000D_
<div id="staticPart">
  Here is static part of page

  <button id="btn" onclick="refresh()">
    Click here to start refreshing every 2s
  </button>
</div>

<div id="dynamicPart">Dynamic part</div>
_x000D_
_x000D_
_x000D_

sql: check if entry in table A exists in table B

The classical answer that works in almost every environment is

SELECT ID, Name, blah, blah
FROM TableB TB
LEFT JOIN TableA TA
ON TB.ID=TA.ID
WHERE TA.ID IS NULL

sometimes NOT EXISTS may be not implemented (not working).

How to create an array of object literals in a loop?

You can do something like that in ES6.

new Array(10).fill().map((e,i) => {
   return {idx: i}
});

phpmyadmin "no data received to import" error, how to fix?

xampp in ubuntu

cd /opt/lampp/etc
vim php.ini

Find:
  post_max_size = 8M
  upload_max_filesize = 2M
  max_execution_time = 30
  max_input_time = 60
  memory_limit = 8M

Change to:
  post_max_size = 750M
  upload_max_filesize = 750M
  max_execution_time = 5000
  max_input_time = 5000
  memory_limit = 1000M

sudo /opt/lampp/lampp restart

Jquery, Clear / Empty all contents of tbody element?

        <table id="table_id" class="table table-hover">
          <thead>
            <tr>
             ...
             ...
            </tr>
          </thead>
        </table>

use this command to clear the body of that table: $("#table_id tbody").empty()

I use jquery to load the table content dynamically, and use this command to clear the body when doing the refreshing.

hope this helps you.

how to check if the input is a number or not in C?

Another way of doing it is by using isdigit function. Below is the code for it:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXINPUT 100
int main()
{
    char input[MAXINPUT] = "";
    int length,i; 

    scanf ("%s", input);
    length = strlen (input);
    for (i=0;i<length; i++)
        if (!isdigit(input[i]))
        {
            printf ("Entered input is not a number\n");
            exit(1);
        }
    printf ("Given input is a number\n");
}

Getting text from td cells with jQuery

First of all, your selector is overkill. I suggest using a class or ID selector like my example below. Once you've corrected your selector, simply use jQuery's .each() to iterate through the collection:

ID Selector:

$('#mytable td').each(function() {
    var cellText = $(this).html();    
});

Class Selector:

$('.myTableClass td').each(function() {
    var cellText = $(this).html();    
});

Additional Information:

Take a look at jQuery's selector docs.

AngularJS - difference between pristine/dirty and touched/untouched

It's worth mentioning that the validation properties are different for forms and form elements (note that touched and untouched are for fields only):

Input fields have the following states:

$untouched The field has not been touched yet
$touched The field has been touched
$pristine The field has not been modified yet
$dirty The field has been modified
$invalid The field content is not valid
$valid The field content is valid

They are all properties of the input field, and are either true or false.

Forms have the following states:

$pristine No fields have been modified yet
$dirty One or more have been modified
$invalid The form content is not valid
$valid The form content is valid
$submitted The form is submitted

They are all properties of the form, and are either true or false.

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

i think this also will be more helpfull.

for the architecture miss match,

i just copy the jdk file from the 32 bit file ?C:\Program Files (x86)\Java\jdk1.7.0_71 and paste it to the 64 bit file ?C:\Program Files\Java\jdk1.7.0_10, then rename the file to match the file you replace to avoid the IDE error(netbeans)

then your good to go.

note: You should buckup you 64bit files so when you want to create 64 bit application you can return it to its location

I can't find my git.exe file in my Github folder

1) Install Git for Windows from here: http://git-scm.com/download/win

2) Note: During installation, Make sure "Use Git and optional Unix tools from the windows command prompt" is selected enter image description here

3) restart the Android Studio and try again

4) Go to File-> New -> Project from version control -> Git

Changing one character in a string

Actually, with strings, you can do something like this:

oldStr = 'Hello World!'    
newStr = ''

for i in oldStr:  
    if 'a' < i < 'z':    
        newStr += chr(ord(i)-32)     
    else:      
        newStr += i
print(newStr)

'HELLO WORLD!'

Basically, I'm "adding"+"strings" together into a new string :).

When do you use map vs flatMap in RxJava?

The way I think about it is that you use flatMap when the function you wanted to put inside of map() returns an Observable. In which case you might still try to use map() but it would be unpractical. Let me try to explain why.

If in such case you decided to stick with map, you would get an Observable<Observable<Something>>. For example in your case, if we used an imaginary RxGson library, that returned an Observable<String> from it's toJson() method (instead of simply returning a String) it would look like this:

Observable.from(jsonFile).map(new Func1<File, Observable<String>>() {
    @Override public Observable<String>> call(File file) {
        return new RxGson().toJson(new FileReader(file), Object.class);
    }
}); // you get Observable<Observable<String>> here

At this point it would be pretty tricky to subscribe() to such an observable. Inside of it you would get an Observable<String> to which you would again need to subscribe() to get the value. Which is not practical or nice to look at.

So to make it useful one idea is to "flatten" this observable of observables (you might start to see where the name _flat_Map comes from). RxJava provides a few ways to flatten observables and for sake of simplicity lets assume merge is what we want. Merge basically takes a bunch of observables and emits whenever any of them emits. (Lots of people would argue switch would be a better default. But if you're emitting just one value, it doesn't matter anyway.)

So amending our previous snippet we would get:

Observable.from(jsonFile).map(new Func1<File, Observable<String>>() {
    @Override public Observable<String>> call(File file) {
        return new RxGson().toJson(new FileReader(file), Object.class);
    }
}).merge(); // you get Observable<String> here

This is a lot more useful, because subscribing to that (or mapping, or filtering, or...) you just get the String value. (Also, mind you, such variant of merge() does not exist in RxJava, but if you understand the idea of merge then I hope you also understand how that would work.)

So basically because such merge() should probably only ever be useful when it succeeds a map() returning an observable and so you don't have to type this over and over again, flatMap() was created as a shorthand. It applies the mapping function just as a normal map() would, but later instead of emitting the returned values it also "flattens" (or merges) them.

That's the general use case. It is most useful in a codebase that uses Rx allover the place and you've got many methods returning observables, which you want to chain with other methods returning observables.

In your use case it happens to be useful as well, because map() can only transform one value emitted in onNext() into another value emitted in onNext(). But it cannot transform it into multiple values, no value at all or an error. And as akarnokd wrote in his answer (and mind you he's much smarter than me, probably in general, but at least when it comes to RxJava) you shouldn't throw exceptions from your map(). So instead you can use flatMap() and

return Observable.just(value);

when all goes well, but

return Observable.error(exception);

when something fails.
See his answer for a complete snippet: https://stackoverflow.com/a/30330772/1402641

Uncaught TypeError: Cannot read property 'length' of undefined

"ProjectID" JSON data format problem Remove "ProjectID": This value collection objeckt key value

 { * * "ProjectID" * * : {
            "name": "ProjectID",
            "value": "16,36,8,7",
            "group": "Genel",
            "editor": {
                "type": "combobox",
                "options": {
                    "url": "..\/jsonEntityVarServices\/?id=6&task=7",
                    "valueField": "value",
                    "textField": "text",
                    "multiple": "true"
                }
            },
            "id": "14",
            "entityVarID": "16",
            "EVarMemID": "47"
        }
    }

ToList().ForEach in Linq

Try with this combination of Lambda expressions:

employees.ToList().ForEach(emp => 
{
    collection.AddRange(emp.Departments);
    emp.Departments.ToList().ForEach(dept => dept.SomeProperty = null);                    
});

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

Does Hibernate create tables in the database automatically

If property hibernate.ddl-auto = update, then it will not create the tables automatically. To create tables automatically, you need to set the property to hibernate.ddl-auto = create

The list of option which is used in the spring boot are

  • validate: validate the schema, makes no changes to the database.

  • update: update the schema.

  • create: creates the schema, destroying previous data.

  • create-drop: drop the schema at the end of the session

  • none: is all other cases

So for the first time you can set it to create and then next time on-wards you should set it to update.

What is the proper use of an EventEmitter?

Yes, go ahead and use it.

EventEmitter is a public, documented type in the final Angular Core API. Whether or not it is based on Observable is irrelevant; if its documented emit and subscribe methods suit what you need, then go ahead and use it.

As also stated in the docs:

Uses Rx.Observable but provides an adapter to make it work as specified here: https://github.com/jhusain/observable-spec

Once a reference implementation of the spec is available, switch to it.

So they wanted an Observable like object that behaved in a certain way, they implemented it, and made it public. If it were merely an internal Angular abstraction that shouldn't be used, they wouldn't have made it public.

There are plenty of times when it's useful to have an emitter which sends events of a specific type. If that's your use case, go for it. If/when a reference implementation of the spec they link to is available, it should be a drop-in replacement, just as with any other polyfill.

Just be sure that the generator you pass to the subscribe() function follows the linked spec. The returned object is guaranteed to have an unsubscribe method which should be called to free any references to the generator (this is currently an RxJs Subscription object but that is indeed an implementation detail which should not be depended on).

export class MyServiceEvent {
    message: string;
    eventId: number;
}

export class MyService {
    public onChange: EventEmitter<MyServiceEvent> = new EventEmitter<MyServiceEvent>();

    public doSomething(message: string) {
        // do something, then...
        this.onChange.emit({message: message, eventId: 42});
    }
}

export class MyConsumer {
    private _serviceSubscription;

    constructor(private service: MyService) {
        this._serviceSubscription = this.service.onChange.subscribe({
            next: (event: MyServiceEvent) => {
                console.log(`Received message #${event.eventId}: ${event.message}`);
            }
        })
    }

    public consume() {
        // do some stuff, then later...

        this.cleanup();
    }

    private cleanup() {
        this._serviceSubscription.unsubscribe();
    }
}

All of the strongly-worded doom and gloom predictions seem to stem from a single Stack Overflow comment from a single developer on a pre-release version of Angular 2.

Correct path for img on React.js

Place the logo in your public folder under e.g. public/img/logo.png and then refer to the public folder as %PUBLIC_URL%:

<img src="%PUBLIC_URL%/img/logo.png"/>

The use of %PUBLIC_URL% in the above will be replaced with the URL of the public folder during the build. Only files inside the public folder can be referenced from the HTML.

Unlike "/img/logo.png" or "logo.png", "%PUBLIC_URL%/img/logo.png" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running npm run build.

Delete specified file from document directory

Swift 3.0:

func removeImage(itemName:String, fileExtension: String) {
  let fileManager = FileManager.default
  let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
  let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
  let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  guard let dirPath = paths.first else {
      return
  }  
  let filePath = "\(dirPath)/\(itemName).\(fileExtension)"
  do {
    try fileManager.removeItem(atPath: filePath)
  } catch let error as NSError {
    print(error.debugDescription)
  }}

Thanks to @Anil Varghese, I wrote very similiar code in swift 2.0:

static func removeImage(itemName:String, fileExtension: String) {
  let fileManager = NSFileManager.defaultManager()
  let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
  let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
  let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
  guard let dirPath = paths.first else {
    return
  }
  let filePath = "\(dirPath)/\(itemName).\(fileExtension)"
  do {
    try fileManager.removeItemAtPath(filePath)
  } catch let error as NSError {
    print(error.debugDescription)
  }
}

How to merge two json string in Python?

As of Python 3.5, you can merge two dicts with:

merged = {**dictA, **dictB}

(https://www.python.org/dev/peps/pep-0448/)

So:

jsonMerged = {**json.loads(jsonStringA), **json.loads(jsonStringB)}
asString = json.dumps(jsonMerged)

etc.

Stopping an Android app from console

I tried all answers here on Linux nothing worked for debugging on unrooted device API Level 23, so i found an Alternative for debugging From Developer Options -> Apps section -> check Do Not keep activities that way when ever you put the app in background it gets killed

P.S remember to uncheck it after you finished debugging

Calculating time difference in Milliseconds

You can use System.nanoTime();

To get the result in readable format, use TimeUnit.MILLISECONDS or NANOSECONDS

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

I encountered a similar problem, I moved the project directory, resulting in installation failure, my solution is as follows: Build->ReBuild

Conversion from 12 hours time to 24 hours time in java

SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a"); 

provided by Bart Kiers answer should be replaced with somethig like

SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a",Locale.UK);

How to properly export an ES6 class in Node 4?

Several of the other answers come close, but honestly, I think you're better off going with the cleanest, simplest syntax. The OP requested a means of exporting a class in ES6 / ES2015. I don't think you can get much cleaner than this:

'use strict';

export default class ClassName {
  constructor () {
  }
}

How to use ConcurrentLinkedQueue?

No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.

First, create your queue:

Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();

Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):

YourProducer producer = new YourProducer(queue);

and:

YourConsumer consumer = new YourConsumer(queue);

and add stuff to it in your producer:

queue.offer(myObject);

and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):

YourObject myObject = queue.poll();

For more info see the Javadoc

EDIT:

If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.

If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:

Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());

A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.

Finally:

Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:

BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();

queue.put(myObject); // Blocks until queue isn't full.

YourObject myObject = queue.take(); // Blocks until queue isn't empty.

Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.

Angular2 *ngFor in select list, set active based on string from object

Check it out in this demo fiddle, go ahead and change the dropdown or default values in the code.

Setting the passenger.Title with a value that equals to a title.Value should work.

View:

<select [(ngModel)]="passenger.Title">
    <option *ngFor="let title of titleArray" [value]="title.Value">
      {{title.Text}}
    </option>
</select>

TypeScript used:

class Passenger {
  constructor(public Title: string) { };
}
class ValueAndText {
  constructor(public Value: string, public Text: string) { }
}

...
export class AppComponent {
    passenger: Passenger = new Passenger("Lord");

    titleArray: ValueAndText[] = [new ValueAndText("Mister", "Mister-Text"),
                                  new ValueAndText("Lord", "Lord-Text")];

}

Returning unique_ptr from functions

unique_ptr doesn't have the traditional copy constructor. Instead it has a "move constructor" that uses rvalue references:

unique_ptr::unique_ptr(unique_ptr && src);

An rvalue reference (the double ampersand) will only bind to an rvalue. That's why you get an error when you try to pass an lvalue unique_ptr to a function. On the other hand, a value that is returned from a function is treated as an rvalue, so the move constructor is called automatically.

By the way, this will work correctly:

bar(unique_ptr<int>(new int(44));

The temporary unique_ptr here is an rvalue.

Correct way to create rounded corners in Twitter Bootstrap

In Bootstrap 4, the correct way to border your elements is to name them as follows in the class list of your elements:

For a slight rounding effect on all corners; class="rounded"
For a slight rounding on the left; class="rounded-left"
For a slight rounding on the top; class="rounded-top"
For a slight rounding on the right; class="rounded-right"
For a slight rounding on the bottom; class="rounded-bottom" 
For a circle rounding, i.e. your element is made circular; class="rounded-circle"
And to remove rounding effects; class="rounded-0"

To use Bootstrap 4 css files, you can simply use the CDN, and use the following link in the of your HTML file:

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

This will provided you with the basics of Bootstrap 4. However if you would like to use the majority of Bootstrap 4 components, including tooltips, popovers, and dropdowns, then you are best to use the following code instead:

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

Alternatively, you can install Bootstrap using NPM, or Bower, and link to the files there.

*Note that the bottom tag of the three is the same as the first tag in the first link path.

A full working example, could be :

<img src="path/to/my/image/image.jpg" width="150" height="150" class="rounded-circle mx-auto">

In the above example, the image is centered by using the Bootstrap auto margin on left and right.

How to get a list of MySQL views?

Another way to find all View:

SELECT DISTINCT table_name FROM information_schema.TABLES WHERE table_type = 'VIEW'

Performance of Arrays vs. Lists

The measurements are nice, but you are going to get significantly different results depending on what you're doing exactly in your inner loop. Measure your own situation. If you're using multi-threading, that alone is a non-trivial activity.

javascript get child by id

If the child is always going to be a specific tag then you could do it like this

function test(el)
{
 var children = el.getElementsByTagName('div');// any tag could be used here..

  for(var i = 0; i< children.length;i++)
  {
    if (children[i].getAttribute('id') == 'child') // any attribute could be used here
    {
     // do what ever you want with the element..  
     // children[i] holds the element at the moment..

    }
  }
}

convert string to char*

First of all, you would have to allocate memory:

char * S = new char[R.length() + 1];

then you can use strcpy with S and R.c_str():

std::strcpy(S,R.c_str());

You can also use R.c_str() if the string doesn't get changed or the c string is only used once. However, if S is going to be modified, you should copy the string, as writing to R.c_str() results in undefined behavior.

Note: Instead of strcpy you can also use str::copy.

How do you get the length of a list in the JSF expression language?

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<h:outputText value="Table Size = #{fn:length(SystemBean.list)}"/>

On screen it displays the Table size

Example: Table Size = 5

Set the space between Elements in Row Flutter

I believe the original post was about removing the space between the buttons in a row, not adding space.

The trick is that the minimum space between the buttons was due to padding built into the buttons as part of the material design specification.

So, don't use buttons! But a GestureDetector instead. This widget type give the onClick / onTap functionality but without the styling.

See this post for an example.

https://stackoverflow.com/a/56001817/766115

Create empty file using python

There is no way to create a file without opening it There is os.mknod("newfile.txt") (but it requires root privileges on OSX). The system call to create a file is actually open() with the O_CREAT flag. So no matter how, you'll always open the file.

So the easiest way to simply create a file without truncating it in case it exists is this:

open(x, 'a').close()

Actually you could omit the .close() since the refcounting GC of CPython will close it immediately after the open() statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.

In case you want touch's behaviour (i.e. update the mtime in case the file exists):

import os
def touch(path):
    with open(path, 'a'):
        os.utime(path, None)

You could extend this to also create any directories in the path that do not exist:

basedir = os.path.dirname(path)
if not os.path.exists(basedir):
    os.makedirs(basedir)

Check if string begins with something?

First, lets extend the string object. Thanks to Ricardo Peres for the prototype, I think using the variable 'string' works better than 'needle' in the context of making it more readable.

String.prototype.beginsWith = function (string) {
    return(this.indexOf(string) === 0);
};

Then you use it like this. Caution! Makes the code extremely readable.

var pathname = window.location.pathname;
if (pathname.beginsWith('/sub/1')) {
    // Do stuff here
}

how to access iFrame parent page using jquery?

yeah it works for me as well.

Note : we need to use window.parent.document

    $("button", window.parent.document).click(function()
    {
        alert("Functionality defined by def");
    });

What is the difference between Class.getResource() and ClassLoader.getResource()?

Class.getResources would retrieve the resource by the classloader which load the object. While ClassLoader.getResource would retrieve the resource using the classloader specified.

How to access a dictionary element in a Django template?

You could use a namedtuple instead of a dict. This is a shorthand for using a data class. Instead of

person = {'name':  'John', 'age':  14}

...do:

from collections import namedtuple
Person = namedtuple('person', ['name', 'age'])
p = Person(name='John', age=14)
p.name # 'John'

This is the same as writing a class that just holds data. In general I would avoid using dicts in django templates because they are awkward.

How to force NSLocalizedString to use a specific language

Swift 3 solution:

let languages = ["bs", "zh-Hant", "en", "fi", "ko", "lv", "ms", "pl", "pt-BR", "ru", "sr-Latn", "sk", "es", "tr"]
UserDefaults.standard.set([languages[0]], forKey: "AppleLanguages")

Gave some examples of language codes that can be used. Hope this helps

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

You don't need to learn JPA. You can use my easy-criteria for JPA2 (https://sourceforge.net/projects/easy-criteria/files/). Here is the example

CriteriaComposer<Pet> petCriteria CriteriaComposer.from(Pet.class).
where(Pet_.type, EQUAL, "Cat").join(Pet_.owner).where(Ower_.name,EQUAL, "foo");

List<Pet> result = CriteriaProcessor.findAllEntiry(petCriteria);

OR

List<Tuple> result =  CriteriaProcessor.findAllTuple(petCriteria);

HTML Input Box - Disable

<input type="text" disabled="disabled" />

See the W3C HTML Specification on the input tag for more information.

Access an arbitrary element in a dictionary in Python

Ignoring issues surrounding dict ordering, this might be better:

next(dict.itervalues())

This way we avoid item lookup and generating a list of keys that we don't use.

Python3

next(iter(dict.values()))

How to check 'undefined' value in jQuery

I am not sure it is the best solution, but it works fine:

if($someObject['length']!=0){
    //do someting
}

Jquery submit form

If you have only 1 form in you page, use this. You do not need to know id or name of the form. I just used this code - working:

document.forms[0].submit();

configuring project ':app' failed to find Build Tools revision

In my case issue was with wrong path to NDK.

If your project requires it please check it in menu File -> Project Structure -> SDK Location:

enter image description here

Split array into chunks

Here's a solution using ImmutableJS, where items is an Immutable List and size is the required grouping size.

const partition = ((items, size) => {
  return items.groupBy((items, i) => Math.floor(i/size))
})

sql query distinct with Row_Number

Try this:

;WITH CTE AS (
               SELECT DISTINCT id FROM table WHERE fid = 64
             )
SELECT id, ROW_NUMBER() OVER (ORDER BY  id) AS RowNum
  FROM cte
 WHERE fid = 64

Does Python have a package/module management system?

As a Ruby and Perl developer and learning-Python guy, I haven't found easy_install or pip to be the equivalent to RubyGems or CPAN.

I tend to keep my development systems running the latest versions of modules as the developers update them, and freeze my production systems at set versions. Both RubyGems and CPAN make it easy to find modules by listing what's available, then install and later update them individually or in bulk if desired.

easy_install and pip make it easy to install a module ONCE I located it via a browser search or learned about it by some other means, but they won't tell me what is available. I can explicitly name the module to be updated, but the apps won't tell me what has been updated nor will they update everything in bulk if I want.

So, the basic functionality is there in pip and easy_install but there are features missing that I'd like to see that would make them friendlier and easier to use and on par with CPAN and RubyGems.

Returning the product of a list

I am surprised no-one has suggested using itertools.accumulate with operator.mul. This avoids using reduce, which is different for Python 2 and 3 (due to the functools import required for Python 3), and moreover is considered un-pythonic by Guido van Rossum himself:

from itertools import accumulate
from operator import mul

def prod(lst):
    for value in accumulate(lst, mul):
        pass
    return value

Example:

prod([1,5,4,3,5,6])
# 1800

How do I remove objects from a JavaScript associative array?

Objects in JavaScript can be thought of as associative arrays, mapping keys (properties) to values.

To remove a property from an object in JavaScript you use the delete operator:

const o = { lastName: 'foo' }
o.hasOwnProperty('lastName') // true
delete o['lastName']
o.hasOwnProperty('lastName') // false

Note that when delete is applied to an index property of an Array, you will create a sparsely populated array (ie. an array with a missing index).

When working with instances of Array, if you do not want to create a sparsely populated array - and you usually don't - then you should use Array#splice or Array#pop.

Note that the delete operator in JavaScript does not directly free memory. Its purpose is to remove properties from objects. Of course, if a property being deleted holds the only remaining reference to an object o, then o will subsequently be garbage collected in the normal way.

Using the delete operator can affect JavaScript engines' ability to optimise code.

Android Studio don't generate R.java for my import project

So, this is the latest solution if anyone get's stuck like I did today especially, for R.Java file.

If you have lost the count of:

  • Clean Project
  • Rebuild Project
  • Invalidate Caches / Restart
  • deleted .gradle folder
  • deleted .idea folder
  • deleted app/build/generated folder
  • checked your xml files
  • checked your drawables and strings

then try this:

check your classpath dependency in your Project Gradle Scripts and if it's, this:

classpath 'com.android.tools.build:gradle:3.3.2'

then downgrade it to, this:

classpath 'com.android.tools.build:gradle:3.2.1'

Using multiple delimiters in awk

The delimiter can be a regular expression.

awk -F'[/=]' '{print $3 "\t" $5 "\t" $8}' file

Produces:

tc0001   tomcat7.1    demo.example.com  
tc0001   tomcat7.2    quest.example.com  
tc0001   tomcat7.5    www.example.com

Can the Android layout folder contain subfolders?

Well, the short answer is no. But you definitely can have multiple res folders. That, I think, is as close as you can get to having subfolders for the layout folder. Here's how you do it.

No module named pkg_resources

On windows, I installed pip downloaded from www.lfd.uci.edu/~gohlke/pythonlibs/ then encontered this problem.

So I should have installed setuptools(easy_install) first.

change the date format in laravel view page

In your Model set:

protected $dates = ['name_field'];

after in your view :

{{ $user->from_date->format('d/m/Y') }}

works

Python - Locating the position of a regex match in a string?

re.Match objects have a number of methods to help you with this:

>>> m = re.search("is", String)
>>> m.span()
(2, 4)
>>> m.start()
2
>>> m.end()
4

What is the difference between IQueryable<T> and IEnumerable<T>?

Below mentioned small test might help you understand one aspect of difference between IQueryable<T> and IEnumerable<T>. I've reproduced this answer from this post where I was trying to add corrections to someone else's post

I created following structure in DB (DDL script):

CREATE TABLE [dbo].[Employee]([PersonId] [int] NOT NULL PRIMARY KEY,[Salary] [int] NOT NULL)

Here is the record insertion script (DML script):

INSERT INTO [EfTest].[dbo].[Employee] ([PersonId],[Salary])VALUES(1, 20)
INSERT INTO [EfTest].[dbo].[Employee] ([PersonId],[Salary])VALUES(2, 30)
INSERT INTO [EfTest].[dbo].[Employee] ([PersonId],[Salary])VALUES(3, 40)
INSERT INTO [EfTest].[dbo].[Employee] ([PersonId],[Salary])VALUES(4, 50)
INSERT INTO [EfTest].[dbo].[Employee] ([PersonId],[Salary])VALUES(5, 60)
GO

Now, my goal was to simply get top 2 records from Employee table in database. I added an ADO.NET Entity Data Model item into my console application pointing to Employee table in my database and started writing LINQ queries.

Code for IQueryable route:

using (var efContext = new EfTestEntities())
{
    IQueryable<int> employees = from e in efContext.Employees  select e.Salary;
    employees = employees.Take(2);

    foreach (var item in employees)
    {
        Console.WriteLine(item);
    }
}

When I started to run this program, I had also started a session of SQL Query profiler on my SQL Server instance and here is the summary of execution:

  1. Total number of queries fired: 1
  2. Query text: SELECT TOP (2) [c].[Salary] AS [Salary] FROM [dbo].[Employee] AS [c]

It is just that IQueryable is smart enough to apply the Top (2) clause on database server side itself so it brings only 2 out of 5 records over the wire. Any further in-memory filtering is not required at all on client computer side.

Code for IEnumerable route:

using (var efContext = new EfTestEntities())
{
    IEnumerable<int> employees = from e in efContext.Employees  select e.Salary;
    employees = employees.Take(2);

    foreach (var item in employees)
    {
        Console.WriteLine(item);
    }
}

Summary of execution in this case:

  1. Total number of queries fired: 1
  2. Query text captured in SQL profiler: SELECT [Extent1].[Salary] AS [Salary] FROM [dbo].[Employee] AS [Extent1]

Now the thing is IEnumerable brought all the 5 records present in Salary table and then performed an in-memory filtering on the client computer to get top 2 records. So more data (3 additional records in this case) got transferred over the wire unnecessarily.

Run ScrollTop with offset of element by ID

No magic involved, just subtract from the offset top of the element

$('html, body').animate({scrollTop: $('#contact').offset().top -100 }, 'slow');

How to fix missing dependency warning when using useEffect React Hook?

just disable eslint for the next line;

useEffect(() => {
   fetchBusinesses();
// eslint-disable-next-line
}, []);

in this way you are using it just like a component did mount (called once)

updated

or

const fetchBusinesses = useCallback(() => {
 // your logic in here
 }, [someDeps])

useEffect(() => {
   fetchBusinesses();
// no need to skip eslint warning
}, [fetchBusinesses]); 

fetchBusinesses will be called everytime someDeps will change

How does paintComponent work?

The internals of the GUI system call that method, and they pass in the Graphics parameter as a graphics context onto which you can draw.

Yum fails with - There are no enabled repos.

ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.

But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:

sudo apt-get install libstdc++.i686

HTTP 404 when accessing .svc file in IIS

None of the above solutions resolved this error for me. I had to set the following in web.config:

system.servicemodel > bindings > webHttpBinding > binding:
<security mode="Transport">
  <transport clientCredentialType="None" />
</security>

I would like to take this opportunity to CURSE Microsoft once again for creating such a huge mess with the .NET Framework and making developer lives so miserable for so long!

How to prune local tracking branches that do not exist on remote anymore

After pruning, you can get the list of remote branches with git branch -r. The list of branches with their remote tracking branch can be retrieved with git branch -vv. So using these two lists you can find the remote tracking branches that are not in the list of remotes.

This line should do the trick (requires bash or zsh, won't work with standard Bourne shell):

git branch -r | awk '{print $1}' | egrep -v -f /dev/fd/0 <(git branch -vv | grep origin) | awk '{print $1}' | xargs git branch -d

This string gets the list of remote branches and passes it into egrep through the standard input. And filters the branches that have a remote tracking branch (using git branch -vv and filtering for those that have origin) then getting the first column of that output which will be the branch name. Finally passing all the branch names into the delete branch command.

Since it is using the -d option, it will not delete branches that have not been merged into the branch that you are on when you run this command.

Also remember that you'll need to run git fetch --prune first, otherwise git branch -r will still see the remote branches.

How to fix "unable to write 'random state' " in openssl

The quickest solution is: set environment variable RANDFILE to path where the 'random state' file can be written (of course check the file access permissions), eg. in your command prompt:

set RANDFILE=C:\MyDir\.rnd
openssl genrsa -out my-prvkey.pem 1024

More explanations: OpenSSL on Windows tries to save the 'random state' file in the following order:

  1. Path taken from RANDFILE environment variable
  2. If HOME environment variable is set then : ${HOME}\.rnd
  3. C:\.rnd

I'm pretty sure that in your case it ends up trying to save it in C:\.rnd (and it fails because lack of sufficient access rights). Unfortunately OpenSSL does not print the path that is actually tries to use in any error messages.

show and hide divs based on radio button click

With $("div.desc").hide(); you are essentially trying to hide a div with a class name of desc. Which doesn't exist. With $("#"+test).show(); you are trying to show either a div with an id of #2 or #3. Those are illegal id's in HTML (can't start with a number), though they will work in many browsers. However, they don't exist.

I'd rename the two divs to carDiv2 and carDiv3 and then use different logic to hide or show.

if((test) == 2) { ... }

Also, use a class for your checkboxes so your binding becomes something like

$('.carCheckboxes').click(function ...

AngularJS $http-post - convert binary to excel file and download

There is no way (to my knowledge) to trigger the download window in your browser from Javascript. The only way to do it is to redirect the browser to a url that streams the file to the browser.

If you can modify your REST service, you might be able to solve it by changing so the POST request doesn't respond with the binary file, but with a url to that file. That'll get you the url in Javascript instead of the binary data, and you can redirect the browser to that url, which should prompt the download without leaving the original page.

String to decimal conversion: dot separation instead of comma

Instead of replace we can force culture like

var x = decimal.Parse("18,285", new NumberFormatInfo() { NumberDecimalSeparator = "," });

it will give output 18.285

Refreshing page on click of a button

This question actually is not JSP related, it is HTTP related. you can just do:

window.location = window.location;

Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager

i found that i had a timer running in the background. when the activity is killed, yet the timer still running. in the timer finish callback i access fragment object to do some work, and here is the bug!!!! the fragment exists but the activity isn't.

if you have service of timer or any background threads, make sure to not access fragments objects.

Can I execute a function after setState is finished updating?

setState(updater[, callback]) is an async function:

https://facebook.github.io/react/docs/react-component.html#setstate

You can execute a function after setState is finishing using the second param callback like:

this.setState({
    someState: obj
}, () => {
    this.afterSetStateFinished();
});

The same can be done with hooks in React functional component:

https://github.com/the-road-to-learn-react/use-state-with-callback#usage

Look at useStateWithCallbackLazy:

import { useStateWithCallbackLazy } from 'use-state-with-callback';

const [count, setCount] = useStateWithCallbackLazy(0);

setCount(count + 1, () => {
   afterSetCountFinished();
});

C#: HttpClient with POST parameters

As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )

The querystring (get) parameters included in your url probably will not do anything.

Try this:

string url = "http://myserver/method";    
string content = "param1=1&param2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);

HTH,

bovako

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

You need to provide iterables as the values for the Pandas DataFrame columns:

df2 = pd.DataFrame({'A':[a],'B':[b]})

How do I center align horizontal <UL> menu?

I used the display:inline-block property: the solution consist in use a wrapper with fixed width. Inside, the ul block with the inline-block for display. Using this, the ul just take the width for the real content! and finally margin: 0 auto, to center this inline-block =)

/*ul wrapper*/
.gallery_wrapper{
        width:          958px;
        margin:         0 auto;
  }
/*ul list*/
ul.gallery_carrousel{
        display:        inline-block;
        margin:         0 auto;
}
.contenido_secundario li{
        float:          left;
}

How to uninstall / completely remove Oracle 11g (client)?

Do everything suggested by ziesemer.

You may also want to :

  • Stop the Oracle-related services (before deleting them from the registry).
  • In the registry, look not only for entries named "Oracle" but also e.g. for "ODP".

Vue.js: Conditional class style binding

if you want to apply separate css classes for same element with conditions in Vue.js you can use the below given method.it worked in my scenario.

html

 <div class="Main" v-bind:class="{ Sub: page}"  >

in here, Main and Sub are two different class names for same div element. v-bind:class directive is used to bind the sub class in here. page is the property we use to update the classes when it's value changed.

js

data:{
page : true;
}

here we can apply a condition if we needed. so, if the page property becomes true element will go with Main and Sub claases css styles. but if false only Main class css styles will be applied.

How to save a BufferedImage as a File

The answer lies within the Java Documentation's Tutorial for Writing/Saving an Image.

The Image I/O class provides the following method for saving an image:

static boolean ImageIO.write(RenderedImage im, String formatName, File output)  throws IOException

The tutorial explains that

The BufferedImage class implements the RenderedImage interface.

so it's able to be used in the method.

For example,

try {
    BufferedImage bi = getMyImage();  // retrieve image
    File outputfile = new File("saved.png");
    ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
    // handle exception
}

It's important to surround the write call with a try block because, as per the API, the method throws an IOException "if an error occurs during writing"

Also explained are the method's objective, parameters, returns, and throws, in more detail:

Writes an image using an arbitrary ImageWriter that supports the given format to a File. If there is already a File present, its contents are discarded.

Parameters:

im - a RenderedImage to be written.

formatName - a String containg the informal name of the format.

output - a File to be written to.

Returns:

false if no appropriate writer is found.

Throws:

IllegalArgumentException - if any parameter is null.

IOException - if an error occurs during writing.

However, formatName may still seem rather vague and ambiguous; the tutorial clears it up a bit:

The ImageIO.write method calls the code that implements PNG writing a “PNG writer plug-in”. The term plug-in is used since Image I/O is extensible and can support a wide range of formats.

But the following standard image format plugins : JPEG, PNG, GIF, BMP and WBMP are always be present.

For most applications it is sufficient to use one of these standard plugins. They have the advantage of being readily available.

There are, however, additional formats you can use:

The Image I/O class provides a way to plug in support for additional formats which can be used, and many such plug-ins exist. If you are interested in what file formats are available to load or save in your system, you may use the getReaderFormatNames and getWriterFormatNames methods of the ImageIO class. These methods return an array of strings listing all of the formats supported in this JRE.

String writerNames[] = ImageIO.getWriterFormatNames();

The returned array of names will include any additional plug-ins that are installed and any of these names may be used as a format name to select an image writer.

For a full and practical example, one can refer to Oracle's SaveImage.java example.

Google map V3 Set Center to specific Marker

may be this will help:

map.setCenter(window.markersArray[2].getPosition());

all the markers info are in markersArray array and it is global. So you can access it from anywhere using window.variablename. Each marker has a unique id and you can put that id in the key of array. so you create marker like this:

window.markersArray[2] = new google.maps.Marker({
            position: new google.maps.LatLng(23.81927, 90.362349),          
            map: map,
            title: 'your info '  
        });

Hope this will help.

Getting the PublicKeyToken of .Net assemblies

If you have included the assembly in your project, you can do :

            var assemblies =
                AppDomain.CurrentDomain.GetAssemblies();


            foreach (var assem in assemblies)
            {
                    Console.WriteLine(assem.FullName);
            }

What are intent-filters in Android?

When there are multiple activities entries in AndroidManifest.xml, how does android know which activity to start first?

There is no "first". In your case, with your manifest as shown, you will have two icons in your launcher. Whichever one the user taps on is the one that gets launched.

I could not understand intent-filters. Can anyone please explain.

There is quite a bit of documentation on the subject. Please consider reading that, then asking more specific questions.

Also, when you get "application has stopped unexpectedly, try again", use adb logcat, DDMS, or the DDMS perspective in Eclipse to examine the Java stack trace associated with the error.

Appending an element to the end of a list in Scala

We can append or prepend two lists or list&array
Append:

var l = List(1,2,3)    
l = l :+ 4 
Result : 1 2 3 4  
var ar = Array(4, 5, 6)    
for(x <- ar)    
{ l = l :+ x }  
  l.foreach(println)

Result:1 2 3 4 5 6

Prepending:

var l = List[Int]()  
   for(x <- ar)  
    { l= x :: l } //prepending    
     l.foreach(println)   

Result:6 5 4 1 2 3

call a function in success of datatable ajax call

You can use dataSrc :

Here is a typical example of datatables.net

var table = $('#example').DataTable( {
    "ajax": {
            "type" : "GET",
            "url" : "ajax.php",
            "dataSrc": function ( json ) {
                //Make your callback here.
                alert("Done!");
                return json.data;
            }       
            },
    "columns": [
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "extn" },
            { "data": "start_date" },
            { "data": "salary" }

        ]
    } );

Spring Boot application can't resolve the org.springframework.boot package

change the version of spring boot parent

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.2.RELEASE</version>
 </parent>

nginx missing sites-available directory

I tried sudo apt install nginx-full. You will get all the required packages.

Xcode Error: "The app ID cannot be registered to your development team."

I was able to get the original bundle identifier to work on my paid team membership account (after having it assigned to my personal team) by revoking the personal team signing certificate that was assigned to the same account id.

  1. On the Apple Developer website sign in with the paid account it, go to Certificates, IDs & Profiles.
  2. Click the personal team certificate.
  3. Click the Revoke button.
  4. Go back to XCode and try signing again. A new certificate will be generated that should work with the bundle id.

This won't work if you still need the certificate for other apps.

How to set MimeBodyPart ContentType to "text/html"?

Try with this:

msg.setContent(email.getBody(), "text/html; charset=ISO-8859-1");

Print string and variable contents on the same line in R

you can use paste0 or cat method to combine string with variable values in R

For Example:

paste0("Value of A : ", a)

cat("Value of A : ", a)

What Are The Best Width Ranges for Media Queries

best bet is targeting features not devices unless you have to, bootstrap do well and you can extend on their breakpoints, for instance targeting pixel density and larger screens above 1920

Difference between modes a, a+, w, w+, and r+ in built-in open function?

I think this is important to consider for cross-platform execution, i.e. as a CYA. :)

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

This is directly quoted from Python Software Foundation 2.7.x.

Ajax request returns 200 OK, but an error event is fired instead of success

Use the following code to ensure the response is in JSON format (PHP version)...

header('Content-Type: application/json');
echo json_encode($return_vars);
exit;

Python - Check If Word Is In A String

You can split string to the words and check the result list.

if word in string.split():
    print 'success'

What's the best way to calculate the size of a directory in .NET?

I know this not a .net solution but here it comes anyways. Maybe it comes handy for people that have windows 10 and want a faster solution. For example if you run this command con your command prompt or by pressing winKey + R:

bash -c "du -sh /mnt/c/Users/; sleep 5"    

The sleep 5 is so you have time to see the results and the windows does not closes

In my computer that displays:

enter image description here

Note at the end how it shows 85G (85 Gigabytes). It is supper fast compared to doing it with .Net. If you want to see the size more accurately remove the h which stands for human readable.

So just do something like Processes.Start("bash",... arguments) That is not the exact code but you get the idea.

How to hide a <option> in a <select> menu with CSS?

The toggleOption function is not perfect and introduced nasty bugs in my application. jQuery will get confused with .val() and .arraySerialize() Try to select options 4 and 5 to see what I mean:

<select id="t">
<option value="v1">options 1</option>
<option value="v2">options 2</option>
<option value="v3" id="o3">options 3</option>
<option value="v4">options 4</option>
<option value="v5">options 5</option>
</select>
<script>
jQuery.fn.toggleOption = function( show ) {
    jQuery( this ).toggle( show );
    if( show ) {
        if( jQuery( this ).parent( 'span.toggleOption' ).length )
            jQuery( this ).unwrap( );
    } else {
        jQuery( this ).wrap( '<span class="toggleOption" style="display: none;" />' );
    }
};

$("#o3").toggleOption(false); 
$("#t").change(function(e) {
    if($(this).val() != this.value) {
    console.log("Error values not equal", this.value, $(this).val());
    }
});
</script>

What is the correct way of reading from a TCP socket in C/C++?

Just to add to things from several of the posts above:

read() -- at least on my system -- returns ssize_t. This is like size_t, except is signed. On my system, it's a long, not an int. You might get compiler warnings if you use int, depending on your system, your compiler, and what warnings you have turned on.

How can I get a specific field of a csv file?

import csv

def read_cell(x, y):
    with open('file.csv', 'r') as f:
        reader = csv.reader(f)
        y_count = 0
        for n in reader:
            if y_count == y:
                cell = n[x]
                return cell
            y_count += 1

print (read_cell(4, 8)) 

This example prints cell 4, 8 in Python 3.

How can I style a PHP echo text?

You cannot style a variable such as $ip['countryName']

You can only style elements like p,div, etc, or classes and ids.

If you want to style $ip['countryName'] there are several ways.

You can echo it within an element:

echo '<p id="style">'.$ip['countryName'].'</p>';
echo '<span id="style">'.$ip['countryName'].'</span>';
echo '<div id="style">'.$ip['countryName'].'</div>';

If you want to style both the variables the same style, then set a class like:

echo '<p class="style">'.$ip['cityName'].'</p>';
echo '<p class="style">'.$ip['countryName'].'</p>';

You could also embed the variables within your actual html rather than echoing them out within the code.

$city = $ip['cityName'];  
$country = $ip['countryName'];
?>
<div class="style"><?php echo $city ?></div>
<div class="style"><?php echo $country?></div>

JDK on OSX 10.7 Lion

You can download the 10.7 Lion JDK from http://connect.apple.com.

  1. Sign in and click the java section on the right.

  2. The jdk is installed into a different location then previous. This will result in IDEs (such as Eclipse) being unable to locate source code and javadocs.

  3. At the time of writing the JDK ended up here:

    /Library/Java/JavaVirtualMachines/1.6.0_26-b03-383.jdk/Contents/Home

  4. Open up eclipse preferences and go to Java --> Installed JREs page

  5. Rather than use the "JVM Contents (MacOS X Default) we will need to use the JDK location

  6. At the time of writing Search is not aware of the new JDK location; we we will need to click on the Add button

  7. From the Add JRE wizard choose "MacOS X VM" for the JRE Type

  8. For the JRE Definition Page we need to fill in the following:

    • JRE Home: /Library/Java/JavaVirtualMachines/1.6.0_26-b03-383.jdk/Contents/Home
  9. The other fields will now auto fill, with the default JRE name being "Home". You can quickly correct this to something more meaningful:

    • JRE name: System JDK
  10. Finish the wizard and return to the Installed JREs page

  11. Choose "System JDK" from the list

  12. You can now develop normally with:

    • javadocs correctly shown for base classes
    • source code correctly shown when debugging

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

Testing Spring's @RequestBody using Spring MockMVC

Use this one

public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

@Test
public void testInsertObject() throws Exception { 
    String url = BASE_URL + "/object";
    ObjectBean anObject = new ObjectBean();
    anObject.setObjectId("33");
    anObject.setUserId("4268321");
    //... more
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
    ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
    String requestJson=ow.writeValueAsString(anObject );

    mockMvc.perform(post(url).contentType(APPLICATION_JSON_UTF8)
        .content(requestJson))
        .andExpect(status().isOk());
}

As described in the comments, this works because the object is converted to json and passed as the request body. Additionally, the contentType is defined as Json (APPLICATION_JSON_UTF8).

More info on the HTTP request body structure

Best way to get whole number part of a Decimal number

I hope help you.

/// <summary>
/// Get the integer part of any decimal number passed trough a string 
/// </summary>
/// <param name="decimalNumber">String passed</param>
/// <returns>teh integer part , 0 in case of error</returns>
private int GetIntPart(String decimalNumber)
{
    if(!Decimal.TryParse(decimalNumber, NumberStyles.Any , new CultureInfo("en-US"), out decimal dn))
    {
        MessageBox.Show("String " + decimalNumber + " is not in corret format", "GetIntPart", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return default(int);
    } 

    return Convert.ToInt32(Decimal.Truncate(dn));
}

What is the best way to prevent session hijacking?

There are many ways to create protection against session hijack, however all of them are either reducing user satisfaction or are not secure.

  • IP and/or X-FORWARDED-FOR checks. These work, and are pretty secure... but imagine the pain of users. They come to an office with WiFi, they get new IP address and lose the session. Got to log-in again.

  • User Agent checks. Same as above, new version of browser is out, and you lose a session. Additionally, these are really easy to "hack". It's trivial for hackers to send fake UA strings.

  • localStorage token. On log-on generate a token, store it in browser storage and store it to encrypted cookie (encrypted on server-side). This has no side-effects for user (localStorage persists through browser upgrades). It's not as secure - as it's just security through obscurity. Additionally you could add some logic (encryption/decryption) to JS to further obscure it.

  • Cookie reissuing. This is probably the right way to do it. The trick is to only allow one client to use a cookie at a time. So, active user will have cookie re-issued every hour or less. Old cookie is invalidated if new one is issued. Hacks are still possible, but much harder to do - either hacker or valid user will get access rejected.

How to align a <div> to the middle (horizontally/width) of the page

_x000D_
_x000D_
parent {_x000D_
    position: relative;_x000D_
}_x000D_
child {_x000D_
    position: absolute;_x000D_
    left: 50%;_x000D_
    transform: translateX(-50%);_x000D_
}
_x000D_
<parent>_x000D_
  <child>_x000D_
  </child>_x000D_
</parent>
_x000D_
_x000D_
_x000D_

Typescript: React event types

you can do like this in react

handleEvent = (e: React.SyntheticEvent<EventTarget>) => {
  const simpleInput = (e.target as HTMLInputElement).value;
  //for simple html input values
  const formInput = (e.target as HTMLFormElement).files[0];
  //for html form elements
}

What are the dark corners of Vim your mom never told you about?

Often, I like changing current directories while editing - so I have to specify paths less.

cd %:h

Razor View Engine : An expression tree may not contain a dynamic operation

Seems like your view is typed dynamic. Set the right type on the view and you'll see the error go away.

How to unmerge a Git merge?

You can reset your branch to the state it was in just before the merge if you find the commit it was on then.

One way is to use git reflog, it will list all the HEADs you've had. I find that git reflog --relative-date is very useful as it shows how long ago each change happened.

Once you find that commit just do a git reset --hard <commit id> and your branch will be as it was before.

If you have SourceTree, you can look up the <commit id> there if git reflog is too overwhelming.

Clearing <input type='file' /> using jQuery

it does not work for me:

$('#Attachment').replaceWith($(this).clone());
or 
$('#Attachment').replaceWith($('#Attachment').clone());

so in asp mvc I use razor features for replacing file input. at first create a variable for input string with Id and Name and then use it for showing in page and replacing on reset button click:

@{
    var attachmentInput = Html.TextBoxFor(c => c.Attachment, new { type = "file" });
}

@attachmentInput

<button type="button" onclick="$('#@(Html.IdFor(p => p.Attachment))').replaceWith('@(attachmentInput)');">--</button>

Getting year in moment.js

_x000D_
_x000D_
var year1 = moment().format('YYYY');_x000D_
var year2 = moment().year();_x000D_
_x000D_
console.log('using format("YYYY") : ',year1);_x000D_
console.log('using year(): ',year2);_x000D_
_x000D_
// using javascript _x000D_
_x000D_
var year3 = new Date().getFullYear();_x000D_
console.log('using javascript :',year3);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Assert an object is a specific type

Solution for JUnit 5

The documentation says:

However, JUnit Jupiter’s org.junit.jupiter.Assertions class does not provide an assertThat() method like the one found in JUnit 4’s org.junit.Assert class which accepts a Hamcrest Matcher. Instead, developers are encouraged to use the built-in support for matchers provided by third-party assertion libraries.

Example for Hamcrest:

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class HamcrestAssertionDemo {

    @Test
    void assertWithHamcrestMatcher() {
        SubClass subClass = new SubClass();
        assertThat(subClass, instanceOf(BaseClass.class));
    }

}

Example for AssertJ:

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

class AssertJDemo {

    @Test
    void assertWithAssertJ() {
        SubClass subClass = new SubClass();
        assertThat(subClass).isInstanceOf(BaseClass.class);
    }

}

Note that this assumes you want to test behaviors similar to instanceof (which accepts subclasses). If you want exact equal type, I don’t see a better way than asserting the two class to be equal like you mentioned in the question.

How to remove a character at the end of each line in unix

Try doing this :

awk '{print substr($0, 1, length($0)-1)}' file.txt

This is more generic than just removing the final comma but any last character

If you'd want to only remove the last comma with awk :

awk '{gsub(/,$/,""); print}' file.txt

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

If the script always outputs lines of 10 characters followed by 3 extra (in other words, you just want the first 10 characters), you can use

script | cut -c 1-10

If it outputs an uncertain number of non-space characters, followed by a space and then 2 other extra characters (in other words, you just want the first field), you can use

script | cut -d ' ' -f 1

... as in majhool's comment earlier. Depending on your platform, you may also have colrm, which, again, would work if the lines are a fixed length:

script | colrm 11

"git rebase origin" vs."git rebase origin/master"

You can make a new file under [.git\refs\remotes\origin] with name "HEAD" and put content "ref: refs/remotes/origin/master" to it. This should solve your problem.

It seems that clone from an empty repos will lead to this. Maybe the empty repos do not have HEAD because no commit object exist.

You can use the

git log --remotes --branches --oneline --decorate

to see the difference between each repository, while the "problem" one do not have "origin/HEAD"

Edit: Give a way using command line
You can also use git command line to do this, they have the same result

git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/master

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

POST Multipart Form Data using Retrofit 2.0 including image

Adding to the answer given by @insomniac. You can create a Map to put the parameter for RequestBody including image.

Code for Interface

public interface ApiInterface {
@Multipart
@POST("/api/Accounts/editaccount")
Call<User> editUser (@Header("Authorization") String authorization, @PartMap Map<String, RequestBody> map);
}

Code for Java class

File file = new File(imageUri.getPath());
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), firstNameField.getText().toString());
RequestBody id = RequestBody.create(MediaType.parse("text/plain"), AZUtils.getUserId(this));

Map<String, RequestBody> map = new HashMap<>();
map.put("file\"; filename=\"pp.png\" ", fbody);
map.put("FirstName", name);
map.put("Id", id);
Call<User> call = client.editUser(AZUtils.getToken(this), map);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(retrofit.Response<User> response, Retrofit retrofit) 
{
    AZUtils.printObject(response.body());
}

@Override
public void onFailure(Throwable t) {
    t.printStackTrace();
 }
});

Javascript Regex: How to put a variable inside a regular expression?

const regex = new RegExp(`ReGeX${testVar}ReGeX`);
...
string.replace(regex, "replacement");

Update

Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)

ES6 Update

In 2019, this would usually be written using a template string, and the above code has been updated. The original answer was:

var regex = new RegExp("ReGeX" + testVar + "ReGeX");
...
string.replace(regex, "replacement");

Difference between JE/JNE and JZ/JNZ

JE and JZ are just different names for exactly the same thing: a conditional jump when ZF (the "zero" flag) is equal to 1.

(Similarly, JNE and JNZ are just different names for a conditional jump when ZF is equal to 0.)

You could use them interchangeably, but you should use them depending on what you are doing:

  • JZ/JNZ are more appropriate when you are explicitly testing for something being equal to zero:

    dec  ecx
    jz   counter_is_now_zero
    
  • JE and JNE are more appropriate after a CMP instruction:

    cmp  edx, 42
    je   the_answer_is_42
    

    (A CMP instruction performs a subtraction, and throws the value of the result away, while keeping the flags; which is why you get ZF=1 when the operands are equal and ZF=0 when they're not.)

How to write URLs in Latex?

A minimalist implementation of the \url macro that uses only Tex primitives:

\def\url#1{\expandafter\string\csname #1\endcsname}

This url absolutely won't break over lines, though; the hypperef package is better for that.

Concatenate columns in Apache Spark DataFrame

concat(*cols)

v1.5 and higher

Concatenates multiple input columns together into a single column. The function works with strings, binary and compatible array columns.

Eg: new_df = df.select(concat(df.a, df.b, df.c))


concat_ws(sep, *cols)

v1.5 and higher

Similar to concat but uses the specified separator.

Eg: new_df = df.select(concat_ws('-', df.col1, df.col2))


map_concat(*cols)

v2.4 and higher

Used to concat maps, returns the union of all the given maps.

Eg: new_df = df.select(map_concat("map1", "map2"))


Using string concat operator (||):

v2.3 and higher

Eg: df = spark.sql("select col_a || col_b || col_c as abc from table_x")

Reference: Spark sql doc

How to diff a commit with its parent?

If you know how far back, you can try something like:

# Current branch vs. parent
git diff HEAD^ HEAD

# Current branch, diff between commits 2 and 3 times back
git diff HEAD~3 HEAD~2

Prior commits work something like this:

# Parent of HEAD
git show HEAD^1

# Grandparent
git show HEAD^2

There are a lot of ways you can specify commits:

# Great grandparent
git show HEAD~3

See this page for details.

Git: "Corrupt loose object"

Try

git stash

This worked for me. It stashes anything you haven't committed and that got around the problem.

kill a process in bash

To interrupt it, you can try pressing ctrl c to send a SIGINT. If it doesn't stop it, you may try to kill it using kill -9 <pid>, which sends a SIGKILL. The latter can't be ignored/intercepted by the process itself (the one being killed).

To move the active process to background, you can press ctrl z. The process is sent to background and you get back to the shell prompt. Use the fg command to do the opposite.

Error when testing on iOS simulator: Couldn't register with the bootstrap server

Mike Ash posted a solution (god bless him!) that doesn't require a reboot. Just run:

launchctl list|grep UIKitApplication|awk '{print $3}'|xargs launchctl remove

The above command lists out all launchd jobs, searches for one with UIKitApplication in the name (which will be the job corresponding to your app that's improperly sticking around), extracts the name, and tells launchd to get rid of that job.

How to copy a row from one SQL Server table to another

INSERT INTO DestTable
SELECT * FROM SourceTable
WHERE ... 

works in SQL Server

How can I set the default timezone in node.js?

You can take moment timezone. It lets you set your location and also takes care of daylight saving time.

How do I read any request header in PHP

Since PHP 5.4.0 you can use getallheaders function which returns all request headers as an associative array:

var_dump(getallheaders());

// array(8) {
//   ["Accept"]=>
//   string(63) "text/html[...]"
//   ["Accept-Charset"]=>
//   string(31) "ISSO-8859-1[...]"
//   ["Accept-Encoding"]=>
//   string(17) "gzip,deflate,sdch"
//   ["Accept-Language"]=>
//   string(14) "en-US,en;q=0.8"
//   ["Cache-Control"]=>
//   string(9) "max-age=0"
//   ["Connection"]=>
//   string(10) "keep-alive"
//   ["Host"]=>
//   string(9) "localhost"
//   ["User-Agent"]=>
//   string(108) "Mozilla/5.0 (Windows NT 6.1; WOW64) [...]"
// }

Earlier this function worked only when PHP was running as an Apache/NSAPI module.

Pandas read_csv low_memory and dtype options

As mentioned earlier by firelynx if dtype is explicitly specified and there is mixed data that is not compatible with that dtype then loading will crash. I used a converter like this as a workaround to change the values with incompatible data type so that the data could still be loaded.

def conv(val):
    if not val:
        return 0    
    try:
        return np.float64(val)
    except:        
        return np.float64(0)

df = pd.read_csv(csv_file,converters={'COL_A':conv,'COL_B':conv})

Printing newlines with print() in R

You can also use a combination of cat and paste0

cat(paste0("File not supplied.\n", "Usage: ./program F=filename"))

I find this to be more useful when incorporating variables into the printout. For example:

file <- "myfile.txt"
cat(paste0("File not supplied.\n", "Usage: ./program F=", file))

How to have stored properties in Swift, the same way I had on Objective-C?

I found this solution more practical

UPDATED for Swift 3

extension UIColor {

    static let graySpace = UIColor.init(red: 50/255, green: 50/255, blue: 50/255, alpha: 1.0)
    static let redBlood = UIColor.init(red: 102/255, green: 0/255, blue: 0/255, alpha: 1.0)
    static let redOrange = UIColor.init(red: 204/255, green: 17/255, blue: 0/255, alpha: 1.0)

    func alpha(value : CGFloat) -> UIColor {
        var r = CGFloat(0), g = CGFloat(0), b = CGFloat(0), a = CGFloat(0)
        self.getRed(&r, green: &g, blue: &b, alpha: &a)
        return UIColor(red: r, green: g, blue: b, alpha: value)
    }

}

...then in your code

class gameController: UIViewController {

    @IBOutlet var game: gameClass!

    override func viewDidLoad() {
        self.view.backgroundColor = UIColor.graySpace

    }
}

stop all instances of node.js server

if you want to kill a specific node process , you can go to command line route and type:

ps aux | grep node

to get a list of all node process ids. now you can get your process id(pid), then do:

kill -9 PID

and if you want to kill all node processes then do:

killall -9 node

-9 switch is like end task on windows. it will force the process to end. you can do:

kill -l

to see all switches of kill command and their comments.

jQuery replace one class with another

Create a class in your CSS file:

.active {
  z-index: 20;
  background: rgb(23,55,94)
  color: #fff;
}

Then in your jQuery

$(this).addClass("active");

Append TimeStamp to a File Name

You can use DateTime.ToString Method (String)

DateTime.Now.ToString("yyyyMMddHHmmssfff")

or string.Format

string.Format("{0:yyyy-MM-dd_HH-mm-ss-fff}", DateTime.Now);

or Interpolated Strings

$"{DateTime.Now:yyyy-MM-dd_HH-mm-ss-fff}"

There are following custom format specifiers y (year), M (month), d (day), h (hour 12), H (hour 24), m (minute), s (second), f (second fraction), F (second fraction, trailing zeroes are trimmed), t (P.M or A.M) and z (time zone).

With Extension Method

Usage:

string result = "myfile.txt".AppendTimeStamp();
//myfile20130604234625642.txt

Extension method

public static class MyExtensions
{
    public static string AppendTimeStamp(this string fileName)
    {
        return string.Concat(
            Path.GetFileNameWithoutExtension(fileName),
            DateTime.Now.ToString("yyyyMMddHHmmssfff"),
            Path.GetExtension(fileName)
            );
    }
}

javascript find and remove object in array based on key value

Array.prototype.removeAt = function(id) {
    for (var item in this) {
        if (this[item].id == id) {
            this.splice(item, 1);
            return true;
        }
    }
    return false;
}

This should do the trick, jsfiddle

How to print the ld(linker) search path

I'm not sure that there is any option for simply printing the full effective search path.

But: the search path consists of directories specified by -L options on the command line, followed by directories added to the search path by SEARCH_DIR("...") directives in the linker script(s). So you can work it out if you can see both of those, which you can do as follows:

If you're invoking ld directly:

  • The -L options are whatever you've said they are.
  • To see the linker script, add the --verbose option. Look for the SEARCH_DIR("...") directives, usually near the top of the output. (Note that these are not necessarily the same for every invocation of ld -- the linker has a number of different built-in default linker scripts, and chooses between them based on various other linker options.)

If you're linking via gcc:

  • You can pass the -v option to gcc so that it shows you how it invokes the linker. In fact, it normally does not invoke ld directly, but indirectly via a tool called collect2 (which lives in one of its internal directories), which in turn invokes ld. That will show you what -L options are being used.
  • You can add -Wl,--verbose to the gcc options to make it pass --verbose through to the linker, to see the linker script as described above.

How do I pipe or redirect the output of curl -v?

This simple example shows how to capture curl output, and use it in a bash script

test.sh

function main
{
  \curl -vs 'http://google.com'  2>&1
  # note: add -o /tmp/ignore.png if you want to ignore binary output, by saving it to a file. 
}

# capture output of curl to a variable
OUT=$(main)

# search output for something using grep.
echo
echo "$OUT" | grep 302 
echo
echo "$OUT" | grep title 

Automatically create an Enum based on values in a database lookup table?

I always like to write my own "custom enum". Than I have one class that is a little bit more complex, but I can reuse it:

public abstract class CustomEnum
{
    private readonly string _name;
    private readonly object _id;

    protected CustomEnum( string name, object id )
    {
        _name = name;
        _id = id;
    }

    public string Name
    {
        get { return _name; }
    }

    public object Id
    {
        get { return _id; }
    }

    public override string ToString()
    {
        return _name;
    }
}

public abstract class CustomEnum<TEnumType, TIdType> : CustomEnum
    where TEnumType : CustomEnum<TEnumType, TIdType>
{
    protected CustomEnum( string name, TIdType id )
        : base( name, id )
    { }

    public new TIdType Id
    {
        get { return (TIdType)base.Id; }
    }

    public static TEnumType FromName( string name )
    {
        try
        {
            return FromDelegate( entry => entry.Name.Equals( name ) );
        }
        catch (ArgumentException ae)
        {
            throw new ArgumentException( "Illegal name for custom enum '" + typeof( TEnumType ).Name + "'", ae );
        }
    }

    public static TEnumType FromId( TIdType id )
    {
        try
        {
            return FromDelegate( entry => entry.Id.Equals( id ) );
        }
        catch (ArgumentException ae)
        {
            throw new ArgumentException( "Illegal id for custom enum '" + typeof( TEnumType ).Name + "'", ae );
        }
    }

    public static IEnumerable<TEnumType> GetAll()
    {
        var elements = new Collection<TEnumType>();
        var infoArray = typeof( TEnumType ).GetFields( BindingFlags.Public | BindingFlags.Static );

        foreach (var info in infoArray)
        {
            var type = info.GetValue( null ) as TEnumType;
            elements.Add( type );
        }

        return elements;
    }

    protected static TEnumType FromDelegate( Predicate<TEnumType> predicate )
    {
        if(predicate == null)
            throw new ArgumentNullException( "predicate" );

        foreach (var entry in GetAll())
        {
            if (predicate( entry ))
                return entry;
        }

        throw new ArgumentException( "Element not found while using predicate" );
    }
}

Now I just need to create my enum I want to use:

 public sealed class SampleEnum : CustomEnum<SampleEnum, int>
    {
        public static readonly SampleEnum Element1 = new SampleEnum( "Element1", 1, "foo" );
        public static readonly SampleEnum Element2 = new SampleEnum( "Element2", 2, "bar" );

        private SampleEnum( string name, int id, string additionalText )
            : base( name, id )
        {
            AdditionalText = additionalText;
        }

        public string AdditionalText { get; private set; }
    }

At last I can use it like I want:

 static void Main( string[] args )
        {
            foreach (var element in SampleEnum.GetAll())
            {
                Console.WriteLine( "{0}: {1}", element, element.AdditionalText );
                Console.WriteLine( "Is 'Element2': {0}", element == SampleEnum.Element2 );
                Console.WriteLine();
            }

            Console.ReadKey();
        }

And my output would be:

Element1: foo
Is 'Element2': False

Element2: bar
Is 'Element2': True    

Getting "A potentially dangerous Request.Path value was detected from the client (&)"

Check the below lines are present in your web.config file

<system.web> <httpRuntime requestPathInvalidCharacters="" /> </system.web>

jQuery change event on dropdown

The html

<select id="drop"  name="company" class="company btn btn-outline   dropdown-toggle" >
   <option value="demo1">Group Medical</option>
   <option value="demo">Motor Insurance</option>
</select>

Script.js

$("#drop").change(function () {                            
   var category= $('select[name=company]').val() // Here we can get the value of selected item
   alert(category); 
});

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

I changed my web.config file to use HTTPMODULE in two forms:

IIS: 6

<httpModules>
    <add name="Module" type="app.Module,app"/>
</httpModules>

IIS: 7.5

<system.webServer>
    <modules>
       <add name="Module" type="app.Module,app"/>
    </modules>
</system.webServer>