Programs & Examples On #Photo management

Docker CE on RHEL - Requires: container-selinux >= 2.9

[SOLVED] Simple one command to fix this issue.

yum install http://mirror.centos.org/centos/7/extras/x86_64/Packages/container-selinux-2.107-3.el7.noarch.rpm

OnClick in Excel VBA

Clearly, there is no perfect answer. However, if you want to allow the user to

  1. select certain cells
  2. allow them to change those cells, and
  3. trap each click,even repeated clicks on the same cell,

then the easiest way seems to be to move the focus off the selected cell, so that clicking it will trigger a Select event.

One option is to move the focus as I suggested above, but this prevents cell editing. Another option is to extend the selection by one cell (left/right/up/down),because this permits editing of the original cell, but will trigger a Select event if that cell is clicked again on its own.

If you only wanted to trap selection of a single column of cells, you could insert a hidden column to the right, extend the selection to include the hidden cell to the right when the user clicked,and this gives you an editable cell which can be trapped every time it is clicked. The code is as follows

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  'prevent Select event triggering again when we extend the selection below
  Application.EnableEvents = False
  Target.Resize(1, 2).Select
  Application.EnableEvents = True
End Sub

How to check "hasRole" in Java Code with Spring Security?

You can get some help from AuthorityUtils class. Checking role as a one-liner:

if (AuthorityUtils.authorityListToSet(SecurityContextHolder.getContext().getAuthentication().getAuthorities()).contains("ROLE_MANAGER")) {
    /* ... */
}

Caveat: This does not check role hierarchy, if such exists.

Select info from table where row has max date

Using an in can have a performance impact. Joining two subqueries will not have the same performance impact and can be accomplished like this:

SELECT *
  FROM (SELECT msisdn
              ,callid
              ,Change_color
              ,play_file_name
              ,date_played
          FROM insert_log
         WHERE play_file_name NOT IN('Prompt1','Conclusion_Prompt_1','silent')
        ORDER BY callid ASC) t1
       JOIN (SELECT MAX(date_played) AS date_played
               FROM insert_log GROUP BY callid) t2
         ON t1.date_played = t2.date_played

Reinitialize Slick js after successful ajax call

I had to unslick the carousel before the ajax call starts, but you can't do that until there is already a slick carousel. So, I set a variable to 0 and only run unslick after it changed

var slide = 0
if(slide>0)      
$('#ui-id-1').slick('unslick');

        $.ajax({
            //do stuff, here
        },
        success: function( data ) {

            $('#ui-id-1').slick();
            slide++;

        }

How to force a script reload and re-execute?

Small tweak to Luke's answer,

 function reloadJs(src) {
    src = $('script[src$="' + src + '"]').attr("src");
    $('script[src$="' + src + '"]').remove();
    $('<script/>').attr('src', src).appendTo('head');
}

and call it like,

reloadJs("myFile.js");

This will not have any path related issues.

TCPDF not render all CSS properties

In the first place, you should note that PDF and HTML and different formats that hardly have anything in common. If TCPDF allows you to provide input data using HTML and CSS it's because it implements a simple parser for these two languages and tries to figure out how to translate that into PDF. So it's logical that TCPDF only supports a little subset of the HTML and CSS specification and, even in supported stuff, it's probably not as perfect as in first class web browsers.

Said that, the question is: what's supported and what's not? The documentation basically skips the issue and let's you enjoy the trial and error method.

Having a look at the source code, we can see there's a protected method called TCPDF::getHtmlDomArray() that, among other things, parses CSS declarations. I can see stuff like font-family, list-style-type or text-indent but there's no margin or padding as far as I can see and, definitively, there's no float at all.

To sum up: with TCPDF, you can use CSS for some basic formatting. If you need to convert from HTML to PDF, it's the wrong tool. (If that's the case, may I suggest wkhtmltopdf?)

How do you remove the title text from the Android ActionBar?

i use this code in App manifest

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:logo="@drawable/logo2"
        android:label="@string/title_text"
        android:theme="@style/Theme.Zinoostyle" >

my logo file is 200*800 pixel and use this code in main activity.java

getActionBar().setDisplayShowTitleEnabled(false);

it will work Corectly

Options for embedding Chromium instead of IE WebBrowser control with WPF/C#

I have used Awesomium.NET. Although I don't like the fact that it's not open-source, and also the fact that it uses a pretty old Webkit rendering engine, it is really easy to use. That's about the only endorsement I can give it.

Why is PHP session_destroy() not working?

After using session_destroy(), the session is destroyed behind the scenes. For some reason this doesn't affect the values in $_SESSION, which was already populated for this request, but it will be empty in future requests.

You can manually clear $_SESSION if you so desire ($_SESSION = [];).

Unix command to check the filesize

ls -lh file.txt | awk '{ print $5 }'

Pass entire form as data in jQuery Ajax function

The other solutions didn't work for me. Maybe the old DOCTYPE in the project I am working on prevents HTML5 options.

My solution:

<form id="form_1" action="result.php" method="post"
 onsubmit="sendForm(this.id);return false">
    <input type="hidden" name="something" value="1">
</form>

js:

function sendForm(form_id){
    var form = $('#'+form_id);
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: $(form).serialize(),
        success: function(result) {
            console.log(result)
        }
    });
}

PHP salt and hash SHA256 for login password

These examples are from php.net. Thanks to you, I also just learned about the new php hashing functions.

Read the php documentation to find out about the possibilities and best practices: http://www.php.net/manual/en/function.password-hash.php

Save a password hash:

$options = [
    'cost' => 11,
];
// Get the password from post
$passwordFromPost = $_POST['password'];

$hash = password_hash($passwordFromPost, PASSWORD_BCRYPT, $options);

// Now insert it (with login or whatever) into your database, use mysqli or pdo!

Get the password hash:

// Get the password from the database and compare it to a variable (for example post)
$passwordFromPost = $_POST['password'];
$hashedPasswordFromDB = ...;

if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

Angular 2 filter/search list

This code nearly worked for me...but I wanted a multiple element filter so my mods to the filter pipe are below:

import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {

  transform(json: any[], args: any[]): any[] {
    const searchText = args[0];
    const jsonKey = args[1];
    let jsonKeyArray = [];

    if (searchText == null || searchText === 'undefined') { return json; }

    if (jsonKey.indexOf(',') > 0) {
        jsonKey.split(',').forEach( function(key) {
            jsonKeyArray.push(key.trim());
        });
    } else {
        jsonKeyArray.push(jsonKey.trim());
    }

    if (jsonKeyArray.length === 0) { return json; }

    // Start with new Array and push found objects onto it.
    let returnObjects = [];
    json.forEach( function ( filterObjectEntry ) {

        jsonKeyArray.forEach( function (jsonKeyValue) {
            if ( typeof filterObjectEntry[jsonKeyValue] !== 'undefined' &&
            filterObjectEntry[jsonKeyValue].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
                // object value contains the user provided text.
                returnObjects.push(filterObjectEntry);
                }
            });

    });
    return returnObjects;
  }
} 

Now, instead of

jsonFilterBy:[ searchText, 'name']

you can do

jsonFilterBy:[ searchText, 'name, other, other2...']

How do I run a program with commandline arguments using GDB within a Bash script?

gdb -ex=r --args myprogram arg1 arg2

-ex=r is short for -ex=run and tells gdb to run your program immediately, rather than wait for you to type "run" at the prompt. Then --args says that everything that follows is the command and arguments, just as you'd normally type them at the commandline prompt.

How to determine the IP address of a Solaris system

Try using ifconfig -a. Look for "inet xxx.xxx.xxx.xxx", that is your IP address

Eclipse copy/paste entire line keyboard shortcut

Ctrl+Alt+Down Copies current line to below like notepad++ (Ctrl+D)

If your whole screen is 180° rotted then you should disable your hotkey settings.

Right Click -> Graphics Options -> Hot Keys -> Disable

enter image description here

That it now you done try shortcut Ctrl+Alt+Down

Javascript how to parse JSON array

You should use a datastore and proxy in ExtJs. There are plenty of examples of this, and the JSON reader automatically parses the JSON message into the model you specified.

There is no need to use basic Javascript when using ExtJs, everything is different, you should use the ExtJs ways to get everything right. Read there documentation carefully, it's good.

By the way, these examples also hold for Sencha Touch (especially v2), which is based on the same core functions as ExtJs.

How do I give ASP.NET permission to write to a folder in Windows 7?

I know this is an old thread but to further expand the answer here, by default IIS 7.5 creates application pool identity accounts to run the worker process under. You can't search for these accounts like normal user accounts when adding file permissions. To add them into NTFS permission ACL you can type the entire name of the application pool identity and it will work.

It is just a slight difference in the way the application pool identity accounts are handle as they are seen to be virtual accounts.

Also the username of the application pool identity is "IIS AppPool\application pool name" so if it was the application pool DefaultAppPool the user account would be "IIS AppPool\DefaultAppPool".

These can be seen if you open computer management and look at the members of the local group IIS_IUSRS. The SID appended to the end of them is not need when adding the account into an NTFS permission ACL.

Hope that helps

How to get object length

For browsers supporting Object.keys() you can simply do:

Object.keys(a).length;

Otherwise (notably in IE < 9), you can loop through the object yourself with a for (x in y) loop:

var count = 0;
var i;

for (i in a) {
    if (a.hasOwnProperty(i)) {
        count++;
    }
}

The hasOwnProperty is there to make sure that you're only counting properties from the object literal, and not properties it "inherits" from its prototype.

Efficient way to do batch INSERTS with JDBC

How about using the INSERT ALL statement ?

INSERT ALL

INTO table_name VALUES ()

INTO table_name VALUES ()

...

SELECT Statement;

I remember that the last select statement is mandatory in order to make this request succeed. Don't remember why though. You might consider using PreparedStatement instead as well. lots of advantages !

Farid

json parsing error syntax error unexpected end of input

I've had the same error parsing a string containing \n into JSON. The solution was to use string.replace('\n','\\n')

Authentication plugin 'caching_sha2_password' cannot be loaded

Rolling back to the previous installations (to MySQL Community Server 5.7 and Workbench 6.1)and setting up new MySQL credentials worked for me!

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

To declare a function that takes a pointer to an int:

void Foo(int *x);

To use this function:


int x = 4;
int *x_ptr = &x;
Foo(x_ptr);
Foo(&x);

If you want a pointer for another type of object, it's much the same:

void Foo(Object *o);

But, you may prefer to use references. They are somewhat less confusing than pointers:


// pass a reference
void Foo(int &x)
{
  x = 2;
}

//pass a pointer
void Foo_p(int *p)
{
   *x = 9;
}

// pass by value
void Bar(int x)
{
   x = 7;
}
int x = 4;
Foo(x);  // x now equals 2.
Foo_p(&x); // x now equals 9.
Bar(x);  // x still equals 9.

With references, you still get to change the x that was passed to the function (as you would with a pointer), but you don't have to worry about dereferencing or address of operations.

As recommended by others, check out the C++FAQLite. It's an excellent resource for this.

Edit 3 response:

bar = &foo means: Make bar point to foo in memory

Yes.

*bar = foo means Change the value that bar points to to equal whatever foo equals

Yes.

If I have a second pointer (int *oof), then:

bar = oof means: bar points to the oof pointer

bar will point to whatever oof points to. They will both point to the same thing.

bar = *oof means: bar points to the value that oof points to, but not to the oof pointer itself

No. You can't do this (assuming bar is of type int *) You can make pointer pointers. (int **), but let's not get into that... You cannot assign a pointer to an int (well, you can, but that's a detail that isn't in line with the discussion).

*bar = *oof means: change the value that bar points to to the value that oof points to

Yes.

&bar = &oof means: change the memory address that bar points to be the same as the memory address that oof points to

No. You can't do this because the address of operator returns an rvalue. Basically, that means you can't assign something to it.

How to asynchronously call a method in Java

Java also provides a nice way of calling async methods. in java.util.concurrent we have ExecutorService that helps in doing the same. Initialize your object like this -

 private ExecutorService asyncExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

and then call the function like-

asyncExecutor.execute(() -> {

                        TimeUnit.SECONDS.sleep(3L);}

What is a constant reference? (not a reference to a constant)

First I think int&const icr=i; is just int& icr = i, Modifier 'const' makes no sense(It just means you cannot make the reference refer to other variable).

const int x = 10;
// int& const y = x; // Compiler error here

Second, constant reference just means you cannot change the value of variable through reference.

const int x = 10;
const int& y = x;
//y = 20; // Compiler error here

Third, Constant references can bind right-value. Compiler will create a temp variable to bind the reference.

float x = 10;
const int& y = x;
const int& z = y + 10;
cout << (long long)&x << endl; //print 348791766212
cout << (long long)&y << endl; //print 348791766276
cout << (long long)&z << endl; //print 348791766340

Concatenate in jQuery Selector

Your concatenation syntax is correct.

Most likely the callback function isn't even being called. You can test that by putting an alert(), console.log() or debugger line in that function.

If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail() handler after $.post() to find out what the error is, e.g.:

$.post('ajaxskeleton.php', {
    red: text       
}, function(){
    $('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(arguments);
});

How to get 30 days prior to current date?

You can do that simply through 1 line of code using moment in Node JS. :)

    let lastOneMonthDate = moment().subtract(30,"days").utc().toISOString()

Don't want UTC format, EASIER :P

    let lastOneMonthDate = moment().subtract(30,"days").toISOString()

Display more Text in fullcalendar

This code can help you :

$(document).ready(function() { 
    $('#calendar').fullCalendar({ 
        events: 
            [ 
                { 
                    id: 1, 
                    title: 'First Event', 
                    start: ..., 
                    end: ..., 
                    description: 'first description' 
                }, 
                { 
                    id: 2, 
                    title: 'Second Event', 
                    start: ..., 
                    end: ..., 
                    description: 'second description'
                }
            ], 
        eventRender: function(event, element) { 
            element.find('.fc-title').append("<br/>" + event.description); 
        } 
    });
}   

Enabling the OpenSSL in XAMPP

Yes, you must open php.ini and remove the semicolon to:

;extension=php_openssl.dll

If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext) and add this to php.ini in the "Dynamic Extensions" section:

extension=php_openssl.dll

Things have changed for PHP > 7. This is what i had to do for PHP 7.2.

Step: 1: Uncomment extension=openssl

Step: 2: Uncomment extension_dir = "ext"

Step: 3: Restart xampp.

Done.

Explanation: ( From php.ini )

If you wish to have an extension loaded automatically, use the following syntax:

extension=modulename

Note : The syntax used in previous PHP versions (extension=<ext>.so and extension='php_<ext>.dll) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>) syntax.

Special Note: Be sure to appropriately set the extension_dir directive.

C++ static virtual members?

I think what you're trying to do can be done through templates. I'm trying to read between the lines here. What you're trying to do is to call a method from some code, where it calls a derived version but the caller doesn't specify which class. Example:

class Foo {
public:
    void M() {...}
};

class Bar : public Foo {
public:
    void M() {...}
};

void Try()
{
    xxx::M();
}

int main()
{
    Try();
}

You want Try() to call the Bar version of M without specifying Bar. The way you do that for statics is to use a template. So change it like so:

class Foo {
public:
    void M() {...}
};

class Bar : public Foo {
public:
    void M() {...}
};

template <class T>
void Try()
{
    T::M();
}

int main()
{
    Try<Bar>();
}

Build not visible in itunes connect

Check your all privacy access policy option in Info.plist file.

How to read a config file using python

In order to use my example,Your file "abc.txt" needs to look like:

[your-config]
path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"

Then in your software you can use the config parser:

import ConfigParser

and then in you code:

 configParser = ConfigParser.RawConfigParser()   
 configFilePath = r'c:\abc.txt'
 configParser.read(configFilePath)

Use case:

self.path = configParser.get('your-config', 'path1')

*Edit (@human.js)

in python 3, ConfigParser is renamed to configparser (as described here)

Floating point exception

It's caused by n % x where x = 0 in the first loop iteration. You can't calculate a modulus with respect to 0.

Node.js: what is ENOSPC error and how to solve?

Can't take credit for this, but @grenade pointed out that npm dedupe will fix the cause (too many files) and not the symptom.

Source: Grunt watch error - Waiting…Fatal error: watch ENOSPC.

How to use subList()

To get the last element, simply use the size of the list as the second parameter. So for example, if you have 35 files, and you want the last five, you would do:

dataList.subList(30, 35);

A guaranteed safe way to do this is:

dataList.subList(Math.max(0, first), Math.min(dataList.size(), last) );

Oracle: how to add minutes to a timestamp?

In addition to being able to add a number of days to a date, you can use interval data types assuming you are on Oracle 9i or later, which can be somewhat easier to read,

SQL> ed
Wrote file afiedt.buf
SELECT sysdate, sysdate + interval '30' minute FROM dual
SQL> /

SYSDATE              SYSDATE+INTERVAL'30'
-------------------- --------------------
02-NOV-2008 16:21:40 02-NOV-2008 16:51:40

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

Also, if your service is sending an object instead of an array add isArray:false to its declaration.

'query': {method: 'GET', isArray: false }

Find a value in DataTable

Maybe you can filter rows by possible columns like this :

DataRow[] filteredRows = 
  datatable.Select(string.Format("{0} LIKE '%{1}%'", columnName, value));

How do I find the distance between two points?

dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )

As others have pointed out, you can also use the equivalent built-in math.hypot():

dist = math.hypot(x2 - x1, y2 - y1)

How do I get the last character of a string using an Excel function?

Just another way to do this:

=MID(A1, LEN(A1), 1)

The difference between Classes, Objects, and Instances

Class is a template or type. An object is an instance of the class.

For example:

public class Tweet {

}

Tweet newTweet = new Tweet();

Tweet is a class and newTweet is an object of the class.

Spring Boot how to hide passwords in properties file

In case you are using quite popular in Spring Boot environment Kubernetes (K8S) or OpenShift, there's a possibility to store and retrieve application properties on runtime. This technique called secrets. In your configuration yaml file for Kubernetes or OpenShift you declare variable and placeholder for it, and on K8S\OpenShift side declare actual value which corresponds to this placeholder. For implementation details, see: K8S: https://kubernetes.io/docs/concepts/configuration/secret/ OpenShift: https://docs.openshift.com/container-platform/3.11/dev_guide/secrets.html

Default instance name of SQL Server Express

Should be .\SQLExpress or localhost\SQLExpress no $ sign at the end

See also here http://www.connectionstrings.com/sql-server-2008

PostgreSQL delete all content

For small tables DELETE is often faster and needs less aggressive locking (for heavy concurrent load):

DELETE FROM tbl;

With no WHERE condition.

For medium or bigger tables, go with TRUNCATE tbl, like @Greg posted.

How to find day of week in php in a specific timezone

Thanks a lot guys for your quick comments.

This is what i will be using now. Posting the function here so that somebody may use it.

public function getDayOfWeek($pTimezone)
{

    $userDateTimeZone = new DateTimeZone($pTimezone);
    $UserDateTime = new DateTime("now", $userDateTimeZone);

    $offsetSeconds = $UserDateTime->getOffset(); 
    //echo $offsetSeconds;

    return gmdate("l", time() + $offsetSeconds);

}

Report if you find any corrections.

Grab a segment of an array in Java without creating a new array on heap

Java references always point to an object. The object has a header that amongst other things identifies the concrete type (so casts can fail with ClassCastException). For arrays, the start of the object also includes the length, the data then follows immediately after in memory (technically an implementation is free to do what it pleases, but it would be daft to do anything else). So, you can;t have a reference that points somewhere into an array.

In C pointers point anywhere and to anything, and you can point to the middle of an array. But you can't safely cast or find out how long the array is. In D the pointer contains an offset into the memory block and length (or equivalently a pointer to the end, I can't remember what the implementation actually does). This allows D to slice arrays. In C++ you would have two iterators pointing to the start and end, but C++ is a bit odd like that.

So getting back to Java, no you can't. As mentioned, NIO ByteBuffer allows you to wrap an array and then slice it, but gives an awkward interface. You can of course copy, which is probably very much faster than you would think. You could introduce your own String-like abstraction that allows you to slice an array (the current Sun implementation of String has a char[] reference plus a start offset and length, higher performance implementation just have the char[]). byte[] is low level, but any class-based abstraction you put on that is going to make an awful mess of the syntax, until JDK7 (perhaps).

Jquery - How to get the style display attribute "none / block"

You could try:

$j('div.contextualError.ckgcellphone').css('display')

Catch browser's "zoom" event in JavaScript

According to MDN, "matchMedia" is the proper way to do this https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio#Monitoring_screen_resolution_or_zoom_level_changes

it's a bit finicky because each instance can only watch one MQ at a time, so if you're interested in any zoom level change you need to make a bunch of matchers.. but since the browser is in charge to emitting the events it's probably still more performant than polling, and you could throttle or debounce the callback or pin it to an animation frame or something - here's an implementation that seems pretty snappy, feel free to swap in _throttle or whatever if you're already depending on that.

Run the code snippet and zoom in and out in your browser, note the updated value in the markup - I only tested this in Firefox! lemme know if you see any issues.

_x000D_
_x000D_
const el = document.querySelector('#dppx')_x000D_
_x000D_
if ('matchMedia' in window) {_x000D_
  function observeZoom(cb, opts) {_x000D_
    opts = {_x000D_
      // first pass for defaults - range and granularity to capture all the zoom levels in desktop firefox_x000D_
      ceiling: 3,_x000D_
      floor: 0.3,_x000D_
      granularity: 0.05,_x000D_
      ...opts_x000D_
    }_x000D_
    const precision = `${opts.granularity}`.split('.')[1].length_x000D_
_x000D_
    let val = opts.floor_x000D_
    const vals = []_x000D_
    while (val <= opts.ceiling) {_x000D_
      vals.push(val)_x000D_
      val = parseFloat((val + opts.granularity).toFixed(precision))_x000D_
    }_x000D_
_x000D_
    // construct a number of mediamatchers and assign CB to all of them_x000D_
    const mqls = vals.map(v => matchMedia(`(min-resolution: ${v}dppx)`))_x000D_
_x000D_
    // poor person's throttle_x000D_
    const throttle = 3_x000D_
    let last = performance.now()_x000D_
    mqls.forEach(mql => mql.addListener(function() {_x000D_
      console.debug(this, arguments)_x000D_
      const now = performance.now()_x000D_
      if (now - last > throttle) {_x000D_
        cb()_x000D_
        last = now_x000D_
      }_x000D_
    }))_x000D_
  }_x000D_
_x000D_
  observeZoom(function() {_x000D_
    el.innerText = window.devicePixelRatio_x000D_
  })_x000D_
} else {_x000D_
  el.innerText = 'unable to observe zoom level changes, matchMedia is not supported'_x000D_
}
_x000D_
<div id='dppx'>--</div>
_x000D_
_x000D_
_x000D_

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

Goto Advanced tab----> data type of column---> Here change data type from DT_STR to DT_TEXT and column width 255. Now you can check it will work perfectly.

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

How do you run a Python script as a service in Windows?

A complete pywin32 example using loop or subthread

After working on this on and off for a few days, here is the answer I would have wished to find, using pywin32 to keep it nice and self contained.

This is complete working code for one loop-based and one thread-based solution. It may work on both python 2 and 3, although I've only tested the latest version on 2.7 and Win7. The loop should be good for polling code, and the tread should work with more server-like code. It seems to work nicely with the waitress wsgi server that does not have a standard way to shut down gracefully.

I would also like to note that there seems to be loads of examples out there, like this that are almost useful, but in reality misleading, because they have cut and pasted other examples blindly. I could be wrong. but why create an event if you never wait for it?

That said I still feel I'm on somewhat shaky ground here, especially with regards to how clean the exit from the thread version is, but at least I believe there are nothing misleading here.

To run simply copy the code to a file and follow the instructions.

update:

Use a simple flag to terminate thread. The important bit is that "thread done" prints.
For a more elaborate example exiting from an uncooperative server thread see my post about the waitress wsgi server.

# uncomment mainthread() or mainloop() call below
# run without parameters to see HandleCommandLine options
# install service with "install" and remove with "remove"
# run with "debug" to see print statements
# with "start" and "stop" watch for files to appear
# check Windows EventViever for log messages

import socket
import sys
import threading
import time
from random import randint
from os import path

import servicemanager
import win32event
import win32service
import win32serviceutil
# see http://timgolden.me.uk/pywin32-docs/contents.html for details


def dummytask_once(msg='once'):
    fn = path.join(path.dirname(__file__),
                '%s_%s.txt' % (msg, randint(1, 10000)))
    with open(fn, 'w') as fh:
        print(fn)
        fh.write('')


def dummytask_loop():
    global do_run
    while do_run:
        dummytask_once(msg='loop')
        time.sleep(3)


class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        global do_run
        do_run = True
        print('thread start\n')
        dummytask_loop()
        print('thread done\n')

    def exit(self):
        global do_run
        do_run = False


class SMWinservice(win32serviceutil.ServiceFramework):
    _svc_name_ = 'PyWinSvc'
    _svc_display_name_ = 'Python Windows Service'
    _svc_description_ = 'An example of a windows service in Python'

    @classmethod
    def parse_command_line(cls):
        win32serviceutil.HandleCommandLine(cls)

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.stopEvt = win32event.CreateEvent(None, 0, 0, None)  # create generic event
        socket.setdefaulttimeout(60)

    def SvcStop(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                            servicemanager.PYS_SERVICE_STOPPED,
                            (self._svc_name_, ''))
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.stopEvt)  # raise event

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                            servicemanager.PYS_SERVICE_STARTED,
                            (self._svc_name_, ''))
        # UNCOMMENT ONE OF THESE
        # self.mainthread()
        # self.mainloop()

    # Wait for stopEvt indefinitely after starting thread.
    def mainthread(self):
        print('main start')
        self.server = MyThread()
        self.server.start()
        print('wait for win32event')
        win32event.WaitForSingleObject(self.stopEvt, win32event.INFINITE)
        self.server.exit()
        print('wait for thread')
        self.server.join()
        print('main done')

    # Wait for stopEvt event in loop.
    def mainloop(self):
        print('loop start')
        rc = None
        while rc != win32event.WAIT_OBJECT_0:
            dummytask_once()
            rc = win32event.WaitForSingleObject(self.stopEvt, 3000)
        print('loop done')


if __name__ == '__main__':
    SMWinservice.parse_command_line()

What is the purpose of mvnw and mvnw.cmd files?

By far the best option nowadays would be using a maven container as a builder tool. A mvn.sh script like this would be enough:

#!/bin/bash
docker run --rm -ti \
 -v $(pwd):/opt/app \
 -w /opt/app \
 -e TERM=xterm \
 -v $HOME/.m2:/root/.m2 \
 maven mvn "$@"

Call ASP.NET function from JavaScript?

The __doPostBack() method works well.

Another solution (very hackish) is to simply add an invisible ASP button in your markup and click it with a JavaScript method.

<div style="display: none;">
   <asp:Button runat="server" ... OnClick="ButtonClickHandlerMethod" />
</div>

From your JavaScript, retrieve the reference to the button using its ClientID and then call the .click() method on it.

var button = document.getElementById(/* button client id */);

button.click();

Selenium Webdriver: Entering text into text field

It might be the JavaScript check for some valid condition.
Two things you can perform a/c to your requirements:

  1. either check for the valid string-input in the text-box.
  2. or set a loop against that text box to enter the value until you post the form/request.
String barcode="0000000047166";

WebElement strLocator = driver.findElement(By.xpath("//*[@id='div-barcode']"));
strLocator.sendKeys(barcode);

How to create a link to another PHP page

echo "<a href='index.php'>Index Page</a>";

if you wanna use html tag like anchor tag you have to put in echo

CodeIgniter Active Record not equal

This should work (which you have tried)

$this->db->where_not_in('emailsToCampaigns.campaignId', $campaignId);

Get the cell value of a GridView row

string id;
foreach (GridViewRow rows in grd.Rows)
{
   TextBox lblStrucID = (TextBox)rows.FindControl("grdtext");
   id=lblStrucID.Text
}

JavaScript click event listener on class

This should work. getElementsByClassName returns an array Array-like object(see edit) of the elements matching the criteria.

var elements = document.getElementsByClassName("classname");

var myFunction = function() {
    var attribute = this.getAttribute("data-myattribute");
    alert(attribute);
};

for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener('click', myFunction, false);
}

jQuery does the looping part for you, which you need to do in plain JavaScript.

If you have ES6 support you can replace your last line with:

    Array.from(elements).forEach(function(element) {
      element.addEventListener('click', myFunction);
    });

Note: Older browsers (like IE6, IE7, IE8) don´t support getElementsByClassName and so they return undefined.


EDIT : Correction

getElementsByClassName doesnt return an array, but a HTMLCollection in most, or a NodeList in some browsers (Mozilla ref). Both of these types are Array-Like, (meaning that they have a length property and the objects can be accessed via their index), but are not strictly an Array or inherited from an Array. (meaning other methods that can be performed on an Array cannot be performed on these types)

Thanks to user @Nemo for pointing this out and having me dig in to fully understand.

Head and tail in one line

For O(1) complexity of head,tail operation you should use deque however.

Following way:

from collections import deque
l = deque([1,2,3,4,5,6,7,8,9])
head, tail = l.popleft(), l

It's useful when you must iterate through all elements of the list. For example in naive merging 2 partitions in merge sort.

Which type of folder structure should be used with Angular 2?

I think structuring the project by functionalities is a practical method. It makes the project scalable and maintainable easily. And it makes each part of the project working in a total autonomy. Let me know what you think about this structure below: ANGULAR TYPESCRIPT PROJECT STRUCTURE – ANGULAR 2

source : http://www.angulartypescript.com/angular-typescript-project-structure/

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

An explicit call to a parent class constructor is required any time the parent class lacks a no-argument constructor. You can either add a no-argument constructor to the parent class or explicitly call the parent class constructor in your child class.

unable to remove file that really exists - fatal: pathspec ... did not match any files

In my instance, there was something completely odd that I'm not sure what the cause was. An entire folder was committed previously. I could see it in Git, Windows Explorer, and GitHub, but any changes I made to the folder itself and the files in it were ignored. Using git check-ignore to see what was ignoring it, and attempting to remove it using git rm --cached had no impact. The changes were not able to be staged.

I fixed it by:

  1. Making a copy of the folder and files in another location.
  2. I deleted the original that was getting ignored somehow.
  3. Commit and push this update.
  4. Finally, I added the files and folder back and git was seeing and reacting to it as expected again.
  5. Stage and commit this, and you're good to go! :)

When to Redis? When to MongoDB?

And you should use neither if you have plenty of RAM. Redis and MongoDB come to the price of a general purpose tool. This introduce a lot of overhead.

There was the saying that Redis is 10 times faster than Mongo. That might not be that true anymore. MongoDB (if i remember correctly) claimed to beat memcache for storing and caching documents as long as the memory configurations are the same.

Anyhow. Redis good, MongoDB is good. If you care about substructures and need aggregation go for MongoDB. If storing keys and values is your main concern its all about Redis. (or any other key value store).

Timeout a command in bash without unnecessary delay

There you go:

timeout --signal=SIGINT 10 /path/to/slow command with options

you may change the SIGINT and 10 as you desire ;)

How to get the seconds since epoch from the time + date output of gmtime()?

ep = datetime.datetime(1970,1,1,0,0,0)
x = (datetime.datetime.utcnow()- ep).total_seconds()

This should be different from int(time.time()), but it is safe to use something like x % (60*60*24)

datetime — Basic date and time types:

Unlike the time module, the datetime module does not support leap seconds.

Spring Boot Multiple Datasource

I think you can find it usefull

http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources

It shows how to define multiple datasources & assign one of them as primary.

Here is a rather full example, also contains distributes transactions - if you need it.

http://fabiomaffioletti.me/blog/2014/04/15/distributed-transactions-multiple-databases-spring-boot-spring-data-jpa-atomikos/

What you need is to create 2 configuration classes, separate the model/repository packages etc to make the config easy.

Also, in above example, it creates the data sources manually. You can avoid this using the method on spring doc, with @ConfigurationProperties annotation. Here is an example of this:

http://xantorohara.blogspot.com.tr/2013/11/spring-boot-jdbc-with-multiple.html

Hope these helps.

jQuery Call to WebService returns "No Transport" error

For me it is an entirely different story.
Since this page has a good search engine ranking, I should add my case and the solution here too.

I built jquery myself with webpack picking only the modules I use. The ajax is always failed with "No Transport" message as the only clue.

After a long debugging, the problem turns out to be XMLHttpRequest is pluggable in jquery and it not include by default.

You have to explicitly include jquery/src/ajax/xhr file in order to make the ajax working in browsers.

Best way to create enum of strings?

Use its name() method:

public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Strings.ONE.name());
    }
}

enum Strings {
    ONE, TWO, THREE
}

yields ONE.

Android statusbar icons color

@eOnOe has answered how we can change status bar tint through xml. But we can also change it dynamically in code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    View decor = getWindow().getDecorView();
    if (shouldChangeStatusBarTintToDark) {
        decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
    } else {
        // We want to change tint color to white again.
        // You can also record the flags in advance so that you can turn UI back completely if
        // you have set other flags before, such as translucent or full screen.
        decor.setSystemUiVisibility(0);
    }
}

How to run a PowerShell script

  1. Launch Windows PowerShell, and wait a moment for the PS command prompt to appear
  2. Navigate to the directory where the script lives

    PS> cd C:\my_path\yada_yada\ (enter)
    
  3. Execute the script:

    PS> .\run_import_script.ps1 (enter)
    

What am I missing??

Or: you can run the PowerShell script from cmd.exe like this:

powershell -noexit "& ""C:\my_path\yada_yada\run_import_script.ps1""" (enter)

according to this blog post here

Or you could even run your PowerShell script from your C# application :-)

Asynchronously execute PowerShell scripts from your C# application

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

How to capture a list of specific type with mockito

Yeah, this is a general generics problem, not mockito-specific.

There is no class object for ArrayList<SomeType>, and thus you can't type-safely pass such an object to a method requiring a Class<ArrayList<SomeType>>.

You can cast the object to the right type:

Class<ArrayList<SomeType>> listClass =
              (Class<ArrayList<SomeType>>)(Class)ArrayList.class;
ArgumentCaptor<ArrayList<SomeType>> argument = ArgumentCaptor.forClass(listClass);

This will give some warnings about unsafe casts, and of course your ArgumentCaptor can't really differentiate between ArrayList<SomeType> and ArrayList<AnotherType> without maybe inspecting the elements.

(As mentioned in the other answer, while this is a general generics problem, there is a Mockito-specific solution for the type-safety problem with the @Captor annotation. It still can't distinguish between an ArrayList<SomeType> and an ArrayList<OtherType>.)

Edit:

Take also a look at tenshis comment. You can change the original code from Paulo Ebermann to this (much simpler)

final ArgumentCaptor<List<SomeType>> listCaptor
        = ArgumentCaptor.forClass((Class) List.class);

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

Make Enable32bit Application to TRUE in the IIS App pool which you are consuming

How do I show my global Git configuration?

Git 2.6 (Sept/Oct 2015) will add the option --name-only to simplify the output of a git config -l:

See commit a92330d, commit f225987, commit 9f1429d (20 Aug 2015) by Jeff King (peff).
See commit ebca2d4 (20 Aug 2015), and commit 905f203, commit 578625f (10 Aug 2015) by SZEDER Gábor (szeder).
(Merged by Junio C Hamano -- gitster -- in commit fc9dfda, 31 Aug 2015)

config: add '--name-only' option to list only variable names

'git config' can only show values or name-value pairs, so if a shell script needs the names of set config variables it has to run 'git config --list' or '--get-regexp' and parse the output to separate config variable names from their values.
However, such a parsing can't cope with multi-line values.

Though 'git config' can produce null-terminated output for newline-safe parsing, that's of no use in such a case, because shells can't cope with null characters.

Even our own bash completion script suffers from these issues.

Help the completion script, and shell scripts in general, by introducing the '--name-only' option to modify the output of '--list' and '--get-regexp' to list only the names of config variables, so they don't have to perform error-prone post processing to separate variable names from their values anymore.

Getting the Username from the HKEY_USERS values

If you look at either of the following keys:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\hivelist

You can find a list of the SIDs there with various values, including where their "home paths" which includes their usernames.

I'm not sure how dependable this is and I wouldn't recommend messing about with this unless you're really sure what you're doing.

Android Fragment onClick button Method

Another option may be to have your fragment implement View.OnClickListener and override onClick(View v) within your fragment. If you need to have your fragment talk to the activity simply add an interface with desired method(s) and have the activity implement the interface and override its method(s).

public class FragName extends Fragment implements View.OnClickListener { 
    public FragmentCommunicator fComm;
    public ImageButton res1, res2;
    int c;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_test, container, false);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            fComm = (FragmentCommunicator) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement FragmentCommunicator");
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        res1 = (ImageButton) getActivity().findViewById(R.id.responseButton1);
        res1.setOnClickListener(this);
        res2 = (ImageButton) getActivity().findViewById(R.id.responseButton2);
        res2.setOnClickListener(this);
    }
    public void onClick(final View v) { //check for what button is pressed
            switch (v.getId()) {
                case R.id.responseButton1:
                  c *= fComm.fragmentContactActivity(2);
                  break;
                case R.id.responseButton2:
                  c *= fComm.fragmentContactActivity(4);
                  break;
                default:
                  c *= fComm.fragmentContactActivity(100);
                  break;
    }
    public interface FragmentCommunicator{
        public int fragmentContactActivity(int b);
    }



public class MainActivity extends FragmentActivity implements FragName.FragmentCommunicator{
    int a = 10;
    //variable a is update by fragment. ex. use to change textview or whatever else you'd like.

    public int fragmentContactActivity(int b) {
        //update info on activity here
        a += b;
        return a;
    }
}

http://developer.android.com/training/basics/firstapp/starting-activity.html http://developer.android.com/training/basics/fragments/communicating.html

How to create an installer for a .net Windows Service using Visual Studio

I follow Kelsey's first set of steps to add the installer classes to my service project, but instead of creating an MSI or setup.exe installer I make the service self installing/uninstalling. Here's a bit of sample code from one of my services you can use as a starting point.

public static int Main(string[] args)
{
    if (System.Environment.UserInteractive)
    {
        // we only care about the first two characters
        string arg = args[0].ToLowerInvariant().Substring(0, 2);

        switch (arg)
        {
            case "/i":  // install
                return InstallService();

            case "/u":  // uninstall
                return UninstallService();

            default:  // unknown option
                Console.WriteLine("Argument not recognized: {0}", args[0]);
                Console.WriteLine(string.Empty);
                DisplayUsage();
                return 1;
        }
    }
    else
    {
        // run as a standard service as we weren't started by a user
        ServiceBase.Run(new CSMessageQueueService());
    }

    return 0;
}

private static int InstallService()
{
    var service = new MyService();

    try
    {
        // perform specific install steps for our queue service.
        service.InstallService();

        // install the service with the Windows Service Control Manager (SCM)
        ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
    }
    catch (Exception ex)
    {
        if (ex.InnerException != null && ex.InnerException.GetType() == typeof(Win32Exception))
        {
            Win32Exception wex = (Win32Exception)ex.InnerException;
            Console.WriteLine("Error(0x{0:X}): Service already installed!", wex.ErrorCode);
            return wex.ErrorCode;
        }
        else
        {
            Console.WriteLine(ex.ToString());
            return -1;
        }
    }

    return 0;
}

private static int UninstallService()
{
    var service = new MyQueueService();

    try
    {
        // perform specific uninstall steps for our queue service
        service.UninstallService();

        // uninstall the service from the Windows Service Control Manager (SCM)
        ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
    }
    catch (Exception ex)
    {
        if (ex.InnerException.GetType() == typeof(Win32Exception))
        {
            Win32Exception wex = (Win32Exception)ex.InnerException;
            Console.WriteLine("Error(0x{0:X}): Service not installed!", wex.ErrorCode);
            return wex.ErrorCode;
        }
        else
        {
            Console.WriteLine(ex.ToString());
            return -1;
        }
    }

    return 0;
}

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

C# DLL config file

Since the assembly resides in a temporary cache, you should combine the path to get the dll's config:

var appConfig = ConfigurationManager.OpenExeConfiguration(
    Path.Combine(Environment.CurrentDirectory, Assembly.GetExecutingAssembly().ManifestModule.Name));

format a Date column in a Data Frame

The data.table package has its IDate class and functionalities similar to lubridate or the zoo package. You could do:

dt = data.table(
  Name = c('Joe', 'Amy', 'John'),
  JoiningDate = c('12/31/09', '10/28/09', '05/06/10'),
  AmtPaid = c(1000, 100, 200)
)

require(data.table)
dt[ , JoiningDate := as.IDate(JoiningDate, '%m/%d/%y') ]

How can I invert color using CSS?

I think the only way to handle this is to use JavaScript

Try this Invert text color of a specific element

If you do this with css3 it's only compatible with the newest browser versions.

Arrays.fill with multidimensional array in Java

how can I fill a multidimensional array in Java without using a loop?

Multidimensional arrays are just arrays of arrays and fill(...) doesn't check the type of the array and the value you pass in (this responsibility is upon the developer).

Thus you can't fill a multidimensional array reasonably well without using a loop.

Be aware of the fact that, unlike languages like C or C++, Java arrays are objects and in multidimensional arrays all but the last level contain references to other Array objects. I'm not 100% sure about this, but most likely they are distributed in memory, thus you can't just fill a contiguous block without a loop, like C/C++ would allow you to do.

SQL query to make all data in a column UPPER CASE?

Permanent:

UPDATE
  MyTable
SET
  MyColumn = UPPER(MyColumn)

Temporary:

SELECT
  UPPER(MyColumn) AS MyColumn
FROM
  MyTable

Java, Calculate the number of days between two dates

Well to start with, you should only deal with them as strings when you have to. Most of the time you should work with them in a data type which actually describes the data you're working with.

I would recommend that you use Joda Time, which is a much better API than Date/Calendar. It sounds like you should use the LocalDate type in this case. You can then use:

int days = Days.daysBetween(date1, date2).getDays();

How to align title at center of ActionBar in default theme(Theme.Holo.Light)

I know my answer is not on time but this is purely code no xml required.
This is for use in Activity

public void setTitle(String title){
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    TextView textView = new TextView(this);
    textView.setText(title);
    textView.setTextSize(20);
    textView.setTypeface(null, Typeface.BOLD);
    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    textView.setGravity(Gravity.CENTER);
    textView.setTextColor(getResources().getColor(R.color.white));
    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    getSupportActionBar().setCustomView(textView);
}


This is for use in Fragment

public void setTitle(String title){
    ((AppCompatActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    TextView textView = new TextView(getActivity());
    textView.setText(title);
    textView.setTextSize(20);
    textView.setTypeface(null, Typeface.BOLD);
    textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    textView.setGravity(Gravity.CENTER);
    textView.setTextColor(getResources().getColor(R.color.white));
    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    ((AppCompatActivity)getActivity()).getSupportActionBar().setCustomView(textView);
}

DateTimePicker time picker in 24 hour but displaying in 12hr?

'DD/MM/YYYY hh:mm A' => 12 hours 'DD/MM/YYYY HH:mm A' => 24 hours

Count work days between two dates

I found the below TSQL a fairly elegant solution (I don't have permissions to run functions). I found the DATEDIFF ignores DATEFIRST and I wanted my first day of the week to be a Monday. I also wanted the first working day to be set a zero and if it falls on a weekend Monday will be a zero. This may help someone who has a slightly different requirement :)

It does not handle bank holidays

SET DATEFIRST 1
SELECT
,(DATEDIFF(DD,  [StartDate], [EndDate]))        
-(DATEDIFF(wk,  [StartDate], [EndDate]))        
-(DATEDIFF(wk, DATEADD(dd,-@@DATEFIRST,[StartDate]), DATEADD(dd,-@@DATEFIRST,[EndDate]))) AS [WorkingDays] 
FROM /*Your Table*/ 

Android: Create a toggle button with image and no text

create toggle_selector.xml in res/drawable

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/toggle_on" android:state_checked="true"/>
  <item android:drawable="@drawable/toggle_off" android:state_checked="false"/>
</selector>

apply the selector to your toggle button

<ToggleButton
            android:id="@+id/chkState"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/toggle_selector"
            android:textOff=""
            android:textOn=""/>

Note: for removing the text i used following in above code

textOff=""
textOn=""

Remove a child with a specific attribute, in SimpleXML for PHP

For future reference, deleting nodes with SimpleXML can be a pain sometimes, especially if you don't know the exact structure of the document. That's why I have written SimpleDOM, a class that extends SimpleXMLElement to add a few convenience methods.

For instance, deleteNodes() will delete all nodes matching a XPath expression. And if you want to delete all nodes with the attribute "id" equal to "A5", all you have to do is:

// don't forget to include SimpleDOM.php
include 'SimpleDOM.php';

// use simpledom_load_string() instead of simplexml_load_string()
$data = simpledom_load_string(
    '<data>
        <seg id="A1"/>
        <seg id="A5"/>
        <seg id="A12"/>
        <seg id="A29"/>
        <seg id="A30"/>
    </data>'
);

// and there the magic happens
$data->deleteNodes('//seg[@id="A5"]');

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

following lines works for me. I am using mac 10.7.2 .

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

SQL query to select distinct row with minimum value

Try:

select id, game, min(point) from t
group by id 

CURRENT_DATE/CURDATE() not working as default DATE value

I have the current latest version of MySQL: 8.0.20

So my table name is visit, my column name is curdate.

alter table visit modify curdate date not null default (current_date);

This writes the default date value with no timestamp.

Better way to revert to a previous SVN revision of a file?

svn merge will merge revisions, not revert them. i.e. if you have some addition in your HEAD version then merge that with a previous revision, then the change will persist.

I use svn cat then redirect it into the file:

svn cat -r 851 l3toks.dtx > l3toks.dtx

Then you have the 851 content in that file and can check it back in.

if arguments is equal to this string, define a variable like this string

It seems that you are looking to parse commandline arguments into your bash script. I have searched for this recently myself. I came across the following which I think will assist you in parsing the arguments:

http://rsalveti.wordpress.com/2007/04/03/bash-parsing-arguments-with-getopts/

I added the snippet below as a tl;dr

#using : after a switch variable means it requires some input (ie, t: requires something after t to validate while h requires nothing.
while getopts “ht:r:p:v” OPTION
do
     case $OPTION in
         h)
             usage
             exit 1
             ;;
         t)
             TEST=$OPTARG
             ;;
         r)
             SERVER=$OPTARG
             ;;
         p)
             PASSWD=$OPTARG
             ;;
         v)
             VERBOSE=1
             ;;
         ?)
             usage
             exit
             ;;
     esac
done

if [[ -z $TEST ]] || [[ -z $SERVER ]] || [[ -z $PASSWD ]]
then
     usage
     exit 1
fi

./script.sh -t test -r server -p password -v

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

View's SELECT contains a subquery in the FROM clause

create view view_clients_credit_usage as
    select client_id, sum(credits_used) as credits_used 
    from credit_usage 
    group by client_id

create view view_credit_status as 
    select 
        credit_orders.client_id, 
        sum(credit_orders.number_of_credits) as purchased, 
        ifnull(t1.credits_used,0) as used 
    from credit_orders
    left outer join view_clients_credit_usage as t1 on t1.client_id = credit_orders.client_id
    where credit_orders.payment_status='Paid'
    group by credit_orders.client_id)

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

I got the same exact error with In case it helps others .. documenting what worked for me useful for very latest (Jan 14, 2017) latest everything. Tried all the Invalidate, build clean, even deleting .gradle/, tweaking the support libs etc.. on multiple stack overflow answers.

I found that upgrading the settings.gradle gradle version fixed it (it was 2.1.3) something in gradle toolchain seems to classpath 'com.android.tools.build:gradle:2.2.3'

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

import java.io.*;
class Initials {

    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s;
        char x;
        int l;
        System.out.print("Enter any sentence: ");
        s = br.readLine();
        s = " " + s; //adding a space infront of the inputted sentence or a name
        s = s.toUpperCase(); //converting the sentence into Upper Case (Capital Letters)
        l = s.length(); //finding the length of the sentence
        System.out.print("Output = ");

        for (int i = 0; i < l; i++) {
            x = s.charAt(i); //taking out one character at a time from the sentence
            if (x == ' ') //if the character is a space, printing the next Character along with a fullstop
                System.out.print(s.charAt(i + 1) + ".");
        }
    }
}

Get all directories within directory nodejs

use fs?path module can got the folder. this use Promise. If your will get the fill, your can change isDirectory() to isFile() Nodejs--fs--fs.Stats.At last, you can get the file'name file'extname and so on Nodejs---Path

var fs = require("fs"),
path = require("path");
//your <MyFolder> path
var p = "MyFolder"
fs.readdir(p, function (err, files) {
    if (err) {
        throw err;
    }
    //this can get all folder and file under  <MyFolder>
    files.map(function (file) {
        //return file or folder path, such as **MyFolder/SomeFile.txt**
        return path.join(p, file);
    }).filter(function (file) {
        //use sync judge method. The file will add next files array if the file is directory, or not. 
        return fs.statSync(file).isDirectory();
    }).forEach(function (files) {
        //The files is array, so each. files is the folder name. can handle the folder.
        console.log("%s", files);
    });
});

How to call gesture tap on UIView programmatically in swift

Swift 4

let tap = UITapGestureRecognizer(target: self, action: #selector(self.touchTapped(_:)))
    self.view.addGestureRecognizer(tap)

@objc func touchTapped(_ sender: UITapGestureRecognizer) {
}

@UniqueConstraint annotation in Java

@UniqueConstraint this annotation is used for annotating single or multiple unique keys at the table level separated by comma, which is why you get an error. it will only work if you let JPA create your tables

Example

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder(builderClassName = "Builder", toBuilder = true)
@Entity
@Table(name = "users", uniqueConstraints = @UniqueConstraint(columnNames = {"person_id", "company_id"}))
public class AppUser extends BaseEntity {

    @Column(name = "person_id")
    private Long personId;

    @ManyToOne
    @JoinColumn(name = "company_id")
    private Company company;
}

https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/UniqueConstraint.html

On the other hand To ensure a field value is unique you can write

@Column(unique=true)
String username;

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

I also encountered this exception with error message,

java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(Unknown Source)
at sun.nio.cs.StreamEncoder.implWrite(Unknown Source)
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at java.io.OutputStreamWriter.write(Unknown Source)
at java.io.BufferedWriter.flushBuffer(Unknown Source)
at java.io.BufferedWriter.write(Unknown Source)
at java.io.Writer.write(Unknown Source)

and found that some strange bug occurs when trying to use

BufferedWriter writer = Files.newBufferedWriter(Paths.get(filePath));

to write a String "orazg 54" cast from a generic type in a class.

//key is of generic type <Key extends Comparable<Key>>
writer.write(item.getKey() + "\t" + item.getValue() + "\n");

This String is of length 9 containing chars with the following code points:

111 114 97 122 103 9 53 52 10

However, if the BufferedWriter in the class is replaced with:

FileOutputStream outputStream = new FileOutputStream(filePath);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));

it can successfully write this String without exceptions. In addition, if I write the same String create from the characters it still works OK.

String string = new String(new char[] {111, 114, 97, 122, 103, 9, 53, 52, 10});
BufferedWriter writer = Files.newBufferedWriter(Paths.get("a.txt"));
writer.write(string);
writer.close();

Previously I have never encountered any Exception when using the first BufferedWriter to write any Strings. It's a strange bug that occurs to BufferedWriter created from java.nio.file.Files.newBufferedWriter(path, options)

Python `if x is not None` or `if not x is None`?

Personally, I use

if not (x is None):

which is understood immediately without ambiguity by every programmer, even those not expert in the Python syntax.

Check if a string contains a substring in SQL Server 2005, using a stored procedure

You can just use wildcards in the predicate (after IF, WHERE or ON):

@mainstring LIKE '%' + @substring + '%'

or in this specific case

' ' + @mainstring + ' ' LIKE '% ME[., ]%'

(Put the spaces in the quoted string if you're looking for the whole word, or leave them out if ME can be part of a bigger word).

How to filter JSON Data in JavaScript or jQuery?

Try this way, allow you even filter by other key

data:

var my_data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},
{"name":"Lenovo Thinkpad 41A2222","website":"google"},
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},
{"name":"Lenovo Thinkpad 41A424448","website":"google"},
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}];

usage:

//We do that to ensure to get a correct JSON
var my_json = JSON.stringify(my_data)
//We can use {'name': 'Lenovo Thinkpad 41A429ff8'} as criteria too
var filtered_json = find_in_object(JSON.parse(my_json), {website: 'yahoo'});

filter function

function find_in_object(my_object, my_criteria){

  return my_object.filter(function(obj) {
    return Object.keys(my_criteria).every(function(c) {
      return obj[c] == my_criteria[c];
    });
  });

}

Does Java support structs?

Java doesn't have an analog to C++'s structs, but you can use classes with all public members.

How to change the status bar background color and text color on iOS 7?

Swift 4:

// Change status bar background color

let statusBar = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView

statusBar?.backgroundColor = UIColor.red

Check if event exists on element

I ended up doing this

typeof ($('#mySelector').data('events').click) == "object"

Python update a key in dict if it doesn't exist

With the following you can insert multiple values and also have default values but you're creating a new dictionary.

d = {**{ key: value }, **default_values}

I've tested it with the most voted answer and on average this is faster as it can be seen in the following example, .

Speed test comparing a for loop based method with a dict comprehension with unpack operator Speed test comparing a for loop based method with a dict comprehension with unpack operator method.

if no copy (d = default_vals.copy()) is made on the first case then the most voted answer would be faster once we reach orders of magnitude of 10**5 and greater. Memory footprint of both methods are the same.

Why does python use 'else' after for and while loops?

I think documentation has a great explanation of else, continue

[...] it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement."

Source: Python 2 docs: Tutorial on control flow

How to Handle Button Click Events in jQuery?

 $("#btnSubmit").click(function(){
        alert("button");
    });    

TypeScript or JavaScript type casting

In typescript it is possible to do an instanceof check in an if statement and you will have access to the same variable with the Typed properties.

So let's say MarkerSymbolInfo has a property on it called marker. You can do the following:

if (symbolInfo instanceof MarkerSymbol) {
    // access .marker here
    const marker = symbolInfo.marker
}

It's a nice little trick to get the instance of a variable using the same variable without needing to reassign it to a different variable name.

Check out these two resources for more information:

TypeScript instanceof & JavaScript instanceof

How can I start PostgreSQL on Windows?

After a lot of search and tests i found the solution : if you are in windows :

1 - first you must found the PG databases directory execute the command as sql command in pgAdmin query tools

$ show data_directory;

result :

------------------------
- D:/PG_DATA/data      -
------------------------

2 - go to the bin directory of postgres in my case it's located "c:/programms/postgresSql/bin"

and open a command prompt (CMD) and execute this command :

pg_ctl -D "D:\PSG_SQL\data" restart

This should do it.

File path issues in R using Windows ("Hex digits in character string" error)

The best way to deal with this in case of txt file which contains data for text mining (speech, newsletter, etc.) is to replace "\" with "/".

Example:

file<-Corpus(DirSource("C:/Users/PRATEEK/Desktop/training tool/Text Analytics/text_file_main"))

How to capture Curl output to a file?

curl -K myconfig.txt -o output.txt 

Writes the first output received in the file you specify (overwrites if an old one exists).

curl -K myconfig.txt >> output.txt

Appends all output you receive to the specified file.

Note: The -K is optional.

How do I get the n-th level parent of an element in jQuery?

Depends on your needs, if you know what parent your looking for you can use the .parents() selector.

E.G: http://jsfiddle.net/HenryGarle/Kyp5g/2/

<div id="One">
    <div id="Two">
        <div id="Three">
            <div id="Four">

            </div>
        </div>
    </div>
</div>


var top = $("#Four").parents("#One");

alert($(top).html());

Example using index:

//First parent - 2 levels up from #Four
// I.e Selects div#One
var topTwo = $("#Four").parents().eq(2);

alert($(topTwo ).html());

Show image using file_get_contents

You can do that, or you can use the readfile function, which outputs it for you:

header('Content-Type: image/x-png'); //or whatever
readfile('thefile.png');
die();

Edit: Derp, fixed obvious glaring typo.

What is the difference between DTR/DSR and RTS/CTS flow control?

An important difference is that some UARTs (16550 notably) will stop receiving characters immediately if their host instructs them to set DSR to be inactive. In contrast, characters will still be received if CTS is inactive. I believe that the intention here is that DSR indicates that the device is no longer listening and so sending any further characters is pointless, while CTS indicates that a buffer is getting full; the latter allows for a certain amount of 'skid' where the flow control line changed state between the DTE sampling it and the next character being transmitted. In (relatively) later devices that support a hardware FIFO it's possible that a number of characters could be transmitted after the DCE has set CTS to be inactive.

Google Chrome "window.open" workaround?

Why is this still so complicated in 2021? For me I wanted to open in a new chrome window fullscreen so I used the below:

window.open("http://my.url.com", "", "fullscreen=yes");

This worked as exepected opening a new chrome window. Without the options at the end it will only open a new tab

Why do package names often begin with "com"

Wikipedia, of all places, actually discusses this.

The idea is to make sure all package names are unique world-wide, by having authors use a variant of a DNS name they own to name the package. For example, the owners of the domain name joda.org created a number of packages whose names begin with org.joda, for example:

  • org.joda.time
  • org.joda.time.base
  • org.joda.time.chrono
  • org.joda.time.convert
  • org.joda.time.field
  • org.joda.time.format

How to construct a relative path in Java from two absolute paths (or URLs)?

If Paths is not available for JRE 1.5 runtime or maven plugin

package org.afc.util;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

public class FileUtil {

    public static String getRelativePath(String basePath, String filePath)  {
        return getRelativePath(new File(basePath), new File(filePath));
    }

    public static String getRelativePath(File base, File file)  {

        List<String> bases = new LinkedList<String>();
        bases.add(0, base.getName());
        for (File parent = base.getParentFile(); parent != null; parent = parent.getParentFile()) {
            bases.add(0, parent.getName());
        }

        List<String> files = new LinkedList<String>();
        files.add(0, file.getName());
        for (File parent = file.getParentFile(); parent != null; parent = parent.getParentFile()) {
            files.add(0, parent.getName());
        }

        int overlapIndex = 0;
        while (overlapIndex < bases.size() && overlapIndex < files.size() && bases.get(overlapIndex).equals(files.get(overlapIndex))) {
            overlapIndex++;
        }

        StringBuilder relativePath = new StringBuilder();
        for (int i = overlapIndex; i < bases.size(); i++) {
            relativePath.append("..").append(File.separatorChar);
        }

        for (int i = overlapIndex; i < files.size(); i++) {
            relativePath.append(files.get(i)).append(File.separatorChar);
        }

        relativePath.deleteCharAt(relativePath.length() - 1);
        return relativePath.toString();
    }

}

What is SuppressWarnings ("unchecked") in Java?

One trick is to create an interface that extends a generic base interface...

public interface LoadFutures extends Map<UUID, Future<LoadResult>> {}

Then you can check it with instanceof before the cast...

Object obj = context.getAttribute(FUTURES);
if (!(obj instanceof LoadFutures)) {
    String format = "Servlet context attribute \"%s\" is not of type "
            + "LoadFutures. Its type is %s.";
    String msg = String.format(format, FUTURES, obj.getClass());
    throw new RuntimeException(msg);
}
return (LoadFutures) obj;

How to compare numbers in bash?

If you have floats you can write a function and then use that e.g.

#!/bin/bash

function float_gt() {
    perl -e "{if($1>$2){print 1} else {print 0}}"
}

x=3.14
y=5.20
if [ $(float_gt $x $y) == 1 ] ; then
    echo "do stuff with x"
else
    echo "do stuff with y"
fi

JQuery Parsing JSON array

Use the parseJSON method:

var json = '["City1","City2","City3"]';
var arr = $.parseJSON(json);

Then you have an array with the city names.

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

If using Nginx and getting a similar problem, then this might help:

Scan your domain on this sslTesturl, and see if the connection is allowed for your device version.

If lower version devices(like < Android 4.4.2 etc) are not able to connect due to TLS support, then try adding this to your Nginx config file,

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

Decimal precision and scale in EF Code First

I had a nice time creating an Custom Attribute for this:

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class DecimalPrecisionAttribute : Attribute
{
    public DecimalPrecisionAttribute(byte precision, byte scale)
    {
        Precision = precision;
        Scale = scale;

    }

    public byte Precision { get; set; }
    public byte Scale { get; set; }

}

using it like this

[DecimalPrecision(20,10)]
public Nullable<decimal> DeliveryPrice { get; set; }

and the magic happens at model creation with some reflection

protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
    foreach (Type classType in from t in Assembly.GetAssembly(typeof(DecimalPrecisionAttribute)).GetTypes()
                                   where t.IsClass && t.Namespace == "YOURMODELNAMESPACE"
                                   select t)
     {
         foreach (var propAttr in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<DecimalPrecisionAttribute>() != null).Select(
                p => new { prop = p, attr = p.GetCustomAttribute<DecimalPrecisionAttribute>(true) }))
         {

             var entityConfig = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(classType).Invoke(modelBuilder, null);
             ParameterExpression param = ParameterExpression.Parameter(classType, "c");
             Expression property = Expression.Property(param, propAttr.prop.Name);
             LambdaExpression lambdaExpression = Expression.Lambda(property, true,
                                                                      new ParameterExpression[]
                                                                          {param});
             DecimalPropertyConfiguration decimalConfig;
             if (propAttr.prop.PropertyType.IsGenericType && propAttr.prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
             {
                 MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[7];
                 decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
             }
             else
             {
                 MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[6];
                 decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
             }

             decimalConfig.HasPrecision(propAttr.attr.Precision, propAttr.attr.Scale);
        }
    }
}

the first part is to get all classes in the model (my custom attribute is defined in that assembly so i used that to get the assembly with the model)

the second foreach gets all properties in that class with the custom attribute, and the attribute itself so i can get the precision and scale data

after that i have to call

modelBuilder.Entity<MODEL_CLASS>().Property(c=> c.PROPERTY_NAME).HasPrecision(PRECISION,SCALE);

so i call the modelBuilder.Entity() by reflection and store it in the entityConfig variable then i build the "c => c.PROPERTY_NAME" lambda expression

After that, if the decimal is nullable i call the

Property(Expression<Func<TStructuralType, decimal?>> propertyExpression) 

method (i call this by the position in the array, it's not ideal i know, any help will be much appreciated)

and if it's not nullable i call the

Property(Expression<Func<TStructuralType, decimal>> propertyExpression)

method.

Having the DecimalPropertyConfiguration i call the HasPrecision method.

Replace new line/return with space using regex

The new line separator is different for different OS-es - '\r\n' for Windows and '\n' for Linux.

To be safe, you can use regex pattern \R - the linebreak matcher introduced with Java 8:

String inlinedText = text.replaceAll("\\R", " ");

What's the difference between utf8_general_ci and utf8_unicode_ci?

This post describes it very nicely.

In short: utf8_unicode_ci uses the Unicode Collation Algorithm as defined in the Unicode standards, whereas utf8_general_ci is a more simple sort order which results in "less accurate" sorting results.

Laravel migration table field's type change

First composer requires doctrine/dbal, then:

$table->longText('column_name')->change();

Bootstrap: align input with button

Bootstrap 5

<div class="input-group">
  <input type="text" class="form-control">
  <button class="btn btn-outline-secondary" type="button">Go</button>
</div>

Bootstrap 3 & 4

you may use the input-group button property to apply the button direct to the input-field.

<div class="input-group">
  <input type="text" class="form-control">
  <span class="input-group-btn">
    <button class="btn btn-default" type="button">Go!</button>
  </span>
</div><!-- /input-group -->

Take a look at BS4 or BS5 Input-Group doc for many more examples.

example for bs3 input group button

Find duplicate characters in a String and count the number of occurances using Java

import java.io.*;
public class CountChar 
{

    public static void main(String[] args) throws IOException
    {
      String ch;
      BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
      System.out.print("Enter the Statement:");
      ch=br.readLine();
      int count=0,len=0;
        do
        {  
          try
          {
          char name[]=ch.toCharArray();
              len=name.length;
              count=0;
              for(int j=0;j<len;j++)
               {
                  if((name[0]==name[j])&&((name[0]>=65&&name[0]<=91)||(name[0]>=97&&name[0]<=123))) 
                      count++;
               }
              if(count!=0)
                System.out.println(name[0]+" "+count+" Times");
              ch=ch.replace(""+name[0],"");          
          }
          catch(Exception ex){}
        }
        while(len!=1);
   }

}

Output

Enter the Statement:asdf23123sfsdf

a 1 Times

s 3 Times

d 2 Times

f 3 Times

Div vertical scrollbar show

Always : If you always want vertical scrollbar, use overflow-y: scroll;

jsFiddle:

<div style="overflow-y: scroll;">
......
</div>

When needed: If you only want vertical scrollbar when needed, use overflow-y: auto; (You need to specify a height in this case)

jsFiddle:

<div style="overflow-y: auto; height:150px; ">
....
</div>

Docker: Container keeps on restarting again on again

I had forgot Minikube running in background and thats what always restarted them back up

How to find out the MySQL root password

thanks to @thusharaK I could reset the root password without knowing the old password.

On ubuntu I did the following:

sudo service mysql stop
sudo mysqld_safe --skip-grant-tables --skip-syslog --skip-networking

Then run mysql in a new terminal:

mysql -u root

And run the following queries to change the password:

UPDATE mysql.user SET authentication_string=PASSWORD('password') WHERE User='root';
FLUSH PRIVILEGES;

In MySQL 5.7, the password field in mysql.user table field was removed, now the field name is 'authentication_string'.

Quit the mysql safe mode and start mysql service by:

mysqladmin shutdown
sudo service mysql start

How can I get a list of locally installed Python modules?

help('modules')

in a Python shell/prompt.

how to define variable in jquery

Here's are some examples:

var name = 'india';
alert(name);  


var name = $("#txtname").val();
alert(name);

Taken from http://way2finder.blogspot.in/2013/09/how-to-create-variable-in-jquery.html

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

Oracle SELECT TOP 10 records

try

SELECT * FROM users FETCH NEXT 10 ROWS ONLY;

python pandas convert index to datetime

Doing

df.index = pd.to_datetime(df.index, errors='coerce')

the data type of the index has changed to

dataframe information

How to apply bold text style for an entire row using Apache POI?

A worked, completed and simple example:

package io.github.baijifeilong.excel;

import lombok.SneakyThrows;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

/**
 * Created by [email protected] at 2019/12/6 11:41
 */
public class ExcelBoldTextDemo {

    @SneakyThrows
    public static void main(String[] args) {

        new XSSFWorkbook() {{
            XSSFRow row = createSheet().createRow(0);
            row.setRowStyle(createCellStyle());
            row.getRowStyle().getFont().setBold(true);
            row.createCell(0).setCellValue("Alpha");
            row.createCell(1).setCellValue("Beta");
            row.createCell(2).setCellValue("Gamma");
        }}.write(new FileOutputStream("demo.xlsx"));
    }
}

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

Here is a simple approach which will print the 2 different elapsed time for each query.

DECLARE @t1 DATETIME;
DECLARE @t2 DATETIME;

SET @t1 = GETDATE();
SELECT DISTINCT u.profession FROM users u; --Query with DISTINCT
SET @t2 = GETDATE();
PRINT 'Elapsed time (ms): ' + CAST(DATEDIFF(millisecond, @t1, @t2) AS varchar);

SET @t1 = GETDATE();
SELECT u.profession FROM users u GROUP BY u.profession; --Query with GROUP BY
SET @t2 = GETDATE();
PRINT 'Elapsed time (ms): ' + CAST(DATEDIFF(millisecond, @t1, @t2) AS varchar);

OR try SET STATISTICS TIME (Transact-SQL)

SET STATISTICS TIME ON;
SELECT DISTINCT u.profession FROM users u; --Query with DISTINCT
SELECT u.profession FROM users u GROUP BY u.profession; --Query with GROUP BY
SET STATISTICS TIME OFF;

It simply displays the number of milliseconds required to parse, compile, and execute each statement as below:

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 2 ms.

Disabling vertical scrolling in UIScrollView

From iOS11 one can use the following property

let frameLayoutGuide: UILayoutGuide

If you set constraints for frameLayoutGuide.topAnchor and frameLayoutGuide.bottomAnchor to the same anchors of some subview of your scrollView then vertical scroll will be disabled and the height of the scrollView will be equal to the height of its subview.

Where are static methods and static variables stored in Java?

It is stored in the heap referenced by the class definition. If you think about it, it has nothing to do with stack because there is no scope.

Skip rows during csv import pandas

skip[1] will skip second line, not the first one.

How to find out whether a file is at its `eof`?

fp.read() reads up to the end of the file, so after it's successfully finished you know the file is at EOF; there's no need to check. If it cannot reach EOF it will raise an exception.

When reading a file in chunks rather than with read(), you know you've hit EOF when read returns less than the number of bytes you requested. In that case, the following read call will return the empty string (not None). The following loop reads a file in chunks; it will call read at most once too many.

assert n > 0
while True:
    chunk = fp.read(n)
    if chunk == '':
        break
    process(chunk)

Or, shorter:

for chunk in iter(lambda: fp.read(n), ''):
    process(chunk)

Set adb vendor keys

In this case what you can do is : Go in developer options on the device Uncheck "USB Debugging" then check it again A confirmation box should then appear DvxWifiScan

Find a line in a file and remove it

public static void deleteLine(String line, String filePath) {

    File file = new File(filePath);

    File file2 = new File(file.getParent() + "\\temp" + file.getName());
    PrintWriter pw = null;
    Scanner read = null;

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel src = null;
    FileChannel dest = null;

    try {


        pw = new PrintWriter(file2);
        read = new Scanner(file);

        while (read.hasNextLine()) {

            String currline = read.nextLine();

            if (line.equalsIgnoreCase(currline)) {
                continue;
            } else {
                pw.println(currline);
            }
        }

        pw.flush();

        fis = new FileInputStream(file2);
        src = fis.getChannel();
        fos = new FileOutputStream(file);
        dest = fos.getChannel();

        dest.transferFrom(src, 0, src.size());


    } catch (IOException e) {
        e.printStackTrace();
    } finally {     
        pw.close();
        read.close();

        try {
            fis.close();
            fos.close();
            src.close();
            dest.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (file2.delete()) {
            System.out.println("File is deleted");
        } else {
            System.out.println("Error occured! File: " + file2.getName() + " is not deleted!");
        }
    }

}

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

How can I build for release/distribution on the Xcode 4?

To set the build configuration to Debug or Release, choose 'Edit Scheme' from the 'Product' menu.

Then you see a clear choice.

The Apple Transition Guide mentions a button at the top left of the Xcode screen, but I cannot see it in Xcode 4.3.

Eloquent get only one column as an array

If you receive multiple entries the correct method is called lists.

    Word_relation::select('word_two')->where('word_one', $word_id)->lists('word_one')->toArray();

How to get an MD5 checksum in PowerShell

Another built-in command that's long been installed in Windows by default dating back to 2003 is Certutil, which of course can be invoked from PowerShell, too.

CertUtil -hashfile file.foo MD5

(Caveat: MD5 should be in all caps for maximum robustness)

How can I make a weak protocol reference in 'pure' Swift (without @objc)

You need to declare the type of the protocol as AnyObject.

protocol ProtocolNameDelegate: AnyObject {
    // Protocol stuff goes here
}

class SomeClass {
    weak var delegate: ProtocolNameDelegate?
}

Using AnyObject you say that only classes can conform to this protocol, whereas structs or enums can't.

How to pass multiple parameters in a querystring

I use the AbsoluteUri and you can get it like this:

string myURI = Request.Url.AbsoluteUri;
 if (!WebSecurity.IsAuthenticated) {
        Response.Redirect("~/Login?returnUrl="
            + Request.Url.AbsoluteUri );

Then after you login:

var returnUrl = Request.QueryString["returnUrl"];
 if(WebSecurity.Login(username,password,true)){
                Context.RedirectLocal(returnUrl);

It works well for me.

The POM for project is missing, no dependency information available

Change:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

To:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

The groupId of net.sourceforge was incorrect. The correct value is net.sourceforge.ant4x.

best way to get the key of a key/value javascript object

// iterate through key-value gracefully
const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
}

Refer MDN

How do AX, AH, AL map onto EAX?

| 0000 0001 0010 0011 0100 0101 0110 0111 | ------> EAX

|                     0100 0101 0110 0111 | ------> AX

|                               0110 0111 | ------> AL

|                     0100 0101           | ------> AH

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

I had similar issue due to a small mistake, when i was trying to convert a List to json. If a List is converted to json it will return JSONArray not JSONObject.

How to set xlim and ylim for a subplot in matplotlib

You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*.

plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.

import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])


ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

and so on for as many axes as you want.

or better, wrap it all up in a loop:

import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

Eclipse keyboard shortcut to indent source code to the left?

On Mac (on french keyboard its) cmd + shift + F

Video streaming over websockets using JavaScript

Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?

Yes.. it is, take a look at this project. Websockets can easily handle HD videostreaming.. However, you should go for Adaptive Streaming. I explain here how you could implement it.

Currently we're working on a webbased instant messaging application with chat, filesharing and video/webcam support. With some bits and tricks we got streaming media through websockets (used HTML5 Media Capture to get the stream from our webcams).

You need to build a stream API and a Media Stream Transceiver to control the related media processing and transport.

Check if string ends with one of the strings from a list

another way which can return the list of matching strings is

sample = "alexis has the control"
matched_strings = filter(sample.endswith, ["trol", "ol", "troll"])
print matched_strings
['trol', 'ol']

Process to convert simple Python script into Windows executable

You could create an installer for you EXE file by:
1. Press WinKey + R
2. Type "iexpress" (without quotes) into the run window
3. Complete the wizard for creating the installation program.
4. Distribute the completed EXE.

MVVM Passing EventArgs As Command Parameter

I've always come back here for the answer so I wanted to make a short simple one to go to.

There are multiple ways of doing this:

1. Using WPF Tools. Easiest.

Add Namespaces:

  • System.Windows.Interactivitiy
  • Microsoft.Expression.Interactions

XAML:

Use the EventName to call the event you want then specify your Method name in the MethodName.

<Window>
    xmlns:wi="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions">

    <wi:Interaction.Triggers>
        <wi:EventTrigger EventName="SelectionChanged">
            <ei:CallMethodAction
                TargetObject="{Binding}"
                MethodName="ShowCustomer"/>
        </wi:EventTrigger>
    </wi:Interaction.Triggers>
</Window>

Code:

public void ShowCustomer()
{
    // Do something.
}

2. Using MVVMLight. Most difficult.

Install GalaSoft NuGet package.

enter image description here

Get the namespaces:

  • System.Windows.Interactivity
  • GalaSoft.MvvmLight.Platform

XAML:

Use the EventName to call the event you want then specify your Command name in your binding. If you want to pass the arguments of the method, mark PassEventArgsToCommand to true.

<Window>
    xmlns:wi="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:cmd="http://www.galasoft.ch/mvvmlight">

    <wi:Interaction.Triggers>
       <wi:EventTrigger EventName="Navigated">
           <cmd:EventToCommand Command="{Binding CommandNameHere}"
               PassEventArgsToCommand="True" />
       </wi:EventTrigger>
    </wi:Interaction.Triggers>
</Window>

Code Implementing Delegates: Source

You must get the Prism MVVM NuGet package for this.

enter image description here

using Microsoft.Practices.Prism.Commands;

// With params.
public DelegateCommand<string> CommandOne { get; set; }
// Without params.
public DelegateCommand CommandTwo { get; set; }

public MainWindow()
{
    InitializeComponent();

    // Must initialize the DelegateCommands here.
    CommandOne = new DelegateCommand<string>(executeCommandOne);
    CommandTwo = new DelegateCommand(executeCommandTwo);
}

private void executeCommandOne(string param)
{
    // Do something here.
}

private void executeCommandTwo()
{
    // Do something here.
}

Code Without DelegateCommand: Source

using GalaSoft.MvvmLight.CommandWpf

public MainWindow()
{
    InitializeComponent();

    CommandOne = new RelayCommand<string>(executeCommandOne);
    CommandTwo = new RelayCommand(executeCommandTwo);
}

public RelayCommand<string> CommandOne { get; set; }

public RelayCommand CommandTwo { get; set; }

private void executeCommandOne(string param)
{
    // Do something here.
}

private void executeCommandTwo()
{
    // Do something here.
}

3. Using Telerik EventToCommandBehavior. It's an option.

You'll have to download it's NuGet Package.

XAML:

<i:Interaction.Behaviors>
    <telerek:EventToCommandBehavior
         Command="{Binding DropCommand}"
         Event="Drop"
         PassArguments="True" />
</i:Interaction.Behaviors>

Code:

public ActionCommand<DragEventArgs> DropCommand { get; private set; }

this.DropCommand = new ActionCommand<DragEventArgs>(OnDrop);

private void OnDrop(DragEventArgs e)
{
    // Do Something
}

What is middleware exactly?

Simply put Middleware is a software component which provides services to integrate disparate systems together.

In an complex enterprise environment, there are a number of challenges when you need to integrate two or more enterprise systems together to talk to each other. Normally these systems do not understand each others language as they are developed on different platforms using different languages (like C++, Java, Cobol, etc.).

So here comes middleware software in picture which provides services like

  • transformation of messages formats from one app to other,
  • routing and enriching messages besides taking care of security,
  • encryption,
  • validation and
  • applying different business rules to these messages.

A typical example of middleware is an ESB products like IBM message broker (WMB/IIB), WESB, Datapower XI50, Oracle Fusion, Mule and many others.

Therefore, middleware sits mostly in between the service consuming apps and services provider apps and help these apps to talk to each other.

Uncaught SyntaxError: Unexpected token < On Chrome

header("Location: route_to_main_page");

I've encountered this problem while having a custom 404 error handling file. Instead of throwing some html content it was suppose to redirect to the main page url. It worked well.

Then I used this as a skeleton for a next project, therefore not changing the "route_to_main_page" actually on the new project (different URL) became a "route_to_external_url" so any 404 errors within your code (missing css stylesheets, js libraries) would return the "Uncaught SyntaxError: Unexpected token <".

Entity Framework and Connection Pooling

According to Daniel Simmons:

Create a new ObjectContext instance in a Using statement for each service method so that it is disposed of before the method returns. This step is critical for scalability of your service. It makes sure that database connections are not kept open across service calls and that temporary state used by a particular operation is garbage collected when that operation is over. The Entity Framework automatically caches metadata and other information it needs in the app domain, and ADO.NET pools database connections, so re-creating the context each time is a quick operation.

This is from his comprehensive article here:

http://msdn.microsoft.com/en-us/magazine/ee335715.aspx

I believe this advice extends to HTTP requests, so would be valid for ASP.NET. A stateful, fat-client application such as a WPF application might be the only case for a "shared" context.

How to search a list of tuples in Python

[i for i, v in enumerate(L) if v[0] == 53]

mysql query order by multiple items

SELECT id, user_id, video_name
FROM sa_created_videos
ORDER BY LENGTH(id) ASC, LENGTH(user_id) DESC

Reverse colormap in matplotlib

As of Matplotlib 2.0, there is a reversed() method for ListedColormap and LinearSegmentedColorMap objects, so you can just do

cmap_reversed = cmap.reversed()

Here is the documentation.

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

You have to load the url helper to access that function. Either you add

$this->load->helper('url');

somewhere in your controller.

Alternately, to have it be loaded automatically everywhere, make sure the line in application/config/autoload.php that looks like

$autoload['helper'] = array('url');

has 'url' in that array (as shown above).

Angular2 Routing with Hashtag to page anchor

Adding on to Kalyoyan's answer, this subscription is tied to the router and will live until the page is fully refreshed. When subscribing to router events in a component, be sure to unsubscribe in ngOnDestroy:

import { OnDestroy } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Subscription } from "rxjs/Rx";

class MyAppComponent implements OnDestroy {

  private subscription: Subscription;

  constructor(router: Router) {
    this.subscription = router.events.subscribe(s => {
      if (s instanceof NavigationEnd) {
        const tree = router.parseUrl(router.url);
        if (tree.fragment) {
          const element = document.querySelector("#" + tree.fragment);
          if (element) { element.scrollIntoView(element); }
        }
      }
    });
  }

  public ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Clearing localStorage in javascript?

window.localStorage.clear(); //try this to clear all local storage

Adding 30 minutes to time formatted as H:i in PHP

Your current solution does not work because $time is a string - it needs to be a Unix timestamp. You can do this instead:

$unix_time = strtotime('January 1 2010 '.$time); // create a unix timestamp
$startTime date( "H:i", strtotime('-30 minutes', $unix_time) );
$endTime date( "H:i", strtotime('+30 minutes', $unix_time) );

How to fix Python Numpy/Pandas installation?

If you're like me and you don't like the idea of deleting things that were part of the standard system installation (which others have suggested) then you might like the solution I ended up using:

  1. Get Homebrew - it's a one-line shell script to install!
  2. Edit your .profile, or whatever is appropriate, and put /usr/local/bin at the start of your PATH so that Homebrew binaries are found before system binaries
  3. brew install python - this installs a newer version of python in /usr/local
  4. pip install pandas

This worked for me in OS X 10.8.2, and I can't see any reason it shouldn't work in 10.6.8.

What is the GAC in .NET?

GAC (Global Assembly Cache) is where all shared .NET assembly reside.

How to get Enum Value from index in Java?

I just tried the same and came up with following solution:

public enum Countries {
    TEXAS,
    FLORIDA,
    OKLAHOMA,
    KENTUCKY;

    private static Countries[] list = Countries.values();

    public static Countries getCountry(int i) {
        return list[i];
    }

    public static int listGetLastIndex() {
        return list.length - 1;
    }
}

The class has it's own values saved inside an array, and I use the array to get the enum at indexposition. As mentioned above arrays begin to count from 0, if you want your index to start from '1' simply change these two methods to:

public static String getCountry(int i) {
    return list[(i - 1)];
}

public static int listGetLastIndex() {
    return list.length;
}

Inside my Main I get the needed countries-object with

public static void main(String[] args) {
   int i = Countries.listGetLastIndex();
   Countries currCountry = Countries.getCountry(i);
}

which sets currCountry to the last country, in this case Countries.KENTUCKY.

Just remember this code is very affected by ArrayOutOfBoundsExceptions if you're using hardcoded indicies to get your objects.

Currency formatting in Python

Not quite sure why it's not mentioned more online (or on this thread), but the Babel package (and Django utilities) from the Edgewall guys is awesome for currency formatting (and lots of other i18n tasks). It's nice because it doesn't suffer from the need to do everything globally like the core Python locale module.

The example the OP gave would simply be:

>>> import babel.numbers
>>> import decimal
>>> babel.numbers.format_currency( decimal.Decimal( "188518982.18" ), "GBP" )
£188,518,982.18

Calendar Recurring/Repeating Events - Best Storage Method

While the proposed solutions work, I was trying to implement with Full Calendar and it would require over 90 database calls for each view (as it loads current, previous, and next month), which, I wasn't too thrilled about.

I found an recursion library https://github.com/tplaner/When where you simply store the rules in the database and one query to pull all the relevant rules.

Hopefully this will help someone else, as I spent so many hours trying to find a good solution.

Edit: This Library is for PHP

Delete item from array and shrink array

object[] newarray = new object[oldarray.Length-1];

for(int x=0; x < array.Length; x++)
{
  if(!(array[x] == value_of_array_to_delete))
  // if(!(x == array_index_to_delete))
   {
     newarray[x] = oldarray[x];
   }
}

There is no way to downsize an array after it is created, but you can copy the contents to another array of a lesser size.

Element-wise addition of 2 lists?

I haven't timed it but I suspect this would be pretty quick:

import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]

list_sum = (np.add(list1, list2)).tolist()

[5, 7, 9]

How can I view the shared preferences file using Android Studio?

This is an old post, but I though I should put a graphical answer here as the question is about viewing the SharedPreferences.xml using Android Studio. So here it goes.

Go to the Tools -> Android Device Monitor. Open the device monitor by clicking it.

enter image description here

Then you need to select the File Explorer tab in the device monitor. Find the data folder and find another data folder inside it. It will contain a folder having the name of your application package and there will be the desired SharedPreferences.xml.

enter image description here

Select the SharedPreferences.xml file and then pull and save the file in your computer using the button marked at the top-right corner of the image above.

I've used a device emulator.

Is there an "exists" function for jQuery?

this is very similar to all of the answers, but why not use the ! operator twice so you can get a boolean:

jQuery.fn.exists = function(){return !!this.length};

if ($(selector).exists()) {
    // the element exists, now what?...
}

ASP.NET MVC Razor pass model to layout

A common solution is to make a base view model which contains the properties used in the layout file and then inherit from the base model to the models used on respective pages.

The problem with this approach is that you now have locked yourself into the problem of a model can only inherit from one other class, and maybe your solution is such that you cannot use inheritance on the model you intended anyways.

My solution also starts of with a base view model:

public class LayoutModel
{
    public LayoutModel(string title)
    {
        Title = title;
    }

    public string Title { get;}
}

What I then use is a generic version of the LayoutModel which inherits from the LayoutModel, like this:

public class LayoutModel<T> : LayoutModel
{
    public LayoutModel(T pageModel, string title) : base(title)
    {
        PageModel = pageModel;
    }

    public T PageModel { get; }
}

With this solution I have disconnected the need of having inheritance between the layout model and the model.

So now I can go ahead and use the LayoutModel in Layout.cshtml like this:

@model LayoutModel
<!doctype html>
<html>
<head>
<title>@Model.Title</title>
</head>
<body>
@RenderBody()
</body>
</html>

And on a page you can use the generic LayoutModel like this:

@model LayoutModel<Customer>
@{
    var customer = Model.PageModel;
}

<p>Customer name: @customer.Name</p>

From your controller you simply return a model of type LayoutModel:

public ActionResult Page()
{
    return View(new LayoutModel<Customer>(new Customer() { Name = "Test" }, "Title");
}

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

Multi value Dictionary

I think this is quite overkill for a dictionary semantics, since dictionary is by definition is a collection of keys and its respective values, just like the way we see a book of language dictionary that contains a word as the key and its descriptive meaning as the value.

But you can represent a dictionary that can contain collection of values, for example:

Dictionary<String,List<Customer>>

Or a dictionary of a key and the value as a dictionary:

Dictionary<Customer,Dictionary<Order,OrderDetail>>

Then you'll have a dictionary that can have multiple values.

How can I select item with class within a DIV?

If you want to select every element that has class attribute "myclass" use

$('#mydiv .myclass');

If you want to select only div elements that has class attribute "myclass" use

$("div#mydiv div.myclass");

find more about jquery selectors refer these articles

Convert UTC Epoch to local date

Epoch time (i.e. Unix Epoch time) is nearly always the number of seconds that have expired since 1st Jan 1970 00:00:00 (UTC time), not the number of milliseconds which some of the answers here have implied.

https://en.wikipedia.org/wiki/Unix_time

Therefore, if you have been given a Unix Epoch time value it will probably be in seconds, and will look something like 1547035195. If you want to make this human readable in JavaScript, you need to convert the value to milliseconds, and pass that value into the Date(value) constructor, e.g.:

const unixEpochTimeMS = 1547035195 * 1000;
const d = new Date(unixEpochTimeMS);
// Careful, the string output here can vary by implementation...
const strDate = d.toLocaleString();

You don't need to do the d.setUTCMilliseconds(0) step in the accepted answer because the JavaScript Date(value) constructor takes a UTC value in milliseconds (not a local time).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax

Also note that you should avoid using the Date(...) constructor that takes a string datetime representation, this is not recommended (see the link above).

Refresh Page and Keep Scroll Position

this will do the magic

    <script>
        document.addEventListener("DOMContentLoaded", function(event) { 
            var scrollpos = localStorage.getItem('scrollpos');
            if (scrollpos) window.scrollTo(0, scrollpos);
        });

        window.onbeforeunload = function(e) {
            localStorage.setItem('scrollpos', window.scrollY);
        };
    </script>

HttpWebRequest-The remote server returned an error: (400) Bad Request

What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.

pip install returning invalid syntax

I use Enthought Canopy for my python, at first I used "pip install --upgrade pip", it showed a syntax error like yours, then I added a "!" in front of the pip, then it finally worked.

Difference between PACKETS and FRAMES

Packets and Frames are the names given to Protocol data units (PDUs) at different network layers

  • Segments/Datagrams are units of data in the Transport Layer.

    In the case of the internet, the term Segment typically refers to TCP, while Datagram typically refers to UDP. However Datagram can also be used in a more general sense and refer to other layers (link):

    Datagram

    A self-contained, independent entity of data carrying sufficient information to be routed from the source to the destination computer without reliance on earlier exchanges between this source and destination computer andthe transporting network.

  • Packets are units of data in the Network Layer (IP in case of the Internet)

  • Frames are units of data in the Link Layer (e.g. Wifi, Bluetooth, Ethernet, etc).

enter image description here

Visual Studio 2015 Update 3 Offline Installer (ISO)

You can check Visual Studio Downloads for available Visual Studio Community, Visual Studio Professional, Visual Studio Enterprise and Visual Studio Code download links.


Update!

There is no direct links of Visual Studio 2015 at Visual Studio Downloads anymore. but the below links still works.


OR simply click on direct links below (for .iso/.exe file):


VSCode area:

Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use

In windows OS do right click on task bar-->start task manager-->process then check java.exe or javaw is running if it is running,then click on it and do end process then restart your tom cat server.

  1. some times skype will occupy port 80 in that case change the skype settings and put 81 for skype or change tomcat configuration.

Convert byte to string in Java

System.out.println(new String(new byte[]{ (byte)0x63 }, "US-ASCII"));

Note especially that converting bytes to Strings always involves an encoding. If you do not specify it, you'll be using the platform default encoding, which means the code can break when running in different environments.