Programs & Examples On #Ar mailer

inserting characters at the start and end of a string

Strings are immutable so you can't insert characters into an existing string. You have to create a new string. You can use string concatenation to do what you want:

yourstring = "L" + yourstring + "LL"

Note that you can also create a string with n Ls by using multiplication:

m = 1
n = 2
yourstring = ("L" * m) + yourstring + ("L" * n)

How can I discover the "path" of an embedded resource?

I'm guessing that your class is in a different namespace. The canonical way to solve this would be to use the resources class and a strongly typed resource:

ProjectNamespace.Properties.Resources.file

Use the IDE's resource manager to add resources.

Python: Checking if a 'Dictionary' is empty doesn't seem to work

Empty dictionaries evaluate to False in Python:

>>> dct = {}
>>> bool(dct)
False
>>> not dct
True
>>>

Thus, your isEmpty function is unnecessary. All you need to do is:

def onMessage(self, socket, message):
    if not self.users:
        socket.send("Nobody is online, please use REGISTER command" \
                    " in order to register into the server")
    else:
        socket.send("ONLINE " + ' ' .join(self.users.keys()))

Create 3D array using Python

def n_arr(n, default=0, size=1):
    if n is 0:
        return default

    return [n_arr(n-1, default, size) for _ in range(size)]

arr = n_arr(3, 42, 3)
assert arr[2][2][2], 42

Hide text using css

So many complicated solutions.

The easiest one is simply to use:

color:rgba(0,0,0,0)

How to convert a date to milliseconds

You don't have a Date, you have a String representation of a date. You should convert the String into a Date and then obtain the milliseconds. To convert a String into a Date and vice versa you should use SimpleDateFormat class.

Here's an example of what you want/need to do (assuming time zone is not involved here):

String myDate = "2014/10/29 18:10:45";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long millis = date.getTime();

Still, be careful because in Java the milliseconds obtained are the milliseconds between the desired epoch and 1970-01-01 00:00:00.


Using the new Date/Time API available since Java 8:

String myDate = "2014/10/29 18:10:45";
LocalDateTime localDateTime = LocalDateTime.parse(myDate,
    DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss") );
/*
  With this new Date/Time API, when using a date, you need to
  specify the Zone where the date/time will be used. For your case,
  seems that you want/need to use the default zone of your system.
  Check which zone you need to use for specific behaviour e.g.
  CET or America/Lima
*/
long millis = localDateTime
    .atZone(ZoneId.systemDefault())
    .toInstant().toEpochMilli();

Using OpenGl with C#?

SharpGL is a project that lets you use OpenGL in your Windows Forms or WPF applications.

Remove attribute "checked" of checkbox

Both of these should work:

$("#captureImage").prop('checked', false);

AND/OR

$("#captureImage").removeAttr('checked');

... you can try both together.

How to send POST in angularjs with multiple params?

If you're using ASP.NET MVC and Web API chances are you have the Newtonsoft.Json NuGet package installed.This library has a class called JObject which allows you to pass through multiple parameters:

Api Controller:

public class ProductController : ApiController
{
    [HttpPost]
    public void Post(Newtonsoft.Json.Linq.JObject data)
    {
        System.Diagnostics.Debugger.Break();

        Product product = data["product"].ToObject<Product>();
        Product product2 = data["product2"].ToObject<Product>();

        int someRandomNumber = data["randomNumber"].ToObject<int>();
        string productName = product.ProductName;
        string product2Name = product2.ProductName;
    }
}

public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
}

View:

<script src="~/Scripts/angular.js"></script>
<script type="text/javascript">
    var myApp = angular.module("app", []);
    myApp.controller('controller', function ($scope, $http) {

        $scope.AddProducts = function () {
            var product = {
                ProductID: 0,
                ProductName: "Orange",
            }

            var product2 = {
                ProductID: 1,
                ProductName: "Mango",
            }

            var data = {
                product: product,
                product2: product2,
                randomNumber:12345
            };

            $http.post("/api/Product", data).
            success(function (data, status, headers, config) {
            }).
            error(function (data, status, headers, config) {
                alert("An error occurred during the AJAX request");
            });
        }
    });
</script>
<div ng-app="app" ng-controller="controller">
    <input type="button" ng-click="AddProducts()" value="Get Full Name" />
</div>

C/C++ check if one bit is set in, i.e. int variable

The precedent answers show you how to handle bit checks, but more often then not, it is all about flags encoded in an integer, which is not well defined in any of the precedent cases.

In a typical scenario, flags are defined as integers themselves, with a bit to 1 for the specific bit it refers to. In the example hereafter, you can check if the integer has ANY flag from a list of flags (multiple error flags concatenated) or if EVERY flag is in the integer (multiple success flags concatenated).

Following an example of how to handle flags in an integer.

Live example available here: https://rextester.com/XIKE82408

//g++  7.4.0

#include <iostream>
#include <stdint.h>

inline bool any_flag_present(unsigned int value, unsigned int flags) {
    return bool(value & flags);
}

inline bool all_flags_present(unsigned int value, unsigned int flags) {
    return (value & flags) == flags;
}

enum: unsigned int {
    ERROR_1 = 1U,
    ERROR_2 = 2U, // or 0b10
    ERROR_3 = 4U, // or 0b100
    SUCCESS_1 = 8U,
    SUCCESS_2 = 16U,
    OTHER_FLAG = 32U,
};

int main(void)
{
    unsigned int value = 0b101011; // ERROR_1, ERROR_2, SUCCESS_1, OTHER_FLAG
    unsigned int all_error_flags = ERROR_1 | ERROR_2 | ERROR_3;
    unsigned int all_success_flags = SUCCESS_1 | SUCCESS_2;
    
    std::cout << "Was there at least one error: " << any_flag_present(value, all_error_flags) << std::endl;
    std::cout << "Are all success flags enabled: " << all_flags_present(value, all_success_flags) << std::endl;
    std::cout << "Is the other flag enabled with eror 1: " << all_flags_present(value, ERROR_1 | OTHER_FLAG) << std::endl;
    return 0;
}

How do I read a string entered by the user in C?

You can use scanf function to read string

scanf("%[^\n]",name);

i don't know about other better options to receive string,

Check whether values in one data frame column exist in a second data frame

Use %in% as follows

A$C %in% B$C

Which will tell you which values of column C of A are in B.

What is returned is a logical vector. In the specific case of your example, you get:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE

Which you can use as an index to the rows of A or as an index to A$C to get the actual values:

# as a row index
A[A$C %in% B$C,  ]  # note the comma to indicate we are indexing rows

# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4  # returns all values of A$C that are in B$C

We can negate it too:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C



If you want to know if a specific value is in B$C, use the same function:

  2 %in% B$C   # "is the value 2 in B$C ?"  
  # FALSE

  A$C[2] %in% B$C  # "is the 2nd element of A$C in B$C ?"  
  # FALSE

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

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

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

How can I disable all views inside the layout?

  private void disableLL(ViewGroup layout){
    for (int i = 0; i < layout.getChildCount(); i++) {
        View child = layout.getChildAt(i);
        child.setClickable(false);
        if (child instanceof ViewGroup)
            disableLL((ViewGroup) child);
    }
}

and call method like this :

RelativeLayout rl_root = (RelativeLayout) findViewById(R.id.rl_root);
disableLL(rl_root);

How to generate a git patch for a specific commit?

Say you have commit id 2 after commit 1 you would be able to run:

git diff 2 1 > mypatch.diff

where 2 and 1 are SHA hashes.

How do I style radio buttons with images - laughing smiley for good, sad smiley for bad?

I have edited one of the previous post. Now, it is way more simple and it works perfectly.

<input style="position: absolute;left:-9999px;" type="radio" name="emotion" id="sad" />
<label for="sad"><img src="red.gif" style="display: inline-block;cursor: pointer;padding: 3px;" alt="I'm sad" /></label>

<input  style="position: absolute;left:-9999px;" type="radio" name="emotion" id="happy" />
<label for="happy"><img src="blue.gif" style="display: inline-block;cursor: pointer;padding: 3px;" alt="I'm happy" /></label>

React.js create loop through Array

As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data with participants.

The alternative to the solution they provided would be to prevent render until participants exist, something like this:

    render: function() {
        if (!this.props.data.participants) {
            return null;
        }
        return (
            <ul className="PlayerList">
            // I'm the Player List {this.props.data}
            // <Player author="The Mini John" />
            {
                this.props.data.participants.map(function(player) {
                    return <li key={player}>{player}</li>
                })
            }
            </ul>
        );
    }

Unable to connect to any of the specified mysql hosts. C# MySQL

Update your connection string as shown below (without port variable as well):

MysqlConn.ConnectionString = "Server=127.0.0.1;Database=patholabs;Uid=pankaj;Pwd=master;"

Hope this helps...

getElementsByClassName not working

There are several issues:

  1. Class names (and IDs) are not allowed to start with a digit.
  2. You have to pass a class to getElementsByClassName().
  3. You have to iterate of the result set.

Example (untested):

<script type="text/javascript">
function hideTd(className){
    var elements = document.getElementsByClassName(className);
    for(var i = 0, length = elements.length; i < length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>
</head>
<body onload="hideTd('td');">
<table border="1">
  <tr>
    <td class="td">not empty</td>
  </tr>
  <tr>
    <td class="td"></td>
  </tr>
  <tr>
    <td class="td"></td>
  </tr>
</table>
</body>

Note that getElementsByClassName() is not available up to and including IE8.

Update:

Alternatively you can give the table an ID and use:

var elements = document.getElementById('tableID').getElementsByTagName('td');

to get all td elements.

To hide the parent row, use the parentNode property of the element:

elements[i].parentNode.style.display = "none";

How to disable textbox from editing?

The TextBox has a property called ReadOnly. If you set that property to true then the TextBox will still be able to scroll but the user wont be able to change the value.

Remove all classes that begin with a certain string

In one line ... Removes all classes that match a regular expression someRegExp

$('#my_element_id').removeClass( function() { return (this.className.match(/someRegExp/g) || []).join(' ').replace(prog.status.toLowerCase(),'');});

How to generate Javadoc from command line

The answers given were not totally complete if multiple sourcepath and subpackages have to be processed.

The following command line will process all the packages under com and LOR (lord of the rings) located into /home/rudy/IdeaProjects/demo/src/main/java and /home/rudy/IdeaProjects/demo/src/test/java/

Please note:

  • it is Linux and the paths and packages are separated by ':'.
  • that I made usage of private and wanted all the classes and members to be documented.

rudy@rudy-ThinkPad-T590:~$ javadoc -d /home/rudy/IdeaProjects/demo_doc
-sourcepath /home/rudy/IdeaProjects/demo/src/main/java/
:/home/rudy/IdeaProjects/demo/src/test/java/
-subpackages com:LOR 
-private

rudy@rudy-ThinkPad-T590:~/IdeaProjects/demo/src/main/java$ ls -R 
.: com LOR
./com: example
./com/example: demo
./com/example/demo: DemowApplication.java
./LOR: Race.java TolkienCharacter.java

rudy@rudy-ThinkPad-T590:~/IdeaProjects/demo/src/test/java$ ls -R 
.: com
./com: example
./com/example: demo
./com/example/demo: AssertJTest.java DemowApplicationTests.java

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

How to filter keys of an object with lodash?

A non-lodash way to solve this in a fairly readable and efficient manner:

_x000D_
_x000D_
function filterByKeys(obj, keys = []) {_x000D_
  const filtered = {}_x000D_
  keys.forEach(key => {_x000D_
    if (obj.hasOwnProperty(key)) {_x000D_
      filtered[key] = obj[key]_x000D_
    }_x000D_
  })_x000D_
  return filtered_x000D_
}_x000D_
_x000D_
const myObject = {_x000D_
  a: 1,_x000D_
  b: 'bananas',_x000D_
  d: null_x000D_
}_x000D_
_x000D_
const result = filterByKeys(myObject, ['a', 'd', 'e']) // {a: 1, d: null}_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

SQL Server: use CASE with LIKE

You can also do like this

select *
from table
where columnName like '%' + case when @varColumn is null then '' else @varColumn end  +  ' %'

Bad operand type for unary +: 'str'

You say that if int(splitLine[0]) > int(lastUnix): is causing the trouble, but you don't actually show anything which suggests that. I think this line is the problem instead:

print 'Pulled', + stock

Do you see why this line could cause that error message? You want either

>>> stock = "AAAA"
>>> print 'Pulled', stock
Pulled AAAA

or

>>> print 'Pulled ' + stock
Pulled AAAA

not

>>> print 'Pulled', + stock
PulledTraceback (most recent call last):
  File "<ipython-input-5-7c26bb268609>", line 1, in <module>
    print 'Pulled', + stock
TypeError: bad operand type for unary +: 'str'

You're asking Python to apply the + symbol to a string like +23 makes a positive 23, and she's objecting.

Updating user data - ASP.NET Identity

Excellent!!!

IdentityResult result = await UserManager.UpdateAsync(user);

How to get last N records with activerecord?

Updated Answer (2020)

You can get last N records simply by using last method:

Record.last(N)

Example:

User.last(5)

Returns 5 users in descending order by their id.

Deprecated (Old Answer)

An active record query like this I think would get you what you want ('Something' is the model name):

Something.find(:all, :order => "id desc", :limit => 5).reverse

edit: As noted in the comments, another way:

result = Something.find(:all, :order => "id desc", :limit => 5)

while !result.empty?
        puts result.pop
end

Most efficient way to reverse a numpy array

Because this seems to not be marked as answered yet... The Answer of Thomas Arildsen should be the proper one: just use

np.flipud(your_array) 

if it is a 1d array (column array).

With matrizes do

fliplr(matrix)

if you want to reverse rows and flipud(matrix) if you want to flip columns. No need for making your 1d column array a 2dimensional row array (matrix with one None layer) and then flipping it.

Simple timeout in java

Use this line of code:

Thread.sleep(1000);

It will sleep for 1 second.

Select method of Range class failed via VBA

This is how you get around that in an easy non-complicated way.
Instead of using sheet(x).range use Activesheet.range("range").select

How to convert numbers between hexadecimal and decimal

To convert from decimal to hex do...

string hexValue = decValue.ToString("X");

To convert from hex to decimal do either...

int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

or

int decValue = Convert.ToInt32(hexValue, 16);

Replace a string in a file with nodejs

ES2017/8 for Node 7.6+ with a temporary write file for atomic replacement.

const Promise = require('bluebird')
const fs = Promise.promisifyAll(require('fs'))

async function replaceRegexInFile(file, search, replace){
  let contents = await fs.readFileAsync(file, 'utf8')
  let replaced_contents = contents.replace(search, replace)
  let tmpfile = `${file}.jstmpreplace`
  await fs.writeFileAsync(tmpfile, replaced_contents, 'utf8')
  await fs.renameAsync(tmpfile, file)
  return true
}

Note, only for smallish files as they will be read into memory.

Convert UIImage to NSData and convert back to UIImage in Swift?

Use imageWithData: method, which gets translated to Swift as UIImage(data:)

let image : UIImage = UIImage(data: imageData)

endsWith in JavaScript

@chakrit's accepted answer is a solid way to do it yourself. If, however, you're looking for a packaged solution, I recommend taking a look at underscore.string, as @mlunoe pointed out. Using underscore.string, the code would be:

function endsWithHash(str) {
  return _.str.endsWith(str, '#');
}

JavaScript - Get Portion of URL Path

If this is the current url use window.location.pathname otherwise use this regular expression:

var reg = /.+?\:\/\/.+?(\/.+?)(?:#|\?|$)/;
var pathname = reg.exec( 'http://www.somedomain.com/account/search?filter=a#top' )[1];

How to resolve ORA 00936 Missing Expression Error?

This answer is not the answer for the above mentioned question but it is related to same topic and might be useful for people searching for same error.

I faced the same error when I executed below mentioned query.

select OR.* from ORDER_REL_STAT OR

problem with above query was OR is keyword so it was expecting other values when I replaced with some other alias it worked fine.

Please run `npm cache clean`

As of npm@5, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use npm cache verify instead. On the other hand, if you're debugging an issue with the installer, you can use npm install --cache /tmp/empty-cache to use a temporary cache instead of nuking the actual one.

If you're sure you want to delete the entire cache, rerun:

npm cache clean --force

A complete log of this run can be found in /Users/USERNAME/.npm/_logs/2019-01-08T21_29_30_811Z-debug.log.

Constructors in Go

There are some equivalents of constructors for when the zero values can't make sensible default values or for when some parameter is necessary for the struct initialization.

Supposing you have a struct like this :

type Thing struct {
    Name  string
    Num   int
}

then, if the zero values aren't fitting, you would typically construct an instance with a NewThing function returning a pointer :

func NewThing(someParameter string) *Thing {
    p := new(Thing)
    p.Name = someParameter
    p.Num = 33 // <- a very sensible default value
    return p
}

When your struct is simple enough, you can use this condensed construct :

func NewThing(someParameter string) *Thing {
    return &Thing{someParameter, 33}
}

If you don't want to return a pointer, then a practice is to call the function makeThing instead of NewThing :

func makeThing(name string) Thing {
    return Thing{name, 33}
}

Reference : Allocation with new in Effective Go.

grep's at sign caught as whitespace

After some time with Google I asked on the ask ubuntu chat room.

A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:

grep -P "(^|\s)abc(\s|$)" gives the result I was looking for. -P is an experimental implementation of perl regexps.

grepping for abc and then using filters like grep -v '@abc' (this is far from perfect...) should also work, but my patch does something similar.

Is it possible to open developer tools console in Chrome on Android phone?

You can do it using remote debugging, here is official documentation. Basic process:

  1. Connect your android device
  2. Select your device: More tools > Inspect devices* from dev tools on pc/mac.
  3. Authorize on your mobile.
  4. Happy debugging!!

* This is now "Remote devices".

Angular directives - when and how to use compile, controller, pre-link and post-link

How to declare the various functions?

Compile, Controller, Pre-link & Post-link

If one is to use all four function, the directive will follow this form:

myApp.directive( 'myDirective', function () {
    return {
        restrict: 'EA',
        controller: function( $scope, $element, $attrs, $transclude ) {
            // Controller code goes here.
        },
        compile: function compile( tElement, tAttributes, transcludeFn ) {
            // Compile code goes here.
            return {
                pre: function preLink( scope, element, attributes, controller, transcludeFn ) {
                    // Pre-link code goes here
                },
                post: function postLink( scope, element, attributes, controller, transcludeFn ) {
                    // Post-link code goes here
                }
            };
        }
    };  
});

Notice that compile returns an object containing both the pre-link and post-link functions; in Angular lingo we say the compile function returns a template function.

Compile, Controller & Post-link

If pre-link isn't necessary, the compile function can simply return the post-link function instead of a definition object, like so:

myApp.directive( 'myDirective', function () {
    return {
        restrict: 'EA',
        controller: function( $scope, $element, $attrs, $transclude ) {
            // Controller code goes here.
        },
        compile: function compile( tElement, tAttributes, transcludeFn ) {
            // Compile code goes here.
            return function postLink( scope, element, attributes, controller, transcludeFn ) {
                    // Post-link code goes here                 
            };
        }
    };  
});

Sometimes, one wishes to add a compile method, after the (post) link method was defined. For this, one can use:

myApp.directive( 'myDirective', function () {
    return {
        restrict: 'EA',
        controller: function( $scope, $element, $attrs, $transclude ) {
            // Controller code goes here.
        },
        compile: function compile( tElement, tAttributes, transcludeFn ) {
            // Compile code goes here.

            return this.link;
        },
        link: function( scope, element, attributes, controller, transcludeFn ) {
            // Post-link code goes here
        }

    };  
});

Controller & Post-link

If no compile function is needed, one can skip its declaration altogether and provide the post-link function under the link property of the directive's configuration object:

myApp.directive( 'myDirective', function () {
    return {
        restrict: 'EA',
        controller: function( $scope, $element, $attrs, $transclude ) {
            // Controller code goes here.
        },
        link: function postLink( scope, element, attributes, controller, transcludeFn ) {
                // Post-link code goes here                 
        },          
    };  
});

No controller

In any of the examples above, one can simply remove the controller function if not needed. So for instance, if only post-link function is needed, one can use:

myApp.directive( 'myDirective', function () {
    return {
        restrict: 'EA',
        link: function postLink( scope, element, attributes, controller, transcludeFn ) {
                // Post-link code goes here                 
        },          
    };  
});

Why do I get a C malloc assertion failure?

We got this error because we forgot to multiply by sizeof(int). Note the argument to malloc(..) is a number of bytes, not number of machine words or whatever.

How to prevent default event handling in an onclick method?

Another way to do that is to use the event object inside the attribute onclick (without the need to add an additional argument to the function to pass the event)

_x000D_
_x000D_
function callmymethod(myVal){_x000D_
    console.log(myVal);_x000D_
}
_x000D_
<a href="#link" onclick="event.preventDefault();callmymethod(24)">Call</a>
_x000D_
_x000D_
_x000D_

How to set bootstrap navbar active class with Angular JS?

If you are working with Angular router, the RouterLinkActive directive can be used really elegantly:

<ul class="navbar-nav">
  <li class="nav-item"><a class="nav-link" routerLink="home" routerLinkActive="active">Home</a></li>
  <li class="nav-item"><a class="nav-link" routerLink="gallery" routerLinkActive="active">Gallery</a></li>
  <li class="nav-item"><a class="nav-link" routerLink="pricing" routerLinkActive="active">Prices</a></li>
  <li class="nav-item"><a class="nav-link" routerLink="contact" routerLinkActive="active">Contact</a></li>
</ul>

Logging with Retrofit 2

You can also add Facebook's Stetho and look at the network traces in Chrome: http://facebook.github.io/stetho/

final OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
    builder.networkInterceptors().add(new StethoInterceptor());
}

Then open "chrome://inspect" in Chrome...

Should C# or C++ be chosen for learning Games Programming (consoles)?

Ok here is my two cents.

If you are planning to seriously get into the game industry I recommend you learn both languages. Starting off with C++ then moving into a managed language like C#. C++ has it's advantages over C#, but C# also has advantages over C++.

Personally I prefer C# over C++ any day. This is because many reasons:, just a few:

  1. C# makes programming fun again ;).
  2. It's managed code helps me complete complex tasks easily and not forget safety.
  3. C#s' is pure OOP, forcing rules in your code that helps keep your code more readable, 'maintainable' and execution is more stable. Productivity rate surpasses C++ by at least 10%, the best C++ programmer could be an even better C# programmer.
  4. This isn't really a reason, more like something 'I' like about C#: LINQ.

Now...there are many things that I miss about C++. I miss being able to (completely) manage my own memory. I can't tell you how many times I caught myself trying to 'delete' an instance/reference. Another thing I dislike about C# is the inability to use multiple-inheritance, but then again it has forced me to think more about how to structure my code.

There has been more discussions on this topic than there are stars in the known universe and they all close at a dead end. Neither language is better than the other and refusing either one for the other will just hurt you in the long run. Times change and so do the standards for computer programming.

Whatever language you choose to keep at the top of your list, always keep your options open and don't set your mind to any one single language. You say you already know C++, why not learn C#, it can't hurt and I 'promise' you, it will make you a better C++ programmer.

Rails: Adding an index after adding column

Add in the generated migration after creating the column the following (example)

add_index :photographers, :email, :unique => true

Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?

Small answer:

onInterceptTouchEvent comes before setOnTouchListener.

Compile to stand alone exe for C# app in Visual Studio 2010

You can use the files from debug folder,however if you look at app debug informations with some inspection software,you can clearly see "Symbols File Name" which can reveals not wanted informations in path to the original exe file.

How to install a private NPM module without my own registry?

Update January 2016

In addition to other answers, there is sometimes the scenario where you wish to have private modules available in a team context.

Both Github and Bitbucket support the concept of generating a team API Key. This API key can be used as the password to perform API requests as this team.

In your private npm modules add

"private": true 

to your package.json

Then to reference the private module in another module, use this in your package.json

    {
        "name": "myapp",
        "dependencies": {
            "private-repo":
"git+https://myteamname:[email protected]/myprivate.git",
        }
    }

where team name = myteamname, and API Key = aQqtcplwFzlumj0mIDdRGCbsAq5d6Xg4

Here I reference a bitbucket repo, but it is almost identical using github too.

Finally, as an alternative, if you really don't mind paying $7 per month (as of writing) then you can now have private NPM modules out of the box.

Loading DLLs at runtime in C#

Right now, you're creating an instance of every type defined in the assembly. You only need to create a single instance of Class1 in order to call the method:

class Program
{
    static void Main(string[] args)
    {
        var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

        var theType = DLL.GetType("DLL.Class1");
        var c = Activator.CreateInstance(theType);
        var method = theType.GetMethod("Output");
        method.Invoke(c, new object[]{@"Hello"});

        Console.ReadLine();
    }
}

How to return result of a SELECT inside a function in PostgreSQL?

Use RETURN QUERY:

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt   text   -- also visible as OUT parameter inside function
               , cnt   bigint
               , ratio bigint) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt
        , count(*) AS cnt                 -- column alias only visible inside
        , (count(*) * 100) / _max_tokens  -- I added brackets
   FROM  (
      SELECT t.txt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      LIMIT  _max_tokens
      ) t
   GROUP  BY t.txt
   ORDER  BY cnt DESC;                    -- potential ambiguity 
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM word_frequency(123);

Explanation:

  • It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query.

  • Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.

    But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:

    1. Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC. Example:
    2. Repeat the expression ORDER BY count(*).
    3. (Not applicable here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See:
  • Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples.

  • Added a missing ; and corrected a syntax error in the header. (_max_tokens int), not (int maxTokens) - type after name.

  • While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric (or a floating point type). See below.

Alternative

This is what I think your query should actually look like (calculating a relative share per token):

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt            text
               , abs_cnt        bigint
               , relative_share numeric) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt, t.cnt
        , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2)  -- AS relative_share
   FROM  (
      SELECT t.txt, count(*) AS cnt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      GROUP  BY t.txt
      ORDER  BY cnt DESC
      LIMIT  _max_tokens
      ) t
   ORDER  BY t.cnt DESC;
END
$func$  LANGUAGE plpgsql;

The expression sum(t.cnt) OVER () is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.

A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters).

round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.

How to get the text node of an element?

ES6 version that return the first #text node content

const extract = (node) => {
  const text = [...node.childNodes].find(child => child.nodeType === Node.TEXT_NODE);
  return text && text.textContent.trim();
}

What are the differences between type() and isinstance()?

For the real differences, we can find it in code, but I can't find the implement of the default behavior of the isinstance().

However we can get the similar one abc.__instancecheck__ according to __instancecheck__.

From above abc.__instancecheck__, after using test below:

# file tree
# /test/__init__.py
# /test/aaa/__init__.py
# /test/aaa/aa.py
class b():
pass

# /test/aaa/a.py
import sys
sys.path.append('/test')

from aaa.aa import b
from aa import b as c

d = b()

print(b, c, d.__class__)
for i in [b, c, object]:
    print(i, '__subclasses__',  i.__subclasses__())
    print(i, '__mro__', i.__mro__)
    print(i, '__subclasshook__', i.__subclasshook__(d.__class__))
    print(i, '__subclasshook__', i.__subclasshook__(type(d)))
print(isinstance(d, b))
print(isinstance(d, c))

<class 'aaa.aa.b'> <class 'aa.b'> <class 'aaa.aa.b'>
<class 'aaa.aa.b'> __subclasses__ []
<class 'aaa.aa.b'> __mro__ (<class 'aaa.aa.b'>, <class 'object'>)
<class 'aaa.aa.b'> __subclasshook__ NotImplemented
<class 'aaa.aa.b'> __subclasshook__ NotImplemented
<class 'aa.b'> __subclasses__ []
<class 'aa.b'> __mro__ (<class 'aa.b'>, <class 'object'>)
<class 'aa.b'> __subclasshook__ NotImplemented
<class 'aa.b'> __subclasshook__ NotImplemented
<class 'object'> __subclasses__ [..., <class 'aaa.aa.b'>, <class 'aa.b'>]
<class 'object'> __mro__ (<class 'object'>,)
<class 'object'> __subclasshook__ NotImplemented
<class 'object'> __subclasshook__ NotImplemented
True
False

I get this conclusion, For type:

# according to `abc.__instancecheck__`, they are maybe different! I have not found negative one 
type(INSTANCE) ~= INSTANCE.__class__
type(CLASS) ~= CLASS.__class__

For isinstance:

# guess from `abc.__instancecheck__`
return any(c in cls.__mro__ or c in cls.__subclasses__ or cls.__subclasshook__(c) for c in {INSTANCE.__class__, type(INSTANCE)})

BTW: better not to mix use relative and absolutely import, use absolutely import from project_dir( added by sys.path)

gcc makefile error: "No rule to make target ..."

In my case it was due to a multi-line rule error in the Makefile. I had something like:

OBJS-$(CONFIG_OBJ1)            += file1.o file2.o \
                                  file3.o file4.o \
OBJS-$(CONFIG_OBJ2)            += file5.o 
OBJS-$(CONFIG_OBJ3)            += file6.o
...

The backslash at the end of file list in CONFIG_OBJ1's rule caused this error. It should be like:

OBJS-$(CONFIG_OBJ1)            += file1.o file2.o \
                                  file3.o file4.o
OBJS-$(CONFIG_OBJ2)            += file5.o
...

Hibernate Error: a different object with the same identifier value was already associated with the session

just commit current transaction.

currentSession.getTransaction().commit();

now you can begin another Transaction and do anything on entity

How to get request URL in Spring Boot RestController

If you don't want any dependency on Spring's HATEOAS or javax.* namespace, use ServletUriComponentsBuilder to get URI of current request:

import org.springframework.web.util.UriComponentsBuilder;

ServletUriComponentsBuilder.fromCurrentRequest();
ServletUriComponentsBuilder.fromCurrentRequestUri();

Jenkins - passing variables between jobs?

The accepted answer here does not work for my use case. I needed to be able to dynamically create parameters in one job and pass them into another. As Mark McKenna mentions there is seemingly no way to export a variable from a shell build step to the post build actions.

I achieved a workaround using the Parameterized Trigger Plugin by writing the values to a file and using that file as the parameters to import via 'Add post-build action' -> 'Trigger parameterized build...' then selecting 'Add Parameters' -> 'Parameters from properties file'.

Java generics - why is "extends T" allowed but not "implements T"?

It may be that the base type is a generic parameter, so the actual type may be an interface of a class. Consider:

class MyGen<T, U extends T> {

Also from client code perspective interfaces are almost indistinguishable from classes, whereas for subtype it is important.

What does "#pragma comment" mean?

#pragma comment is a compiler directive which indicates Visual C++ to leave a comment in the generated object file. The comment can then be read by the linker when it processes object files.

#pragma comment(lib, libname) tells the linker to add the 'libname' library to the list of library dependencies, as if you had added it in the project properties at Linker->Input->Additional dependencies

See #pragma comment on MSDN

How to access the value of a promise?

pixelbits answer is correct and you should always use .then() to access the value of a promise in production code.

However, there is a way to access the promise's value directly after it has been resolved by using the following unsupported internal node.js binding:

process.binding('util').getPromiseDetails(myPromise)[1]

WARNING: process.binding was never meant to be used outside of nodejs core and the nodejs core team is actively looking to deprecate it

https://github.com/nodejs/node/pull/22004 https://github.com/nodejs/node/issues/22064

Reset select value to default

<select id="my_select">
    <option value="a">a</option>
    <option value="b" selected="selected">b</option>
    <option value="c">c</option>
</select>

<div id="reset">
    reset
</div>

$("#reset").on("click", function () {
    $('#my_select').prop('selectedIndex',0);
});

This is a simple way for your question. only one line answer.

Is there a way to compile node.js source files?

javascript does not not have a compiler like for example Java/C(You can compare it more to languages like PHP for example). If you want to write compiled code you should read the section about addons and learn C. Although this is rather complex and I don't think you need to do this but instead just write javascript.

jquery clear input default value

You may use this..

<body>
    <form method="" action="">
        <input type="text" name="email" class="input" />
        <input type="submit" value="Sign Up" class="button" />
    </form>
</body>

<script>
    $(document).ready(function() {
        $(".input").val("Email Address");
        $(".input").on("focus", function() {
            $(".input").val("");
        });
        $(".button").on("click", function(event) {
            $(".input").val("");
        });
    });
</script>

Talking of your own code, the problem is that the attr api of jquery is set by

$('.input').attr('value','Email Adress');

and not as you have done:

$('.input').attr('value') = 'Email address';

Regex to get NUMBER only from String

Either [0-9] or \d1 should suffice if you only need a single digit. Append + if you need more.


1 The semantics are slightly different as \d potentially matches any decimal digit in any script out there that uses decimal digits.

How to read from a text file using VBScript?

Use first the method OpenTextFile, and then...

either read the file at once with the method ReadAll:

Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll

or line by line with the method ReadLine:

Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
  line = file.Readline
  dict.Add row, line
  row = row + 1
Loop

file.Close

'Loop over it
For Each line in dict.Items
  WScript.Echo line
Next

Remove all special characters from a string

Here, check out this function:

function seo_friendly_url($string){
    $string = str_replace(array('[\', \']'), '', $string);
    $string = preg_replace('/\[.*\]/U', '', $string);
    $string = preg_replace('/&(amp;)?#?[a-z0-9]+;/i', '-', $string);
    $string = htmlentities($string, ENT_COMPAT, 'utf-8');
    $string = preg_replace('/&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);/i', '\\1', $string );
    $string = preg_replace(array('/[^a-z0-9]/i', '/[-]+/') , '-', $string);
    return strtolower(trim($string, '-'));
}

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

How do I work with dynamic multi-dimensional arrays in C?

Since C99, C has 2D arrays with dynamical bounds. If you want to avoid that such beast are allocated on the stack (which you should), you can allocate them easily in one go as the following

double (*A)[n] = malloc(sizeof(double[n][n]));

and that's it. You can then easily use it as you are used for 2D arrays with something like A[i][j]. And don't forget that one at the end

free(A);

Randy Meyers wrote series of articles explaining variable length arrays (VLAs).

How to align a div inside td element using CSS class

div { margin: auto; }

This will center your div.

Div by itself is a blockelement. Therefor you need to define the style to the div how to behave.

PHP Excel Header

You are giving multiple Content-Type headers. application/vnd.ms-excel is enough.

And there are couple of syntax error too. To statement termination with ; on the echo statement and wrong filename extension.

header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=abc.xls");  //File name extension was wrong
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
echo "Some Text"; //no ending ; here

Sending HTML Code Through JSON

You can send it as a String, why not. But you are probably missusing JSON here a bit since as far as I understand the point is to send just the data needed and wrap them into HTML on the client.

Playing sound notifications using Javascript?

Using the html5 audio tag and jquery:

// appending HTML5 Audio Tag in HTML Body
$('<audio id="chatAudio">
    <source src="notify.ogg" type="audio/ogg">
    <source src="notify.mp3" type="audio/mpeg">
</audio>').appendTo('body');

// play sound
$('#chatAudio')[0].play();

Code from here.

In my implementation I added the audio embed directly into the HTML without jquery append.

What is the difference between fastcgi and fpm?

What Anthony says is absolutely correct, but I'd like to add that your experience will likely show a lot better performance and efficiency (due not to fpm-vs-fcgi but more to the implementation of your httpd).

For example, I had a quad-core machine running lighttpd + fcgi humming along nicely. I upgraded to a 16-core machine to cope with growth, and two things exploded: RAM usage, and segfaults. I found myself restarting lighttpd every 30 minutes to keep the website up.

I switched to php-fpm and nginx, and RAM usage dropped from >20GB to 2GB. Segfaults disappeared as well. After doing some research, I learned that lighttpd and fcgi don't get along well on multi-core machines under load, and also have memory leak issues in certain instances.

Is this due to php-fpm being better than fcgi? Not entirely, but how you hook into php-fpm seems to be a whole heckuva lot more efficient than how you serve via fcgi.

How to resolve "git pull,fatal: unable to access 'https://github.com...\': Empty reply from server"

I was stuck in this problem until I noticed that I was not logged into my VPN.

  1. If you have configured your proxy for a VPN, you need to login to your VPN to use the proxy.

  2. to use it outside the VPN use the unset command:

    git config --global --unset http.proxy
    

And remember to set the proxy when within the VPN.

How to install "make" in ubuntu?

I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.

To answer the question in the header: To install make in ubuntu you have to install build-essentials

sudo apt-get install build-essential

Java 8 lambdas, Function.identity() or t->t

From the JDK source:

static <T> Function<T, T> identity() {
    return t -> t;
}

So, no, as long as it is syntactically correct.

Quickest way to compare two generic lists for differences

Enumerable.SequenceEqual Method

Determines whether two sequences are equal according to an equality comparer. MS.Docs

Enumerable.SequenceEqual(list1, list2);

This works for all primitive data types. If you need to use it on custom objects you need to implement IEqualityComparer

Defines methods to support the comparison of objects for equality.

IEqualityComparer Interface

Defines methods to support the comparison of objects for equality. MS.Docs for IEqualityComparer

Sending GET request with Authentication headers using restTemplate

You're not missing anything. RestTemplate#exchange(..) is the appropriate method to use to set request headers.

Here's an example (with POST, but just change that to GET and use the entity you want).

Here's another example.

Note that with a GET, your request entity doesn't have to contain anything (unless your API expects it, but that would go against the HTTP spec). It can be an empty String.

Spark java.lang.OutOfMemoryError: Java heap space

To add a use case to this that is often not discussed, I will pose a solution when submitting a Spark application via spark-submit in local mode.

According to the gitbook Mastering Apache Spark by Jacek Laskowski:

You can run Spark in local mode. In this non-distributed single-JVM deployment mode, Spark spawns all the execution components - driver, executor, backend, and master - in the same JVM. This is the only mode where a driver is used for execution.

Thus, if you are experiencing OOM errors with the heap, it suffices to adjust the driver-memory rather than the executor-memory.

Here is an example:

spark-1.6.1/bin/spark-submit
  --class "MyClass"
  --driver-memory 12g
  --master local[*] 
  target/scala-2.10/simple-project_2.10-1.0.jar 

Common elements in two lists

Use Collection#retainAll().

listA.retainAll(listB);
// listA now contains only the elements which are also contained in listB.

If you want to avoid that changes are being affected in listA, then you need to create a new one.

List<Integer> common = new ArrayList<Integer>(listA);
common.retainAll(listB);
// common now contains only the elements which are contained in listA and listB.

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

"Uncaught Error: [$injector:unpr]" with angular after deployment

Add the $http, $scope services in the controller fucntion, sometimes if they are missing these errors occur.

MySQL WHERE: how to write "!=" or "not equals"?

The != operator most certainly does exist! It is an alias for the standard <> operator.

Perhaps your fields are not actually empty strings, but instead NULL?

To compare to NULL you can use IS NULL or IS NOT NULL or the null safe equals operator <=>.

Append to string variable

Like this:

var str = 'blah blah blah';
str += ' blah';

str += ' ' + 'and some more blah';

'numpy.float64' object is not iterable

numpy.linspace() gives you a one-dimensional NumPy array. For example:

>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])

Therefore:

for index,point in my_array

cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:

>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])

Now you can do this:

>>> for x, y in two_d:
    print(x, y)

1 2
4 5

How to analyze a JMeter summary report?

Sample: Number of requests sent.

The Throughput: is the number of requests per unit of time (seconds, minutes, hours) that are sent to your server during the test.

The Response time: is the elapsed time from the moment when a given request is sent to the server until the moment when the last bit of information has returned to the client.

The throughput is the real load processed by your server during a run but it does not tell you anything about the performance of your server during this same run. This is the reason why you need both measures in order to get a real idea about your server’s performance during a run. The response time tells you how fast your server is handling a given load.

Average: This is the Average (Arithmetic mean µ = 1/n * Si=1…n xi) Response time of your total samples.

Min and Max are the minimum and maximum response time.

An important thing to understand is that the mean value can be very misleading as it does not show you how close (or far) your values are from the average.For this purpose, we need the Deviation value since Average value can be the Same for different response time of the samples!!

Deviation: The standard deviation (s) measures the mean distance of the values to their average (µ).It gives you a good idea of the dispersion or variability of the measures to their mean value.

The following equation show how the standard deviation (s) is calculated:

s = 1/n * v Si=1…n (xi-µ)2

For Details, see here!!

So, if the deviation value is low compared to the mean value, it will indicate you that your measures are not dispersed (or mostly close to the mean value) and that the mean value is significant.

Kb/sec: The throughput measured in Kilobytes per second.

Error % : Percent of requests with errors.

An example is always better to understand!!! I think, this article will help you.

Reordering Chart Data Series

To change the stacking order for series in charts under Excel for Mac 2011:

  1. select the chart,
  2. select the series (easiest under Ribbon>Chart Layout>Current Selection),
  3. click Chart Layout>Format Selection or Menu>Format>Data Series …,
  4. on popup menu Format Data Series click Order, then click individual series and click Move Up or Move Down buttons to adjust the stacking order on the Axis for the subject series. This changes the order for the plot and for the legend, but may not change the order number in the Series formula.

I had a three series plot on the secondary axis, and the series I wanted on top was stuck on the bottom in defiance of the Move Up and Move Down buttons. It happened to be formatted as markers only. I inserted a line, and presto(!), I could change its order in the plot. Later I could remove the line and sometimes it could still be ordered, but sometimes not.

Convert JsonObject to String

I think you need this :

Suppose you have Sample JSON like this :

{"ParamOne":"InnerParamOne":"InnerParamOneValue","InnerParamTwo":"InnerParamTwoValue","InnerParamThree":"InnerParamThreeValue","InnerParamFour":"InnerParamFourValue","InnerParamFive":"InnerParamFiveValue"}}

Converted to String :

String response = {\"ParamOne\":{\"InnerParamOne\":\"InnerParamOneValue\",\"InnerParamTwo\":\"InnerParamTwoValue\",\"InnerParamThree\":\"InnerParamThreeValue\",\"InnerParamFour\":\"InnerParamFourValue\",\"InnerParamFive\":\"InnerParamFiveValue\"}} ;

Just replace " by \"

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

How can I simulate an array variable in MySQL?

If we have one table like that

mysql> select * from user_mail;
+------------+-------+
| email      | user | 
+------------+-------+-
| email1@gmail |     1 | 
| email2@gmail |     2 |
+------------+-------+--------+------------+

and the array table:

mysql> select * from user_mail_array;
+------------+-------+-------------+
| email      | user | preferences |
+------------+-------+-------------+
| email1@gmail |     1 |           1 |
| email1@gmail |     1 |           2 |
| email1@gmail |     1 |           3 |
| email1@gmail |     1 |           4 |
| email2@gmail |     2 |           5 |
| email2@gmail |     2 |           6 |

We can select the rows of the second table as one array with CONCAT function:

mysql> SELECT t1.*, GROUP_CONCAT(t2.preferences) AS preferences
     FROM user_mail t1,user_mail_array t2
       where t1.email=t2.email and t1.user=t2.user
     GROUP BY t1.email,t1.user;

+------------+-------+--------+------------+-------------+
| email      | user | preferences |
+------------+-------+--------+------------+-------------+
|email1@gmail |     1 | 1,3,2,4     |
|email2@gmail |     2 | 5,6         |
+------------+-------+--------+------------+-------------+

Node.js version on the command line? (not the REPL)

By default node package is nodejs, so use

$ nodejs -v

or

$ nodejs --version 

You can make a link using

$ sudo ln -s /usr/bin/nodejs /usr/bin/node

then u can use

$ node --version

or

$ node -v

Insert variable values in the middle of a string

There's now (C# 6) a more succinct way to do it: string interpolation.

From another question's answer:

In C# 6 you can use string interpolation:

string name = "John";
string result = $"Hello {name}";

The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.

possible EventEmitter memory leak detected

I'd like to point out here that that warning is there for a reason and there's a good chance the right fix is not increasing the limit but figuring out why you're adding so many listeners to the same event. Only increase the limit if you know why so many listeners are being added and are confident it's what you really want.

I found this page because I got this warning and in my case there was a bug in some code I was using that was turning the global object into an EventEmitter! I'd certainly advise against increasing the limit globally because you don't want these things to go unnoticed.

R memory management / cannot allocate vector of size n Mb

I encountered a similar problem, and I used 2 flash drives as 'ReadyBoost'. The two drives gave additional 8GB boost of memory (for cache) and it solved the problem and also increased the speed of the system as a whole. To use Readyboost, right click on the drive, go to properties and select 'ReadyBoost' and select 'use this device' radio button and click apply or ok to configure.

Gradle Build Android Project "Could not resolve all dependencies" error

  1. Install android sdk manager
  2. check if building tools installed. install api 23.
  3. from the Android SDK Manager download the 'Android Support Repository'
  4. remove cordova-plugin-android-support-v4
  5. build

Matplotlib color according to class labels

A simple solution is to assign color for each class. This way, we can control how each color is for each class. For example:

arr1 = [1, 2, 3, 4, 5]
arr2 = [2, 3, 3, 4, 4]
labl = [0, 1, 1, 0, 0]
color= ['red' if l == 0 else 'green' for l in labl]
plt.scatter(arr1, arr2, color=color)

jQuery $.ajax request of dataType json will not retrieve data from PHP script

In addition to McHerbie's note, try json_encode( $json_arr, JSON_FORCE_OBJECT ); if you are on PHP 5.3...

Best way to select random rows PostgreSQL

postgresql order by random(), select rows in random order:

select your_columns from your_table ORDER BY random()

postgresql order by random() with a distinct:

select * from 
  (select distinct your_columns from your_table) table_alias
ORDER BY random()

postgresql order by random limit one row:

select your_columns from your_table ORDER BY random() limit 1

Installing packages in Sublime Text 2

Try using Sublime Package Control to install your packages.

Also take a look at these tips

Sort collection by multiple fields in Kotlin

Use sortedWith to sort a list with Comparator.

You can then construct a comparator using several ways:

  • compareBy, thenBy construct the comparator in a chain of calls:

    list.sortedWith(compareBy<Person> { it.age }.thenBy { it.name }.thenBy { it.address })
    
  • compareBy has an overload which takes multiple functions:

    list.sortedWith(compareBy({ it.age }, { it.name }, { it.address }))
    

Connect Android to WiFi Enterprise network EAP(PEAP)

Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.

The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.

There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.

Its name is Wifi Config Advanced Editor.

  • First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.

  • Save it.

  • Go to the WCE and edit the parameters of the network you have created in the previous step.

  • There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
    As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.

  • When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.

  • Do not Edit the network again with the Android wifi interface.

I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.

How to format a JavaScript date

A simple function that can return the date, the date + time, or just the time:

var myDate = dateFormatter("2019-01-24 11:33:24", "date-time");
// >> RETURNS "January 24, 2019 11:33:24"

var myDate2 = dateFormatter("2019-01-24 11:33:24", "date");
// >> RETURNS "January 24, 2019"

var myDate3 = dateFormatter("2019-01-24 11:33:24", "time");
// >> RETURNS "11:33:24"


function dateFormatter(strDate, format){
    var theDate = new Date(strDate);
    if (format=="time")
       return getTimeFromDate(theDate);
    else{
       var dateOptions = {year:'numeric', month:'long', day:'numeric'};
       var formattedDate = theDate.toLocaleDateString("en-US", + dateOptions);
       if (format=="date")
           return formattedDate;
       return formattedDate + " " + getTimeFromDate(theDate);
    }
}

function getTimeFromDate(theDate){
    var sec = theDate.getSeconds();
    if (sec<10)
        sec = "0" + sec;
    var min = theDate.getMinutes();
    if (min<10)
        min = "0" + min;
    return theDate.getHours() + ':'+ min + ':' + sec;
}

How do I use Ruby for shell scripting?

In ruby, the constant __FILE__ will always give you the path of the script you're running.

On Linux, /usr/bin/env is your friend:

#! /usr/bin/env ruby
# Extension of this script does not matter as long
# as it is executable (chmod +x)
puts File.expand_path(__FILE__)

On Windows it depends whether or not .rb files are associated with ruby. If they are:

# This script filename must end with .rb
puts File.expand_path(__FILE__)

If they are not, you have to explicitly invoke ruby on them, I use a intermediate .cmd file:

my_script.cmd:

@ruby %~dp0\my_script.rb

my_script.rb:

puts File.expand_path(__FILE__)

Is there an equivalent method to C's scanf in Java?

You can format your output in Java as described in below code snippet.

public class TestFormat {

    public static void main(String[] args) {
      long n = 461012;
      System.out.format("%d%n", n);      //  -->  "461012"
      System.out.format("%08d%n", n);    //  -->  "00461012"
      System.out.format("%+8d%n", n);    //  -->  " +461012"
      System.out.format("%,8d%n", n);    // -->  " 461,012"
      System.out.format("%+,8d%n%n", n); //  -->  "+461,012"
   }
}

You can read more here.

Stop setInterval

Use a variable and call clearInterval to stop it.

var interval;

$(document).on('ready',function()
  interval = setInterval(updateDiv,3000);
  });

  function updateDiv(){
    $.ajax({
      url: 'getContent.php',
      success: function(data){
        $('.square').html(data);
      },
      error: function(){
        $.playSound('oneday.wav');
        $('.square').html('<span style="color:red">Connection problems</span>');
        // I want to stop it here
        clearInterval(interval);
      }
    });
  }

Python list iterator behavior and next(iterator)

For those who still do not understand.

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    next(a)
... 
0 # print(i) printed this
1 # next(a) printed this
2 # print(i) printed this
3 # next(a) printed this
4 # print(i) printed this
5 # next(a) printed this
6 # print(i) printed this
7 # next(a) printed this
8 # print(i) printed this
9 # next(a) printed this

As others have already said, next increases the iterator by 1 as expected. Assigning its returned value to a variable doesn't magically changes its behaviour.

Java: convert List<String> to a String

With java 1.8 stream can be used ,

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
List<String> list = Arrays.asList("Bill","Bob","Steve").
String str = list.stream().collect(Collectors.joining(" and "));

Command output redirect to file and terminal

It is worth mentioning that 2>&1 means that standard error will be redirected too, together with standard output. So

someCommand | tee someFile

gives you just the standard output in the file, but not the standard error: standard error will appear in console only. To get standard error in the file too, you can use

someCommand 2>&1 | tee someFile

(source: In the shell, what is " 2>&1 "? ). Finally, both the above commands will truncate the file and start clear. If you use a sequence of commands, you may want to get output&error of all of them, one after another. In this case you can use -a flag to "tee" command:

someCommand 2>&1 | tee -a someFile

Repeat a string in JavaScript a number of times

If you're not opposed to including a library in your project, lodash has a repeat function.

_.repeat('*', 3);
// ? '***

https://lodash.com/docs#repeat

Add a Progress Bar in WebView

The best approch which worked for me is

webView.setWebViewClient(new WebViewClient() {

    @Override public void onPageStarted(WebView view, String url, Bitmap favicon) {
          super.onPageStarted(view, url, favicon);
          mProgressBar.setVisibility(ProgressBar.VISIBLE);
          webView.setVisibility(View.INVISIBLE);
        }

    @Override public void onPageCommitVisible(WebView view, String url) {
      super.onPageCommitVisible(view, url);
      mProgressBar.setVisibility(ProgressBar.GONE);
      webView.setVisibility(View.VISIBLE);
      isWebViewLoadingFirstPage=false;
    }
}

How do I unload (reload) a Python module?

The following code allows you Python 2/3 compatibility:

try:
    reload
except NameError:
    # Python 3
    from imp import reload

The you can use it as reload() in both versions which makes things simpler.

How do I catch an Ajax query post error?

jQuery 1.5 added deferred objects that handle this nicely. Simply call $.post and attach any handlers you'd like after the call. Deferred objects even allow you to attach multiple success and error handlers.

Example:

$.post('status.ajax.php', {deviceId: id})
    .done( function(msg) { ... } )
    .fail( function(xhr, textStatus, errorThrown) {
        alert(xhr.responseText);
    });

Prior to jQuery 1.8, the function done was called success and fail was called error.

Fastest way to copy a file in Node.js

Fast to write and convenient to use, with promise and error management:

function copyFile(source, target) {
  var rd = fs.createReadStream(source);
  var wr = fs.createWriteStream(target);
  return new Promise(function(resolve, reject) {
    rd.on('error', reject);
    wr.on('error', reject);
    wr.on('finish', resolve);
    rd.pipe(wr);
  }).catch(function(error) {
    rd.destroy();
    wr.end();
    throw error;
  });
}

The same with async/await syntax:

async function copyFile(source, target) {
  var rd = fs.createReadStream(source);
  var wr = fs.createWriteStream(target);
  try {
    return await new Promise(function(resolve, reject) {
      rd.on('error', reject);
      wr.on('error', reject);
      wr.on('finish', resolve);
      rd.pipe(wr);
    });
  } catch (error) {
    rd.destroy();
    wr.end();
    throw error;
  }
}

ASP.NET MVC Razor render without encoding

@(new HtmlString(myString))

cannot import name patterns

This is the code which worked for me. My django version is 1.10.4 final

from django.conf.urls import url, include

from django.contrib import admin
admin.autodiscover()

urlpatterns = [
    # Examples:
    # url(r'^$', 'blog.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
]

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

Class library is shared compiled code.

Shared project is shared source code.

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

As @Agam said,

You need this statement in your driver file: from AthleteList import AtheleteList

setup android on eclipse but don't know SDK directory

a simple windows search for android-sdk should help you find it, assuming you named it that. You also might just wanna try sdk

Using BigDecimal to work with currencies

Use BigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP) when you want to round up to the 2 decimal points for cents. Be aware of rounding off error when you do calculations though. You need to be consistent when you will be doing the rounding of money value. Either do the rounding right at the end just once after all calculations are done, or apply rounding to each value before doing any calculations. Which one to use would depend on your business requirement, but generally, I think doing rounding right at the end seems to make a better sense to me.

Use a String when you construct BigDecimal for money value. If you use double, it will have a trailing floating point values at the end. This is due to computer architecture regarding how double/float values are represented in binary format.

How can I disable the default console handler, while using the java logging API?

You must instruct your logger not to send its messages on up to its parent logger:

...
import java.util.logging.*;
...
Logger logger = Logger.getLogger(this.getClass().getName());
logger.setUseParentHandlers(false);
...

However, this should be done before adding any more handlers to logger.

Check if input value is empty and display an alert

Better one is here.

$('#submit').click(function()
{
    if( !$('#myMessage').val() ) {
       alert('warning');
    }
});

And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:

$('#submit').on('click',function()
{
    if( $('#myMessage').val().length === 0 ) {
        alert('warning');
    }
});

If you're sure it will always operate on a textfield element then you can just use this.value.

$('#submit').click(function()
{
      if( !document.getElementById('myMessage').value ) {
          alert('warning');
      }
});

Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).

Get scroll position using jquery

Use scrollTop() to get or set the scroll position.

make an ID in a mysql table auto_increment (after the fact)

This worked for me (i wanted to make id primary and set auto increment)

ALTER TABLE table_name CHANGE id id INT PRIMARY KEY AUTO_INCREMENT;

Send file via cURL from form POST in PHP

This should work:

$tmpfile = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);

$data = array(
    'uploaded_file' => '@'.$tmpfile.';filename='.$filename,
);

$ch = curl_init();   
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// set your other cURL options here (url, etc.)

curl_exec($ch);

In the receiving script, you would have:

print_r($_FILES);
/* which would output something like
     Array (
        [uploaded_file] => Array (
            [tmp_name] => /tmp/f87453hf
            [name] => myimage.jpg
            [error] => 0
            [size] => 12345
            [type] => image/jpeg
        )
     )
*/

Then, if you want to properly handle the file upload, you would do something like this:

if (move_uploaded_file($_FILES['uploaded_file'], '/path/to/destination/file.zip')) {
   // do stuff
}

Find all elements on a page whose element ID contains a certain text using jQuery

$('*[id*=mytext]:visible').each(function() {
    $(this).doStuff();
});

Note the asterisk '*' at the beginning of the selector matches all elements.

See the Attribute Contains Selectors, as well as the :visible and :hidden selectors.

Understanding Spring @Autowired usage

Yes, you can configure the Spring servlet context xml file to define your beans (i.e., classes), so that it can do the automatic injection for you. However, do note, that you have to do other configurations to have Spring up and running and the best way to do that, is to follow a tutorial ground up.

Once you have your Spring configured probably, you can do the following in your Spring servlet context xml file for Example 1 above to work (please replace the package name of com.movies to what the true package name is and if this is a 3rd party class, then be sure that the appropriate jar file is on the classpath) :

<beans:bean id="movieFinder" class="com.movies.MovieFinder" />

or if the MovieFinder class has a constructor with a primitive value, then you could something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg value="100" />
</beans:bean>

or if the MovieFinder class has a constructor expecting another class, then you could do something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg ref="otherBeanRef" />
</beans:bean>

...where 'otherBeanRef' is another bean that has a reference to the expected class.

Convert SQL Server result set into string

Assign a value when declaring the variable.

DECLARE @result VARCHAR(1000) ='';

SELECT @result = CAST(StudentId AS VARCHAR) + ',' FROM Student WHERE condition = xyz

get the value of input type file , and alert if empty

HTML Code

<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload"  class="send_upload" value="upload" />

jQuery Code using bind method

$(document).ready(function() {
    $('#upload').bind("click",function() 
    { if(!$('#uploadImage').val()){
                alert("empty");
                return false;} });  });

Enterprise app deployment doesn't work on iOS 7.1

Our team uses dropbox for ad-hoc distribution which uses https but still our app was failing to install. After much trouble-shooting we realized that the title field is required too. Whenever we sent out a link without this field safari ignored the link and did not prompt the user to install. Sometimes for quick development tests we skipped over the title node in the xml and not populate it. In case this is helpful for anyone having this issue make sure that your .plist contains the following nodes populated:

      ....
     <string>software</string>
    <key>title</key>
     <string>Your App Name</string>
      ...

Format date and time in a Windows batch script

The offset:length formatting supported with the SET command in Windows will not allow you to pad the 0 as you seem to be interested in.

However, you can code a BATCH script to check for the hour being less than 10 and
pad accordingly with a different echo string.

You will find some information on the SET command on this link.


You can also change to other programming methods to get here.

It is quite simple in unix bash (available with Cygwin on Windows) to just say,

date +%Y_%m_%d__%H_%M_%S

And, it always pads correctly.

How to change button text or link text in JavaScript?

You can simply use:

document.getElementById(button_id).innerText = 'Your text here';

If you want to use HTML formatting, use the innerHTML property instead.

C# Convert List<string> to Dictionary<string, string>

EDIT

another way to deal with duplicate is you can do like this

var dic = slist.Select((element, index)=> new{element,index} )
            .ToDictionary(ele=>ele.index.ToString(), ele=>ele.element);

or


easy way to do is

var res = list.ToDictionary(str => str, str=> str); 

but make sure that there is no string is repeating...again otherewise above code will not work for you

if there is string is repeating than its better to do like this

Dictionary<string,string> dic= new Dictionary<string,string> ();

    foreach(string s in Stringlist)
    {
       if(!dic.ContainsKey(s))
       {
        //  dic.Add( value to dictionary
      }
    }

How can I check if an InputStream is empty without reading from it?

public void run() {
    byte[] buffer = new byte[256];  
    int bytes;                      

    while (true) {
        try {
            bytes = mmInStream.read(buffer);
            mHandler.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();
        } catch (IOException e) {
            break;
        }
    }
}

How to use AND in IF Statement

Brief syntax lesson

Cells(Row, Column) identifies a cell. Row must be an integer between 1 and the maximum for version of Excel you are using. Column must be a identifier (for example: "A", "IV", "XFD") or a number (for example: 1, 256, 16384)

.Cells(Row, Column) identifies a cell within a sheet identified in a earlier With statement:

With ActiveSheet
  :
  .Cells(Row,Column)
  :
End With

If you omit the dot, Cells(Row,Column) is within the active worksheet. So wsh = ActiveWorkbook wsh.Range is not strictly necessary. However, I always use a With statement so I do not wonder which sheet I meant when I return to my code in six months time. So, I would write:

With ActiveSheet
  :
  .Range.  
  :
End With

Actually, I would not write the above unless I really did want the code to work on the active sheet. What if the user has the wrong sheet active when they started the macro. I would write:

With Sheets("xxxx")
  :
  .Range.  
  :
End With

because my code only works on sheet xxxx.

Cells(Row,Column) identifies a cell. Cells(Row,Column).xxxx identifies a property of the cell. Value is a property. Value is the default property so you can usually omit it and the compiler will know what you mean. But in certain situations the compiler can be confused so the advice to include the .Value is good.

Cells(Row,Column) like "*Miami*" will give True if the cell is "Miami", "South Miami", "Miami, North" or anything similar.

Cells(Row,Column).Value = "Miami" will give True if the cell is exactly equal to "Miami". "MIAMI" for example will give False. If you want to accept MIAMI, use the lower case function:

Lcase(Cells(Row,Column).Value) = "miami"  

My suggestions

Your sample code keeps changing as you try different suggestions which I find confusing. You were using Cells(Row,Column) <> "Miami" when I started typing this.

Use

If Cells(i, "A").Value like "*Miami*" And Cells(i, "D").Value like "*Florida*" Then
  Cells(i, "C").Value = "BA"

if you want to accept, for example, "South Miami" and "Miami, North".

Use

If Cells(i, "A").Value = "Miami" And Cells(i, "D").Value like "Florida" Then
  Cells(i, "C").Value = "BA"

if you want to accept, exactly, "Miami" and "Florida".

Use

If Lcase(Cells(i, "A").Value) = "miami" And _
   Lcase(Cells(i, "D").Value) = "florida" Then
  Cells(i, "C").Value = "BA"

if you don't care about case.

How do I configure Notepad++ to use spaces instead of tabs?

Go to the Preferences menu command under menu Settings, and select Language Menu/Tab Settings, depending on your version. Earlier versions use Tab Settings. Later versions use Language. Click the Replace with space check box. Set the size to 4.

Enter image description here

See documentation: http://docs.notepad-plus-plus.org/index.php/Built-in_Languages#Tab_settings

how to attach url link to an image?

"How to attach url link to an image?"

You do it like this:

<a href="http://www.google.com"><img src="http://www.google.com/intl/en_ALL/images/logo.gif"/></a>

See it in action.

How can I get argv[] as int?

Basic usage

The "string to long" (strtol) function is standard for this ("long" can hold numbers much larger than "int"). This is how to use it:

#include <stdlib.h>

long arg = strtol(argv[1], NULL, 10);
// string to long(string, endpointer, base)

Since we use the decimal system, base is 10. The endpointer argument will be set to the "first invalid character", i.e. the first non-digit. If you don't care, set the argument to NULL instead of passing a pointer, as shown.

Error checking (1)

If you don't want non-digits to occur, you should make sure it's set to the "null terminator", since a \0 is always the last character of a string in C:

#include <stdlib.h>

char* p;
long arg = strtol(argv[1], &p, 10);
if (*p != '\0') // an invalid character was found before the end of the string

Error checking (2)

As the man page mentions, you can use errno to check that no errors occurred (in this case overflows or underflows).

#include <stdlib.h>
#include <errno.h>

char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
    return 1; // In main(), returning non-zero means failure
}

// Everything went well, print it as 'long decimal'
printf("%ld", arg);

Convert to integer

So now we are stuck with this long, but we often want to work with integers. To convert a long into an int, we should first check that the number is within the limited capacity of an int. To do this, we add a second if-statement, and if it matches, we can just cast it.

#include <stdlib.h>
#include <errno.h>
#include <limits.h>

char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
    return 1; // In main(), returning non-zero means failure
}

if (arg < INT_MIN || arg > INT_MAX) {
    return 1;
}
int arg_int = arg;

// Everything went well, print it as a regular number
printf("%d", arg_int);

To see what happens if you don't do this check, test the code without the INT_MIN/MAX if-statement. You'll see that if you pass a number larger than 2147483647 (231), it will overflow and become negative. Or if you pass a number smaller than -2147483648 (-231-1), it will underflow and become positive. Values beyond those limits are too large to fit in an integer.

Full example

#include <stdio.h>  // for printf()
#include <stdlib.h> // for strtol()
#include <errno.h>  // for errno
#include <limits.h> // for INT_MIN and INT_MAX

int main(int argc, char** argv) {
    char* p;
    errno = 0; // not 'int errno', because the '#include' already defined it
    long arg = strtol(argv[1], &p, 10);
    if (*p != '\0' || errno != 0) {
        return 1; // In main(), returning non-zero means failure
    }

    if (arg < INT_MIN || arg > INT_MAX) {
        return 1;
    }
    int arg_int = arg;

    // Everything went well, print it as a regular number plus a newline
    printf("Your value was: %d\n", arg_int);
    return 0;
}

In Bash, you can test this with:

cc code.c -o example  # Compile, output to 'example'
./example $((2**31-1))  # Run it
echo "exit status: $?"  # Show the return value, also called 'exit status'

Using 2**31-1, it should print the number and 0, because 231-1 is just in range. If you pass 2**31 instead (without -1), it will not print the number and the exit status will be 1.

Beyond this, you can implement custom checks: test whether the user passed an argument at all (check argc), test whether the number is in the range that you want, etc.

When should we use mutex and when should we use semaphore

Trying not to sound zany, but can't help myself.

Your question should be what is the difference between mutex and semaphores ? And to be more precise question should be, 'what is the relationship between mutex and semaphores ?'

(I would have added that question but I'm hundred % sure some overzealous moderator would close it as duplicate without understanding difference between difference and relationship.)

In object terminology we can observe that :

observation.1 Semaphore contains mutex

observation.2 Mutex is not semaphore and semaphore is not mutex.

There are some semaphores that will act as if they are mutex, called binary semaphores, but they are freaking NOT mutex.

There is a special ingredient called Signalling (posix uses condition_variable for that name), required to make a Semaphore out of mutex. Think of it as a notification-source. If two or more threads are subscribed to same notification-source, then it is possible to send them message to either ONE or to ALL, to wakeup.

There could be one or more counters associated with semaphores, which are guarded by mutex. The simple most scenario for semaphore, there is a single counter which can be either 0 or 1.

This is where confusion pours in like monsoon rain.

A semaphore with a counter that can be 0 or 1 is NOT mutex.

Mutex has two states (0,1) and one ownership(task). Semaphore has a mutex, some counters and a condition variable.

Now, use your imagination, and every combination of usage of counter and when to signal can make one kind-of-Semaphore.

  1. Single counter with value 0 or 1 and signaling when value goes to 1 AND then unlocks one of the guy waiting on the signal == Binary semaphore

  2. Single counter with value 0 to N and signaling when value goes to less than N, and locks/waits when values is N == Counting semaphore

  3. Single counter with value 0 to N and signaling when value goes to N, and locks/waits when values is less than N == Barrier semaphore (well if they dont call it, then they should.)

Now to your question, when to use what. (OR rather correct question version.3 when to use mutex and when to use binary-semaphore, since there is no comparison to non-binary-semaphore.) Use mutex when 1. you want a customized behavior, that is not provided by binary semaphore, such are spin-lock or fast-lock or recursive-locks. You can usually customize mutexes with attributes, but customizing semaphore is nothing but writing new semaphore. 2. you want lightweight OR faster primitive

Use semaphores, when what you want is exactly provided by it.

If you dont understand what is being provided by your implementation of binary-semaphore, then IMHO, use mutex.

And lastly read a book rather than relying just on SO.

"The specified Android SDK Build Tools version (26.0.0) is ignored..."

invalidate cache in android studio will resolve this issue. Go to file-> click on invalidate cache/restart option.

Launching Spring application Address already in use

image of Spring Tool Suite and stop application button

In my case looking in the servers window only showed a tomcat server that I had never used for this project. My SpringBoot project used an embedded tomcat server and it did not stop when my application finished. This button which I indicate with a red arrow will stop the application and the Tomcat server so next time I run the application I will not get the error that an Instance of Tomcat is already running on port 8080.

actual error messages:

Verify the connector's configuration, identify and stop any process that's listening on port 8080, or configure this application to listen on another port.

Caused by: java.net.BindException: Address already in use Caused by: org.apache.catalina.LifecycleException: service.getName(): "Tomcat"; Protocol handler start failed

I will now be looking into a way to shut down all services on completion of my SpringBoot Consuming Rest application in this tutorial https://spring.io/guides/gs/consuming-rest/

spring-boot

When should I use a struct rather than a class in C#?

Here is a basic rule.

  • If all member fields are value types create a struct.

  • If any one member field is a reference type, create a class. This is because the reference type field will need the heap allocation anyway.

Exmaples

public struct MyPoint 
{
    public int X; // Value Type
    public int Y; // Value Type
}

public class MyPointWithName 
{
    public int X; // Value Type
    public int Y; // Value Type
    public string Name; // Reference Type
}

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

This is often caused by an attempt to process a null object. An example, trying to empty a Bindable list that is null will trigger the exception:

public class MyViewModel {
    [BindableProperty]
    public virtual IList<Products> ProductsList{ get; set; }

    public MyViewModel ()
    {
        ProductsList.Clear(); // here is the problem
    }
}

This could easily be fixed by checking for null:

if (ProductsList!= null) ProductsList.Clear();

What evaluates to True/False in R?

If you think about it, comparing numbers to logical statements doesn't make much sense. However, since 0 is often associated with "Off" or "False" and 1 with "On" or "True", R has decided to allow 1 == TRUE and 0 == FALSE to both be true. Any other numeric-to-boolean comparison should yield false, unless it's something like 3 - 2 == TRUE.

How to assign more memory to docker container

Allocate maximum memory to your docker machine from (docker preference -> advance )

Screenshot of advance settings: Screenshot of advance settings.

This will set the maximum limit docker consume while running containers. Now run your image in new container with -m=4g flag for 4 gigs ram or more. e.g.

docker run -m=4g {imageID}

Remember to apply the ram limit increase changes. Restart the docker and double check that ram limit did increased. This can be one of the factor you not see the ram limit increase in docker containers.

require(vendor/autoload.php): failed to open stream

First, review route inside index.php

require __DIR__.'/../vendor/autoload.php';

$app = require_once __DIR__.'/../bootstrap/app.php';

in my case the route did not work, I had to review the directories.

How to fix corrupt HDFS FIles

start all daemons and run the command as "hadoop namenode -recover -force" stop the daemons and start again.. wait some time to recover data.

Put content in HttpResponseMessage object?

The easiest single-line solution is to use

return new HttpResponseMessage( HttpStatusCode.OK ) {Content =  new StringContent( "Your message here" ) };

For serialized JSON content:

return new HttpResponseMessage( HttpStatusCode.OK ) {Content =  new StringContent( SerializedString, System.Text.Encoding.UTF8, "application/json" ) };

Different font size of strings in the same TextView

Method 1

public static void increaseFontSizeForPath(Spannable spannable, String path, float increaseTime) {
    int startIndexOfPath = spannable.toString().indexOf(path);
    spannable.setSpan(new RelativeSizeSpan(increaseTime), startIndexOfPath,
            startIndexOfPath + path.length(), 0);
}

using

Utils.increaseFontSizeForPath(spannable, "big", 3); // make "big" text bigger 3 time than normal text

enter image description here

Method 2

public static void setFontSizeForPath(Spannable spannable, String path, int fontSizeInPixel) {
    int startIndexOfPath = spannable.toString().indexOf(path);
    spannable.setSpan(new AbsoluteSizeSpan(fontSizeInPixel), startIndexOfPath,
            startIndexOfPath + path.length(), 0);
}

using

Utils.setFontSizeForPath(spannable, "big", (int) textView.getTextSize() + 20); // make "big" text bigger 20px than normal text

enter image description here

Copy multiple files from one directory to another from Linux shell

Try this simpler one,

cp /home/ankur/folder/file{1,2} /home/ankur/dest

If you want to copy all the 10 files then run this command,

 cp ~/Desktop/{xyz,file{1,2},next,files,which,are,not,similer} foo-bar

Include jQuery in the JavaScript Console

It's pretty easy to do this manually, as the other answers explain. But there's also the jQuerify plug-in.

Print a list of all installed node.js modules

Generally, there are two ways to list out installed packages - through the Command Line Interface (CLI) or in your application using the API.

Both commands will print to stdout all the versions of packages that are installed, as well as their dependencies, in a tree-structure.


CLI

npm list

Use the -g (global) flag to list out all globally-installed packages. Use the --depth=0 flag to list out only the top packages and not their dependencies.


API

In your case, you want to run this within your script, so you'd need to use the API. From the docs:

npm.commands.ls(args, [silent,] callback)

In addition to printing to stdout, the data will also be passed into the callback.

Android: converting String to int

It's already a string? Remove the getText() call.

int myNum = 0;

try {
    myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
  // Handle parse error.
}

Use of Java's Collections.singletonList()?

singletonList can hold instance of any object. Object state can be modify.

List<Character> list = new ArrayList<Character>();
list.add('X');
list.add('Y');
System.out.println("Initial list: "+ list);
List<List<Character>> list2 = Collections.singletonList(list);
list.add('Z');
System.out.println(list);
System.out.println(list2);

We can not define unmodifiableList like above.

PHP - find entry by object property from an array of objects

I sometimes like using the array_reduce() function to carry out the search. It's similar to array_filter() but does not affect the searched array, allowing you to carry out multiple searches on the same array of objects.

$haystack = array($obj1, $obj2, ...); //some array of objects
$needle = 'looking for me?'; //the value of the object's property we want to find

//carry out the search
$search_results_array = array_reduce(
  $haystack,

  function($result_array, $current_item) use ($needle){
      //Found the an object that meets criteria? Add it to the the result array 
      if ($current_item->someProperty == $needle){
          $result_array[] = $current_item;
      }
      return $result_array;
  },
  array() //initially the array is empty (i.e.: item not found)
);

//report whether objects found
if (count($search_results_array) > 0){
  echo "found object(s): ";
  print_r($search_results_array[0]); //sample object found
} else {
  echo "did not find object(s): ";
}

How to secure an ASP.NET Web API

Update:

I have added this link to my other answer how to use JWT authentication for ASP.NET Web API here for anyone interested in JWT.


We have managed to apply HMAC authentication to secure Web API, and it worked okay. HMAC authentication uses a secret key for each consumer which both consumer and server both know to hmac hash a message, HMAC256 should be used. Most of the cases, hashed password of the consumer is used as a secret key.

The message normally is built from data in the HTTP request, or even customized data which is added to HTTP header, the message might include:

  1. Timestamp: time that request is sent (UTC or GMT)
  2. HTTP verb: GET, POST, PUT, DELETE.
  3. post data and query string,
  4. URL

Under the hood, HMAC authentication would be:

Consumer sends a HTTP request to web server, after building the signature (output of hmac hash), the template of HTTP request:

User-Agent: {agent}   
Host: {host}   
Timestamp: {timestamp}
Authentication: {username}:{signature}

Example for GET request:

GET /webapi.hmac/api/values

User-Agent: Fiddler    
Host: localhost    
Timestamp: Thursday, August 02, 2012 3:30:32 PM 
Authentication: cuongle:LohrhqqoDy6PhLrHAXi7dUVACyJZilQtlDzNbLqzXlw=

The message to hash to get signature:

GET\n
Thursday, August 02, 2012 3:30:32 PM\n
/webapi.hmac/api/values\n

Example for POST request with query string (signature below is not correct, just an example)

POST /webapi.hmac/api/values?key2=value2

User-Agent: Fiddler    
Host: localhost    
Content-Type: application/x-www-form-urlencoded
Timestamp: Thursday, August 02, 2012 3:30:32 PM 
Authentication: cuongle:LohrhqqoDy6PhLrHAXi7dUVACyJZilQtlDzNbLqzXlw=

key1=value1&key3=value3

The message to hash to get signature

GET\n
Thursday, August 02, 2012 3:30:32 PM\n
/webapi.hmac/api/values\n
key1=value1&key2=value2&key3=value3

Please note that form data and query string should be in order, so the code on the server get query string and form data to build the correct message.

When HTTP request comes to the server, an authentication action filter is implemented to parse the request to get information: HTTP verb, timestamp, uri, form data and query string, then based on these to build signature (use hmac hash) with the secret key (hashed password) on the server.

The secret key is got from the database with the username on the request.

Then server code compares the signature on the request with the signature built; if equal, authentication is passed, otherwise, it failed.

The code to build signature:

private static string ComputeHash(string hashedPassword, string message)
{
    var key = Encoding.UTF8.GetBytes(hashedPassword.ToUpper());
    string hashString;

    using (var hmac = new HMACSHA256(key))
    {
        var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
        hashString = Convert.ToBase64String(hash);
    }

    return hashString;
}

So, how to prevent replay attack?

Add constraint for the timestamp, something like:

servertime - X minutes|seconds  <= timestamp <= servertime + X minutes|seconds 

(servertime: time of request coming to server)

And, cache the signature of the request in memory (use MemoryCache, should keep in the limit of time). If the next request comes with the same signature with the previous request, it will be rejected.

The demo code is put as here: https://github.com/cuongle/Hmac.WebApi

Valid values for android:fontFamily and what they map to?

Available fonts (as of Oreo)

Preview of all fonts

The Material Design Typography page has demos for some of these fonts and suggestions on choosing fonts and styles.

For code sleuths: fonts.xml is the definitive and ever-expanding list of Android fonts.


Using these fonts

Set the android:fontFamily and android:textStyle attributes, e.g.

<!-- Roboto Bold -->
<TextView
    android:fontFamily="sans-serif"
    android:textStyle="bold" />

to the desired values from this table:

Font                     | android:fontFamily          | android:textStyle
-------------------------|-----------------------------|-------------------
Roboto Thin              | sans-serif-thin             |
Roboto Light             | sans-serif-light            |
Roboto Regular           | sans-serif                  |
Roboto Bold              | sans-serif                  | bold
Roboto Medium            | sans-serif-medium           |
Roboto Black             | sans-serif-black            |
Roboto Condensed Light   | sans-serif-condensed-light  |
Roboto Condensed Regular | sans-serif-condensed        |
Roboto Condensed Medium  | sans-serif-condensed-medium |
Roboto Condensed Bold    | sans-serif-condensed        | bold
Noto Serif               | serif                       |
Noto Serif Bold          | serif                       | bold
Droid Sans Mono          | monospace                   |
Cutive Mono              | serif-monospace             |
Coming Soon              | casual                      |
Dancing Script           | cursive                     |
Dancing Script Bold      | cursive                     | bold
Carrois Gothic SC        | sans-serif-smallcaps        |

(Noto Sans is a fallback font; you can't specify it directly)

Note: this table is derived from fonts.xml. Each font's family name and style is listed in fonts.xml, e.g.

<family name="serif-monospace">
    <font weight="400" style="normal">CutiveMono.ttf</font>
</family>

serif-monospace is thus the font family, and normal is the style.


Compatibility

Based on the log of fonts.xml and the former system_fonts.xml, you can see when each font was added:

  • Ice Cream Sandwich: Roboto regular, bold, italic, and bold italic
  • Jelly Bean: Roboto light, light italic, condensed, condensed bold, condensed italic, and condensed bold italic
  • Jelly Bean MR1: Roboto thin and thin italic
  • Lollipop:
    • Roboto medium, medium italic, black, and black italic
    • Noto Serif regular, bold, italic, bold italic
    • Cutive Mono
    • Coming Soon
    • Dancing Script
    • Carrois Gothic SC
    • Noto Sans
  • Oreo MR1: Roboto condensed medium

iOS: Multi-line UILabel in Auto Layout

I have a UITableViewCell which has a text wrap label. I worked text wrapping as follows.

1) Set UILabel constraints as follows.

enter image description here

2) Set no. of lines to 0.

3) Added UILabel height constraint to UITableViewCell.

@IBOutlet weak var priorityLabelWidth: NSLayoutConstraint!

4) On UITableViewCell:

priorityLabel.sizeToFit()
priorityLabelWidth.constant = priorityLabel.intrinsicContentSize().width+5

What is the right way to check for a null string in Objective-C?

For string:

+ (BOOL) checkStringIsNotEmpty:(NSString*)string {
if (string == nil || string.length == 0) return NO;
return YES;

}

Refer the picture below:

enter image description here

Html.fromHtml deprecated in Android N

If you are lucky enough to develop on Kotlin, just create an extension function:

fun String.toSpanned(): Spanned {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY)
    } else {
        @Suppress("DEPRECATION")
        return Html.fromHtml(this)
    }
}

And then it's so sweet to use it everywhere:

yourTextView.text = anyString.toSpanned()

PermissionError: [Errno 13] in python

When doing;

a_file = open('E:\Python Win7-64-AMD 3.3\Test', encoding='utf-8')

...you're trying to open a directory as a file, which may (and on most non UNIX file systems will) fail.

Your other example though;

a_file = open('E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

should work well if you just have the permission on a.txt. You may want to use a raw (r-prefixed) string though, to make sure your path does not contain any escape characters like \n that will be translated to special characters.

a_file = open(r'E:\Python Win7-64-AMD 3.3\Test\a.txt', encoding='utf-8')

How do I check out a specific version of a submodule using 'git submodule'?

Step 1: Add the submodule

   git submodule add git://some_repository.git some_repository

Step 2: Fix the submodule to a particular commit

By default the new submodule will be tracking HEAD of the master branch, but it will NOT be updated as you update your primary repository. In order to change the submodule to track a particular commit or different branch, change directory to the submodule folder and switch branches just like you would in a normal repository.

   git checkout -b some_branch origin/some_branch

Now the submodule is fixed on the development branch instead of HEAD of master.

From Two Guys Arguing — Tie Git Submodules to a Particular Commit or Branch .

identifier "string" undefined?

You must use std namespace. If this code in main.cpp you should write

using namespace std;

If this declaration is in header, then you shouldn't include namespace and just write

std::string level;

How do I get the path of the Python script I am running in?

import os
print os.path.abspath(__file__)

SQL query to get most recent row for each instance of a given key

Can't post comments yet, but @Cristi S's answer works a treat for me.

In my scenario, I needed to keep only the most recent 3 records in Lowest_Offers for all product_ids.

Need to rework his SQL to delete - thought that this would be ok, but syntax is wrong.

DELETE from (
SELECT product_id, id, date_checked,
  ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY date_checked DESC) rn
FROM lowest_offers
) tmp WHERE > 3;

How to Reload ReCaptcha using JavaScript?

If you are using version 1

Recaptcha.reload();

If you are using version 2

grecaptcha.reset();

Creating a DateTime in a specific Time Zone in c#

I altered Jon Skeet answer a bit for the web with extension method. It also works on azure like a charm.

public static class DateTimeWithZone
{

private static readonly TimeZoneInfo timeZone;

static DateTimeWithZone()
{
//I added web.config <add key="CurrentTimeZoneId" value="Central Europe Standard Time" />
//You can add value directly into function.
    timeZone = TimeZoneInfo.FindSystemTimeZoneById(ConfigurationManager.AppSettings["CurrentTimeZoneId"]);
}


public static DateTime LocalTime(this DateTime t)
{
     return TimeZoneInfo.ConvertTime(t, timeZone);   
}
}

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

You can find some technical comparison on npmcompare

Comparing browserify vs. grunt vs. gulp vs. webpack

As you can see webpack is very well maintained with a new version coming out every 4 days on average. But Gulp seems to have the biggest community of them all (with over 20K stars on Github) Grunt seems a bit neglected (compared to the others)

So if need to choose one over the other i would go with Gulp

Filter Pyspark dataframe column with None value

Try to just use isNotNull function.

df.filter(df.dt_mvmt.isNotNull()).count()

What size should apple-touch-icon.png be for iPad and iPhone?

The relevant documentation on Apple's site, Specifying a Webpage Icon for Web Clip.

There is no need to put anything in the head of your document. If no icons are specified using a link element, the website root directory is searched for icons with the apple-touch-icon or apple-touch-icon-precomposed prefix.

For example, if the appropriate icon size for the device is 57 x 57, the system searches for filenames in the following order:

  • apple-touch-icon-57x57-precomposed.png
  • apple-touch-icon-57x57.png
  • apple-touch-icon-precomposed.png
  • apple-touch-icon.png

"std::endl" vs "\n"

They will both write the appropriate end-of-line character(s). In addition to that endl will cause the buffer to be committed. You usually don't want to use endl when doing file I/O because the unnecessary commits can impact performance.

How can I declare a Boolean parameter in SQL statement?

SQL Server recognizes 'TRUE' and 'FALSE' as bit values. So, use a bit data type!

declare @var bit
set @var = 'true'
print @var

That returns 1.

How to resize Image in Android?

You can use Matrix to resize your camera image ....

BitmapFactory.Options options=new BitmapFactory.Options();
InputStream is = getContentResolver().openInputStream(currImageURI);
bm = BitmapFactory.decodeStream(is,null,options);
int Height = bm.getHeight();
int Width = bm.getWidth();
int newHeight = 300;
int newWidth = 300;
float scaleWidth = ((float) newWidth) / Width;
float scaleHeight = ((float) newHeight) / Height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0,Width, Height, matrix, true);
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Add FormsModule in Imports Array.
i.e

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})

Or this can be done without using [(ngModel)] by using

<input [value]='hero.name' (input)='hero.name=$event.target.value' placeholder="name">

instead of

<input [(ngModel)]="hero.name" placeholder="Name">

Command to get nth line of STDOUT

Try this sed version:

ls -l | sed '2 ! d'

It says "delete all the lines that aren't the second one".

Cannot make Project Lombok work on Eclipse

Just faced this issue (compiler errors for generated getters) and none of the proposed solutions helped.

Setup: Eclipse Oxygen (32bit), SAP_JVM (32bit), Lombok 1.16.18 (Eclipse plugin properly installed).

Created a plain new test project, which worked like a charm. Afterwards deleted the failing project and checked it out again from my Github repo, which fixed the errors. Just deleting the project from the workspace and importing it again, didn't help.

Implement a loading indicator for a jQuery AJAX call

There is a global configuration using jQuery. This code runs on every global ajax request.

<div id='ajax_loader' style="position: fixed; left: 50%; top: 50%; display: none;">
    <img src="themes/img/ajax-loader.gif"></img>
</div>

<script type="text/javascript">
    jQuery(function ($){
        $(document).ajaxStop(function(){
            $("#ajax_loader").hide();
         });
         $(document).ajaxStart(function(){
             $("#ajax_loader").show();
         });    
    });    
</script>

Here is a demo: http://jsfiddle.net/sd01fdcm/

including parameters in OPENQUERY

In the following example I'm passing a department parameter to a stored procedure(spIncreaseTotalsRpt) and at the same time I'm creating a temp table all from an OPENQUERY. The Temp table needs to be a global Temp (##) so it can be referenced outside it's intance. By using exec sp_executesql you can pass the department parameter.

Note: be careful when using sp_executeSQL. Also your admin might not have this option available to you.

Hope this helps someone.

 IF OBJECT_ID('tempdb..##Temp') IS NOT NULL
/*Then it exists*/
    begin
       DROP TABLE ##Temp
    end 
 Declare @Dept as nvarchar(20) ='''47'''

 declare @OPENQUERY  as nvarchar(max)
set @OPENQUERY = 'Select ' + @Dept + ' AS Dept,  * into ##Temp from openquery(SQL_AWSPROD01,''' 

declare @sql nvarchar(max)= @openquery +  'SET FMTONLY OFF EXECUTE SalaryCompensation.dbo.spIncreaseTotalsRpts ' + '''' + @Dept + ''''  + ''')'
declare @parmdef nvarchar(25) 
DECLARE @param nvarchar(20) 

SET @parmdef = N'@Dept varchar(20)'
-- select @sql
-- Print @sql + @parmdef  + @dept
exec sp_executesql @sql,@parmdef, @Dept  
Select * from ##Temp

Results

Dept increase Cnt 0 1 2 3 4 5 6 0.0000 1.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000

What are the uses of "using" in C#?

It also can be used for creating scopes for Example:

class LoggerScope:IDisposable {
   static ThreadLocal<LoggerScope> threadScope = 
        new ThreadLocal<LoggerScope>();
   private LoggerScope previous;

   public static LoggerScope Current=> threadScope.Value;

   public bool WithTime{get;}

   public LoggerScope(bool withTime){
       previous = threadScope.Value;
       threadScope.Value = this;
       WithTime=withTime;
   }

   public void Dispose(){
       threadScope.Value = previous;
   }
}


class Program {
   public static void Main(params string[] args){
       new Program().Run();
   }

   public void Run(){
      log("something happend!");
      using(new LoggerScope(false)){
          log("the quick brown fox jumps over the lazy dog!");
          using(new LoggerScope(true)){
              log("nested scope!");
          }
      }
   }

   void log(string message){
      if(LoggerScope.Current!=null){
          Console.WriteLine(message);
          if(LoggerScope.Current.WithTime){
             Console.WriteLine(DateTime.Now);
          }
      }
   }

}

how to check if List<T> element contains an item with a Particular Property Value

var item = pricePublicList.FirstOrDefault(x => x.Size == 200);
if (item != null) {
   // There exists one with size 200 and is stored in item now
}
else {
  // There is no PricePublicModel with size 200
}

Delete an element from a dictionary

Here a top level design approach:

def eraseElement(d,k):
    if isinstance(d, dict):
        if k in d:
            d.pop(k)
            print(d)
        else:
            print("Cannot find matching key")
    else:
        print("Not able to delete")


exp = {'A':34, 'B':55, 'C':87}
eraseElement(exp, 'C')

I'm passing the dictionary and the key I want into my function, validates if it's a dictionary and if the key is okay, and if both exist, removes the value from the dictionary and prints out the left-overs.

Output: {'B': 55, 'A': 34}

Hope that helps!

Java Regex Capturing Groups

Your understanding is correct. However, if we walk through:

  • (.*) will swallow the whole string;
  • it will need to give back characters so that (\\d+) is satistifed (which is why 0 is captured, and not 3000);
  • the last (.*) will then capture the rest.

I am not sure what the original intent of the author was, however.

How do I connect to a specific Wi-Fi network in Android programmatically?

If your device knows the Wifi configs (already stored), we can bypass rocket science. Just loop through the configs an check if the SSID is matching. If so, connect and return.

Set permissions:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

Connect:

    try {
    String ssid = null;
    if (wifi == Wifi.PCAN_WIRELESS_GATEWAY) {
        ssid = AesPrefs.get(AesConst.PCAN_WIRELESS_SSID,
                context.getString(R.string.pcan_wireless_ssid_default));
    } else if (wifi == Wifi.KJ_WIFI) {
        ssid = context.getString(R.string.remote_wifi_ssid_default);
    }

    WifiManager wifiManager = (WifiManager) context.getApplicationContext()
            .getSystemService(Context.WIFI_SERVICE);

    List<WifiConfiguration> wifiConfigurations = wifiManager.getConfiguredNetworks();

    for (WifiConfiguration wifiConfiguration : wifiConfigurations) {
        if (wifiConfiguration.SSID.equals("\"" + ssid + "\"")) {
            wifiManager.enableNetwork(wifiConfiguration.networkId, true);
            Log.i(TAG, "connectToWifi: will enable " + wifiConfiguration.SSID);
            wifiManager.reconnect();
            return null; // return! (sometimes logcat showed me network-entries twice,
            // which may will end in bugs)
        }
    }
} catch (NullPointerException | IllegalStateException e) {
    Log.e(TAG, "connectToWifi: Missing network configuration.");
}
return null;

Why can templates only be implemented in the header file?

Another reason that it's a good idea to write both declarations and definitions in header files is for readability. Suppose there's such a template function in Utility.h:

template <class T>
T min(T const& one, T const& theOther);

And in the Utility.cpp:

#include "Utility.h"
template <class T>
T min(T const& one, T const& other)
{
    return one < other ? one : other;
}

This requires every T class here to implement the less than operator (<). It will throw a compiler error when you compare two class instances that haven't implemented the "<".

Therefore if you separate the template declaration and definition, you won't be able to only read the header file to see the ins and outs of this template in order to use this API on your own classes, though the compiler will tell you in this case about which operator needs to be overridden.

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

  1. Open phpMyAdmin in a browser and log in as root.
  2. Create a database called phpmyadmin
  3. Create a user called pma and set the "host" to the hostname or IP address of your web server (if the web server and MySQL are on the same box use localhost), make a note of the password, and grant the new user full control over the phpmyadmin database. It is recommended that this user does not have access to anything other than this database.
  4. Go to the phpMyAdmin installation directory, where you should find a sub-directory called sql.
  5. In sql you will find a file called create_tables.sql. Open it in a text editor.
  6. In phpMyAdmin, select the phpmyadmin database and click on the "SQL" tab.
  7. Copy/paste the entire text from create_tables.sql into the text box, and run the query.
  8. Open the config.inc.php file in the phpMyAdmin install directory, and add the following lines (or change the existing settings if they are already there):

    $cfg['Servers'][1]['pmadb'] = 'phpmyadmin';
    $cfg['Servers'][1]['controluser'] = 'pma';
    $cfg['Servers'][1]['controlpass'] = '<your password>';
    
    // Note: The list below may grow as PMA evolves and more control tables are added
    // Use your common sense! Don't just blindly copypasta, look at what it means!
    $cfg['Servers'][1]['bookmarktable'] = 'pma_bookmark';
    $cfg['Servers'][1]['relation'] = 'pma_relation';
    $cfg['Servers'][1]['userconfig'] = 'pma_userconfig';
    $cfg['Servers'][1]['table_info'] = 'pma_table_info';
    $cfg['Servers'][1]['column_info'] = 'pma_column_info';
    $cfg['Servers'][1]['history'] = 'pma_history';
    $cfg['Servers'][1]['recent'] = 'pma_recent';
    $cfg['Servers'][1]['table_uiprefs'] = 'pma_table_uiprefs';
    $cfg['Servers'][1]['tracking'] = 'pma_tracking';
    $cfg['Servers'][1]['table_coords'] = 'pma_table_coords';
    $cfg['Servers'][1]['pdf_pages'] = 'pma_pdf_pages';
    $cfg['Servers'][1]['designer_coords'] = 'pma_designer_coords';
    
  9. Save and close the file.

IMPORTANT - PMA loads the config on login, evaluates it and stores it into the session data so the message will not disappear until you do this:

  1. Log out of phpMyAdmin and log in again

Problem solved.

How do I remove a CLOSE_WAIT socket connection

It is also worth noting that if your program spawns a new process, that process may inherit all your opened handles. Even after your own program closs, those inherited handles can still be alive via the orphaned child process. And they don't necessarily show up quite the same in netstat. But all the same, the socket will hang around in CLOSE_WAIT while this child process is alive.

I had a case where I was running ADB. ADB itself spawns a server process if its not already running. This inherited all my handles initially, but did not show up as owning any of them when I was investigating (the same was true for both macOS and Windows - not sure about Linux).

How to fix error Base table or view not found: 1146 Table laravel relationship table?

For solving your Base Table or view not found error you can do As @Alexey Mezenin said that change table name category_post to category_posts,

but if you don't want to change the name like in my case i am using inventory table so i don't want to suffix it by s so i will provide table name in model as protected $table = 'Table_name_as_you_want' and then there is no need to change table name:

Change your Model of the module in which you are getting error for example:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Inventory extends Model
{
    protected $table = 'inventory';

    protected $fillable = [
        'supply', 'order',
    ];
}

you have to provide table name in model then it will not give error.

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

Here is an alternative that works also

public final class Storage : AnyObject {

    var object:Any?

    public init(_ object:Any) {
        self.object = object
    }
}

extension Date {

    private static let associationMap = NSMapTable<NSString, AnyObject>()
    private struct Keys {
        static var Locale:NSString = "locale"
    }

    public var locale:Locale? {
        get {

            if let storage = Date.associationMap.object(forKey: Keys.Locale) {
                return (storage as! Storage).object as? Locale
            }
            return nil
        }
        set {
            if newValue != nil {
                Date.associationMap.setObject(Storage(newValue), forKey: Keys.Locale)
            }
        }
    }
}



var date = Date()
date.locale = Locale(identifier: "pt_BR")
print( date.locale )

How to convert JSON to XML or XML to JSON?

I searched for a long time to find alternative code to the accepted solution in the hopes of not using an external assembly/project. I came up with the following thanks to the source code of the DynamicJson project:

public XmlDocument JsonToXML(string json)
{
    XmlDocument doc = new XmlDocument();

    using (var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max))
    {
        XElement xml = XElement.Load(reader);
        doc.LoadXml(xml.ToString());
    }

    return doc;
}

Note: I wanted an XmlDocument rather than an XElement for xPath purposes. Also, this code obviously only goes from JSON to XML, there are various ways to do the opposite.

How to get all Errors from ASP.Net MVC modelState?

This is expanding upon the answer from @Dunc . See xml doc comments

// ReSharper disable CheckNamespace
using System.Linq;
using System.Web.Mvc;


public static class Debugg
{
    /// <summary>
    /// This class is for debugging ModelState errors either in the quick watch 
    /// window or the immediate window.
    /// When the model state contains dozens and dozens of properties, 
    /// it is impossible to inspect why a model state is invalid.
    /// This method will pull up the errors
    /// </summary>
    /// <param name="modelState">modelState</param>
    /// <returns></returns>
    public static ModelError[]  It(ModelStateDictionary modelState)
    {
        var errors = modelState.Values.SelectMany(x => x.Errors).ToArray();
        return errors;            
    }
}

Bulk Record Update with SQL

Your approach is OK

Maybe slightly clearer (to me anyway!)

UPDATE
  T1
SET
  [Description] = t2.[Description]
FROM
   Table1 T1
   JOIN
   [Table2] t2 ON t2.[ID] = t1.DescriptionID

Both this and your query should run the same performance wise because it is the same query, just laid out differently.

String Concatenation in EL

1.The +(operator) has not effect to that in using EL. 2.so this is the way,to use that

<c:set var="enabled" value="${value} enabled" />


<c:out value="${empty value ? 'none' : enabled}" />

is this helpful to You ?

Command to open file with git

To open a file in git, with windows you will type explorer . , notice the space between explorer and the dot. On mac you can open it with open . , and in Linux with nautilus . , notice the period at the end of each one.

Use dynamic variable names in JavaScript

a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);

Try this...

Show image using file_get_contents

you can do like this :

<?php
    $file = 'your_images.jpg';

    header('Content-Type: image/jpeg');
    header('Content-Length: ' . filesize($file));
    echo file_get_contents($file);
?>