Programs & Examples On #Jsr82

JSR 82 - Java ME API for Bluetooth

JSON.stringify doesn't work with normal Javascript array

Alternatively you can use like this

var test = new Array();
test[0]={};
test[0]['a'] = 'test';
test[1]={};
test[1]['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);

Like this you JSON-ing a array.

How do I set proxy for chrome in python webdriver?

from selenium import webdriver

PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % PROXY)

chrome = webdriver.Chrome(options=chrome_options)
chrome.get("http://whatismyipaddress.com")

How to get URI from an asset File?

enter image description here

Be sure ,your assets folder put in correct position.

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

pyinstaller myscript.py

You can find more information about how to use Pyinstaller and customize the build process via the documentation.


You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

A more useful statusline in vim?

Here's mine:

set statusline=
set statusline +=%1*\ %n\ %*            "buffer number
set statusline +=%5*%{&ff}%*            "file format
set statusline +=%3*%y%*                "file type
set statusline +=%4*\ %<%F%*            "full path
set statusline +=%2*%m%*                "modified flag
set statusline +=%1*%=%5l%*             "current line
set statusline +=%2*/%L%*               "total lines
set statusline +=%1*%4v\ %*             "virtual column number
set statusline +=%2*0x%04B\ %*          "character under cursor

vim statusline

And here's the colors I used:

hi User1 guifg=#eea040 guibg=#222222
hi User2 guifg=#dd3333 guibg=#222222
hi User3 guifg=#ff66ff guibg=#222222
hi User4 guifg=#a0ee40 guibg=#222222
hi User5 guifg=#eeee40 guibg=#222222

Laravel use same form for create and edit

You can use form binding and 3 methods in your Controller. Here's what I do

class ActivitiesController extends BaseController {
    public function getAdd() {
        return $this->form();
    }
    public function getEdit($id) {
        return $this->form($id);
    }
    protected function form($id = null) {
        $activity = ! is_null($id) ? Activity::findOrFail($id) : new Activity;

        //
        // Your logic here
        //

        $form = View::make('path.to.form')
            ->with('activity', $activity);

        return $form->render(); 
    }
}

And in my views I have

{{ Form::model($activity, array('url' => "/admin/activities/form/{$activity->id}", 'method' => 'post')) }}
{{ Form::close() }}

How to get $HOME directory of different user in bash script?

So you want to:

  1. execute part of a bash script as a different user
  2. change to that user's $HOME directory

Inspired by this answer, here's the adapted version of your script:

#!/usr/bin/env bash

different_user=deploy

useradd -m -s /bin/bash "$different_user"

echo "Current user: $(whoami)"
echo "Current directory: $(pwd)"
echo

echo "Switching user to $different_user"
sudo -u "$different_user" -i /bin/bash - <<-'EOF'
    echo "Current user: $(id)"
    echo "Current directory: $(pwd)"
EOF
echo

echo "Switched back to $(whoami)"

different_user_home="$(eval echo ~"$different_user")"
echo "$different_user home directory: $different_user_home"

When you run it, you should get the following:

Current user: root
Current directory: /root

Switching user to deploy
Current user: uid=1003(deploy) gid=1003(deploy) groups=1003(deploy)
Current directory: /home/deploy

Switched back to root
deploy home directory: /home/deploy

What is "String args[]"? parameter in main method Java

in public static void main(String args[]) args is an array of console line argument whose data type is String. in this array, you can store various string arguments by invoking them at the command line as shown below: java myProgram Shaan Royal then Shaan and Royal will be stored in the array as arg[0]="Shaan"; arg[1]="Royal"; you can do this manually also inside the program, when you don't call them at the command line.

Get Android shared preferences value in activity/normal class

If you have a SharedPreferenceActivity by which you have saved your values

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String imgSett = prefs.getString(keyChannel, "");

if the value is saved in a SharedPreference in an Activity then this is the correct way to saving it.

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString(keyChannel, email);
editor.commit();// commit is important here.

and this is how you can retrieve the values.

SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyChannel, ""));

Also be aware that you can do so in a non-Activity class too but the only condition is that you need to pass the context of the Activity. use this context in to get the SharedPreferences.

mContext.getSharedPreferences(PREF_NAME, MODE_PRIVATE);

foreach vs someList.ForEach(){}

For fun, I popped List into reflector and this is the resulting C#:

public void ForEach(Action<T> action)
{
    if (action == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
    }
    for (int i = 0; i < this._size; i++)
    {
        action(this._items[i]);
    }
}

Similarly, the MoveNext in Enumerator which is what is used by foreach is this:

public bool MoveNext()
{
    if (this.version != this.list._version)
    {
        ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
    }
    if (this.index < this.list._size)
    {
        this.current = this.list._items[this.index];
        this.index++;
        return true;
    }
    this.index = this.list._size + 1;
    this.current = default(T);
    return false;
}

The List.ForEach is much more trimmed down than MoveNext - far less processing - will more likely JIT into something efficient..

In addition, foreach() will allocate a new Enumerator no matter what. The GC is your friend, but if you're doing the same foreach repeatedly, this will make more throwaway objects, as opposed to reusing the same delegate - BUT - this is really a fringe case. In typical usage you will see little or no difference.

What's the difference between passing by reference vs. passing by value?

pass by value means how to pass value to a function by making use of arguments. in pass by value we copy the data stored in the variable we specify and it is slower than pass by reference bcse t he data is copied . of we make changes in the copied data the original data is not affected. nd in pass by refernce or pass by address we send direct link to the variable itself . or passing pointer to a variable. it is faster bcse less time is consumed

invalid_grant trying to get oAuth token from google

After considering and trying all of the other ways here, here's how I solved the issue in nodejs with the googleapis module in conjunction with the request module, which I used to fetch the tokens instead of the provided getToken() method:

const request = require('request');

//SETUP GOOGLE AUTH
var google = require('googleapis');
const oAuthConfigs = rootRequire('config/oAuthConfig')
const googleOAuthConfigs = oAuthConfigs.google

//for google OAuth: https://github.com/google/google-api-nodejs-client
var OAuth2 = google.auth.OAuth2;
var googleOAuth2Client = new OAuth2(
    process.env.GOOGLE_OAUTH_CLIENT_ID || googleOAuthConfigs.clientId, 
    process.env.GOOGLE_OAUTH_CLIENT_SECRET || googleOAuthConfigs.clientSecret, 
    process.env.GOOGLE_OAUTH_CLIENT_REDIRECT_URL || googleOAuthConfigs.callbackUrl);

/* generate a url that asks permissions for Google+ and Google Calendar scopes
https://developers.google.com/identity/protocols/googlescopes#monitoringv3*/
var googleOAuth2ClientScopes = [
    'https://www.googleapis.com/auth/plus.me',
    'https://www.googleapis.com/auth/userinfo.email'
];

var googleOAuth2ClientRedirectURL = process.env.GOOGLE_OAUTH_CLIENT_REDIRECT_URL || googleOAuthConfigs.callbackUrl; 

var googleOAuth2ClientAuthUrl = googleOAuth2Client.generateAuthUrl({
  access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
  scope: googleOAuth2ClientScopes // If you only need one scope you can pass it as string
});

//AFTER SETUP, THE FOLLOWING IS FOR OBTAINING TOKENS FROM THE AUTHCODE


        const ci = process.env.GOOGLE_OAUTH_CLIENT_ID || googleOAuthConfigs.clientId
        const cs = process.env.GOOGLE_OAUTH_CLIENT_SECRET || googleOAuthConfigs.clientSecret
        const ru = process.env.GOOGLE_OAUTH_CLIENT_REDIRECT_URL || googleOAuthConfigs.callbackUrl
        var oauth2Client = new OAuth2(ci, cs, ru);

        var hostUrl = "https://www.googleapis.com";
        hostUrl += '/oauth2/v4/token?code=' + authCode + '&client_id=' + ci + '&client_secret=' + cs + '&redirect_uri=' + ru + '&grant_type=authorization_code',
        request.post({url: hostUrl}, function optionalCallback(err, httpResponse, data) {
            // Now tokens contains an access_token and an optional refresh_token. Save them.
            if(!err) {
                //SUCCESS! We got the tokens
                const tokens = JSON.parse(data)
                oauth2Client.setCredentials(tokens);

                //AUTHENTICATED PROCEED AS DESIRED.
                googlePlus.people.get({ userId: 'me', auth: oauth2Client }, function(err, response) {
                // handle err and response
                    if(!err) {
                        res.status(200).json(response);
                    } else {
                        console.error("/google/exchange 1", err.message);
                        handleError(res, err.message, "Failed to retrieve google person");
                    }
                });
            } else {
                console.log("/google/exchange 2", err.message);
                handleError(res, err.message, "Failed to get access tokens", err.code);
            }
        });

I simply use request to make the api request via HTTP as described here: https://developers.google.com/identity/protocols/OAuth2WebServer#offline

POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded

code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2.example.com/code&
grant_type=authorization_code

Getting the class name of an instance?

To get instance classname:

type(instance).__name__

or

instance.__class__.__name__

both are the same

WCF Service, the type provided as the service attribute values…could not be found

I also had same problem. Purposely my build output path was "..\bin" and it works for me when I set the build output path as "\bin".

Regular expression for extracting tag attributes

If youre in .NET I recommend the HTML agility pack, very robust even with malformed HTML.

Then you can use XPath.

MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB

I have changed the length of value from varchar(255) to varchar(25) to all varchar columns and i get the solution.

Selenium WebDriver How to Resolve Stale Element Reference Exception?

In Selenium 3, you can use ExpectedConditions.refreshed(your condition).

It will handle the StaleElementReferenceException and retry the condition.

getting file size in javascript

If you could access the file system of a user with javascript, image the bad that could happen.

However, you can use File System Object but this will work only in IE:

http://bytes.com/topic/javascript/answers/460516-check-file-size-javascript

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

MySQL's utf8 permits only the Unicode characters that can be represented with 3 bytes in UTF-8. Here you have a character that needs 4 bytes: \xF0\x90\x8D\x83 (U+10343 GOTHIC LETTER SAUIL).

If you have MySQL 5.5 or later you can change the column encoding from utf8 to utf8mb4. This encoding allows storage of characters that occupy 4 bytes in UTF-8.

You may also have to set the server property character_set_server to utf8mb4 in the MySQL configuration file. It seems that Connector/J defaults to 3-byte Unicode otherwise:

For example, to use 4-byte UTF-8 character sets with Connector/J, configure the MySQL server with character_set_server=utf8mb4, and leave characterEncoding out of the Connector/J connection string. Connector/J will then autodetect the UTF-8 setting.

IIS7: Setup Integrated Windows Authentication like in IIS6

Two-stage authentication is not supported with IIS7 Integrated mode. Authentication is now modularized, so rather than IIS performing authentication followed by asp.net performing authentication, it all happens at the same time.

You can either:

  1. Change the app domain to be in IIS6 classic mode...
  2. Follow this example (old link) of how to fake two-stage authentication with IIS7 integrated mode.
  3. Use Helicon Ape and mod_auth to provide basic authentication

How to make --no-ri --no-rdoc the default for gem install?

Step by steps:

To create/edit the .gemrc file from the terminal:

vi  ~/.gemrc

You will open a editor called vi. paste in:

gem: --no-ri --no-rdoc

click 'esc'-button.

type in:

:exit

You can check if everything is correct with this command:

sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit ~/.gemrc

Setting up SSL on a local xampp/apache server

I did all of the suggested stuff here and my code still did not work because I was using curl

If you are using curl in the php file, curl seems to reject all ssl traffic by default. A quick-fix that worked for me was to add:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

before calling:

 curl_exec():

in the php file.

I believe that this disables all verification of SSL certificates.

How can I pass variable to ansible playbook in the command line?

This also worked for me if you want to use shell environment variables:

ansible-playbook -i "localhost," ldap.yaml --extra-vars="LDAP_HOST={{ lookup('env', 'LDAP_HOST') }} clustername=mycluster env=dev LDAP_USERNAME={{ lookup('env', 'LDAP_USERNAME') }} LDAP_PASSWORD={{ lookup('env', 'LDAP_PASSWORD') }}"

Row names & column names in R

And another expansion:

# create dummy matrix
set.seed(10)
m <- matrix(round(runif(25, 1, 5)), 5)
d <- as.data.frame(m)

If you want to assign new column names you can do following on data.frame:

# an identical effect can be achieved with colnames()   
names(d) <- LETTERS[1:5]
> d
  A B C D E
1 3 2 4 3 4
2 2 2 3 1 3
3 3 2 1 2 4
4 4 3 3 3 2
5 1 3 2 4 3

If you, however run previous command on matrix, you'll mess things up:

names(m) <- LETTERS[1:5]
> m
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    2    4    3    4
[2,]    2    2    3    1    3
[3,]    3    2    1    2    4
[4,]    4    3    3    3    2
[5,]    1    3    2    4    3
attr(,"names")
 [1] "A" "B" "C" "D" "E" NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA 
[20] NA  NA  NA  NA  NA  NA 

Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames().

So there...

How to add anchor tags dynamically to a div in Javascript?

I recommend that you use jQuery for this, as it makes the process much easier. Here are some examples using jQuery:

$("div#id").append('<a href="' + url + '">' + text + '</a>');

If you need a list though, as in a <ul>, you can do this:

$("div#id").append('<ul>');
var ul = $("div#id > ul");

ul.append('<li><a href="' + url + '">' + text + '</a></li>');

mkdir -p functionality in Python

I've had success with the following personally, but my function should probably be called something like 'ensure this directory exists':

def mkdirRecursive(dirpath):
    import os
    if os.path.isdir(dirpath): return

    h,t = os.path.split(dirpath) # head/tail
    if not os.path.isdir(h):
        mkdirRecursive(h)

    os.mkdir(join(h,t))
# end mkdirRecursive

How can I change the app display name build with Flutter?

As of 2019-12-21, you need to change the name [NameOfYourApp] in file pubspec.yaml. Then go to menu Edit ? Find ? Replace in Path, and replace all occurrences of your previous name.

Also, just for good measure, change the folder names in your android directory, e.g. android/app/src/main/java/com/example/yourappname.

Then in the console, in your app's root directory, run

flutter clean

Excel VBA Loop on columns

If you want to stick with the same sort of loop then this will work:

Option Explicit

Sub selectColumns()

Dim topSelection As Integer
Dim endSelection As Integer
topSelection = 2
endSelection = 10

Dim columnSelected As Integer
columnSelected = 1
Do
   With Excel.ThisWorkbook.ActiveSheet
        .Range(.Cells(columnSelected, columnSelected), .Cells(endSelection, columnSelected)).Select
   End With
   columnSelected = columnSelected + 1
Loop Until columnSelected > 10

End Sub

EDIT

If in reality you just want to loop through every cell in an area of the spreadsheet then use something like this:

Sub loopThroughCells()

'=============
'this is the starting point
Dim rwMin As Integer
Dim colMin As Integer
rwMin = 2
colMin = 2
'=============

'=============
'this is the ending point
Dim rwMax As Integer
Dim colMax As Integer
rwMax = 10
colMax = 5
'=============

'=============
'iterator
Dim rwIndex As Integer
Dim colIndex As Integer
'=============

For rwIndex = rwMin To rwMax
        For colIndex = colMin To colMax
            Cells(rwIndex, colIndex).Select
        Next colIndex
Next rwIndex

End Sub

When should I use Async Controllers in ASP.NET MVC?

Is it good to use async action everywhere in ASP.NET MVC?

It's good to do so wherever you can use an async method especially when you have performance issues at the worker process level which happens for massive data and calculation operations. Otherwise, no need because unit testing will need casting.

Regarding awaitable methods: shall I use async/await keywords when I want to query a database (via EF/NHibernate/other ORM)?

Yes, it's better to use async for any DB operation as could as possible to avoid performance issues at the level of worker processes. Note that EF has created many async alternatives for most operations, such as:

.ToListAsync()
.FirstOrDefaultAsync()
.SaveChangesAsync()
.FindAsync()

How many times can I use await keywords to query the database asynchronously in one single action method?

The sky is the limit

Converting json results to a date

If you use jQuery

In case you use jQuery on the client side, you may be interested in this blog post that provides code how to globally extend jQuery's $.parseJSON() function to automatically convert dates for you.

You don't have to change existing code in case of adding this code. It doesn't affect existing calls to $.parseJSON(), but if you start using $.parseJSON(data, true), dates in data string will be automatically converted to Javascript dates.

It supports Asp.net date strings: /Date(2934612301)/ as well as ISO strings 2010-01-01T12_34_56-789Z. The first one is most common for most used back-end web platform, the second one is used by native browser JSON support (as well as other JSON client side libraries like json2.js).

Anyway. Head over to blog post to get the code. http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html

WPF Check box: Check changed handling

As a checkbox click = a checkbox change the following will also work:

<CheckBox Click="CheckBox_Click" />
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
    // ... do some stuff
}

It has the additional advantage of working when IsThreeState="True" whereas just handling Checked and Unchecked does not.

joining two select statements

Not sure what you are trying to do, but you have two select clauses. Do this instead:

SELECT * 
FROM ( SELECT * 
       FROM orders_products 
       INNER JOIN orders ON orders_products.orders_id = orders.orders_id 
       WHERE products_id = 181) AS A
JOIN ( SELECT * 
       FROM orders_products 
       INNER JOIN orders ON orders_products.orders_id = orders.orders_id
       WHERE products_id = 180) AS B

ON A.orders_id=B.orders_id

Update:

You could probably reduce it to something like this:

SELECT o.orders_id, 
       op1.products_id, 
       op1.quantity, 
       op2.products_id, 
       op2.quantity
FROM orders o
INNER JOIN orders_products op1 on o.orders_id = op1.orders_id  
INNER JOIN orders_products op2 on o.orders_id = op2.orders_id  
WHERE op1.products_id = 180
AND op2.products_id = 181

How to check if directory exists in %PATH%?

You can accomplish this using PoweShell;

Test-Path $ENV:SystemRoot\YourDirectory
Test-Path C:\Windows\YourDirectory

This returns TRUE or FALSE

Short, simle and easy!

Java - Writing strings to a CSV file

 private static final String FILE_HEADER ="meter_Number,latestDate";
    private static final String COMMA_DELIMITER = ",";
    private static final String NEW_LINE_SEPARATOR = "\n";
    static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:m m:ss");

    private void writeToCsv(Map<String, Date> meterMap) {
        try {
            Iterator<Map.Entry<String, Date>> iter = meterMap.entrySet().iterator();
            FileWriter fw = new FileWriter("smaple.csv");
            fw.append(FILE_HEADER.toString());
            fw.append(NEW_LINE_SEPARATOR);
            while (iter.hasNext()) {
                Map.Entry<String, Date> entry = iter.next();
                try {
                    fw.append(entry.getKey());
                    fw.append(COMMA_DELIMITER);
                    fw.append(formatter.format(entry.getValue()));
                    fw.append(NEW_LINE_SEPARATOR);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    iter.remove();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

How to determine tables size in Oracle

If you don't have DBA rights then you can use user_segments table:

select bytes/1024/1024 MB from user_segments where segment_name='Table_name'

How can I sort a dictionary by key?

My suggestion is this as it allows you to sort a dict or keep a dict sorted as you are adding items and might need to add items in the future:

Build a dict from scratch as you go along. Have a second data structure, a list, with your list of keys. The bisect package has an insort function which allows inserting into a sorted list, or sort your list after completely populating your dict. Now, when you iterate over your dict, you instead iterate over the list to access each key in an in-order fashion without worrying about the representation of the dict structure (which was not made for sorting).

What is the most efficient way to store a list in the Django models?

If you are using Django >= 1.9 with Postgres you can make use of ArrayField advantages

A field for storing lists of data. Most field types can be used, you simply pass another field instance as the base_field. You may also specify a size. ArrayField can be nested to store multi-dimensional arrays.

It is also possible to nest array fields:

from django.contrib.postgres.fields import ArrayField
from django.db import models

class ChessBoard(models.Model):
    board = ArrayField(
        ArrayField(
            models.CharField(max_length=10, blank=True),
            size=8,
        ),
        size=8,
    )

As @thane-brimhall mentioned it is also possible to query elements directly. Documentation reference

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

I got it with an import loop:

---FILE B.h
#import "A.h"
@interface B{
  A *a;
}
@end

---FILE A.h
#import "B.h"
@interface A{      
}
@end

Vibrate and Sound defaults on notification

For Kotlin you can Try this.

var builder = NotificationCompat.Builder(this,CHANNEL_ID)
     .setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000))
     .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)

How to create an integer-for-loop in Ruby?

for i in 0..max
   puts "Value of local variable is #{i}"
end

All Ruby loops

jQuery AJAX single file upload

After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))

HTML:

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File to stash:</label>
    <input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>

jQuery:

$(function(){
    $('#uploadBTN').on('click', function(){ 
        var fd = new FormData($("#fileinfo"));
        //fd.append("CustomField", "This is some extra data");
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

In the upload.php file you can access the data passed with $_FILES['file'].

Thanks everyone for trying to help:)

I took the answer from here (with some changes) MDN

Make a dictionary in Python from input values

I have taken an empty dictionary as f and updated the values in f as name,password or balance are keys.

f=dict()
f.update(name=input(),password=input(),balance=input())
print(f)

Loop through all nested dictionary values?

Alternative iterative solution:

def myprint(d):
    stack = d.items()
    while stack:
        k, v = stack.pop()
        if isinstance(v, dict):
            stack.extend(v.iteritems())
        else:
            print("%s: %s" % (k, v))

How to pass a file path which is in assets folder to File(String path)?

AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.

But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).

Try to do something like:

AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

   return null;
}

Let me know about your progress.

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

As suggested here you can also inject the HttpServletRequest as a method param, e.g.:

public MyResponseObject myApiMethod(HttpServletRequest request, ...) {
    ...
}

What does it mean when Statement.executeUpdate() returns -1?

I haven't seen this anywhere, either, but my instinct would be that this means that the IF prevented the whole statement from executing.

Try to run the statement with a database where the IF passes.

Also check if there are any triggers involved which might change the result.

[EDIT] When the standard says that this function should never return -1, that doesn't enforce this. Java doesn't have pre and post conditions. A JDBC driver could return a random number and there was no way to stop it.

If it's important to know why this happens, run the statement against different database until you have tried all execution paths (i.e. one where the IF returns false and one where it returns true).

If it's not that important, mark it off as a "clever trick" by a Microsoft engineer and remember how much you liked it when you feel like being clever yourself next time.

Split string into strings by length?

The string splitting is required in many cases like where you have to sort the characters of the string given, replacing a character with an another character etc. But all these operations can be performed with the following mentioned string splitting methods.

The string splitting can be done in two ways:

  1. Slicing the given string based on the length of split.

  2. Converting the given string to a list with list(str) function, where characters of the string breakdown to form the the elements of a list. Then do the required operation and join them with 'specified character between the characters of the original string'.join(list) to get a new processed string.

How to create a String with carriage returns?

The fastest way I know to generate a new-line character in Java is: String.format("%n")

Of course you can put whatever you want around the %n like:

String.format("line1%nline2")

Or even if you have a lot of lines:

String.format("%s%n%s%n%s%n%s", "line1", "line2", "line3", "line4")

SSIS Text was truncated with status value 4

If this is coming from SQL Server Import Wizard, try editing the definition of the column on the Data Source, it is 50 characters by default, but it can be longer.

Data Soruce -> Advanced -> Look at the column that goes in error -> change OutputColumnWidth to 200 and try again.

getResources().getColor() is deprecated

You need to use ContextCompat.getColor(), which is part of the Support V4 Library (so it will work for all the previous API).

ContextCompat.getColor(context, R.color.my_color)

As specified in the documentation, "Starting in M, the returned color will be styled for the specified Context's theme". SO no need to worry about it.

You can add the Support V4 library by adding the following to the dependencies array inside your app build.gradle:

compile 'com.android.support:support-v4:23.0.1'

Redirect on Ajax Jquery Call

JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm page.

One idea is to let the the browser know that it should redirect by adding a redirect variable to to the resulting object and checking for it in JQuery:

$(document).ready(function(){ 
    jQuery.ajax({ 
        type: "GET", 
        url: "populateData.htm", 
        dataType:"json", 
        data:"userId=SampleUser", 
        success:function(response){ 
            if (response.redirect) {
                window.location.href = response.redirect;
            }
            else {
                // Process the expected results...
            }
        }, 
     error: function(xhr, textStatus, errorThrown) { 
            alert('Error!  Status = ' + xhr.status); 
         } 

    }); 
}); 

You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1") and in JQuery you do on success(!):

//....
        success:function(response){ 
            if (response.getResponseHeader('REQUIRES_AUTH') === '1'){ 
                window.location.href = 'login.htm'; 
            }
            else {
                // Process the expected results...
            }
        }
//....

Hope that helps.

My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.

Command not found error in Bash variable assignment

You cannot have spaces around the = sign.

When you write:

STR = "foo"

bash tries to run a command named STR with 2 arguments (the strings = and foo)

When you write:

STR =foo

bash tries to run a command named STR with 1 argument (the string =foo)

When you write:

STR= foo

bash tries to run the command foo with STR set to the empty string in its environment.

I'm not sure if this helps to clarify or if it is mere obfuscation, but note that:

  1. the first command is exactly equivalent to: STR "=" "foo",
  2. the second is the same as STR "=foo",
  3. and the last is equivalent to STR="" foo.

The relevant section of the sh language spec, section 2.9.1 states:

A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.

In that context, a word is the command that bash is going to run. Any string containing = (in any position other than at the beginning of the string) which is not a redirection and in which the portion of the string before the = is a valid variable name is a variable assignment, while any string that is not a redirection or a variable assignment is a command. In STR = "foo", STR is not a variable assignment.

How to compare Boolean?

From your comments, it seems like you're looking for "best practices" for the use of the Boolean wrapper class. But there really aren't any best practices, because it's a bad idea to use this class to begin with. The only reason to use the object wrapper is in cases where you absolutely must (such as when using Generics, i.e., storing a boolean in a HashMap<String, Boolean> or the like). Using the object wrapper has no upsides and a lot of downsides, most notably that it opens you up to NullPointerExceptions.

Does it matter if '!' is used instead of .equals() for Boolean?

Both techniques will be susceptible to a NullPointerException, so it doesn't matter in that regard. In the first scenario, the Boolean will be unboxed into its respective boolean value and compared as normal. In the second scenario, you are invoking a method from the Boolean class, which is the following:

public boolean equals(Object obj) {
    if (obj instanceof Boolean) {
        return value == ((Boolean)obj).booleanValue();
    }
    return false;
}

Either way, the results are the same.

Would it matter if .equals(false) was used to check for the value of the Boolean checker?

Per above, no.

Secondary question: Should Boolean be dealt differently than boolean?

If you absolutely must use the Boolean class, always check for null before performing any comparisons. e.g.,

Map<String, Boolean> map = new HashMap<String, Boolean>();
//...stuff to populate the Map
Boolean value = map.get("someKey");
if(value != null && value) {
    //do stuff
}

This will work because Java short-circuits conditional evaluations. You can also use the ternary operator.

boolean easyToUseValue = value != null ? value : false;

But seriously... just use the primitive type, unless you're forced not to.

How to install MySQLdb package? (ImportError: No module named setuptools)

I am experiencing the same problem right now. According to this post you need to have a C Compiler or GCC. I'll try to fix the problem by installing C compiler. I'll inform you if it works (we'll I guess you don't need it anymore, but I'll post the result anyway) :)

C++ Fatal Error LNK1120: 1 unresolved externals

My problem was int Main() instead of int main()

good luck

MySQL - How to select data by string length

You are looking for CHAR_LENGTH() to get the number of characters in a string.

For multi-byte charsets LENGTH() will give you the number of bytes the string occupies, while CHAR_LENGTH() will return the number of characters.

CORS Access-Control-Allow-Headers wildcard being ignored?

here's the incantation for nginx, inside a

location / {
    # Simple requests
    if ($request_method ~* "(GET|POST)") {
      add_header "Access-Control-Allow-Origin"  *;
    }

    # Preflighted requests
    if ($request_method = OPTIONS ) {
      add_header "Access-Control-Allow-Origin"  *;
      add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
      add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    }

}

How to see full absolute path of a symlink

realpath <path to the symlink file> should do the trick.

Matplotlib discrete colorbar

You can create a custom discrete colorbar quite easily by using a BoundaryNorm as normalizer for your scatter. The quirky bit (in my method) is making 0 showup as grey.

For images i often use the cmap.set_bad() and convert my data to a numpy masked array. That would be much easier to make 0 grey, but i couldnt get this to work with the scatter or the custom cmap.

As an alternative you can make your own cmap from scratch, or read-out an existing one and override just some specific entries.

import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt

fig, ax = plt.subplots(1, 1, figsize=(6, 6))  # setup the plot

x = np.random.rand(20)  # define the data
y = np.random.rand(20)  # define the data
tag = np.random.randint(0, 20, 20)
tag[10:12] = 0  # make sure there are some 0 values to show up as grey

cmap = plt.cm.jet  # define the colormap
# extract all colors from the .jet map
cmaplist = [cmap(i) for i in range(cmap.N)]
# force the first color entry to be grey
cmaplist[0] = (.5, .5, .5, 1.0)

# create the new map
cmap = mpl.colors.LinearSegmentedColormap.from_list(
    'Custom cmap', cmaplist, cmap.N)

# define the bins and normalize
bounds = np.linspace(0, 20, 21)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# make the scatter
scat = ax.scatter(x, y, c=tag, s=np.random.randint(100, 500, 20),
                  cmap=cmap, norm=norm)

# create a second axes for the colorbar
ax2 = fig.add_axes([0.95, 0.1, 0.03, 0.8])
cb = plt.colorbar.ColorbarBase(ax2, cmap=cmap, norm=norm,
    spacing='proportional', ticks=bounds, boundaries=bounds, format='%1i')

ax.set_title('Well defined discrete colors')
ax2.set_ylabel('Very custom cbar [-]', size=12)

enter image description here

I personally think that with 20 different colors its a bit hard to read the specific value, but thats up to you of course.

Matching special characters and letters in regex

I tried a bunch of these but none of them worked for all of my tests. So I found this:

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$

from this source: https://www.w3resource.com/javascript/form/password-validation.php

How to add a custom HTTP header to every WCF call?

var endpoint = new EndpointAddress(new Uri(RemoteAddress),
               new[] { AddressHeader.CreateAddressHeader(
                       "APIKey", 
                       "",
                       "bda11d91-7ade-4da1-855d-24adfe39d174") 
                     });

What does the @ symbol before a variable name mean in C#?

It allows you to use a C# keyword as a variable. For example:

class MyClass
{
   public string name { get; set; }
   public string @class { get; set; }
}

Cycles in an Undirected Graph

Actually, depth first (or indeed breadth first) search isn't quite enough. You need a sightly more complex algorithm.

For instance, suppose there is graph with nodes {a,b,c,d} and edges {(a,b),(b,c),(b,d),(d,c)} where an edge (x,y) is an edge from x to y. (looks something like this, with all edges directed downwards.)

    (a)
     |
     |
    (b)
    / \ 
  (d)  |
   |   |
    \ /
    (c)

Then doing depth first search may visit node (a), then (b), then (c), then backtrack to (b), then visit (d), and finally visit (c) again and conclude there is a cycle -- when there isn't. A similar thing happens with breadth first.

What you need to do is keep track of which nodes your in the middle of visiting. In the example above, when the algorithm reaches (d) it has finished visiting (c) but not (a) or (b). So revisiting a finished node is fine, but visiting an unfinished node means you have a cycle. The usual way to do this is colour each node white(not yet visited), grey(visiting descendants) or black(finished visiting).

here is some pseudo code!

define visit(node n):
  if n.colour == grey: //if we're still visiting this node or its descendants
    throw exception("Cycle found")

  n.colour = grey //to indicate this node is being visited
  for node child in n.children():
    if child.colour == white: //if the child is unexplored
      visit(child)

  n.colour = black //to show we're done visiting this node
  return

then running visit(root_node) will throw an exception if and only if there is a cycle (initially all nodes should be white).

Eclipse: Java was started but returned error code=13

This is caused when java is updated. You have to delete in environement path : C:**ProgramData\Oracle\Java\javapath**

How to get the full URL of a Drupal page?

For Drupal 8 you can do this :

$url = 'YOUR_URL';
$url = \Drupal\Core\Url::fromUserInput('/' . $url,  array('absolute' => 'true'))->toString();

How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

This following works better if you need to scroll to an arbitrary item in the list (rather than always to the bottom):

function scrollIntoView(element, container) {
  var containerTop = $(container).scrollTop(); 
  var containerBottom = containerTop + $(container).height(); 
  var elemTop = element.offsetTop;
  var elemBottom = elemTop + $(element).height(); 
  if (elemTop < containerTop) {
    $(container).scrollTop(elemTop);
  } else if (elemBottom > containerBottom) {
    $(container).scrollTop(elemBottom - $(container).height());
  }
}

How to convert a Java String to an ASCII byte array?

If you are a user there is a handy Charsets class:

String s = "Hello, world!";
byte[] b = s.getBytes(Charsets.US_ASCII);

Apart from not hard-coding arbitrary charset name in your source code it has a much bigger advantage: Charsets.US_ASCII is of Charset type (not String) so you avoid checked UnsupportedEncodingException thrown only from String.getBytes(String), but not from String.getBytes(Charset).

In Java 7 there is equivalent StandardCharsets class.

Invoke a second script with arguments from a script

Invoke-Expression should work perfectly, just make sure you are using it correctly. For your case it should look like this:

Invoke-Expression "$scriptPath $argumentList"

I tested this approach with Get-Service and seems to be working as expected.

Is it possible to pass a flag to Gulp to have it run tasks in different ways?

There's a very simple way to do on/off flags without parsing the arguments. gulpfile.js is just a file that's executed like any other, so you can do:

var flags = {
  production: false
};

gulp.task('production', function () {
  flags.production = true;
});

And use something like gulp-if to conditionally execute a step

gulp.task('build', function () {
  gulp.src('*.html')
    .pipe(gulp_if(flags.production, minify_html()))
    .pipe(gulp.dest('build/'));
});

Executing gulp build will produce a nice html, while gulp production build will minify it.

How to install pip with Python 3?

if you're using python 3.4+

just type:

python3 -m pip

What is SOA "in plain english"?

I see many answers explaining a Service Oriented Architecture (SOA) using even more advanced words and technical terms. I'd like to give a shot at explaining it for the layman, using an analogy in plain english.

But first a description of a SOA
SOA could be described in three layers as seen in the picture below. On one side we have the Provider and on the other side we have the Consumer, separated by a Bridge where the two sides communicate.

The consumer uses a number of Applications necessary for it's business and the provider uses Components that provide these applications with information. They communicate through a set of Services using a common architecture.


enter image description here


The analogy
Imagine a house on the country side, that in many ways is part of a larger community, like a city or town. The city has it's own complex systems for providing water and electricity, handling sanitation, providing transportation and other utilities. The House is the consumer in this model, the City (or community) is the provider and the pipes, sewers, powerlines, optical fibers etc. is the Infrastructure in which they communicate.

This model could loosely be compared to a SOA. The people in the house uses a number of different "applications" like radiators, computers, toilets, lamps, underfloor heating, bathtubs etc. These applications don't care how the city generates the water, creates the electricity or handles the waste as long as it works. The components of the city are generators, water pumps and sanitation areas. It provides the house with all these needs but it's up to the house to use it in what ever way it sees fit.

I hope this gave at least someone a better picture of a SOA.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

NullPointerExceptions are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.

Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerExceptions is accidentally declaring an object with local scope when there is an instance variable with the same name.

In your case, the exception occurred in your constructor for Workshop on line 75. <init> means the constructor for a class. If you look on that line in your code, you'll see the line

denimjeansButton.addItemListener(this);

There are fairly clearly two objects on this line: denimjeansButton and this. this is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this. denimjeansButton is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton or instantiate it.

Run a Python script from another Python script, passing in arguments

This is inherently the wrong thing to do. If you are running a Python script from another Python script, you should communicate through Python instead of through the OS:

import script1

In an ideal world, you will be able to call a function inside script1 directly:

for i in range(whatever):
    script1.some_function(i)

If necessary, you can hack sys.argv. There's a neat way of doing this using a context manager to ensure that you don't make any permanent changes.

import contextlib
@contextlib.contextmanager
def redirect_argv(num):
    sys._argv = sys.argv[:]
    sys.argv=[str(num)]
    yield
    sys.argv = sys._argv

with redirect_argv(1):
    print(sys.argv)

I think this is preferable to passing all your data to the OS and back; that's just silly.

How to convert NSData to byte array in iPhone?

You can't declare an array using a variable so Byte byteData[len]; won't work. If you want to copy the data from a pointer, you also need to memcpy (which will go through the data pointed to by the pointer and copy each byte up to a specified length).

Try:

NSData *data = [NSData dataWithContentsOfFile:filePath];
NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);

This code will dynamically allocate the array to the correct size (you must free(byteData) when you're done) and copy the bytes into it.

You could also use getBytes:length: as indicated by others if you want to use a fixed length array. This avoids malloc/free but is less extensible and more prone to buffer overflow issues so I rarely ever use it.

How do you add a scroll bar to a div?

to add scroll u need to define max-height of your div and then add overflow-y

so do something like this

.my_scroll_div{
    overflow-y: auto;
    max-height: 100px;
}

Change class on mouseover in directive

I have run into problems in the past with IE and the css:hover selector so the approach that I have taken, is to use a custom directive.

.directive('hoverClass', function () {
    return {
        restrict: 'A',
        scope: {
            hoverClass: '@'
        },
        link: function (scope, element) {
            element.on('mouseenter', function() {
                element.addClass(scope.hoverClass);
            });
            element.on('mouseleave', function() {
                element.removeClass(scope.hoverClass);
            });
        }
    };
})

then on the element itself you can add the directive with the class names that you want enabled when the mouse is over the the element for example:

<li data-ng-repeat="item in social" hover-class="hover tint" class="social-{{item.name}}" ng-mouseover="hoverItem(true);" ng-mouseout="hoverItem(false);"
                index="{{$index}}"><i class="{{item.icon}}"
                box="course-{{$index}}"></i></li>

This should add the class hover and tint when the mouse is over the element and doesn't run the risk of a scope variable name collision. I haven't tested but the mouseenter and mouseleave events should still bubble up to the containing element so in the given scenario the following should still work

<div hover-class="hover" data-courseoverview data-ng-repeat="course in courses | orderBy:sortOrder | filter:search"
 data-ng-controller ="CourseItemController"
 data-ng-class="{ selected: isSelected }">

providing of course that the li's are infact children of the parent div

Get AVG ignoring Null or Zero values

this should work, haven't tried though. this will exclude zero. NULL is excluded by default

AVG (CASE WHEN SecurityW <> 0 THEN SecurityW ELSE NULL END)

port forwarding in windows

I've used this little utility whenever the need arises: http://www.analogx.com/contents/download/network/pmapper/freeware.htm

The last time this utility was updated was in 2009. I noticed on my Win10 machine, it hangs for a few seconds when opening new windows sometimes. Other then that UI glitch, it still does its job fine.

How do I set a JLabel's background color?

Use

label.setOpaque(true);

Otherwise the background is not painted, since the default of opaque is false for JLabel.

From the JavaDocs:

If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.

For more information, read the Java Tutorial How to Use Labels.

Check if a String is in an ArrayList of Strings

temp = bankAccNos.contains(no) ? 1 : 2;

to remove first and last element in array

This can be done with lodash _.tail and _.dropRight:

_x000D_
_x000D_
var fruits = ["Banana", "Orange", "Apple", "Mango"];_x000D_
console.log(_.dropRight(_.tail(fruits)));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Oracle SQL : timestamps in where clause

to_timestamp()

You need to use to_timestamp() to convert your string to a proper timestamp value:

to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

to_date()

If your column is of type DATE (which also supports seconds), you need to use to_date()

to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

Example

To get this into a where condition use the following:

select * 
from TableA 
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
  and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')

Note

You never need to use to_timestamp() on a column that is of type timestamp.

How I can check if an object is null in ruby on rails 2?

You can use the simple not flag to validate that. Example

if !@objectname

This will return true if @objectname is nil. You should not use dot operator or a nil value, else it will throw

*** NoMethodError Exception: undefined method `isNil?' for nil:NilClass

An ideal nil check would be like:

!@objectname || @objectname.nil? || @objectname.empty?

Radio Buttons "Checked" Attribute Not Working

The jQuery documentation provides a detailed explanation for checked property vs attribute.

Accordingly, here is another way to retrieve selected radio button value

var accepted = $('input[name="Contact0_AmericanExpress"]:checked').val();

How to check if the key pressed was an arrow key in Java KeyListener?

You should be using things like: KeyEvent.VK_UP instead of the actual code.

How are you wanting to refactor it? What is the goal of the refactoring?

Inverse dictionary lookup in Python

Through values in dictionary can be object of any kind they can't be hashed or indexed other way. So finding key by the value is unnatural for this collection type. Any query like that can be executed in O(n) time only. So if this is frequent task you should take a look for some indexing of key like Jon sujjested or maybe even some spatial index (DB or http://pypi.python.org/pypi/Rtree/ ).

How can I append a query parameter to an existing URL?

I suggest an improvement of the Adam's answer accepting HashMap as parameter

/**
 * Append parameters to given url
 * @param url
 * @param parameters
 * @return new String url with given parameters
 * @throws URISyntaxException
 */
public static String appendToUrl(String url, HashMap<String, String> parameters) throws URISyntaxException
{
    URI uri = new URI(url);
    String query = uri.getQuery();

    StringBuilder builder = new StringBuilder();

    if (query != null)
        builder.append(query);

    for (Map.Entry<String, String> entry: parameters.entrySet())
    {
        String keyValueParam = entry.getKey() + "=" + entry.getValue();
        if (!builder.toString().isEmpty())
            builder.append("&");

        builder.append(keyValueParam);
    }

    URI newUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), builder.toString(), uri.getFragment());
    return newUri.toString();
}

How to gzip all files in all sub-directories into one compressed file in bash

tar -zcvf compressFileName.tar.gz folderToCompress

everything in folderToCompress will go to compressFileName

Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName

Process with an ID #### is not running in visual studio professional 2013 update 3

I had a similar problem with Chrome.

It appears that VS can't attach to the Chrome process for some reason.

Solution: 1. Close Chrome 2. With Chrome closed, start the web project and allow VS to open Chrome.

Hope that helps.

How do I force Robocopy to overwrite files?

From the documentation:

/is Includes the same files. /it Includes "tweaked" files.

"Same files" means files that are identical (name, size, times, attributes). "Tweaked files" means files that have the same name, size, and times, but different attributes.

robocopy src dst sample.txt /is      # copy if attributes are equal
robocopy src dst sample.txt /it      # copy if attributes differ
robocopy src dst sample.txt /is /it  # copy irrespective of attributes

This answer on Super User has a good explanation of what kind of files the selection parameters match.

With that said, I could reproduce the behavior you describe, but from my understanding of the documentation and the output robocopy generated in my tests I would consider this a bug.

PS C:\temp> New-Item src -Type Directory >$null
PS C:\temp> New-Item dst -Type Directory >$null
PS C:\temp> New-Item src\sample.txt -Type File -Value "test001" >$null
PS C:\temp> New-Item dst\sample.txt -Type File -Value "test002" >$null
PS C:\temp> Set-ItemProperty src\sample.txt -Name LastWriteTime -Value "2016/1/1 15:00:00"
PS C:\temp> Set-ItemProperty dst\sample.txt -Name LastWriteTime -Value "2016/1/1 15:00:00"
PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir
...
  Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30

------------------------------------------------------------------------------

                           1    C:\temp\src\
            Modified                   7        sample.txt

------------------------------------------------------------------------------

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :         1         0         0         0         0         0
   Files :         1         1         0         0         0         0
   Bytes :         7         7         0         0         0         0
...
PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir
...
  Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30

------------------------------------------------------------------------------

                           1    C:\temp\src\
            Same                       7        sample.txt

------------------------------------------------------------------------------

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :         1         0         0         0         0         0
   Files :         1         1         0         0         0         0
   Bytes :         7         7         0         0         0         0
...
PS C:\temp> Get-Content .\src\sample.txt
test001
PS C:\temp> Get-Content .\dst\sample.txt
test002

The file is listed as copied, and since it becomes a same file after the first robocopy run at least the times are synced. However, even though seven bytes have been copied according to the output no data was actually written to the destination file in both cases despite the data flag being set (via /copyall). The behavior also doesn't change if the data flag is set explicitly (/copy:d).

I had to modify the last write time to get robocopy to actually synchronize the data.

PS C:\temp> Set-ItemProperty src\sample.txt -Name LastWriteTime -Value (Get-Date)
PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir
...
  Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30

------------------------------------------------------------------------------

                           1    C:\temp\src\
100%        Newer                      7        sample.txt

------------------------------------------------------------------------------

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :         1         0         0         0         0         0
   Files :         1         1         0         0         0         0
   Bytes :         7         7         0         0         0         0
...
PS C:\temp> Get-Content .\dst\sample.txt
test001

An admittedly ugly workaround would be to change the last write time of same/tweaked files to force robocopy to copy the data:

& robocopy src dst /is /it /l /ndl /njh /njs /ns /nc |
  Where-Object { $_.Trim() } |
  ForEach-Object {
    $f = Get-Item $_
    $f.LastWriteTime = $f.LastWriteTime.AddSeconds(1)
  }
& robocopy src dst /copyall /mir

Switching to xcopy is probably your best option:

& xcopy src dst /k/r/e/i/s/c/h/f/o/x/y

JSON.net: how to deserialize without using the default constructor?

The default behaviour of Newtonsoft.Json is going to find the public constructors. If your default constructor is only used in containing class or the same assembly, you can reduce the access level to protected or internal so that Newtonsoft.Json will pick your desired public constructor.

Admittedly, this solution is rather very limited to specific cases.

internal Result() { }

public Result(int? code, string format, Dictionary<string, string> details = null)
{
    Code = code ?? ERROR_CODE;
    Format = format;

    if (details == null)
        Details = new Dictionary<string, string>();
    else
        Details = details;
}

Logging POST data from $request_body

FWIW, this config worked for me:

location = /logpush.html {
  if ($request_method = POST) {
    access_log /var/log/nginx/push.log push_requests;
    proxy_pass $scheme://127.0.0.1/logsink;
    break;
  }   
  return 200 $scheme://$host/serviceup.html;
}   
#
location /logsink {
  return 200;
}

How to write a cron that will run a script every day at midnight?

Here's a good tutorial on what crontab is and how to use it on Ubuntu. Your crontab line will look something like this:

00 00 * * * ruby path/to/your/script.rb

(00 00 indicates midnight--0 minutes and 0 hours--and the *s mean every day of every month.)

Syntax: 
  mm hh dd mt wd  command

  mm minute 0-59
  hh hour 0-23
  dd day of month 1-31
  mt month 1-12
  wd day of week 0-7 (Sunday = 0 or 7)
  command: what you want to run
  all numeric values can be replaced by * which means all

How to display an image from a path in asp.net MVC 4 and Razor view?

you can also try with this answer :

 <img src="~/Content/img/@Html.DisplayFor(model =>model.ImagePath)" style="height:200px;width:200px;"/>

CSS selector last row from main table

Your tables should have as immediate children just tbody and thead elements, with the rows within*. So, amend the HTML to be:

<table border="1" width="100%" id="test">
  <tbody>
    <tr>
     <td>
      <table border="1" width="100%">
        <tbody>
          <tr>
            <td>table 2</td>
          </tr>
        </tbody>
      </table>
     </td>
    </tr> 
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
  </tbody>
</table>

Then amend your selector slightly to this:

#test > tbody > tr:last-child { background:#ff0000; }

See it in action here. That makes use of the child selector, which:

...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.

So, you are targeting only direct children of tbody elements that are themselves direct children of your #test table.

Alternative solution

The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:

#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }

* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:

...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.

Python convert tuple to string

Use str.join:

>>> tup = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
>>> ''.join(tup)
'abcdgxre'
>>>
>>> help(str.join)
Help on method_descriptor:

join(...)
    S.join(iterable) -> str

    Return a string which is the concatenation of the strings in the
    iterable.  The separator between elements is S.

>>>

A monad is just a monoid in the category of endofunctors, what's the problem?

That particular phrasing is by James Iry, from his highly entertaining Brief, Incomplete and Mostly Wrong History of Programming Languages, in which he fictionally attributes it to Philip Wadler.

The original quote is from Saunders Mac Lane in Categories for the Working Mathematician, one of the foundational texts of Category Theory. Here it is in context, which is probably the best place to learn exactly what it means.

But, I'll take a stab. The original sentence is this:

All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor.

X here is a category. Endofunctors are functors from a category to itself (which is usually all Functors as far as functional programmers are concerned, since they're mostly dealing with just one category; the category of types - but I digress). But you could imagine another category which is the category of "endofunctors on X". This is a category in which the objects are endofunctors and the morphisms are natural transformations.

And of those endofunctors, some of them might be monads. Which ones are monads? Exactly the ones which are monoidal in a particular sense. Instead of spelling out the exact mapping from monads to monoids (since Mac Lane does that far better than I could hope to), I'll just put their respective definitions side by side and let you compare:

A monoid is...

  • A set, S
  • An operation, • : S × S ? S
  • An element of S, e : 1 ? S

...satisfying these laws:

  • (a • b) • c = a • (b • c), for all a, b and c in S
  • e • a = a • e = a, for all a in S

A monad is...

  • An endofunctor, T : X ? X (in Haskell, a type constructor of kind * -> * with a Functor instance)
  • A natural transformation, µ : T × T ? T, where × means functor composition (µ is known as join in Haskell)
  • A natural transformation, ? : I ? T, where I is the identity endofunctor on X (? is known as return in Haskell)

...satisfying these laws:

  • µ ° Tµ = µ ° µT
  • µ ° T? = µ ° ?T = 1 (the identity natural transformation)

With a bit of squinting you might be able to see that both of these definitions are instances of the same abstract concept.

npm install hangs

The registry(https://registry.npmjs.org/cordova) was blocked by our firewall. Unblocking it fixed the issue.

How to add an onchange event to a select box via javascript?

replace:

transport_select.onChange = function(){toggleSelect(transport_select_id);};

with:

transport_select.onchange = function(){toggleSelect(transport_select_id);};

on'C'hange >> on'c'hange


You can use addEventListener too.

How do you obtain a Drawable object from a resource id in android package?

Following a solution for Kotlin programmers (from API 22)

val res = context?.let { ContextCompat.getDrawable(it, R.id.any_resource }

Generate a unique id

Why don't use GUID?

Guid guid = Guid.NewGuid();
string str = guid.ToString();

How can I express that two values are not equal to eachother?

"Not equals" can be expressed with the "not" operator ! and the standard .equals.

if (a.equals(b)) // a equals b
if (!a.equals(b)) // a not equal to b

"The page has expired due to inactivity" - Laravel 5.5

I encountered the same issue on Linux-mint but then realized that the htdocs folder had no full permissions. So I changed the permissions of all the subdirectories in the htdocs folder by doing: sudo chown -c -R $USER:$USER /opt/lampp/htdocs/*

How to set cornerRadius for only top-left and top-right corner of a UIView?

I am not sure why your solution did not work but the following code is working for me. Create a bezier mask and apply it to your view. In my code below I was rounding the bottom corners of the _backgroundView with a radius of 3 pixels. self is a custom UITableViewCell:

UIBezierPath *maskPath = [UIBezierPath
    bezierPathWithRoundedRect:self.backgroundImageView.bounds
    byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerBottomRight)
    cornerRadii:CGSizeMake(20, 20)
];

CAShapeLayer *maskLayer = [CAShapeLayer layer];

maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;

self.backgroundImageView.layer.mask = maskLayer;

Swift version with some improvements:

let path = UIBezierPath(roundedRect:viewToRound.bounds, byRoundingCorners:[.TopRight, .BottomLeft], cornerRadii: CGSizeMake(20, 20))
let maskLayer = CAShapeLayer()

maskLayer.path = path.CGPath
viewToRound.layer.mask = maskLayer

Swift 3.0 version:

let path = UIBezierPath(roundedRect:viewToRound.bounds,
                        byRoundingCorners:[.topRight, .bottomLeft],
                        cornerRadii: CGSize(width: 20, height:  20))

let maskLayer = CAShapeLayer()

maskLayer.path = path.cgPath
viewToRound.layer.mask = maskLayer

Swift extension here

How to add element in List while iterating in java?

I do this by adding the elements to an new, empty tmp List, then adding the tmp list to the original list using addAll(). This prevents unnecessarily copying a large source list.

Imagine what happens when the OP's original list has a few million items in it; for a while you'll suck down twice the memory.

In addition to conserving resources, this technique also prevents us from having to resort to 80s-style for loops and using what are effectively array indexes which could be unattractive in some cases.

How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

Quiet Late though!.

This method is properly tested and it converts the excel to DataSet.

public DataSet Dtl()
        {
            //Instance reference for Excel Application
            Microsoft.Office.Interop.Excel.Application objXL = null;        
            //Workbook refrence
            Microsoft.Office.Interop.Excel.Workbook objWB = null;
            DataSet ds = new DataSet();
            try
            {
                objXL = new Microsoft.Office.Interop.Excel.Application();
                objWB = objXL.Workbooks.Open(@"Book1.xlsx");//Your path to excel file.
                foreach (Microsoft.Office.Interop.Excel.Worksheet objSHT in objWB.Worksheets)
                {
                    int rows = objSHT.UsedRange.Rows.Count;
                    int cols = objSHT.UsedRange.Columns.Count;
                    DataTable dt = new DataTable();
                    int noofrow = 1;
                    //If 1st Row Contains unique Headers for datatable include this part else remove it
                    //Start
                    for (int c = 1; c <= cols; c++)
                    {
                        string colname = objSHT.Cells[1, c].Text;
                        dt.Columns.Add(colname);
                        noofrow = 2;
                    }
                    //END
                    for (int r = noofrow; r <= rows; r++)
                    {
                        DataRow dr = dt.NewRow();
                        for (int c = 1; c <= cols; c++)
                        {
                            dr[c - 1] = objSHT.Cells[r, c].Text;
                        }
                        dt.Rows.Add(dr);
                    }
                   ds.Tables.Add(dt);
                }
                //Closing workbook
                objWB.Close();
                //Closing excel application
                objXL.Quit();
                return ds;
            }

            catch (Exception ex)
            {
               objWB.Saved = true;
                //Closing work book
                objWB.Close();
                //Closing excel application
                objXL.Quit();
                //Response.Write("Illegal permission");
                return ds;
            }
        }

node.js, socket.io with SSL

This is my nginx config file and iosocket code. Server(express) is listening on port 9191. It works well: nginx config file:

server {
    listen       443 ssl;
    server_name  localhost;
    root   /usr/share/nginx/html/rdist;

    location /user/ {
        proxy_pass   http://localhost:9191;
    }
    location /api/ {
        proxy_pass   http://localhost:9191;
    }
    location /auth/ {
        proxy_pass   http://localhost:9191;
    }

    location / {
        index  index.html index.htm;
        if (!-e $request_filename){
          rewrite ^(.*)$ /index.html break;
        }
    }
    location /socket.io/ {
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_pass   http://localhost:9191/socket.io/;
    }


    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    ssl_certificate /etc/nginx/conf.d/sslcert/xxx.pem;
    ssl_certificate_key /etc/nginx/conf.d/sslcert/xxx.key;

}

Server:

const server = require('http').Server(app)
const io = require('socket.io')(server)
io.on('connection', (socket) => {
    handleUserConnect(socket)

  socket.on("disconnect", () => {
   handleUserDisConnect(socket)
  });
})

server.listen(9191, function () {
  console.log('Server listening on port 9191')
})

Client(react):

    const socket = io.connect('', { secure: true, query: `userId=${this.props.user._id}` })

        socket.on('notifications', data => {
            console.log('Get messages from back end:', data)
            this.props.mergeNotifications(data)
        })

Algorithm to detect overlapping periods

There is a wonderful library with good reviews on CodeProject: http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET

That library does a lot of work concerning overlap, intersecting them, etc. It's too big to copy/paste all of it, but I'll see which specific parts which can be useful to you.

Is there a need for range(len(a))?

If you need to work with indices of a sequence, then yes - you use it... eg for the equivalent of numpy.argsort...:

>>> a = [6, 3, 1, 2, 5, 4]
>>> sorted(range(len(a)), key=a.__getitem__)
[2, 3, 1, 5, 4, 0]

javascript: detect scroll end

I could not get either of the above answers to work so here is a third option that works for me! (This is used with jQuery)

if (($(window).innerHeight() + $(window).scrollTop()) >= $("body").height()) {
    //do stuff
}

Hope this helps anyone!

How to hide column of DataGridView when using custom DataSource?

If you want to use the BrowsableAttribute, then you can look for it at runtime on the model and hide the column accordingly:

private void Form_Load(object sender, EventArgs e)
{
    //add this line after your DataGridView initialization
    HideColumns<MyModel>(myDvg);
}

private void HideColumns<T>(DataGridView dvg)
{
    var type = typeof(T);
    foreach (var column in dvg.Columns.Cast<DataGridViewColumn>())
        column.Visible = IsBrowsable(type.GetProperty(column.Name));
}

private bool IsBrowsable(PropertyInfo propertyInfo)
{
    var attribute = propertyInfo.GetCustomAttributes(true).FirstOrDefault(att => att.GetType() == typeof(BrowsableAttribute));
    return attribute == null || (attribute as BrowsableAttribute).Browsable;
}

URL Encoding using C#

Url Encoding is easy in .NET. Use:

System.Web.HttpUtility.UrlEncode(string url)

If that'll be decoded to get the folder name, you'll still need to exclude characters that can't be used in folder names (*, ?, /, etc.)

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

The straight up answer to your question is: No. The signature for the PostAsync method is as follows:

public Task PostAsync(Uri requestUri, HttpContent content)

So, while you can pass an object to PostAsync it must be of type HttpContent and your anonymous type does not meet that criteria.

However, there are ways to accomplish what you want to accomplish. First, you will need to serialize your anonymous type to JSON, the most common tool for this is Json.NET. And the code for this is pretty trivial:

var myContent = JsonConvert.SerializeObject(data);

Next, you will need to construct a content object to send this data, I will use a ByteArrayContent object, but you could use or create a different type if you wanted.

var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);

Next, you want to set the content type to let the API know this is JSON.

byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

Then you can send your request very similar to your previous example with the form content:

var result = client.PostAsync("", byteContent).Result

On a side note, calling the .Result property like you're doing here can have some bad side effects such as dead locking, so you want to be careful with this.

css absolute position won't work with margin-left:auto margin-right: auto

Working JSFiddle below. When using position absolute, margin: 0 auto will not work, but you can do like this (will also scale):

left: 50%;
transform: translateX(-50%);

Update: Working JSFiddle

TSQL Default Minimum DateTime

Unless you are doing a DB to track historical times more than a century ago, using

Modified datetime DEFAULT ((0)) 

is perfectly safe and sound and allows more elegant queries than '1753-01-01' and more efficient queries than NULL.

However, since first Modified datetime is the time at which the record was inserted, you can use:

Modified datetime NOT NULL DEFAULT (GETUTCDATE())

which avoids the whole issue and makes your inserts easier and safer - as in you don't insert it at all and SQL does the housework :-)

With that in place you can still have elegant and fast queries by using 0 as a practical minimum since it's guranteed to always be lower than any insert-generated GETUTCDATE().

Python: Find a substring in a string and returning the index of the substring

There is one other option in regular expression, the search method

import re

string = 'Happy Birthday'
pattern = 'py'
print(re.search(pattern, string).span()) ## this prints starting and end indices
print(re.search(pattern, string).span()[0]) ## this does what you wanted

By the way, if you would like to find all the occurrence of a pattern, instead of just the first one, you can use finditer method

import re

string = 'i think that that that that student wrote there is not that right'
pattern = 'that'

print([match.start() for match in re.finditer(pattern, string)])

which will print all the starting positions of the matches.

How do I view the SQL generated by the Entity Framework?

In my case for EF 6+, instead of using this in the Immediate Window to find the query string:

var sql = ((System.Data.Entity.Core.Objects.ObjectQuery)query).ToTraceString();

I ended up having to use this to get the generated SQL command:

var sql = ((System.Data.Entity.Infrastructure.DbQuery<<>f__AnonymousType3<string,string,string,short,string>>)query).ToString();

Of course your anonymous type signature might be different.

HTH.

How to split csv whose columns may contain ,

Use a library like LumenWorks to do your CSV reading. It'll handle fields with quotes in them and will likely overall be more robust than your custom solution by virtue of having been around for a long time.

What is callback in Android?

It was discussed before here.

In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.

How to find list of possible words from a letter matrix [Boggle Solver]

I realize this question's time has come and gone, but since I was working on a solver myself, and stumbled onto this while googling about, I thought I should post a reference to mine as it seems a bit different from some of the others.

I chose to go with a flat array for the game board, and to do recursive hunts from each letter on the board, traversing from valid neighbor to valid neighbor, extending the hunt if the current list of letters if a valid prefix in an index. While traversing the notion of the current word is list of indexes into board, not letters that make up a word. When checking the index, the indexes are translated to letters and the check done.

The index is a brute force dictionary that's a bit like a trie, but allows for Pythonic queries of the index. If the words 'cat' and 'cater' are in the list, you'll get this in the dictionary:

   d = { 'c': ['cat','cater'],
     'ca': ['cat','cater'],
     'cat': ['cat','cater'],
     'cate': ['cater'],
     'cater': ['cater'],
   }

So if the current_word is 'ca' you know that it is a valid prefix because 'ca' in d returns True (so continue the board traversal). And if the current_word is 'cat' then you know that it is a valid word because it is a valid prefix and 'cat' in d['cat'] returns True too.

If felt like this allowed for some readable code that doesn't seem too slow. Like everyone else the expense in this system is reading/building the index. Solving the board is pretty much noise.

The code is at http://gist.github.com/268079. It is intentionally vertical and naive with lots of explicit validity checking because I wanted to understand the problem without crufting it up with a bunch of magic or obscurity.

Android studio- "SDK tools directory is missing"

The same problem observed on my side while looking for uiautomatorviewer.bat. After installing Android studio 3.6.2 (at Win10) I was looking for Android SDK Tools section at SDK Manager. Currently, this section is Hidden as Obsolete. enter image description here Fix: uncheck Hide Obsolete Packages, then check the mentioned package and install it - C:\Users..\AppData\Local\Android\Sdk\tools\bin is created.

How to specify jackson to only use fields - preferably globally

If you want a way to do this globally without worrying about the configuration of your ObjectMapper, you can create your own annotation:

@Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonAutoDetect(
        getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE,
        setterVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.NONE,
        creatorVisibility = JsonAutoDetect.Visibility.NONE
)
public @interface JsonExplicit {
}

Now you just have to annotate your classes with @JsonExplicit and you're good to go!

Also make sure to edit the above call to @JsonAutoDetect to make sure you have the values set to what works with your program.

Credit to https://stackoverflow.com/a/13408807 for helping me find out about @JacksonAnnotationsInside

What is the easiest way to initialize a std::vector with hardcoded elements?

If you don't want to use boost, but want to enjoy syntax like

std::vector<int> v;
v+=1,2,3,4,5;

just include this chunk of code

template <class T> class vector_inserter{
public:
    std::vector<T>& v;
    vector_inserter(std::vector<T>& v):v(v){}
    vector_inserter& operator,(const T& val){v.push_back(val);return *this;}
};
template <class T> vector_inserter<T> operator+=(std::vector<T>& v,const T& x){
    return vector_inserter<T>(v),x;
}

PHP Convert String into Float/Double

If the function floatval does not work you can try to make this :

    $string = "2968789218";
    $float = $string * 1.0;
    echo $float;

But for me all the previous answer worked ( try it in http://writecodeonline.com/php/ ) Maybe the problem is on your server ?

JavaScript, Node.js: is Array.forEach asynchronous?

There is a common pattern for doing a really heavy computation in Node that may be applicable to you...

Node is single-threaded (as a deliberate design choice, see What is Node.js?); this means that it can only utilize a single core. Modern boxes have 8, 16, or even more cores, so this could leave 90+% of the machine idle. The common pattern for a REST service is to fire up one node process per core, and put these behind a local load balancer like http://nginx.org/.

Forking a child - For what you are trying to do, there is another common pattern, forking off a child process to do the heavy lifting. The upside is that the child process can do heavy computation in the background while your parent process is responsive to other events. The catch is that you can't / shouldn't share memory with this child process (not without a LOT of contortions and some native code); you have to pass messages. This will work beautifully if the size of your input and output data is small compared to the computation that must be performed. You can even fire up a child node.js process and use the same code you were using previously.

For example:

var child_process = require('child_process');
function run_in_child(array, cb) {
    var process = child_process.exec('node libfn.js', function(err, stdout, stderr) {
        var output = JSON.parse(stdout);
        cb(err, output);
    });
    process.stdin.write(JSON.stringify(array), 'utf8');
    process.stdin.end();
}

How do I auto-submit an upload form when a file is selected?

If you already using jQuery simple:

<input type="file" onChange="$(this).closest('form').submit()"/>

How to list all methods for an object in Ruby?

Module#instance_methods

Returns an array containing the names of the public and protected instance methods in the receiver. For a module, these are the public and protected methods; for a class, they are the instance (not singleton) methods. With no argument, or with an argument that is false, the instance methods in mod are returned, otherwise the methods in mod and mod’s superclasses are returned.

module A
  def method1()  end
end
class B
  def method2()  end
end
class C < B
  def method3()  end
end

A.instance_methods                #=> [:method1]
B.instance_methods(false)         #=> [:method2]
C.instance_methods(false)         #=> [:method3]
C.instance_methods(true).length   #=> 43

C++ Returning reference to local variable

A good thing to remember are these simple rules, and they apply to both parameters and return types...

  • Value - makes a copy of the item in question.
  • Pointer - refers to the address of the item in question.
  • Reference - is literally the item in question.

There is a time and place for each, so make sure you get to know them. Local variables, as you've shown here, are just that, limited to the time they are locally alive in the function scope. In your example having a return type of int* and returning &i would have been equally incorrect. You would be better off in that case doing this...

void func1(int& oValue)
{
    oValue = 1;
}

Doing so would directly change the value of your passed in parameter. Whereas this code...

void func1(int oValue)
{
    oValue = 1;
}

would not. It would just change the value of oValue local to the function call. The reason for this is because you'd actually be changing just a "local" copy of oValue, and not oValue itself.

How to make readonly all inputs in some div in Angular2?

If you meant disable all the inputs in an Angular form at once:

1- Reactive Forms:

myFormGroup.disable() // where myFormGroup is a FormGroup 

2- Template driven forms (NgForm):

You should get hold of the NgForm in a NgForm variable (for ex. named myNgForm) then

myNgForm.form.disable() // where form here is an attribute of NgForm 
                      // & of type FormGroup so it accepts the disable() function

In case of NgForm , take care to call the disable method in the right time

To determine when to call it, You can find more details in this Stackoverflow answer

Dataframe to Excel sheet

I tested the previous answers found here: Assuming that we want the other four sheets to remain, the previous answers here did not work, because the other four sheets were deleted. In case we want them to remain use xlwings:

import xlwings as xw
import pandas as pd

filename = "test.xlsx"

df = pd.DataFrame([
    ("a", 1, 8, 3),
    ("b", 1, 2, 5),
    ("c", 3, 4, 6),
    ], columns=['one', 'two', 'three', "four"])

app = xw.App(visible=False)
wb = xw.Book(filename)
ws = wb.sheets["Sheet5"]

ws.clear()
ws["A1"].options(pd.DataFrame, header=1, index=False, expand='table').value = df

# If formatting of column names and index is needed as xlsxwriter does it, 
# the following lines will do it (if the dataframe is not multiindex).
ws["A1"].expand("right").api.Font.Bold = True
ws["A1"].expand("down").api.Font.Bold = True
ws["A1"].expand("right").api.Borders.Weight = 2
ws["A1"].expand("down").api.Borders.Weight = 2

wb.save(filename)
app.quit()

Undefined variable: $_SESSION

You need make sure to start the session at the top of every PHP file where you want to use the $_SESSION superglobal. Like this:

<?php
  session_start();
  echo $_SESSION['youritem'];
?>

You forgot the Session HELPER.

Check this link : book.cakephp.org/2.0/en/core-libraries/helpers/session.html

What "wmic bios get serialnumber" actually retrieves?

run cmd

Enter wmic baseboard get product,version,serialnumber

Press the enter key. The result you see under serial number column is your motherboard serial number

Process all arguments except the first one (in a bash script)

Came across this looking for something else. While the post looks fairly old, the easiest solution in bash is illustrated below (at least bash 4) using set -- "${@:#}" where # is the starting number of the array element we want to preserve forward:

    #!/bin/bash

    someVar="${1}"
    someOtherVar="${2}"
    set -- "${@:3}"
    input=${@}

    [[ "${input[*],,}" == *"someword"* ]] && someNewVar="trigger"

    echo -e "${someVar}\n${someOtherVar}\n${someNewVar}\n\n${@}"

Basically, the set -- "${@:3}" just pops off the first two elements in the array like perl's shift and preserves all remaining elements including the third. I suspect there's a way to pop off the last elements as well.

How to find serial number of Android device?

TelephonyManager tManager = (TelephonyManager)myActivity.getSystemService(Context.TELEPHONY_SERVICE);
String uid = tManager.getDeviceId();

getSystemService is a method from the Activity class. getDeviceID() will return the MDN or MEID of the device depending on which radio the phone uses (GSM or CDMA).

Each device MUST return a unique value here (assuming it's a phone). This should work for any Android device with a sim slot or CDMA radio. You're on your own with that Android powered microwave ;-)

How do I start/stop IIS Express Server?

You can stop any IIS Express application or you can stop all application. Right click on IIS express icon , which is located at right bottom corner of task bar. Then Select Show All Application

enter image description here

How do I handle the window close event in Tkinter?

If you want to change what the x button does or make it so that you cannot close it at all try this.

yourwindow.protocol("WM_DELETE_WINDOW", whatever)

then defy what "whatever" means

def whatever():
    #Replace this with what you want python to do when the user hits the x button

You can also make it so that when you close that window you can call it back like this

yourwindow.withdraw() 

This hides the window but does not close it

yourwindow.deiconify()

This makes the window visible again

Default string initialization: NULL or Empty?

I either set it to "" or null - I always check by using String.IsNullOrEmpty, so either is fine.

But the inner geek in me says I should set it to null before I have a proper value for it...

Hibernate error: ids for this class must be manually assigned before calling save():

Your @Entity class has a String type for its @Id field, so it can't generate ids for you.

If you change it to an auto increment in the DB and a Long in java, and add the @GeneratedValue annotation:

@Id
@Column(name="U_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long U_id;

it will handle incrementing id generation for you.

"register" keyword in C?

I have read that it is used for optimizing but is not clearly defined in any standard.

In fact it is clearly defined by the C standard. Quoting the N1570 draft section 6.7.1 paragraph 6 (other versions have the same wording):

A declaration of an identifier for an object with storage-class specifier register suggests that access to the object be as fast as possible. The extent to which such suggestions are effective is implementation-defined.

The unary & operator may not be applied to an object defined with register, and register may not be used in an external declaration.

There are a few other (fairly obscure) rules that are specific to register-qualified objects:

  • Defining an array object with register has undefined behavior.
    Correction: It's legal to define an array object with register, but you can't do anything useful with such an object (indexing into an array requires taking the address of its initial element).
  • The _Alignas specifier (new in C11) may not be applied to such an object.
  • If the parameter name passed to the va_start macro is register-qualified, the behavior is undefined.

There may be a few others; download a draft of the standard and search for "register" if you're interested.

As the name implies, the original meaning of register was to require an object to be stored in a CPU register. But with improvements in optimizing compilers, this has become less useful. Modern versions of the C standard don't refer to CPU registers, because they no longer (need to) assume that there is such a thing (there are architectures that don't use registers). The common wisdom is that applying register to an object declaration is more likely to worsen the generated code, because it interferes with the compiler's own register allocation. There might still be a few cases where it's useful (say, if you really do know how often a variable will be accessed, and your knowledge is better than what a modern optimizing compiler can figure out).

The main tangible effect of register is that it prevents any attempt to take an object's address. This isn't particularly useful as an optimization hint, since it can be applied only to local variables, and an optimizing compiler can see for itself that such an object's address isn't taken.

How can I give access to a private GitHub repository?

If you are the owner it is simple:

  • Go to your repo and click the Settings button.
  • In the left menu click Collaborators
  • Then Add their name.

Then collaborator should visit this example repo link https://github.com/user/repo/invitations

Source: Github Docs.

Converting a Java Keystore into PEM Format

Well, OpenSSL should do it handily from a #12 file:

openssl pkcs12 -in pkcs-12-certificate-file -out pem-certificate-file
openssl pkcs12 -in pkcs-12-certificate-and-key-file -out pem-certificate-and-key-file

Maybe more details on what the error/failure is?

Python+OpenCV: cv2.imwrite

This following code should extract face in images and save faces on disk

def detect(image):
    image_faces = []
    bitmap = cv.fromarray(image)
    faces = cv.HaarDetectObjects(bitmap, cascade, cv.CreateMemStorage(0))
    if faces:
        for (x,y,w,h),n in faces:
            image_faces.append(image[y:(y+h), x:(x+w)])
            #cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,255),3)
    return image_faces

if __name__ == "__main__":
    cam = cv2.VideoCapture(0)
    while 1:
        _,frame =cam.read()
        image_faces = []
        image_faces = detect(frame)
        for i, face in enumerate(image_faces):
            cv2.imwrite("face-" + str(i) + ".jpg", face)

        #cv2.imshow("features", frame)
        if cv2.waitKey(1) == 0x1b: # ESC
            print 'ESC pressed. Exiting ...'
            break

Convert the values in a column into row names in an existing data frame

It looks like the one-liner got even simpler along the line (currently using R 3.5.3):

# generate original data.frame
df <- data.frame(a = letters[1:10], b = 1:10, c = LETTERS[1:10])
# use first column for row names
df <- data.frame(df, row.names = 1)

The column used for row names is removed automatically.

jQuery DIV click, with anchors

I know that if you were to change that to an href you'd do:

$("a#link1").click(function(event) {
  event.preventDefault();
  $('div.link1').show();
  //whatever else you want to do
});

so if you want to keep it with the div, I'd try

$("div.clickable").click(function(event) {
  event.preventDefault();
  window.location = $(this).attr("url");
});

What is the difference between syntax and semantics in programming languages?

Semantics is what your code means--what you might describe in pseudo-code. Syntax is the actual structure--everything from variable names to semi-colons.

Where should I put <script> tags in HTML markup?

I think it depends on the webpage execution. If the page that you want to display can not displayed properly without loading JavaScript first then you should include JavaScript file first. But If you can display/render a webpage without initially download JavaScript file, then you should put JavaScript code at the bottom of the page. Because it will emulate a speedy page load, and from an user's point of view it would seems like that page is loading faster.

sql primary key and index

Primary keys are always indexed by default.

You can define a primary key in SQL Server 2012 by using SQL Server Management Studio or Transact-SQL. Creating a primary key automatically creates a corresponding unique, clustered or nonclustered index.

http://technet.microsoft.com/en-us/library/ms189039.aspx

jQuery ajax request being block because Cross-Origin

There is nothing you can do on your end (client side). You can not enable crossDomain calls yourself, the source (dailymotion.com) needs to have CORS enabled for this to work.

The only thing you can really do is to create a server side proxy script which does this for you. Are you using any server side scripts in your project? PHP, Python, ASP.NET etc? If so, you could create a server side "proxy" script which makes the HTTP call to dailymotion and returns the response. Then you call that script from your Javascript code, since that server side script is on the same domain as your script code, CORS will not be a problem.

How to skip the OPTIONS preflight request?

When performing certain types of cross-domain AJAX requests, modern browsers that support CORS will insert an extra "preflight" request to determine whether they have permission to perform the action. From example query:

$http.get( ‘https://example.com/api/v1/users/’ +userId,
  {params:{
           apiKey:’34d1e55e4b02e56a67b0b66’
          }
  } 
);

As a result of this fragment we can see that the address was sent two requests (OPTIONS and GET). The response from the server includes headers confirming the permissibility the query GET. If your server is not configured to process an OPTIONS request properly, client requests will fail. For example:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: accept, origin, x-requested-with, content-type
Access-Control-Allow-Methods: DELETE
Access-Control-Allow-Methods: OPTIONS
Access-Control-Allow-Methods: PUT
Access-Control-Allow-Methods: GET
Access-Control-Allow-Methods: POST
Access-Control-Allow-Orgin: *
Access-Control-Max-Age: 172800
Allow: PUT
Allow: OPTIONS
Allow: POST
Allow: DELETE
Allow: GET

How do I convert a string to enum in TypeScript?

This note relates to basarat's answer, not the original question.

I had an odd issue in my own project where the compiler was giving an error roughly equivalent to "cannot convert string to Color" using the equivalent of this code:

var colorId = myOtherObject.colorId; // value "Green";
var color: Color = <Color>Color[colorId]; // TSC error here: Cannot convert string to Color.

I found that the compiler type inferencing was getting confused and it thought that colorId was an enum value and not an ID. To fix the problem I had to cast the ID as a string:

var colorId = <string>myOtherObject.colorId; // Force string value here
var color: Color = Color[colorId]; // Fixes lookup here.

I'm not sure what caused the issue but I'll leave this note here in case anyone runs into the same problem I did.

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

The latest set of guidance is as follows: (from https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables)

Use:

System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);

From the docs:

public static class EnvironmentVariablesExample
{
    [FunctionName("GetEnvironmentVariables")]
    public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
    {
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
        log.LogInformation(GetEnvironmentVariable("AzureWebJobsStorage"));
        log.LogInformation(GetEnvironmentVariable("WEBSITE_SITE_NAME"));
    }

    public static string GetEnvironmentVariable(string name)
    {
        return name + ": " +
            System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
    }
}

App settings can be read from environment variables both when developing locally and when running in Azure. When developing locally, app settings come from the Values collection in the local.settings.json file. In both environments, local and Azure, GetEnvironmentVariable("<app setting name>") retrieves the value of the named app setting. For instance, when you're running locally, "My Site Name" would be returned if your local.settings.json file contains { "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }.

The System.Configuration.ConfigurationManager.AppSettings property is an alternative API for getting app setting values, but we recommend that you use GetEnvironmentVariable as shown here.

How to Extract Year from DATE in POSTGRESQL

This line solved my same problem in postgresql:

SELECT DATE_PART('year', column_name::date) from tableName;

If you want month, then simply replacing year with month solves that as well and likewise.

hibernate: LazyInitializationException: could not initialize proxy

The problem is that you are trying to access a collection in an object that is detached. You need to re-attach the object before accessing the collection to the current session. You can do that through

session.update(object);

Using lazy=false is not a good solution because you are throwing away the Lazy Initialization feature of hibernate. When lazy=false, the collection is loaded in memory at the same time that the object is requested. This means that if we have a collection with 1000 items, they all will be loaded in memory, despite we are going to access them or not. And this is not good.

Please read this article where it explains the problem, the possible solutions and why is implemented this way. Also, to understand Sessions and Transactions you must read this other article.

How to get first and last day of the current week in JavaScript

This works across year and month changes.

Date.prototype.GetFirstDayOfWeek = function() {
    return (new Date(this.setDate(this.getDate() - this.getDay())));
}

Date.prototype.GetLastDayOfWeek = function() {
    return (new Date(this.setDate(this.getDate() - this.getDay() +6)));
}

var today = new Date();

alert(today.GetFirstDayOfWeek());

alert(today.GetLastDayOfWeek());

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

goto command prompt

netstat -aon

for linux

netstat -tulpn | grep 'your_port_number'

it will show you something like

 TCP    192.1.200.48:2053      24.43.246.60:443       ESTABLISHED     248
 TCP    192.1.200.48:2055      24.43.246.60:443       ESTABLISHED     248
 TCP    192.1.200.48:2126      213.146.189.201:12350  ESTABLISHED     1308
 TCP    192.1.200.48:3918      192.1.200.2:8073       ESTABLISHED     1504
 TCP    192.1.200.48:3975      192.1.200.11:49892     TIME_WAIT       0
 TCP    192.1.200.48:3976      192.1.200.11:49892     TIME_WAIT       0
 TCP    192.1.200.48:4039      209.85.153.100:80      ESTABLISHED     248
 TCP    192.1.200.48:8080      209.85.153.100:80      ESTABLISHED     248

check which process has binded your port. here in above example its 248 now if you are sure that you need to kill that process fire

Linux:

kill -9 248

Windows:

taskkill /f /pid 248

it will kill that process

VBA (Excel) Initialize Entire Array without Looping

For VBA you need to initialise in two lines.

Sub TestArray()

Dim myArray
myArray = Array(1, 2, 4, 8)

End Sub

Authentication failed because remote party has closed the transport stream

If you want to use an older version of .net, create your own flag and cast it.

    //
    // Summary:
    //     Specifies the security protocols that are supported by the Schannel security
    //     package.
    [Flags]
    private enum MySecurityProtocolType
    {
        //
        // Summary:
        //     Specifies the Secure Socket Layer (SSL) 3.0 security protocol.
        Ssl3 = 48,
        //
        // Summary:
        //     Specifies the Transport Layer Security (TLS) 1.0 security protocol.
        Tls = 192,
        //
        // Summary:
        //     Specifies the Transport Layer Security (TLS) 1.1 security protocol.
        Tls11 = 768,
        //
        // Summary:
        //     Specifies the Transport Layer Security (TLS) 1.2 security protocol.
        Tls12 = 3072
    }
    public Session()
    {
        System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)(MySecurityProtocolType.Tls12 | MySecurityProtocolType.Tls11 | MySecurityProtocolType.Tls);
    }

Get Android Phone Model programmatically

You can get the phone device name from the

BluetoothAdapter

In case phone doesn't support Bluetooth, then you have to construct the device name from

android.os.Build class

Here is the sample code to get the phone device name.

public String getPhoneDeviceName() {  
        String name=null;
        // Try to take Bluetooth name
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter != null) {
            name = adapter.getName();
        }

        // If not found, use MODEL name
        if (TextUtils.isEmpty(name)) {
            String manufacturer = Build.MANUFACTURER;
            String model = Build.MODEL;
            if (model.startsWith(manufacturer)) {
                name = model;
            } else {
                name = manufacturer + " " + model;
            }
        } 
        return name;
}

What does Docker add to lxc-tools (the userspace LXC tools)?

Going to keep this pithier, this is already asked and answered above .

I'd step back however and answer it slightly differently, the docker engine itself adds orchestration as one of its extras and this is the disruptive part. Once you start running an app as a combination of containers running 'somewhere' across multiple container engines it gets really exciting. Robustness, Horizontal Scaling, complete abstraction from the underlying hardware, i could go on and on...

Its not just Docker that gives you this, in fact the de facto Container Orchestration standard is Kubernetes which comes in a lot of flavours, a Docker one, but also OpenShift, SuSe, Azure, AWS...

Then beneath K8S there are alternative container engines; the interesting ones are Docker and CRIO - recently built, daemonless, intended as a container engine specifically for Kubernetes but immature. Its the competition between these that I think will be the real long term choice for a container engine.

How to show text in combobox when no item selected?

Here's how I do it. It might not be the best method, and offers least control; however, it's simple and quick and I thought it might be a good idea to share it so that more options are available for others.

<ComboBox SelectedIndex="0">
    <ComboBoxItem Visibility="Collapsed">Please select one...</ComboBoxItem>
    <ComboBoxItem>1</ComboBoxItem>
    <ComboBoxItem>2</ComboBoxItem>
    <ComboBoxItem>3</ComboBoxItem>
    <ComboBoxItem>4</ComboBoxItem>
</ComboBox>

The idea behind this is that the initial selection is index 0, which is collapsed, so it's not available under selection for the user once they select something else. The downside is that you have to remember that if you're checking for a selected index, remember that index 0 means there was no selection made.

git with development, staging and production branches

Actually what made this so confusing is that the Beanstalk people stand behind their very non-standard use of Staging (it comes before development in their diagram, and it's not a mistake!

https://twitter.com/Beanstalkapp/status/306129447885631488

How to create a jar with external libraries included in Eclipse?

If you want to export all JAR-files of a Java web-project, open the latest generated WAR-file with a ZIP-tool (e.g. 7-Zip), navigate to the /WEB-INF/lib/ folder. Here you will find all JAR-files you need for this project (as listed in "Referenced Libraries").

How do I detect whether a Python variable is a function?

If you have learned C++, you must be familiar with function object or functor, means any object that can be called as if it is a function.

In C++, an ordinary function is a function object, and so is a function pointer; more generally, so is an object of a class that defines operator(). In C++11 and greater, the lambda expression is the functor too.

Similarity, in Python, those functors are all callable. An ordinary function can be callable, a lambda expression can be callable, a functional.partial can be callable, the instances of class with a __call__() method can be callable.


Ok, go back to question : I have a variable, x, and I want to know whether it is pointing to a function or not.

If you want to judge weather the object acts like a function, then the callable method suggested by @John Feminella is ok.

If you want to judge whether a object is just an ordinary function or not( not a callable class instance, or a lambda expression), then the xtypes.XXX suggested by @Ryan is a better choice.

Then I do an experiment using those code:

#!/usr/bin/python3
# 2017.12.10 14:25:01 CST
# 2017.12.10 15:54:19 CST

import functools
import types
import pprint

Define a class and an ordinary function.

class A():
    def __call__(self, a,b):
        print(a,b)
    def func1(self, a, b):
        print("[classfunction]:", a, b)
    @classmethod
    def func2(cls, a,b):
        print("[classmethod]:", a, b)
    @staticmethod
    def func3(a,b):
        print("[staticmethod]:", a, b)

def func(a,b):
    print("[function]", a,b)

Define the functors:

#(1.1) built-in function
builtins_func = open
#(1.2) ordinary function
ordinary_func = func
#(1.3) lambda expression
lambda_func  = lambda a : func(a,4)
#(1.4) functools.partial
partial_func = functools.partial(func, b=4)

#(2.1) callable class instance
class_callable_instance = A()
#(2.2) ordinary class function
class_ordinary_func = A.func1
#(2.3) bound class method
class_bound_method = A.func2
#(2.4) static class method
class_static_func = A.func3

Define the functors' list and the types' list:

## list of functors
xfuncs = [builtins_func, ordinary_func, lambda_func, partial_func, class_callable_instance, class_ordinary_func, class_bound_method, class_static_func]
## list of type
xtypes = [types.BuiltinFunctionType, types.FunctionType, types.MethodType, types.LambdaType, functools.partial]

Judge wether the functor is callable. As you can see, they all are callable.

res = [callable(xfunc)  for xfunc in xfuncs]
print("functors callable:")
print(res)

"""
functors callable:
[True, True, True, True, True, True, True, True]
"""

Judge the functor's type( types.XXX). Then the types of functors are not all the same.

res = [[isinstance(xfunc, xtype) for xtype in xtypes] for xfunc in xfuncs]

## output the result
print("functors' types")
for (row, xfunc) in zip(res, xfuncs):
    print(row, xfunc)

"""
functors' types
[True, False, False, False, False] <built-in function open>
[False, True, False, True, False] <function func at 0x7f1b5203e048>
[False, True, False, True, False] <function <lambda> at 0x7f1b5081fd08>
[False, False, False, False, True] functools.partial(<function func at 0x7f1b5203e048>, b=4)
[False, False, False, False, False] <__main__.A object at 0x7f1b50870cc0>
[False, True, False, True, False] <function A.func1 at 0x7f1b5081fb70>
[False, False, True, False, False] <bound method A.func2 of <class '__main__.A'>>
[False, True, False, True, False] <function A.func3 at 0x7f1b5081fc80>
"""

I draw a table of callable functor's types using the data.

enter image description here

Then you can choose the functors' types that suitable.

such as:

def func(a,b):
    print("[function]", a,b)

>>> callable(func)
True
>>> isinstance(func,  types.FunctionType)
True
>>> isinstance(func, (types.BuiltinFunctionType, types.FunctionType, functools.partial))
True
>>> 
>>> isinstance(func, (types.MethodType, functools.partial))
False

Importing text file into excel sheet

There are many ways you can import Text file to the current sheet. Here are three (including the method that you are using above)

  1. Using a QueryTable
  2. Open the text file in memory and then write to the current sheet and finally applying Text To Columns if required.
  3. If you want to use the method that you are currently using then after you open the text file in a new workbook, simply copy it over to the current sheet using Cells.Copy

Using a QueryTable

Here is a simple macro that I recorded. Please amend it to suit your needs.

Sub Sample()
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Sample.txt", Destination:=Range("$A$1") _
        )
        .Name = "Sample"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

Open the text file in memory

Sub Sample()
    Dim MyData As String, strData() As String

    Open "C:\Sample.txt" For Binary As #1
    MyData = Space$(LOF(1))
    Get #1, , MyData
    Close #1
    strData() = Split(MyData, vbCrLf)
End Sub

Once you have the data in the array you can export it to the current sheet.

Using the method that you are already using

Sub Sample()
    Dim wbI As Workbook, wbO As Workbook
    Dim wsI As Worksheet

    Set wbI = ThisWorkbook
    Set wsI = wbI.Sheets("Sheet1") '<~~ Sheet where you want to import

    Set wbO = Workbooks.Open("C:\Sample.txt")

    wbO.Sheets(1).Cells.Copy wsI.Cells

    wbO.Close SaveChanges:=False
End Sub

FOLLOWUP

You can use the Application.GetOpenFilename to choose the relevant file. For example...

Sub Sample()
    Dim Ret

    Ret = Application.GetOpenFilename("Prn Files (*.prn), *.prn")

    If Ret <> False Then
        With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;" & Ret, Destination:=Range("$A$1"))

            '~~> Rest of the code

        End With
    End If
End Sub

Python in Xcode 4+?

This Technical Note TN2328 from Apple Developer Library helped me a lot about Changes To Embedding Python Using Xcode 5.0.

Get client IP address via third party web service

A more reliable REST endpoint would be http://freegeoip.net/json/

Returns the ip address along with the geo-location too. Also has cross-domain requests enabled (Access-Control-Allow-Origin: *) so you don't have to code around JSONP.

How to add default signature in Outlook

I have made this a Community Wiki answer because I could not have created it without PowerUser's research and the help in earlier comments.

I took PowerUser's Sub X and added

Debug.Print "n------"    'with different values for n
Debug.Print ObjMail.HTMLBody

after every statement. From this I discovered the signature is not within .HTMLBody until after ObjMail.Display and then only if I haven't added anything to the body.

I went back to PowerUser's earlier solution that used C:\Users\" & Environ("username") & "\AppData\Roaming\Microsoft\Signatures\Mysig.txt"). PowerUser was unhappy with this because he wanted his solution to work for others who would have different signatures.

My signature is in the same folder and I cannot find any option to change this folder. I have only one signature so by reading the only HTM file in this folder, I obtained my only/default signature.

I created an HTML table and inserted it into the signature immediately following the <body> element and set the html body to the result. I sent the email to myself and the result was perfectly acceptable providing you like my formatting which I included to check that I could.

My modified subroutine is:

Sub X()

  Dim OlApp As Outlook.Application
  Dim ObjMail As Outlook.MailItem

  Dim BodyHtml As String
  Dim DirSig As String
  Dim FileNameHTMSig As String
  Dim Pos1 As Long
  Dim Pos2 As Long
  Dim SigHtm As String

  DirSig = "C:\Users\" & Environ("username") & _
                               "\AppData\Roaming\Microsoft\Signatures"

  FileNameHTMSig = Dir$(DirSig & "\*.htm")

  ' Code to handle there being no htm signature or there being more than one

  SigHtm = GetBoiler(DirSig & "\" & FileNameHTMSig)
  Pos1 = InStr(1, LCase(SigHtm), "<body")

  ' Code to handle there being no body

  Pos2 = InStr(Pos1, LCase(SigHtm), ">")

  ' Code to handle there being no closing > for the body element

   BodyHtml = "<table border=0 width=""100%"" style=""Color: #0000FF""" & _
         " bgColor=#F0F0F0><tr><td align= ""center"">HTML table</td>" & _
         "</tr></table><br>"
  BodyHtml = Mid(SigHtm, 1, Pos2 + 1) & BodyHtml & Mid(SigHtm, Pos2 + 2)

  Set OlApp = Outlook.Application
  Set ObjMail = OlApp.CreateItem(olMailItem)
  ObjMail.BodyFormat = olFormatHTML
  ObjMail.Subject = "Subject goes here"
  ObjMail.Recipients.Add "my email address"
  ObjMail.Display

End Sub

Since both PowerUser and I have found our signatures in C:\Users\" & Environ("username") & "\AppData\Roaming\Microsoft\Signatures I suggest this is the standard location for any Outlook installation. Can this default be changed? I cannot find anything to suggest it can. The above code clearly needs some development but it does achieve PowerUser's objective of creating an email body containing an HTML table above a signature.

Creating and throwing new exception

To call a specific exception such as FileNotFoundException use this format

if (-not (Test-Path $file)) 
{
    throw [System.IO.FileNotFoundException] "$file not found."
}

To throw a general exception use the throw command followed by a string.

throw "Error trying to do a task"

When used inside a catch, you can provide additional information about what triggered the error

Get Return Value from Stored procedure in asp.net

2 things.

  • The query has to complete on sql server before the return value is sent.

  • The results have to be captured and then finish executing before the return value gets to the object.

In English, finish the work and then retrieve the value.

this will not work:

                cmm.ExecuteReader();
                int i = (int) cmm.Parameters["@RETURN_VALUE"].Value;

This will work:

                        SqlDataReader reader = cmm.ExecuteReader();
                        reader.Close();

                        foreach (SqlParameter prm in cmd.Parameters)
                        {
                           Debug.WriteLine("");
                           Debug.WriteLine("Name " + prm.ParameterName);
                           Debug.WriteLine("Type " + prm.SqlDbType.ToString());
                           Debug.WriteLine("Size " + prm.Size.ToString());
                           Debug.WriteLine("Direction " + prm.Direction.ToString());
                           Debug.WriteLine("Value " + prm.Value);

                        }

if you are not sure check the value of the parameter before during and after the results have been processed by the reader.

What does <![CDATA[]]> in XML mean?

The Cdata is a data which you may want to pass to an xml parser and still not interpreted as an xml.

Say for eg :- You have an xml which has encapsulates question/answer object . Such open fields can have any data which does not strictly fall under basic data type or xml defined custom data types. Like --Is this a correct tag for xml comment ? .-- You may have a requirement to pass it as it is without being interpreted by the xml parser as another child element. Here Cdata comes to your rescue . By declaring as Cdata you are telling the parser don't treat the data wrapped as an xml (though it may look like one )

Equivalent VB keyword for 'break'

In both Visual Basic 6.0 and VB.NET you would use:

  • Exit For to break from For loop
  • Wend to break from While loop
  • Exit Do to break from Do loop

depending on the loop type. See Exit Statements for more details.

What do curly braces mean in Verilog?

The curly braces mean concatenation, from most significant bit (MSB) on the left down to the least significant bit (LSB) on the right. You are creating a 32-bit bus (result) whose 16 most significant bits consist of 16 copies of bit 15 (the MSB) of the a bus, and whose 16 least significant bits consist of just the a bus (this particular construction is known as sign extension, which is needed e.g. to right-shift a negative number in two's complement form and keep it negative rather than introduce zeros into the MSBits).

There is a tutorial here*, but it doesn't explain too much more than the above paragraph.

For what it's worth, the nested curly braces around a[15:0] are superfluous.

*Beware: the example within the tutorial link contains a typo when demonstrating multiple concatenations - the (2{C}} should be a {2{2}}.

CSS fill remaining width

Include your image in the searchBar div, it will do the task for you

<div id="searchBar">
    <img src="img/logo.png" />                
    <input type="text" />
</div>

How do you get the current page number of a ViewPager for Android?

For this problem Onpagechange listener is the best one But it will also have one small mistake that is it will not detect the starting time time of 0th position Once you will change the page it will starts to detect the Page selected position...For this problem I fount the easiest solution

1.You have to maintain the selected position value then use it....
2. Case 1: At the starting of the position is always Zero....
Case 2: Suppose if you set the current item means you will set that value into maintain position
3.Then do your action with the use of that maintain in your activity...

Public int maintain=0;
myViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i2) {
             //Toast.makeText(MyActivity.this, i+"  Is Selected  "+data.size(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPageSelected( int i) {
          // here you will get the position of selected page
            maintain = i;


        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });


updateButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            Toast.makeText(MyActivity.this, i+"  Is Selected  "+data.size(), Toast.LENGTH_SHORT).show();
            data.set(maintain, "Replaced "+maintain);         
            myViewPager.getAdapter().notifyDataSetChanged();
        }
    });

Fetching data from MySQL database to html dropdown list

To do this you want to loop through each row of your query results and use this info for each of your drop down's options. You should be able to adjust the code below fairly easily to meet your needs.

// Assume $db is a PDO object
$query = $db->query("YOUR QUERY HERE"); // Run your query

echo '<select name="DROP DOWN NAME">'; // Open your drop down box

// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
   echo '<option value="'.$row['something'].'">'.$row['something'].'</option>';
}

echo '</select>';// Close your drop down box

Is it possible to use JS to open an HTML select to show its option list?

<select id="myDropDown">
  <option>html5</option>
  <option>javascript</option>
  <option>jquery</option>
  <option>css</option>
  <option>sencha</option>
</select>

By jQuery:

var myDropDown=$("#myDropDown");
var length = $('#myDropDown> option').length;
//open dropdown
myDropDown.attr('size',length);
//close dropdown
myDropDown.attr('size',0);

By javascript:

var myDropDown=document.getElementById("myDropDown");
var length = myDropDown.options.length;
//open dropdown
myDropDown.size = length;
//close dropdown
myDropDown.size = 0;

Copied from: Open close select

What does the "undefined reference to varName" in C mean?

An initial reaction to this would be to ask and ensure that the two object files are being linked together. This is done at the compile stage by compiling both files at the same time:

gcc -o programName a.c b.c

Or if you want to compile separately, it would be:

gcc -c a.c
gcc -c b.c
gcc -o programName a.o b.o

Create list of object from another using Java 8 Streams

I prefer to solve this in the classic way, creating a new array of my desired data type:

List<MyNewType> newArray = new ArrayList<>();
myOldArray.forEach(info -> newArray.add(objectMapper.convertValue(info, MyNewType.class)));

JavaScript check if value is only undefined, null or false

The best way to do it I think is:

if(val != true){
//do something
} 

This will be true if val is false, NaN, or undefined.

How to use an arraylist as a prepared statement parameter

You may want to use setArray method as mentioned in the javadoc below:

http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setArray(int, java.sql.Array)

Sample Code:

PreparedStatement pstmt = 
                conn.prepareStatement("select * from employee where id in (?)");
Array array = conn.createArrayOf("VARCHAR", new Object[]{"1", "2","3"});
pstmt.setArray(1, array);
ResultSet rs = pstmt.executeQuery();

Fatal error: iostream: No such file or directory in compiling C program using GCC

Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t. I am glad that you did.

Anyways, You have a .c source file, and most of the code looks as per C standards, except that #include <iostream> and using namespace std;

C equivalent for the built-in functions of C++ standard #include<iostream> can be availed through #include<stdio.h>

  1. Replace #include <iostream> with #include <stdio.h>, delete using namespace std;
  2. With #include <iostream> taken off, you would need a C standard alternative for cout << endl;, which can be done by printf("\n"); or putchar('\n');
    Out of the two options, printf("\n"); works the faster as I observed.

    When used printf("\n"); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.031s
    user    0m0.030s
    sys     0m0.030s
    

    When used putchar('\n'); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.047s
    user    0m0.030s
    sys     0m0.030s
    

Compiled with Cygwin gcc (GCC) 4.8.3 version. results averaged over 10 samples. (Took me 15 mins)

Android studio: emulator is running but not showing up in Run App "choose a running device"

Check the android path of the emulator.

I had to change the registry in here:

 HKEY_LOCAL_MACHINE > SOFTWARE > WOW6432Node > Android SDK Tools

to the actual path of the sdk location (which can be found in android studio: settings-> System Settings -> Android SDK)

All the credit goes to the author of this blogpost www.clearlyagileinc.com/

Best way to remove an event handler in jQuery?

maybe the unbind method will work for you

$("#myimage").unbind("click");

Interface naming in Java

There may be several reasons Java does not generally use the IUser convention.

  1. Part of the Object-Oriented approach is that you should not have to know whether the client is using an interface or an implementation class. So, even List is an interface and String is an actual class, a method might be passed both of them - it doesn't make sense to visually distinguish the interfaces.

  2. In general, we will actually prefer the use of interfaces in client code (prefer List to ArrayList, for instance). So it doesn't make sense to make the interfaces stand out as exceptions.

  3. The Java naming convention prefers longer names with actual meanings to Hungarian-style prefixes. So that code will be as readable as possible: a List represents a list, and a User represents a user - not an IUser.

How is the default max Java heap size determined?

Ernesto is right. According to the link he posted [1]:

Updated Client JVM heap configuration

In the Client JVM...

  • The default maximum heap size is half of the physical memory up to a physical memory size of 192 megabytes and otherwise one fourth of the physical memory up to a physical memory size of 1 gigabyte.

    For example, if your machine has 128 megabytes of physical memory, then the maximum heap size is 64 megabytes, and greater than or equal to 1 gigabyte of physical memory results in a maximum heap size of 256 megabytes.

  • The maximum heap size is not actually used by the JVM unless your program creates enough objects to require it. A much smaller amount, termed the initial heap size, is allocated during JVM initialization. ...

  • ...
  • Server JVM heap configuration ergonomics are now the same as the Client, except that the default maximum heap size for 32-bit JVMs is 1 gigabyte, corresponding to a physical memory size of 4 gigabytes, and for 64-bit JVMs is 32 gigabytes, corresponding to a physical memory size of 128 gigabytes.

[1] http://www.oracle.com/technetwork/java/javase/6u18-142093.html

How to program a delay in Swift 3

I like one-line notation for GCD, it's more elegant:

    DispatchQueue.main.asyncAfter(deadline: .now() + 42.0) {
        // do stuff 42 seconds later
    }

Also, in iOS 10 we have new Timer methods, e.g. block initializer:

(so delayed action may be canceled)

    let timer = Timer.scheduledTimer(withTimeInterval: 42.0, repeats: false) { (timer) in
        // do stuff 42 seconds later
    }

Btw, keep in mind: by default, timer is added to the default run loop mode. It means timer may be frozen when the user is interacting with the UI of your app (for example, when scrolling a UIScrollView) You can solve this issue by adding the timer to the specific run loop mode:

RunLoop.current.add(timer, forMode: .common)

At this blog post you can find more details.

Connecting to remote MySQL server using PHP

It is very easy to connect remote MySQL Server Using PHP, what you have to do is:

  1. Create a MySQL User in remote server.

  2. Give Full privilege to the User.

  3. Connect to the Server using PHP Code (Sample Given Below)

$link = mysql_connect('your_my_sql_servername or IP Address', 'new_user_which_u_created', 'password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

echo 'Connected successfully';

mysql_select_db('sandsbtob',$link) or die ("could not open db".mysql_error());
// we connect to localhost at port 3306

Is it possible to hide/encode/encrypt php source code and let others have the system?

There are some online services for obfuscate php to hide the code from others. This is one Right Coder's Free Obfuscator Online

@Glavic is right. "Nothing is bulletproof". You can encode your source code and hide from bigger programmers, not from experts.

How to get an array of specific "key" in multidimensional array without looping

You can also use array_reduce() if you prefer a more functional approach

For instance:

$userNames = array_reduce($users, function ($carry, $user) {
    array_push($carry, $user['name']);
    return $carry;
}, []);

Or if you like to be fancy,

$userNames = [];
array_map(function ($user) use (&$userNames){
    $userNames[]=$user['name'];
}, $users);

This and all the methods above do loop behind the scenes though ;)

How to use Google fonts in React.js?

If you are using Create React App environment simply add @import rule to index.css as such:

@import url('https://fonts.googleapis.com/css?family=Anton');

Import index.css in your main React app:

import './index.css'

React gives you a choice of Inline styling, CSS Modules or Styled Components in order to apply CSS:

font-family: 'Anton', sans-serif;

No log4j2 configuration file found. Using default configuration: logging only errors to the console

I am working on TestNG Maven project, This worked for me by adding <resources> tag in pom.xml, this happens to be the path of my custom configuration file log4j2.xml.

<url>http://maven.apache.org</url>
<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<build>
  <resources>
    <resource>
      <directory>src/main/java/resources</directory>
      <filtering>true</filtering>
    </resource>
  </resources>
  <pluginManagement>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M3</version>
        <configuration>
          <suiteXmlFiles>
            <suiteXmlFile>testng.xml</suiteXmlFile>
          </suiteXmlFiles>
        </configuration>
      </plugin>
    </plugins>
  </pluginManagement>
</build>
<dependencies>
  <dependency>

runOnUiThread in fragment

I used this for getting Date and Time in a fragment.

private Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_head_screen, container, false);

    dateTextView =  root.findViewById(R.id.dateView);
    hourTv = root.findViewById(R.id.hourView);

        Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(1000);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            //Calendario para obtener fecha & hora
                            Date currentTime = Calendar.getInstance().getTime();
                            SimpleDateFormat date_sdf = new SimpleDateFormat("dd/MM/yyyy");
                            SimpleDateFormat hour_sdf = new SimpleDateFormat("HH:mm a");

                            String currentDate = date_sdf.format(currentTime);
                            String currentHour = hour_sdf.format(currentTime);

                            dateTextView.setText(currentDate);
                            hourTv.setText(currentHour);
                        }
                    });
                }
            } catch (InterruptedException e) {
                Log.v("InterruptedException", e.getMessage());
            }
        }
    };
}

matplotlib: Group boxplots

Mock data:

df = pd.DataFrame({'Group':['A','A','A','B','C','B','B','C','A','C'],\
                  'Apple':np.random.rand(10),'Orange':np.random.rand(10)})
df = df[['Group','Apple','Orange']]

        Group    Apple     Orange
    0      A  0.465636  0.537723
    1      A  0.560537  0.727238
    2      A  0.268154  0.648927
    3      B  0.722644  0.115550
    4      C  0.586346  0.042896
    5      B  0.562881  0.369686
    6      B  0.395236  0.672477
    7      C  0.577949  0.358801
    8      A  0.764069  0.642724
    9      C  0.731076  0.302369

You can use the Seaborn library for these plots. First melt the dataframe to format data and then create the boxplot of your choice.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
dd=pd.melt(df,id_vars=['Group'],value_vars=['Apple','Orange'],var_name='fruits')
sns.boxplot(x='Group',y='value',data=dd,hue='fruits')

enter image description here

Using Chrome's Element Inspector in Print Preview Mode?

Chrome v50:

Way 1:

  1. Menu > More Tools > Rendering settings (see image)
  2. Down: Rendering Tab > Emulate media "print"

Way 2:

  1. Open Console [esc]
  2. Console Menu > rendering

String.Format alternative in C++

You can use sprintf in combination with std::string.c_str().

c_str() returns a const char* and works with sprintf:

string a = "test";
string b = "text.txt";
string c = "text1.txt";
char* x = new char[a.length() + b.length() + c.length() + 32];

sprintf(x, "%s %s > %s", a.c_str(), b.c_str(), c.c_str() );

string str = x;
delete[] x;

or you can use a pre-allocated char array if you know the size:

string a = "test";
string b = "text.txt";
string c = "text1.txt";
char x[256];

sprintf(x, "%s %s > %s", a.c_str(), b.c_str(), c.c_str() );

how to view the contents of a .pem certificate

Use the -printcert command like this:

keytool -printcert -file certificate.pem

Generate random password string with requirements in javascript

And finally, without using floating point hacks:

function genpasswd(n) {
    // 36 ** 11 > Number.MAX_SAFE_INTEGER
    if (n > 10)
        throw new Error('Too big n for this function');
    var x = "0000000000" + Math.floor(Number.MAX_SAFE_INTEGER * Math.random()).toString(36);
    return x.slice(-n);
}

How can I run a windows batch file but hide the command window?

This little VBScript from technet does the trick:

Const HIDDEN_WINDOW = 12

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objStartup = objWMIService.Get("Win32_ProcessStartup")

Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = HIDDEN_WINDOW
Set objProcess = GetObject("winmgmts:root\cimv2:Win32_Process")
errReturn = objProcess.Create("mybatch.bat", null, objConfig, intProcessID)

Edit mybatch.bat to your bat file name, save as a vbs, run it.

Doc says it's not tested in Win7, but I just tested it, it works fine. Won't show any window for whatever process you run

Creating a JSON response using Django and Python

How to use google app engine with ajax (json)?

Code Javascript with JQuery:

$.ajax({
    url: '/ajax',
    dataType : 'json',
    cache: false,
    success: function(data) {
        alert('Load was performed.'+data.ajax_resp);
    }
});

Code Python

class Ajax(webapp2.RequestHandler):
    def get(self):
        my_response = {'ajax_resp':'Hello, webapp World!'}
        datos = json.dumps(my_response)

        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
        self.response.out.write(datos)

How do you run JavaScript script through the Terminal?

If you're using MacBook.

  1. Set up node.js in your system and open up the terminal
  2. Navigate to the directory, where the js file is saved.
  3. To execute run node <filename.js>

example, if filename is script.js run node script.js