Programs & Examples On #Pep8

Coding conventions and style guidelines for Python. Not to be confused with the PEP/8 assembly language.

Should I use "camel case" or underscores in python?

Function names should be lowercase, with words separated by underscores as necessary to improve readability. mixedCase is allowed only in contexts where that's already the prevailing style

Check out its already been answered, click here

what is trailing whitespace and how can I handle this?

I have got similar pep8 warning W291 trailing whitespace

long_text = '''Lorem Ipsum is simply dummy text  <-remove whitespace
of the printing and typesetting industry.'''

Try to explore trailing whitespaces and remove them. ex: two whitespaces at the end of Lorem Ipsum is simply dummy text

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

I would prefer the more readable form x is not y than I would think how to eventually write the code handling precedence of the operators in order to produce much more readable code.

Why does PEP-8 specify a maximum line length of 79 characters?

I believe those who study typography would tell you that 66 characters per a line is supposed to be the most readable width for length. Even so, if you need to debug a machine remotely over an ssh session, most terminals default to 80 characters, 79 just fits, trying to work with anything wider becomes a real pain in such a case. You would also be suprised by the number of developers using vim + screen as a day to day environment.

Pylint, PyChecker or PyFlakes?

pep8 was recently added to PyPi.

  • pep8 - Python style guide checker
  • pep8 is a tool to check your Python code against some of the style conventions in PEP 8.

It is now super easy to check your code against pep8.

See http://pypi.python.org/pypi/pep8

How do I set the maximum line length in PyCharm?

For PyCharm 2018.1 on Mac:

Preferences (?+,), then Editor -> Code Style:

enter image description here

For PyCharm 2018.3 on Windows:

File -> Settings (Ctrl+Alt+S), then Editor -> Code Style:

To follow PEP-8 set Hard wrap at to 80.

What is PEP8's E128: continuation line under-indented for visual indent?

This goes also for statements like this (auto-formatted by PyCharm):

    return combine_sample_generators(sample_generators['train']), \
           combine_sample_generators(sample_generators['dev']), \
           combine_sample_generators(sample_generators['test'])

Which will give the same style-warning. In order to get rid of it I had to rewrite it to:

    return \
        combine_sample_generators(sample_generators['train']), \
        combine_sample_generators(sample_generators['dev']), \
        combine_sample_generators(sample_generators['test'])

How do I perform a Perl substitution on a string while keeping the original?

The one-liner solution is more useful as a shibboleth than good code; good Perl coders will know it and understand it, but it's much less transparent and readable than the two-line copy-and-modify couplet you're starting with.

In other words, a good way to do this is the way you're already doing it. Unnecessary concision at the cost of readability isn't a win.

How to remove unused imports in Intellij IDEA on commit?

You can check checkbox in the commit dialog.

enter image description here

You can use settings to automatically optimize imports since 11.1 and above.

enter image description here

Evaluate empty or null JSTL c tags

Here's the one liner.

Ternary operator inside EL

${empty value?'value is empty or null':'value is NOT empty or null'}

Exception: Can't bind to 'ngFor' since it isn't a known native property

Another typo leading to the OP's error could be using in:

<div *ngFor="let talk in talks">

You should use of instead:

<div *ngFor="let talk of talks">

Android: How can I get the current foreground activity (from a service)?

Update: this no longer works with other apps' activities as of Android 5.0


Here's a good way to do it using the activity manager. You basically get the runningTasks from the activity manager. It will always return the currently active task first. From there you can get the topActivity.

Example here

There's an easy way of getting a list of running tasks from the ActivityManager service. You can request a maximum number of tasks running on the phone, and by default, the currently active task is returned first.

Once you have that you can get a ComponentName object by requesting the topActivity from your list.

Here's an example.

    ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
    Log.d("topActivity", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName());
    ComponentName componentInfo = taskInfo.get(0).topActivity;
    componentInfo.getPackageName();

You will need the following permission on your manifest:

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

What online brokers offer APIs?

There are a few. I was looking into MBTrading for a friend. I didn't get too far, as my friend lost interest. Seemed relatively straigt forward with a C# and VB.Net SDK. They had some docs and everything. This was ~6 months ago, so it may be better (or worse) by now.

IIRC, you can create a demo account for free. I don't remember all the details, but it let you connect to their test server and pull quotes and make fake trades and such to get your software fine tuned.

Don't know much about cost for an actual account or anything.

Angular 2: Passing Data to Routes?

You can do this:

app-routing-modules.ts:

import { NgModule                  }    from '@angular/core';
import { RouterModule, Routes      }    from '@angular/router';
import { PowerBoosterComponent     }    from './component/power-booster.component';


export const routes: Routes = [
  { path:  'pipeexamples',component: PowerBoosterComponent, 
data:{  name:'shubham' } },
    ];
    @NgModule({
      imports: [ RouterModule.forRoot(routes) ],
      exports: [ RouterModule ]
    })
    export class AppRoutingModule {}

In this above route, I want to send data via a pipeexamples path to PowerBoosterComponent.So now I can receive this data in PowerBoosterComponent like this:

power-booster-component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';

@Component({
  selector: 'power-booster',
  template: `
    <h2>Power Booster</h2>`
})

export class PowerBoosterComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router

  ) { }
  ngOnInit() {
    //this.route.snapshot.data['name']
    console.log("Data via params: ",this.route.snapshot.data['name']);
  }
}

So you can get the data by this.route.snapshot.data['name'].

How to restart VScode after editing extension's config?

You can do the following

  1. Click on extensions
  2. Type Reload
  3. Then install

It will add a reload button on your right hand at the bottom of the vs code.

Sending HTTP Post request with SOAP action using org.apache.http

It was giving 415 Http response Code as error,

So I added

httppost.addHeader("Content-Type", "text/xml; charset=utf-8");

Everything alright now, Http: 200

Get type of all variables

lapply(your_dataframe, class) gives you something like:

$tikr [1] "factor"

$Date [1] "Date"

$Open [1] "numeric"

$High [1] "numeric"

... etc.

Check for null variable in Windows batch

rem set defaults:
set filename1="c:\file1.txt"
set filename2="c:\file2.txt"
set filename3="c:\file3.txt"
rem set parameters:
IF NOT "a%1"=="a" (set filename1="%1")
IF NOT "a%2"=="a" (set filename2="%2")
IF NOT "a%3"=="a" (set filename1="%3")
echo %filename1%, %filename2%, %filename3%

Be careful with quotation characters though, you may or may not need them in your variables.

What is a simple C or C++ TCP server and client example?

Although many year ago, clsocket seems a really nice small cross-platform (Windows, Linux, Mac OSX): https://github.com/DFHack/clsocket

How to get all subsets of a set? (powerset)

Almost all of these answers use list rather than set, which felt like a bit of a cheat to me. So, out of curiosity I tried to do a simple version truly on set and summarize for other "new to Python" folks.

I found there's a couple oddities in dealing with Python's set implementation. The main surprise to me was handling empty sets. This is in contrast to Ruby's Set implementation, where I can simply do Set[Set[]] and get a Set containing one empty Set, so I found it initially a little confusing.

To review, in doing powerset with sets, I encountered two problems:

  1. set() takes an iterable, so set(set()) will return set() because the empty set iterable is empty (duh I guess :))
  2. to get a set of sets, set({set()}) and set.add(set) won't work because set() isn't hashable

To solve both issues, I made use of frozenset(), which means I don't quite get what I want (type is literally set), but makes use of the overall set interace.

def powerset(original_set):
  # below gives us a set with one empty set in it
  ps = set({frozenset()}) 
  for member in original_set:
    subset = set()
    for m in ps:
      # to be added into subset, needs to be
      # frozenset.union(set) so it's hashable
      subset.add(m.union(set([member]))
    ps = ps.union(subset)
  return ps

Below we get 2² (16) frozensets correctly as output:

In [1]: powerset(set([1,2,3,4]))
Out[2]:
{frozenset(),
 frozenset({3, 4}),
 frozenset({2}),
 frozenset({1, 4}),
 frozenset({3}),
 frozenset({2, 3}),
 frozenset({2, 3, 4}),
 frozenset({1, 2}),
 frozenset({2, 4}),
 frozenset({1}),
 frozenset({1, 2, 4}),
 frozenset({1, 3}),
 frozenset({1, 2, 3}),
 frozenset({4}),
 frozenset({1, 3, 4}),
 frozenset({1, 2, 3, 4})}

As there's no way to have a set of sets in Python, if you want to turn these frozensets into sets, you'll have to map them back into a list (list(map(set, powerset(set([1,2,3,4])))) ) or modify the above.

Fill DataTable from SQL Server database

If the variable table contains invalid characters (like a space) you should add square brackets around the variable.

public DataTable fillDataTable(string table)
{
    string query = "SELECT * FROM dstut.dbo.[" + table + "]";

    using(SqlConnection sqlConn = new SqlConnection(conSTR))
    using(SqlCommand cmd = new SqlCommand(query, sqlConn))
    {
        sqlConn.Open();
        DataTable dt = new DataTable();
        dt.Load(cmd.ExecuteReader());
        return dt;
    }
}

By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input

How can I obfuscate (protect) JavaScript?

You can obfuscate the javascript source all you want, but it will always be reverse-engineerable just by virtue of requiring all the source code to actually run on the client machine... the best option I can think of is having all your processing done with server-side code, and all the client code javascript does is send requests for processing to the server itself. Otherwise, anyone will always be able to keep track of all operations that the code is doing.

Someone mentioned base64 to keep strings safe. This is a terrible idea. Base64 is immediately recognizable by the types of people who would want to reverse engineer your code. The first thing they'll do is unencode it and see what it is.

What is the result of % in Python?

Modulus operator, it is used for remainder division on integers, typically, but in Python can be used for floating point numbers.

http://docs.python.org/reference/expressions.html

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].

Set Encoding of File to UTF8 With BOM in Sublime Text 3

By default, Sublime Text set 'UTF8 without BOM', but that wasn't specified.

The only specicified things is 'UTF8 with BOM'.

Hope this help :)

Side-by-side plots with ggplot2

In my experience gridExtra:grid.arrange works perfectly, if you are trying to generate plots in a loop.

Short Code Snippet:

gridExtra::grid.arrange(plot1, plot2, ncol = 2)

** Updating this comment to show how to use grid.arrange() within a for loop to generate plots for different factors of a categorical variable.

for (bin_i in levels(athlete_clean$BMI_cat)) {

plot_BMI <- athlete_clean %>% filter(BMI_cat == bin_i) %>% group_by(BMI_cat,Team) %>% summarize(count_BMI_team = n()) %>% 
          mutate(percentage_cbmiT = round(count_BMI_team/sum(count_BMI_team) * 100,2)) %>% 
          arrange(-count_BMI_team) %>% top_n(10,count_BMI_team) %>% 
          ggplot(aes(x = reorder(Team,count_BMI_team), y = count_BMI_team, fill = Team)) +
            geom_bar(stat = "identity") +
            theme_bw() +
            # facet_wrap(~Medal) +
            labs(title = paste("Top 10 Participating Teams with \n",bin_i," BMI",sep=""), y = "Number of Athletes", 
                 x = paste("Teams - ",bin_i," BMI Category", sep="")) +
            geom_text(aes(label = paste(percentage_cbmiT,"%",sep = "")), 
                      size = 3, check_overlap = T,  position = position_stack(vjust = 0.7) ) +
            theme(axis.text.x = element_text(angle = 00, vjust = 0.5), plot.title = element_text(hjust = 0.5), legend.position = "none") +
            coord_flip()

plot_BMI_Medal <- athlete_clean %>% 
          filter(!is.na(Medal), BMI_cat == bin_i) %>% 
          group_by(BMI_cat,Team) %>% 
          summarize(count_BMI_team = n()) %>% 
          mutate(percentage_cbmiT = round(count_BMI_team/sum(count_BMI_team) * 100,2)) %>% 
          arrange(-count_BMI_team) %>% top_n(10,count_BMI_team) %>% 
          ggplot(aes(x = reorder(Team,count_BMI_team), y = count_BMI_team, fill = Team)) +
            geom_bar(stat = "identity") +
            theme_bw() +
            # facet_wrap(~Medal) +
            labs(title = paste("Top 10 Winning Teams with \n",bin_i," BMI",sep=""), y = "Number of Athletes", 
                 x = paste("Teams - ",bin_i," BMI Category", sep="")) +
            geom_text(aes(label = paste(percentage_cbmiT,"%",sep = "")), 
                      size = 3, check_overlap = T,  position = position_stack(vjust = 0.7) ) +
            theme(axis.text.x = element_text(angle = 00, vjust = 0.5), plot.title = element_text(hjust = 0.5), legend.position = "none") +
            coord_flip()

gridExtra::grid.arrange(plot_BMI, plot_BMI_Medal, ncol = 2)

}

One of the Sample Plots from the above for loop is included below. The above loop will produce multiple plots for all levels of BMI category.

Sample Image

If you wish to see a more comprehensive use of grid.arrange() within for loops, check out https://rpubs.com/Mayank7j_2020/olympic_data_2000_2016

What is a blob URL and why it is used?

What is blob url? Why it is used?

BLOB is just byte sequence. Browser recognize it as byte stream. It is used to get byte stream from source.

A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

Can i make my own blob url on a server?

Yes you can there are serveral ways to do so for example try http://php.net/manual/en/function.ibase-blob-echo.php

Read more on

Bootstrap 3: Scroll bars

You need to use overflow option like below:

.nav{
    max-height: 300px;
    overflow-y: scroll; 
}

Change the height according to amount of items you need to show

Javascript Thousand Separator / string format

// thousand separates a digit-only string using commas
// by element:  onkeyup = "ThousandSeparate(this)"
// by ID:       onkeyup = "ThousandSeparate('txt1','lbl1')"
function ThousandSeparate()
{
    if (arguments.length == 1)
    {
        var V = arguments[0].value;
        V = V.replace(/,/g,'');
        var R = new RegExp('(-?[0-9]+)([0-9]{3})'); 
        while(R.test(V))
        {
            V = V.replace(R, '$1,$2');
        }
        arguments[0].value = V;
    }
    else  if ( arguments.length == 2)
    {
        var V = document.getElementById(arguments[0]).value;
        var R = new RegExp('(-?[0-9]+)([0-9]{3})'); 
        while(R.test(V))
        {
            V = V.replace(R, '$1,$2');
        }
        document.getElementById(arguments[1]).innerHTML = V;
    }
    else return false;
}   

What is the correct XPath for choosing attributes that contain "foo"?

For the code above... //*[contains(@prop,'foo')]

Java current machine name and logged in user?

To get the currently logged in user:

System.getProperty("user.name");

To get the host name of the machine:

InetAddress.getLocalHost().getHostName();

To answer the last part of your question, the Java API says that getHostName() will return

the host name for this IP address, or if the operation is not allowed by the security check, the textual representation of the IP address.

How do I do a case-insensitive string comparison?

Section 3.13 of the Unicode standard defines algorithms for caseless matching.

X.casefold() == Y.casefold() in Python 3 implements the "default caseless matching" (D144).

Casefolding does not preserve the normalization of strings in all instances and therefore the normalization needs to be done ('å' vs. 'a°'). D145 introduces "canonical caseless matching":

import unicodedata

def NFD(text):
    return unicodedata.normalize('NFD', text)

def canonical_caseless(text):
    return NFD(NFD(text).casefold())

NFD() is called twice for very infrequent edge cases involving U+0345 character.

Example:

>>> 'å'.casefold() == 'a°'.casefold()
False
>>> canonical_caseless('å') == canonical_caseless('a°')
True

There are also compatibility caseless matching (D146) for cases such as '?' (U+3392) and "identifier caseless matching" to simplify and optimize caseless matching of identifiers.

How to compare two dates in php

Don't know what your problem is but:

function date_compare($d1, $d2)
{
    $d1 = explode('_', $d1);
    $d2 = explode('_', $d2);
    
    $d1 = array_reverse($d1);
    $d2 = array_reverse($d2);
    
    if (strtotime(implode('-', $d1)) > strtotime(implode('-', $d2)))
    {
        return $d2;
    }
    else
    {
        return $d1;
    }
}

Hexadecimal To Decimal in Shell Script

Dealing with a very lightweight embedded version of busybox on Linux means many of the traditional commands are not available (bc, printf, dc, perl, python)

echo $((0x2f))
47

hexNum=2f
echo $((0x${hexNum}))
47

Credit to Peter Leung for this solution.

Hide keyboard in react-native

Keyboard module is used to control keyboard events.

  • import { Keyboard } from 'react-native'
  • Add below code in render method.

    render() { return <TextInput onSubmitEditing={Keyboard.dismiss} />; }

You can use -

Keyboard.dismiss()

static dismiss() Dismisses the active keyboard and removes focus as per react native documents.

How do you monitor network traffic on the iPhone?

You didnt specify the platform you use, so I assume it's a Mac ;-)

What I do is use a proxy. I use SquidMan, a standalone implementation of Squid

I start SquidMan on the Mac, then on the iPhone I enter the Proxy params in the General/Wifi Settings.

Then I can watch the HTTP trafic in the Console App, looking at the squid-access.log

If I need more infos, I switch to tcpdump, but I suppose WireShark should work too.

Open directory using C

Parameters passed to the C program executable is nothing but an array of string(or character pointer),so memory would have been already allocated for these input parameter before your program access these parameters,so no need to allocate buffer,and that way you can avoid error handling code in your program as well(Reduce chances of segfault :)).

Limiting number of displayed results when using ngRepeat

Use limitTo filter to display a limited number of results in ng-repeat.

<ul class="phones">
      <li ng-repeat="phone in phones | limitTo:5">
        {{phone.name}}
        <p>{{phone.snippet}}</p>
      </li>
</ul>

Is it possible to use "return" in stored procedure?

CREATE PROCEDURE pr_emp(dept_id IN NUMBER,vv_ename out varchar2  )
 AS
 v_ename emp%rowtype;
CURSOR c_emp IS
    SELECT ename
    FROM emp where deptno=dept_id;
 BEGIN
     OPEN c;
     loop
        FETCH c_emp INTO v_ename;
        return v_ename; 
        vv_ename := v_ename 
        exit when c_emp%notfound;
     end loop;
     CLOSE c_emp;


 END pr_emp;

How to SELECT based on value of another SELECT

SELECT x.name, x.summary, (x.summary / COUNT(*)) as percents_of_total
FROM tbl t
INNER JOIN 
(SELECT name, SUM(value) as summary
FROM tbl
WHERE year BETWEEN 2000 AND 2001
GROUP BY name) x ON x.name = t.name
GROUP BY x.name, x.summary

Convert utf8-characters to iso-88591 and back in PHP

set meta tag in head as

 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> 

use the link http://www.i18nqa.com/debug/utf8-debug.html to replace the symbols character you want.

then use str_replace like

    $find = array('“', '’', '…', '—', '–', '‘', 'é', 'Â', '•', 'Ëœ', 'â€'); // en dash
                        $replace = array('“', '’', '…', '—', '–', '‘', 'é', '', '•', '˜', '”');
$content = str_replace($find, $replace, $content);

Its the method i use and help alot. Thanks!

kubectl apply vs kubectl create?

+----------------------------------------------------------+
¦ command ¦ object does not exist ¦ object already exists  ¦
+---------+-----------------------+------------------------¦
¦ create  ¦ create new object     ¦          ERROR         ¦ 
¦         ¦                       ¦                        ¦
¦ apply   ¦ create new object     ¦ configure object       ¦
¦         ¦ (needs complete spec) ¦ (accepts partial spec) ¦
¦         ¦                       ¦                        ¦
¦ replace ¦         ERROR         ¦ delete object          ¦
¦         ¦                       ¦ create new object      ¦
+----------------------------------------------------------+

VERR_VMX_MSR_VMXON_DISABLED when starting an image from Oracle virtual box

Which version VirtualBox do you use? I found the same problem and when use update latest version on my X64 win7 machine VirtualBox-4.3.4-91027-Win But I uninstall it and back to VirtualBox-4.2.18-88781-Win

It works well, try it until Oracle fix it.

Combining "LIKE" and "IN" for SQL Server

I know this is old but I got a kind of working solution

SELECT Tbla.* FROM Tbla
INNER JOIN Tblb ON
Tblb.col1 Like '%'+Tbla.Col2+'%'

You can expand it further with your where clause etc. I only answered this because this is what I was looking for and I had to figure out a way of doing it.

How to access the elements of a 2D array?

Seems to work here:

>>> a=[[1,1],[2,1],[3,1]]
>>> a
[[1, 1], [2, 1], [3, 1]]
>>> a[1]
[2, 1]
>>> a[1][0]
2
>>> a[1][1]
1

Filter dict to contain only certain keys?

This one liner lambda should work:

dictfilt = lambda x, y: dict([ (i,x[i]) for i in x if i in set(y) ])

Here's an example:

my_dict = {"a":1,"b":2,"c":3,"d":4}
wanted_keys = ("c","d")

# run it
In [10]: dictfilt(my_dict, wanted_keys)
Out[10]: {'c': 3, 'd': 4}

It's a basic list comprehension iterating over your dict keys (i in x) and outputs a list of tuple (key,value) pairs if the key lives in your desired key list (y). A dict() wraps the whole thing to output as a dict object.

How do I convert from a string to an integer in Visual Basic?

Convert.ToIntXX doesn't like being passed strings of decimals.

To be safe use

Convert.ToInt32(Convert.ToDecimal(txtPrice.Text))

Changing the Status Bar Color for specific ViewControllers using Swift in iOS8

I can suggest you a simpler way,

  1. Just call setNeedsStatusBarAppearanceUpdate in viewDidLoad as Apple docs says,

Call this method if the view controller's status bar attributes, such as hidden/unhidden status or style, change. If you call this method within an animation block, the changes are animated along with the rest of the animation block.

  1. Implement preferredStatusBarStyle returning your preferred type.

It worked for me in iOS 10.1.

Objective C

[self setNeedsStatusBarAppearanceUpdate];

-(UIStatusBarStyle)preferredStatusBarStyle {
     return UIStatusBarStyleLightContent;
}

Swift

setNeedsStatusBarAppearanceUpdate()

var preferredStatusBarStyle: UIStatusBarStyle { 
    return .lightContent
}

I am surprised nobody pointed this out. Anyway enjoy :)

Error when using scp command "bash: scp: command not found"

Check if scp is installed or not on from where you want want to copy check using which scp

If it's already installed, it will print you a path like /usr/bin/scp Else, install scp using:

yum -y install openssh-clients

Then copy command

scp -r [email protected]:/var/www/html/database_backup/restore_fullbackup/backup_20140308-023002.sql  /var/www/html/db_bkp/

RVM is not a function, selecting rubies with 'rvm use ...' will not work

If RVM was installed with dedicated ubuntu RVM installer https://github.com/rvm/ubuntu_rvm the path to RVM scripts will be different /usr/share/rvm/scripts/rvm. So to add it to your .bashrc run the following command:

echo 'source "/usr/share/rvm/scripts/rvm"' >> ~/.bashrc

Using Apache httpclient for https

I put together this test app to reproduce the issue using the HTTP testing framework from the Apache HttpClient package:

ClassLoader cl = HCTest.class.getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore  = KeyStore.getInstance("jks");
char[] pwd = "nopassword".toCharArray();
keystore.load(url.openStream(), pwd);

TrustManagerFactory tmf = TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keystore);
TrustManager[] tm = tmf.getTrustManagers();

KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
        KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, pwd);
KeyManager[] km = kmfactory.getKeyManagers();

SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(km, tm, null);

LocalTestServer localServer = new LocalTestServer(sslcontext);
localServer.registerDefaultHandlers();

localServer.start();
try {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    TrustStrategy trustStrategy = new TrustStrategy() {

        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            for (X509Certificate cert: chain) {
                System.err.println(cert);
            }
            return false;
        }

    };

    SSLSocketFactory sslsf = new SSLSocketFactory("TLS", null, null, keystore, null,
            trustStrategy, new AllowAllHostnameVerifier());
    Scheme https = new Scheme("https", 443, sslsf);
    httpclient.getConnectionManager().getSchemeRegistry().register(https);

    InetSocketAddress address = localServer.getServiceAddress();
    HttpHost target1 = new HttpHost(address.getHostName(), address.getPort(), "https");
    HttpGet httpget1 = new HttpGet("/random/100");
    HttpResponse response1 = httpclient.execute(target1, httpget1);
    System.err.println(response1.getStatusLine());
    HttpEntity entity1 = response1.getEntity();
    EntityUtils.consume(entity1);
    HttpHost target2 = new HttpHost("www.verisign.com", 443, "https");
    HttpGet httpget2 = new HttpGet("/");
    HttpResponse response2 = httpclient.execute(target2, httpget2);
    System.err.println(response2.getStatusLine());
    HttpEntity entity2 = response2.getEntity();
    EntityUtils.consume(entity2);
} finally {
    localServer.stop();
}

Even though, Sun's JSSE implementation appears to always read the trust material from the default trust store for some reason, it does not seem to get added to the SSL context and to impact the process of trust verification during the SSL handshake.

Here's the output of the test app. As you can see, the first request succeeds whereas the second fails as the connection to www.verisign.com is rejected as untrusted.

[
[
  Version: V1
  Subject: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown
  Signature Algorithm: SHA1withDSA, OID = 1.2.840.10040.4.3

  Key:  Sun DSA Public Key
    Parameters:DSA
    p:     fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80 b6512669
    455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b 801d346f f26660b7
    6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6 1bf83b57 e7c6a8a6 150f04fb
    83f6d3c5 1ec30235 54135a16 9132f675 f3ae2b61 d72aeff2 2203199d d14801c7
    q:     9760508f 15230bcc b292b982 a2eb840b f0581cf5
    g:     f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b 3d078267
    5159578e bad4594f e6710710 8180b449 167123e8 4c281613 b7cf0932 8cc8a6e1
    3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f 0bfa2135 62f1fb62 7a01243b
    cca4f1be a8519089 a883dfe1 5ae59f06 928b665e 807b5525 64014c3b fecf492a

  y:
    f0cc639f 702fd3b1 03fa8fa6 676c3756 ea505448 23cd1147 fdfa2d7f 662f7c59
    a02ddc1a fd76673e 25210344 cebbc0e7 6250fff1 a814a59f 30ff5c7e c4f186d8
    f0fd346c 29ea270d b054c040 c74a9fc0 55a7020f eacf9f66 a0d86d04 4f4d23de
    7f1d681f 45c4c674 5762b71b 808ded17 05b74baf 8de3c4ab 2ef662e3 053af09e

  Validity: [From: Sat Dec 11 14:48:35 CET 2004,
               To: Tue Dec 09 14:48:35 CET 2014]
  Issuer: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown
  SerialNumber: [    41bafab3]

]
  Algorithm: [SHA1withDSA]
  Signature:
0000: 30 2D 02 15 00 85 BE 6B   D0 91 EF 34 72 05 FF 1A  0-.....k...4r...
0010: DB F6 DE BF 92 53 9B 14   27 02 14 37 8D E8 CB AC  .....S..'..7....
0020: 4E 6C 93 F2 1F 7D 20 A1   2D 6F 80 5F 58 AE 33     Nl.... .-o._X.3

]
HTTP/1.1 200 OK
[
[
  Version: V3
  Subject: CN=www.verisign.com, OU=" Production Security Services", O="VeriSign, Inc.", STREET=487 East Middlefield Road, L=Mountain View, ST=California, OID.2.5.4.17=94043, C=US, SERIALNUMBER=2497886, OID.2.5.4.15="V1.0, Clause 5.(b)", OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US
  Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5

  Key:  Sun RSA public key, 2048 bits
  modulus: 20699622354183393041832954221256409980425015218949582822286196083815087464214375375678538878841956356687753084333860738385445545061253653910861690581771234068858443439641948884498053425403458465980515883570440998475638309355278206558031134532548167239684215445939526428677429035048018486881592078320341210422026566944903775926801017506416629554190534665876551381066249522794321313235316733139718653035476771717662585319643139144923795822646805045585537550376512087897918635167815735560529881178122744633480557211052246428978388768010050150525266771462988042507883304193993556759733514505590387262811565107773578140271
  public exponent: 65537
  Validity: [From: Wed May 26 02:00:00 CEST 2010,
               To: Sat May 26 01:59:59 CEST 2012]
  Issuer: CN=VeriSign Class 3 Extended Validation SSL SGC CA, OU=Terms of use at https://www.verisign.com/rpa (c)06, OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US
  SerialNumber: [    53d2bef9 24a7245e 83ca01e4 6caa2477]

Certificate Extensions: 10
[1]: ObjectId: 1.3.6.1.5.5.7.1.1 Criticality=false
AuthorityInfoAccess [
  [accessMethod: 1.3.6.1.5.5.7.48.1
   accessLocation: URIName: http://EVIntl-ocsp.verisign.com, accessMethod: 1.3.6.1.5.5.7.48.2
   accessLocation: URIName: http://EVIntl-aia.verisign.com/EVIntl2006.cer]
]

...

]
Exception in thread "main" javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
    at com.sun.net.ssl.internal.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:345)
    at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
    at org.apache.http.conn.ssl.SSLSocketFactory.createLayeredSocket(SSLSocketFactory.java:446)
...

phpMyAdmin - Error > Incorrect format parameter?

None of the above answers solved it for me.

I cant even find the 'libraries' folder in my xampp - ubuntu also.

So, I simply restarted using the following commands:

sudo service apache2 restart

and

sudo service mysql restart

Just restarted apache and mysql. Logged in phpmyadmin again and it worked as usual.

Thanks me..!!

Ctrl+click doesn't work in Eclipse Juno

Please check your .classpath file as well. Some times Eclipse do not redirect when using "ctrl+click" to Class or method if classpath is not proper. I had faced same issue in Eclipse Mars but it got resolved when I got proper .classpath file at my work location.

How do you loop in a Windows batch file?

FOR will give you any information you'll ever need to know about FOR loops, including examples on proper usage.

How can I change the Bootstrap default font family using font from Google?

If you want the font you chose to be applied and not the one in bootstrap without modifying the original bootstrap files you can rearrange the tags in your HTML documents so your CSS files that applies the font called after the bootstrap one. In this way since the browser reads the documents line after line first it will read the bootstrap files and apply it roles then it will read your file and override the roles in the bootstrap and replace it with the ones in your file.

Github: error cloning my private repository

I solved the problem installing the Git from: https://git-for-windows.github.io/ Locate the cert file path:

D:\Program Files\Git\mingw64\ssl\certs\ca-bundle.crt

Configure the Git path:

git config --system http.sslcainfo "D:\Program Files\Git\mingw64\ssl\certs\ca-bundle.crt"

Try again

How to fetch the row count for all tables in a SQL SERVER database

Short and sweet

sp_MSForEachTable 'DECLARE @t AS VARCHAR(MAX); 
SELECT @t = CAST(COUNT(1) as VARCHAR(MAX)) 
+ CHAR(9) + CHAR(9) + ''?'' FROM ? ; PRINT @t'

Output:

enter image description here

Where to download visual studio express 2005?

Small tip for you. Microsoft frequently has 'launch parties' or 'launch events' in which they frequently distribute licensed, not for resale copies, of that product. I've gotten the last two versions of VS (2005 and 2008) by attending my local .NET user group chapter during those days.

process.waitFor() never returns

It appears you are not reading the output before waiting for it to finish. This is fine only if the output doesn't fill the buffer. If it does, it will wait until you read the output, catch-22.

Perhaps you have some errors which you are not reading. This would case the application to stop and waitFor to wait forever. A simple way around this is to re-direct the errors to the regular output.

ProcessBuilder pb = new ProcessBuilder("tasklist");
pb.redirectErrorStream(true);
Process process = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
    System.out.println("tasklist: " + line);
process.waitFor();

Difference between $(document.body) and $('body')

The answers here are not actually completely correct. Close, but there's an edge case.

The difference is that $('body') actually selects the element by the tag name, whereas document.body references the direct object on the document.

That means if you (or a rogue script) overwrites the document.body element (shame!) $('body') will still work, but $(document.body) will not. So by definition they're not equivalent.

I'd venture to guess there are other edge cases (such as globally id'ed elements in IE) that would also trigger what amounts to an overwritten body element on the document object, and the same situation would apply.

Convert integer value to matching Java Enum

You could add a static method in your enum that accepts an int as a parameter and returns a PcapLinkType.

public static PcapLinkType of(int linkType) {

    switch (linkType) {
        case -1: return DLT_UNKNOWN
        case 0: return DLT_NULL;

        //ETC....

        default: return null;

    }
}

Is it possible to modify a registry entry via a .bat/.cmd script?

This is how you can modify registry, without yes or no prompt and don't forget to run as administrator

reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\etc\etc   /v Valuename /t REG_SZ /d valuedata  /f 

Below is a real example to set internet explorer as my default browser

reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice   /v ProgId /t REG_SZ /d IE.HTTPS  /f 

/f Force: Force an update without prompting "Value exists, overwrite Y/N"

/d Data : The actual data to store as a "String", integer etc

/v Value : The value name eg ProgId

/t DataType : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ

Learn more about Read, Set or Delete registry keys and values, save and restore from a .REG file. from here

Getting Database connection in pure JPA setup

If you are using JAVA EE 5.0, the best way to do this is to use the @Resource annotation to inject the datasource in an attribute of a class (for instance an EJB) to hold the datasource resource (for instance an Oracle datasource) for the legacy reporting tool, this way:

@Resource(mappedName="jdbc:/OracleDefaultDS") DataSource datasource;

Later you can obtain the connection, and pass it to the legacy reporting tool in this way:

Connection conn = dataSource.getConnection();

Can I force pip to reinstall the current version?

You might want to have all three options: --upgrade and --force-reinstall ensures reinstallation, while --no-deps avoids reinstalling dependencies.

$ sudo pip install --upgrade --no-deps --force-reinstall <packagename>

Otherwise you might run into the problem that pip starts to recompile Numpy or other large packages.

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

Why powershell does not run Angular commands?

script1.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170

This error happens due to a security measure which won't let scripts be executed on your system without you having approved of it. You can do so by opening up a powershell with administrative rights (search for powershell in the main menu and select Run as administrator from the context menu) and entering:

set-executionpolicy remotesigned

Create a List of primitive int?

Java Collection should be collections of Object only.

List<Integer> integerList = new ArrayList<Integer>();

Integer is wrapper class of primitive data type int.

more from JAVA wrapper classes here!

U can directly save and get int to/from integerList as, integerList.add(intValue); int intValue = integerList.get(i)

How to find minimum value from vector?

template <class ForwardIterator>
ForwardIterator min_element ( ForwardIterator first, ForwardIterator last )
{
    ForwardIterator lowest = first;
    if (first == last) return last;
    while (++first != last)
    if (*first < *lowest) 
        lowest = first;
    return lowest;
}

Keras, How to get the output of each layer?

In case you have one of the following cases:

  • error: InvalidArgumentError: input_X:Y is both fed and fetched
  • case of multiple inputs

You need to do the following changes:

  • add filter out for input layers in outputs variable
  • minnor change on functors loop

Minimum example:

from keras.engine.input_layer import InputLayer
inp = model.input
outputs = [layer.output for layer in model.layers if not isinstance(layer, InputLayer)]
functors = [K.function(inp + [K.learning_phase()], [x]) for x in outputs]
layer_outputs = [fun([x1, x2, xn, 1]) for fun in functors]

How do you check if a variable is an array in JavaScript?

For those who code-golf, an unreliable test with fewest characters:

function isArray(a) {
  return a.map;
}

This is commonly used when traversing/flattening a hierarchy:

function golf(a) {
  return a.map?[].concat.apply([],a.map(golf)):a;
}

input: [1,2,[3,4,[5],6],[7,[8,[9]]]]
output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Python handling socket.error: [Errno 104] Connection reset by peer

There is a way to catch the error directly in the except clause with ConnectionResetError, better to isolate the right error. This example also catches the timeout.

from urllib.request import urlopen 
from socket import timeout

url = "http://......"
try: 
    string = urlopen(url, timeout=5).read()
except ConnectionResetError:
    print("==> ConnectionResetError")
    pass
except timeout: 
    print("==> Timeout")
    pass

How to sort a list of objects based on an attribute of the objects?

Readers should notice that the key= method:

ut.sort(key=lambda x: x.count, reverse=True)

is many times faster than adding rich comparison operators to the objects. I was surprised to read this (page 485 of "Python in a Nutshell"). You can confirm this by running tests on this little program:

#!/usr/bin/env python
import random

class C:
    def __init__(self,count):
        self.count = count

    def __cmp__(self,other):
        return cmp(self.count,other.count)

longList = [C(random.random()) for i in xrange(1000000)] #about 6.1 secs
longList2 = longList[:]

longList.sort() #about 52 - 6.1 = 46 secs
longList2.sort(key = lambda c: c.count) #about 9 - 6.1 = 3 secs

My, very minimal, tests show the first sort is more than 10 times slower, but the book says it is only about 5 times slower in general. The reason they say is due to the highly optimizes sort algorithm used in python (timsort).

Still, its very odd that .sort(lambda) is faster than plain old .sort(). I hope they fix that.

Create PDF from a list of images

If you use Python 3, you can use the python module img2pdf

install it using pip3 install img2pdf and then you can use it in a script using import img2pdf

sample code

import os
import img2pdf

with open("output.pdf", "wb") as f:
    f.write(img2pdf.convert([i for i in os.listdir('path/to/imageDir') if i.endswith(".jpg")]))

or (If you get any error with previous approach due to some path issue)

# convert all files matching a glob
import glob
with open("name.pdf","wb") as f:
    f.write(img2pdf.convert(glob.glob("/path/to/*.jpg")))

How to print binary number via printf

printf() doesn't directly support that. Instead you have to make your own function.

Something like:

while (n) {
    if (n & 1)
        printf("1");
    else
        printf("0");

    n >>= 1;
}
printf("\n");

How to force NSLocalizedString to use a specific language

whatever you all do, the best way is to take the short_name for the specified language, i.e.: fr, en, nl, de, it, etc... and assign the same to a global value.

make a picker view to pop up like a drop down menu (combination of a button on click of which a picker view appears from below with a list of languages) and select the language you desire. let the short name be stored internally. make a .h + .m file named LocalisedString.

Set the global value of short_name to be equal to the obtained value in LocalisedString.m When the required language is selected assign the NSBundlePath to create project sub-directories for the needed language. for eg, nl.proj, en.proj.

When the particular proj folder is selected call the localised string for the respective language and change the language dynamically.

no rules broken.

How to make jQuery UI nav menu horizontal?

This post has inspired me to try the jQuery ui menu.

http://jsfiddle.net/7Bvap/

<ul id="nav">
    <li><a href="#">Item 1</a></li>
    <li><a href="#">Item 2</a></li>
    <li><a href="#">Item 3</a>
        <ul>
            <li><a href="#">Item 3-1</a>
            <ul>
                <li><a href="#">Item 3-11</a></li>
                <li><a href="#">Item 3-12</a></li>
                <li><a href="#">Item 3-13</a></li>
            </ul>
            </li>
            <li><a href="#">Item 3-2</a></li>
            <li><a href="#">Item 3-3</a></li>
            <li><a href="#">Item 3-4</a></li>
            <li><a href="#">Item 3-5</a></li>
        </ul>
    </li>
    <li><a href="#">Item 4</a></li>
    <li><a href="#">Item 5</a></li>
</ul>


.ui-menu { 
    overflow: hidden;
}
.ui-menu .ui-menu {
    overflow: visible !important;
}
.ui-menu > li { 
    float: left;
    display: block;
    width: auto !important;
}
.ui-menu ul li {
    display:block;
    float:none;
}
.ui-menu ul li ul {
    left:120px !important;
    width:100%;
}
.ui-menu ul li ul li {
    width:auto;
}
.ui-menu ul li ul li a {
    float:left;
}
.ui-menu > li {
    margin: 5px 5px !important;
    padding: 0 0 !important;
}
.ui-menu > li > a { 
    float: left;
    display: block;
    clear: both;
    overflow: hidden;
}
.ui-menu .ui-menu-icon { 
    margin-top: 0.3em !important;
}
.ui-menu .ui-menu .ui-menu li { 
    float: left;
    display: block;
}


$( "#nav" ).menu({position: {at: "left bottom"}});

http://jsfiddle.net/vapD7/

<ul id="nav">
    <li><a href="#">Item 1</a></li>
    <li><a href="#">Item 2</a></li>
    <li><a href="#">Item 3</a>
        <ul>
            <li><a href="#">Item 3-1</a>
            <ul>
                <li><a href="#">Item 3-11</a></li>
                <li><a href="#">Item 3-12</a></li>
                <li><a href="#">Item 3-13</a></li>
            </ul>
            </li>
            <li><a href="#">Item 3-2</a></li>
            <li><a href="#">Item 3-3</a></li>
            <li><a href="#">Item 3-4</a></li>
            <li><a href="#">Item 3-5</a></li>
        </ul>
    </li>
    <li><a href="#">Item 4</a></li>
    <li><a href="#">Item 5</a></li>
</ul>

.ui-menu { list-style:none; padding: 2px; margin: 0; display:block; outline: none; }
.ui-menu .ui-menu { margin-top: -3px; position: absolute; }
.ui-menu .ui-menu-item {
    display: inline-block;
    float: left;
    margin: 0;
    padding: 0;
    width: auto;
}
.ui-menu .ui-menu-divider { margin: 5px -2px 5px -2px; height: 0; font-size: 0; line-height: 0; border-width: 1px 0 0 0; }
.ui-menu .ui-menu-item a { text-decoration: none; display: block; padding: 2px .4em; line-height: 1.5; zoom: 1; font-weight: normal; }
.ui-menu .ui-menu-item a.ui-state-focus,
.ui-menu .ui-menu-item a.ui-state-active { font-weight: normal; margin: -1px; }

.ui-menu .ui-state-disabled { font-weight: normal; margin: .4em 0 .2em; line-height: 1.5; }
.ui-menu .ui-state-disabled a { cursor: default; }
.ui-menu:after {
    content: ".";
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
}

$( "#nav" ).menu({position: {at: "left bottom"}});

Adding a tooltip to an input box

It seems to be a bug, it work for all input type that aren't textbox (checkboxes, radio,...)

There is a quick workaround that will work.

<div data-tip="This is the text of the tooltip2">
    <input type="text" name="test" value="44"/>
</div>

JsFiddle

How to TryParse for Enum value?

In the end you have to implement this around Enum.GetNames:

public bool TryParseEnum<T>(string str, bool caseSensitive, out T value) where T : struct {
    // Can't make this a type constraint...
    if (!typeof(T).IsEnum) {
        throw new ArgumentException("Type parameter must be an enum");
    }
    var names = Enum.GetNames(typeof(T));
    value = (Enum.GetValues(typeof(T)) as T[])[0];  // For want of a better default
    foreach (var name in names) {
        if (String.Equals(name, str, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)) {
            value = (T)Enum.Parse(typeof(T), name);
            return true;
        }
    }
    return false;
}

Additional notes:

  • Enum.TryParse is included in .NET 4. See here http://msdn.microsoft.com/library/dd991876(VS.100).aspx
  • Another approach would be to directly wrap Enum.Parse catching the exception thrown when it fails. This could be faster when a match is found, but will likely to slower if not. Depending on the data you are processing this may or may not be a net improvement.

EDIT: Just seen a better implementation on this, which caches the necessary information: http://damieng.com/blog/2010/10/17/enums-better-syntax-improved-performance-and-tryparse-in-net-3-5

sass --watch with automatic minify?

If you are using JetBrains editors like IntelliJ IDEA, PhpStorm, WebStorm etc. Use the following settings in Settings > File Watchers. enter image description here

  1. Convert style.scss to style.css set the arguments

    --no-cache --update $FileName$:$FileNameWithoutExtension$.css
    

    and output paths to refresh

    $FileNameWithoutExtension$.css
    
  2. Convert style.scss to compressed style.min.css set the arguments

    --no-cache --update $FileName$:$FileNameWithoutExtension$.min.css --style compressed
    

    and output paths to refresh

    $FileNameWithoutExtension$.min.css
    

Create an Excel file using vbscripts

Here is a sample code

strFileName = "c:\test.xls"

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True

Set objWorkbook = objExcel.Workbooks.Add()
objWorkbook.SaveAs(strFileName)

objExcel.Quit

How to sparsely checkout only one single file from a git repository?

Very simple:

git checkout from-branch-name -- path/to/the/file/you/want

This will not checkout the from-branch-name branch. You will stay on whatever branch you are on, and only that single file will be checked out from the specified branch.

Here's the relevant part of the manpage for git-checkout

git checkout [-p|--patch] [<tree-ish>] [--] <pathspec>...
       When <paths> or --patch are given, git checkout does not switch
       branches. It updates the named paths in the working tree from the
       index file or from a named <tree-ish> (most often a commit). In
       this case, the -b and --track options are meaningless and giving
       either of them results in an error. The <tree-ish> argument can be
       used to specify a specific tree-ish (i.e. commit, tag or tree) to
       update the index for the given paths before updating the working
       tree.

Hat tip to Ariejan de Vroom who taught me this from this blog post.

Get value of input field inside an iframe

Without Iframe We can do this by JQuery but it will give you only HTML page source and no dynamic links or html tags will display. Almost same as php solution but in JQuery :) Code---

var purl = "http://www.othersite.com";
$.getJSON('http://whateverorigin.org/get?url=' +
    encodeURIComponent(purl) + '&callback=?',
    function (data) {
    $('#viewer').html(data.contents);
});

Flexbox not working in Internet Explorer 11

I have tested a full layout using flexbox it contains header, footer, main body with left, center and right panels and the panels can contain menu items or footer and headers that should scroll. Pretty complex

IE11 and even IE EDGE have some problems displaying the flex content but it can be overcome. I have tested it in most browsers and it seems to work.

Some fixed i have applies are IE11 height bug, Adding height:100vh and min-height:100% to the html/body. this also helps to not have to set height on container in the dom. Also make the body/html a flex container. Otherwise IE11 will compress the view.

html,body {
    display: flex;
    flex-flow:column nowrap;
    height:100vh; /* fix IE11 */
    min-height:100%; /* fix IE11 */  
}

A fix for IE EDGE that overflows the flex container: overflow:hidden on main flex container. if you remove the overflow, IE EDGE wil push the content out of the viewport instead of containing it inside the flex main container.

main{
    flex:1 1 auto;
    overflow:hidden; /* IE EDGE overflow fix */  
}

enter image description here

You can see my testing and example on my codepen page. I remarked the important css parts with the fixes i have applied and hope someone finds it useful.

Meaning of 'const' last in a function declaration of a class?

Meaning of a Const Member Function in C++ Common Knowledge: Essential Intermediate Programming gives a clear explanation:

The type of the this pointer in a non-const member function of a class X is X * const. That is, it’s a constant pointer to a non-constant X (see Const Pointers and Pointers to Const [7, 21]). Because the object to which this refers is not const, it can be modified. The type of this in a const member function of a class X is const X * const. That is, it’s a constant pointer to a constant X. Because the object to which this refers is const, it cannot be modified. That’s the difference between const and non-const member functions.

So in your code:

class foobar
{
  public:
     operator int () const;
     const char* foo() const;
};

You can think it as this:

class foobar
{
  public:
     operator int (const foobar * const this) const;
     const char* foo(const foobar * const this) const;
};

How to store file name in database, with other info while uploading image to server using PHP?

Adding the following avoids problems with quotes in file names, e.g.

"freddy's pic.jpg"

which are acceptable on some operating systems.

Before:

$pic=($_FILES['photo']['name']);

After:

$pic=(mysql_real_escape_string($_FILES['photo']['name']));

Can anyone explain what JSONP is, in layman terms?

Preface:

This answer is over six years old. While the concepts and application of JSONP haven't changed (i.e. the details of the answer are still valid), you should look to use CORS where possible (i.e. your server or API supports it, and the browser support is adequate), as JSONP has inherent security risks.


JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers. (You are not allowed to make AJAX requests to a web page perceived to be on a different server by the browser.)

JSON and JSONP behave differently on the client and the server. JSONP requests are not dispatched using the XMLHTTPRequest and the associated browser methods. Instead a <script> tag is created, whose source is set to the target URL. This script tag is then added to the DOM (normally inside the <head> element).

JSON Request:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    // success
  };
};

xhr.open("GET", "somewhere.php", true);
xhr.send();

JSONP Request:

var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';

document.getElementsByTagName("head")[0].appendChild(tag);

The difference between a JSON response and a JSONP response is that the JSONP response object is passed as an argument to a callback function.

JSON:

{ "bar": "baz" }

JSONP:

foo( { "bar": "baz" } );

This is why you see JSONP requests containing the callback parameter, so that the server knows the name of the function to wrap the response.

This function must exist in the global scope at the time the <script> tag is evaluated by the browser (once the request has completed).


Another difference to be aware of between the handling of a JSON response and a JSONP response is that any parse errors in a JSON response could be caught by wrapping the attempt to evaluate the responseText in a try/catch statement. Because of the nature of a JSONP response, parse errors in the response will cause an uncatchable JavaScript parse error.

Both formats can implement timeout errors by setting a timeout before initiating the request and clearing the timeout in the response handler.


Using jQuery

The usefulness of using jQuery to make JSONP requests, is that jQuery does all of the work for you in the background.

By default jQuery requires you to include &callback=? in the URL of your AJAX request. jQuery will take the success function you specify, assign it a unique name, and publish it in the global scope. It will then replace the question mark ? in &callback=? with the name it has assigned.


Comparable JSON/JSONP Implementations

The following assumes a response object { "bar" : "baz" }

JSON:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    document.getElementById("output").innerHTML = eval('(' + this.responseText + ')').bar;
  };
};

xhr.open("GET", "somewhere.php", true);
xhr.send();

JSONP:

function foo(response) {
  document.getElementById("output").innerHTML = response.bar;
};

var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';

document.getElementsByTagName("head")[0].appendChild(tag);

What is meant with "const" at end of function declaration?

Function can't change its parameters via the pointer/reference you gave it.

I go to this page every time I need to think about it:

http://www.parashift.com/c++-faq-lite/const-correctness.html

I believe there's also a good chapter in Meyers' "More Effective C++".

Java Pass Method as Parameter

Since Java 8 there is a Function<T, R> interface (docs), which has method

R apply(T t);

You can use it to pass functions as parameters to other functions. T is the input type of the function, R is the return type.

In your example you need to pass a function that takes Component type as an input and returns nothing - Void. In this case Function<T, R> is not the best choice, since there is no autoboxing of Void type. The interface you are looking for is called Consumer<T> (docs) with method

void accept(T t);

It would look like this:

public void setAllComponents(Component[] myComponentArray, Consumer<Component> myMethod) {
    for (Component leaf : myComponentArray) {
        if (leaf instanceof Container) { 
            Container node = (Container) leaf;
            setAllComponents(node.getComponents(), myMethod);
        } 
        myMethod.accept(leaf);
    } 
}

And you would call it using method references:

setAllComponents(this.getComponents(), this::changeColor);
setAllComponents(this.getComponents(), this::changeSize); 

Assuming that you have defined changeColor() and changeSize() methods in the same class.


If your method happens to accept more than one parameter, you can use BiFunction<T, U, R> - T and U being types of input parameters and R being return type. There is also BiConsumer<T, U> (two arguments, no return type). Unfortunately for 3 and more input parameters, you have to create an interface by yourself. For example:

public interface Function4<A, B, C, D, R> {

    R apply(A a, B b, C c, D d);
}

MySQL Join Where Not Exists

I'd use a 'where not exists' -- exactly as you suggest in your title:

SELECT `voter`.`ID`, `voter`.`Last_Name`, `voter`.`First_Name`,
       `voter`.`Middle_Name`, `voter`.`Age`, `voter`.`Sex`,
       `voter`.`Party`, `voter`.`Demo`, `voter`.`PV`,
       `household`.`Address`, `household`.`City`, `household`.`Zip`
FROM (`voter`)
JOIN `household` ON `voter`.`House_ID`=`household`.`id`
WHERE `CT` = '5'
AND `Precnum` = 'CTY3'
AND  `Last_Name`  LIKE '%Cumbee%'
AND  `First_Name`  LIKE '%John%'

AND NOT EXISTS (
  SELECT * FROM `elimination`
   WHERE `elimination`.`voter_id` = `voter`.`ID`
)

ORDER BY `Last_Name` ASC
LIMIT 30

That may be marginally faster than doing a left join (of course, depending on your indexes, cardinality of your tables, etc), and is almost certainly much faster than using IN.

Error: Cannot find module 'ejs'

Reinstalling npm, express and ejs fixed my problem

This one worked for me,

  1. On your terminal or cmd -> Go to your apps directory,
  2. cd pathtoyourapp/AppName
  3. rerun your 'npm install'
  4. rerun your 'npm install express'
  5. rerun your 'npm install ejs'

after that, the error was fixed.

Dependent DLL is not getting copied to the build output folder in Visual Studio

If you right Click the referenced assembly, you will see a property called Copy Local. If Copy Local is set to true, then the assembly should be included in the bin. However, there seams to be a problem with Visual studio, that sometimes it does not include the referenced dll in the bin folder... this is the workaround that worked for me:

enter image description here

Can't resolve module (not found) in React.js

I faced the same issue when I created a new react app, I tried all options in https://github.com/facebook/create-react-app/issues/2534 but it didn't help. I had to change the port for the new app and then it worked. By default, apps use the port 3000.I changed the port to 8001 in package.json as follows:

  "scripts": {
    "start": "PORT=8001 react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

How to center text vertically with a large font-awesome icon?

Another option to fine-tune the line height of an icon is by using a percentage of the vertical-align property. Usually, 0% is a the bottom, and 100% at the top, but one could use negative values or more than a hundred to create interesting effects.

.my-element i.fa {
    vertical-align: 100%; // top
    vertical-align: 50%; // middle
    vertical-align: 0%; // bottom
}

Hyper-V: Create shared folder between host and guest with internal network

Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Prerequisites

  1. Ensure that Enhanced session mode settings are enabled on the Hyper-V host.

    Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".

    hyper-v-settings

    Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.

    use-enhanced-session-mode

  2. Enable Hyper-V Guest Services for your virtual machine

    Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.

    enable-guest-services

Steps to share devices with Hyper-v virtual machine:

  1. Start a virtual machine and click Show Options in the pop-up windows.

    connect-to-vm

    Or click "Edit Session Settings..." in the Actions panel on the right

    edit-session-sessions

    It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.

  2. View local resources. Then, select the "More..." menu.

    click-more

  3. From there, you can choose which devices to share. Removable drives are especially useful for file sharing.

    choose-the-devices-that-you-want-to-use

  4. Choose to "Save my settings for future connections to this virtual machine".

    save-my-settings-for-future-connections-to-this-vm

  5. Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.

    shared-drives-from-local-pc

Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Adding sheets to end of workbook in Excel (normal method not working?)

mainWB.Sheets.Add(After:=Sheets(Sheets.Count)).Name = new_sheet_name 

should probably be

mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name 

Null vs. False vs. 0 in PHP

Below is an example:

            Comparisons of $x with PHP functions

Expression          gettype()   empty()     is_null()   isset() boolean : if($x)
$x = "";            string      TRUE        FALSE       TRUE    FALSE
$x = null;          NULL        TRUE        TRUE        FALSE   FALSE
var $x;             NULL        TRUE        TRUE        FALSE   FALSE
$x is undefined     NULL        TRUE        TRUE        FALSE   FALSE
$x = array();       array       TRUE        FALSE       TRUE    FALSE
$x = false;         boolean     TRUE        FALSE       TRUE    FALSE
$x = true;          boolean     FALSE       FALSE       TRUE    TRUE
$x = 1;             integer     FALSE       FALSE       TRUE    TRUE
$x = 42;            integer     FALSE       FALSE       TRUE    TRUE
$x = 0;             integer     TRUE        FALSE       TRUE    FALSE
$x = -1;            integer     FALSE       FALSE       TRUE    TRUE
$x = "1";           string      FALSE       FALSE       TRUE    TRUE
$x = "0";           string      TRUE        FALSE       TRUE    FALSE
$x = "-1";          string      FALSE       FALSE       TRUE    TRUE
$x = "php";         string      FALSE       FALSE       TRUE    TRUE
$x = "true";        string      FALSE       FALSE       TRUE    TRUE
$x = "false";       string      FALSE       FALSE       TRUE    TRUE

Please see this for more reference of type comparisons in PHP. It should give you a clear understanding.

Link to Flask static files with url_for

In my case I had special instruction into nginx configuration file:

location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
            try_files $uri =404;
    }

All clients have received '404' because nginx nothing known about Flask.

I hope it help someone.

Read all worksheets in an Excel workbook into an R list with data.frames

Adding to Paul's answer. The sheets can also be concatenated using something like this:

data = path %>% 
excel_sheets() %>% 
set_names() %>% 
map_df(~ read_excel(path = path, sheet = .x), .id = "Sheet")

Libraries needed:

if(!require(pacman))install.packages("pacman")
pacman::p_load("tidyverse","readxl","purrr")

Ant task to run an Ant target only if a file exists?

Available and Condition

<target name="check-abc">
    <available file="abc.txt" property="abc.present"/>
</target>

<target name="do-if-abc" depends="check-abc" if="abc.present">
    ...
</target> 

JavaScript closure inside loops – simple practical example

try this shorter one

  • no array

  • no extra for loop


for (var i = 0; i < 3; i++) {
    createfunc(i)();
}

function createfunc(i) {
    return function(){console.log("My value: " + i);};
}

http://jsfiddle.net/7P6EN/

Creating a daemon in Linux

Daemon Template

I wrote a daemon template following the new-style daemon: link

You can find the entire template code on GitHub: here

Main.cpp

// This function will be called when the daemon receive a SIGHUP signal.
void reload() {
    LOG_INFO("Reload function called.");
}

int main(int argc, char **argv) {
    // The Daemon class is a singleton to avoid be instantiate more than once
    Daemon& daemon = Daemon::instance();
    // Set the reload function to be called in case of receiving a SIGHUP signal
    daemon.setReloadFunction(reload);
    // Daemon main loop
    int count = 0;
    while(daemon.IsRunning()) {
        LOG_DEBUG("Count: ", count++);
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    LOG_INFO("The daemon process ended gracefully.");
}

Daemon.hpp

class Daemon {
    public:

    static Daemon& instance() {
        static Daemon instance;
        return instance;
    }

    void setReloadFunction(std::function<void()> func);

    bool IsRunning();

    private:

    std::function<void()> m_reloadFunc;
    bool m_isRunning;
    bool m_reload;

    Daemon();
    Daemon(Daemon const&) = delete;
    void operator=(Daemon const&) = delete;

    void Reload();

    static void signalHandler(int signal);
};

Daemon.cpp

Daemon::Daemon() {
    m_isRunning = true;
    m_reload = false;
    signal(SIGINT, Daemon::signalHandler);
    signal(SIGTERM, Daemon::signalHandler);
    signal(SIGHUP, Daemon::signalHandler);
}

void Daemon::setReloadFunction(std::function<void()> func) {
    m_reloadFunc = func;
}

bool Daemon::IsRunning() {
    if (m_reload) {
        m_reload = false;
        m_reloadFunc();
    }
    return m_isRunning;
}

void Daemon::signalHandler(int signal) {
    LOG_INFO("Interrup signal number [", signal,"] recived.");
    switch(signal) {
        case SIGINT:
        case SIGTERM: {
            Daemon::instance().m_isRunning = false;
            break;
        }
        case SIGHUP: {
            Daemon::instance().m_reload = true;
            break;
        }
    }
}

daemon-template.service

[Unit]
Description=Simple daemon template
After=network.taget

[Service]
Type=simple
ExecStart=/usr/bin/daemon-template --conf_file /etc/daemon-template/daemon-tenplate.conf
ExecReload=/bin/kill -HUP $MAINPID
User=root
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=daemon-template

[Install]
WantedBy=multi-user.target

Compile to a stand-alone executable (.exe) in Visual Studio

If I understand you correctly, yes you can, but not under Visual Studio (from what I know). To force the compiler to generate a real, standalone executable (which means you use C# like any other language) you use the program mkbundle (shipped with Mono). This will compile your C# app into a real, no dependency executable.

There is a lot of misconceptions about this around the internet. It does not defeat the purpose of the .net framework like some people state, because how can you lose future features of the .net framework if you havent used these features to begin with? And when you ship updates to your app, it's not exactly hard work to run it through the mkbundle processor before building your installer. There is also a speed benefit involved making your app run at native speed (because now it IS native).

In C++ or Delphi you have the same system, but without the middle MSIL layer. So if you use a namespace or sourcefile (called a unit under Delphi), then it's compiled and included in your final binary. So your final binary will be larger (Read: "Normal" size for a real app). The same goes for the parts of the framework you use in .net, these are also included in your app. However, smart linking does shave a conciderable amount.

Hope it helps!

Map with Key as String and Value as List in Groovy

you don't need to declare Map groovy internally recognizes it

def personDetails = [firstName:'John', lastName:'Doe', fullName:'John Doe']

// print the values..
    println "First Name: ${personDetails.firstName}"
    println "Last Name: ${personDetails.lastName}"

http://grails.asia/groovy-map-tutorial

Access PHP variable in JavaScript

metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:

<script type="text/javascript">
var something=<?php echo json_encode($a); ?>;
</script>

Javascript swap array elements

Here is a variation that first checks if the index exists in the array:

Array.prototype.swapItems = function(a, b){
    if(  !(a in this) || !(b in this) )
        return this;
    this[a] = this.splice(b, 1, this[a])[0];
    return this;
}

It currently will just return this if the index does not exist, but you could easily modify behavior on fail

What is [Serializable] and when should I use it?

Here is short example of how serialization works. I was also learning about the same and I found two links useful. What Serialization is and how it can be done in .NET.

A sample program explaining serialization

If you don't understand the above program a much simple program with explanation is given here.

Why do I need an IoC container as opposed to straightforward DI code?

Whenever you use the "new" keyword, you are creating a concrete class dependency and a little alarm bell should go off in your head. It becomes harder to test this object in isolation. The solution is to program to interfaces and inject the dependency so that the object can be unit tested with anything that implements that interface (eg. mocks).

The trouble is you have to construct objects somewhere. A Factory pattern is one way to shift the coupling out of your POXOs (Plain Old "insert your OO language here" Objects). If you and your co-workers are all writing code like this then an IoC container is the next "Incremental Improvement" you can make to your codebase. It'll shift all that nasty Factory boilerplate code out of your clean objects and business logic. They'll get it and love it. Heck, give a company talk on why you love it and get everyone enthused.

If your co-workers aren't doing DI yet, then I'd suggest you focus on that first. Spread the word on how to write clean code that is easily testable. Clean DI code is the hard part, once you're there, shifting the object wiring logic from Factory classes to an IoC container should be relatively trivial.

Catch Ctrl-C in C

Or you can put the terminal in raw mode, like this:

struct termios term;

term.c_iflag |= IGNBRK;
term.c_iflag &= ~(INLCR | ICRNL | IXON | IXOFF);
term.c_lflag &= ~(ICANON | ECHO | ECHOK | ECHOE | ECHONL | ISIG | IEXTEN);
term.c_cc[VMIN] = 1;
term.c_cc[VTIME] = 0;
tcsetattr(fileno(stdin), TCSANOW, &term);

Now it should be possible to read Ctrl+C keystrokes using fgetc(stdin). Beware using this though because you can't Ctrl+Z, Ctrl+Q, Ctrl+S, etc. like normally any more either.

Why should you use strncpy instead of strcpy?

strncpy combats buffer overflow by requiring you to put a length in it. strcpy depends on a trailing \0, which may not always occur.

Secondly, why you chose to only copy 5 characters on 7 character string is beyond me, but it's producing expected behavior. It's only copying over the first n characters, where n is the third argument.

The n functions are all used as defensive coding against buffer overflows. Please use them in lieu of older functions, such as strcpy.

I need to get all the cookies from the browser

Added trim() to the key in object, and name it str, so it would be more clear that we are dealing with string here.

export const getAllCookies = () => document.cookie.split(';').reduce((ac, str) => Object.assign(ac, {[str.split('=')[0].trim()]: str.split('=')[1]}), {});

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

How to return temporary table from stored procedure

What version of SQL Server are you using? In SQL Server 2008 you can use Table Parameters and Table Types.

An alternative approach is to return a table variable from a user defined function but I am not a big fan of this method.

You can find an example here

Java output formatting for Strings

System.out.println(String.format("%-20s= %s" , "label", "content" ));
  • Where %s is a placeholder for you string.
  • The '-' makes the result left-justified.
  • 20 is the width of the first string

The output looks like this:

label               = content

As a reference I recommend Javadoc on formatter syntax

Java8: sum values from specific field of the objects in a list

You can do

int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(o -> o.getField()).sum();

or (using Method reference)

int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(Obj::getField).sum();

Standardize data columns in R

You can easily normalize the data also using data.Normalization function in clusterSim package. It provides different method of data normalization.

    data.Normalization (x,type="n0",normalization="column")

Arguments

x
vector, matrix or dataset type
type of normalization: n0 - without normalization

n1 - standardization ((x-mean)/sd)

n2 - positional standardization ((x-median)/mad)

n3 - unitization ((x-mean)/range)

n3a - positional unitization ((x-median)/range)

n4 - unitization with zero minimum ((x-min)/range)

n5 - normalization in range <-1,1> ((x-mean)/max(abs(x-mean)))

n5a - positional normalization in range <-1,1> ((x-median)/max(abs(x-median)))

n6 - quotient transformation (x/sd)

n6a - positional quotient transformation (x/mad)

n7 - quotient transformation (x/range)

n8 - quotient transformation (x/max)

n9 - quotient transformation (x/mean)

n9a - positional quotient transformation (x/median)

n10 - quotient transformation (x/sum)

n11 - quotient transformation (x/sqrt(SSQ))

n12 - normalization ((x-mean)/sqrt(sum((x-mean)^2)))

n12a - positional normalization ((x-median)/sqrt(sum((x-median)^2)))

n13 - normalization with zero being the central point ((x-midrange)/(range/2))

normalization
"column" - normalization by variable, "row" - normalization by object

Remove last characters from a string in C#. An elegant way?

Perhaps this:

str = str.Split(",").First();

How do I access refs of a child component in the parent component

I think this guide explains it pretty well https://github.com/yannickcr/eslint-plugin-react/issues/678

class Field extends Component {
  const { inputRef } = this.props;
  render() {
    return (
      <input type="text" ref={inputRef} />
    )
  }
}

class MyComponent extends Component {
  componentDidMount() {
    this.inputNode.focus();
  }

  render() {
    return (
      <div>
        Hello, <Field inputRef={node => this.inputNode = node} />
      </div>
    )
  }
}

How to capture Curl output to a file?

If you want to store your output into your desktop, follow the below command using post command in git bash.It worked for me.

curl https://localhost:8080 --request POST --header "Content-Type: application/json" -o "C:\Desktop\test.txt"

A default document is not configured for the requested URL, and directory browsing is not enabled on the server

Have you add a default route to this class?

public class RouteConfig {
    public static void RegisterRoutes (RouteCollection routes) {`
        //"HomePage" is the root view of your app
        routes.MapRoute (
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new {
                controller = "Home", action = "HomePage", id = UrlParameter.Optional
            }
        );
    }
}

` After that in Global.asax.cs add this line to Application_Start() method:

RouteConfig.RegisterRoutes (RouteTable.Routes);

I had this problem after I made an upgrade from MVC4 to MVC5 following this post and I had that line commented for a reason that I've forgot.

Hope this helps!

What Regex would capture everything from ' mark to the end of a line?

When I tried '.* in windows (Notepad ++) it would match everything after first ' until end of last line.

To capture everything until end of that line I typed the following:

'.*?\n

This would only capture everything from ' until end of that line.

Auto insert date and time in form input field?

If you are using HTML5 date

use this code

HTML

<input type="date" name="bday" id="start_date"/>

Java Script

document.getElementById('start_date').value = Date();

How to get memory available or used in C#

System.Environment has WorkingSet- a 64-bit signed integer containing the number of bytes of physical memory mapped to the process context.

If you want a lot of details there is System.Diagnostics.PerformanceCounter, but it will be a bit more effort to setup.

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

Sorry, no reputation to add this as a comment. So it goes as an complementary answer.

Depending on how often you will call clock_gettime(), you should keep in mind that only some of the "clocks" are provided by Linux in the VDSO (i.e. do not require a syscall with all the overhead of one -- which only got worse when Linux added the defenses to protect against Spectre-like attacks).

While clock_gettime(CLOCK_MONOTONIC,...), clock_gettime(CLOCK_REALTIME,...), and gettimeofday() are always going to be extremely fast (accelerated by the VDSO), this is not true for, e.g. CLOCK_MONOTONIC_RAW or any of the other POSIX clocks.

This can change with kernel version, and architecture.

Although most programs don't need to pay attention to this, there can be latency spikes in clocks accelerated by the VDSO: if you hit them right when the kernel is updating the shared memory area with the clock counters, it has to wait for the kernel to finish.

Here's the "proof" (GitHub, to keep bots away from kernel.org): https://github.com/torvalds/linux/commit/2aae950b21e4bc789d1fc6668faf67e8748300b7

Convert pandas DataFrame into list of lists

EDIT: as_matrix is deprecated since version 0.23.0

You can use the built in values or to_numpy (recommended option) method on the dataframe:

In [8]:
df.to_numpy()

Out[8]:
array([[  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.8,   6.1,   5.4, ...,  15.9,  14.4,   8.6],
   ..., 
   [  0.2,   1.3,   2.3, ...,  16.1,  16.1,  10.8],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4]])

If you explicitly want lists and not a numpy array add .tolist():

df.to_numpy().tolist()

How enable auto-format code for Intellij IDEA?

The formatting shortcuts in Intellij IDEA are :

  • For Windows : Ctrl + Alt + L
  • For Ubuntu : Ctrl + Alt + Windows + L
  • For Mac : ? (Option) + ? (Command) + L

How can I hide a TD tag using inline JavaScript or CSS?

.hide{

visibility: hidden

}

<td class="hide"/>

Edit- Just for you

The difference between display and visibility is this.

"display": has many properties or values, but the ones you're focused on are "none" and "block". "none" is like a hide value, and "block" is like show. If you use the "none" value you will totally hide what ever html tag you have applied this css style. If you use "block" you will see the html tag and it's content. very simple.

"visibility": has many values, but we want to know more about the "hidden" and "visible" values. "hidden" will work in the same way as the "block" value for display, but this will hide tag and it's content, but it will not hide the phisical space of that tag. For example, if you have a couple of text lines, then and image (picture) and then a table with three columns and two rows with icons and text. Now if you apply the visibility css with the hidden value to the image, the image will disappear but the space the image was using will remaing in it's place, in other words, you will end with a big space (hole) between the text and the table. Now if you use the "visible" value your target tag and it's elements will be visible again.

what is the differences between sql server authentication and windows authentication..?

Authentication is the process of confirming a user or computer’s identity. The process normally consists of four steps: The user makes a claim of identity, usually by providing a username. For example, I might make this claim by telling a database that my username is “mchapple”. The system challenges the user to prove his or her identity. The most common challenge is a request for a password. The user responds to the challenge by providing the requested proof. In this example, I would provide the database with my password The system verifies that the user has provided acceptable proof by, for example, checking the password against a local password database or using a centralized authentication server

How do I get the month and day with leading 0's in SQL? (e.g. 9 => 09)

For SQL Server 2012 and up , with leading zeroes:

 SELECT FORMAT(GETDATE(),'MM') 

without:

SELECT    MONTH(GETDATE())

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

You can replace it with its clone like so

var clone = $('#control').clone();

$('#control').replacewith(clone);

But this clones with its value too so you had better like so

var emtyValue = $('#control').val('');
var clone = emptyValue.clone();

$('#control').replacewith(clone);

It is more efficient to use if-return-return or if-else-return?

I personally avoid else blocks when possible. See the Anti-if Campaign

Also, they don't charge 'extra' for the line, you know :p

"Simple is better than complex" & "Readability is king"

delta = 1 if (A > B) else -1
return A + delta

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

I had the same error because of character '@' in my resources/application.properties. All I did was replacing the '@' for its unicode value: eureka.client.serviceUrl.defaultZone=http://discUser:discPassword\u0040localhost:8082/eureka/ and it worked like charm. I know the '@' is a perfectly valid character in .properties files and the file was in UTF-8 encoding and it makes me question my career till today but it's worth a shot if you delete content of your resource files to see if you can get pass this error.

Convert np.array of type float64 to type uint8 scaling values

A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2], the code right now would scale that to have intensities of [0, 128, 255]. You want these to remain small after converting to np.uint8.

Therefore, divide every value by the largest value possible by the image type, not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo and provide it the type (dtype) of the image and you will obtain a structure of information for that type. You would then access the max field from this structure to determine the maximum value.

So with the above, do the following modifications to your code:

import numpy as np
import cv2
[...]
info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64) / info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)

Note that I've additionally converted the image into np.float64 in case the incoming data type is not so and to maintain floating-point precision when doing the division.

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

When using the attribute to restrict the maximum input length for text from a form on a webpage, the StringLength seems to generate the maxlength html attribute (at least in my test with MVC 5). The one to choose then depnds on how you want to alert the user that this is the maximum text length. With the stringlength attribute, the user will simply not be able to type beyond the allowed length. The maxlength attribute doesn't add this html attribute, instead it generates data validation attributes, meaning the user can type beyond the indicated length and that preventing longer input depends on the validation in javascript when he moves to the next field or clicks submit (or if javascript is disabled, server side validation). In this case the user can be notified of the restriction by an error message.

Function to convert timestamp to human date in javascript

why not simply

new Date (timestamp);

A date is a date, the formatting of it is a different matter.

Android Studio - How to increase Allocated Heap Size

If you are using MAC BOOK, this option is available inside Applications -> Right click Android Studio then choose Show Package contents -> bin.

enter image description here

or

open -e /Applications/Android\ Studio.app/Contents/bin/studio.vmoptions

Then increase Xmx value

-Xms128m
-Xmx2048m
-XX:MaxPermSize=350m
-XX:ReservedCodeCacheSize=64m
-XX:+UseCodeCacheFlushing
-XX:+UseCompressedOops

Now your Android Studio will be super-fast.

PowerShell: Create Local User Account

Try using Carbon's Install-User and Add-GroupMember functions:

Install-User -Username "User" -Description "LocalAdmin" -FullName "Local Admin by Powershell" -Password "Password01"
Add-GroupMember -Name 'Administrators' -Member 'User'

Disclaimer: I am the creator/maintainer of the Carbon project.

Can an AWS Lambda function call another

Others pointed out to use SQS and Step Functions. But both these solutions add additional cost. Step Function state transitions are supposedly very expensive.

AWS lambda offers some retry logic. Where it tries something for 3 times. I am not sure if that is still valid when you trigger it use the API.

How could I create a function with a completion handler in Swift?

In addition to above : Trailing closure can be used .

downloadFileFromURL(NSURL(string: "url_str")!)  { (success) -> Void in

  // When download completes,control flow goes here.
  if success {
      // download success
  } else {
    // download fail
  }
}

How to add a downloaded .box file to Vagrant?

Alternatively to add downloaded box, a json file with metadata can be created. This way some additional details can be applied. For example to import box and specifying its version create file:

{
  "name": "laravel/homestead",
  "versions": [
    {
      "version": "7.0.0",
      "providers": [
        {
          "name": "virtualbox",
          "url": "file:///path/to/box/virtualbox.box"
        }
      ]
    }
  ]
}

Then run vagrant box add command with parameter:

vagrant box add laravel/homestead /path/to/metadata.json

Xcode is not currently available from the Software Update server

The command

xcode-select --install

proposes 3 options: Get Xcode; Not Now; Install.

When I choose to get full Xcode the command finished successfully. It took a while, but this way I was able to complete all macports migration instructions.

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

Strangely enough, I don't think there is a standard solution to this problem, as the spring-security access control is expression based, not java-based. you might check the source code for DefaultMethodSecurityExpressionHandler to see if you can re-use something they are doing there

Java: int[] array vs int array[]

There is virtually no difference.

jQuery Mobile: document ready vs. page events

While you use .on(), it's basically a live query that you are using.

On the other hand, .ready (as in your case) is a static query. While using it, you can dynamically update data and do not have to wait for the page to load. You can simply pass on the values into your database (if required) when a particular value is entered.

The use of live queries is common in forms where we enter data (account or posts or even comments).

C# event with custom arguments

Here's a reworking of your sample to get you started.

  • your sample has a static event - it's more usual for an event to come from a class instance, but I've left it static below.

  • the sample below also uses the more standard naming OnXxx for the method that raises the event.

  • the sample below does not consider thread-safety, which may well be more of an issue if you insist on your event being static.

.

public enum MyEvents{ 
     Event1 
} 

public class MyEventArgs : EventArgs
{
    public MyEventArgs(MyEvents myEvents)
    {
        MyEvents = myEvents;
    }

    public MyEvents MyEvents { get; private set; }
}

public static class MyClass
{
     public static event EventHandler<MyEventArgs> EventTriggered; 

     public static void Trigger(MyEvents myEvents) 
     {
         OnMyEvent(new MyEventArgs(myEvents));
     }

     protected static void OnMyEvent(MyEventArgs e)
     {
         if (EventTriggered != null)
         {
             // Normally the first argument (sender) is "this" - but your example
             // uses a static event, so I'm passing null instead.
             // EventTriggered(this, e);
             EventTriggered(null, e);
         } 
     }
}

Generate .pem file used to set up Apple Push Notifications

According to Troubleshooting Push Certificate Problems

The SSL certificate available in your Apple Developer Program account contains a public key but not a private key. The private key exists only on the Mac that created the Certificate Signing Request uploaded to Apple. Both the public and private keys are necessary to export the Privacy Enhanced Mail (PEM) file.

Chances are the reason you can't export a working PEM from the certificate provided by the client is that you do not have the private key. The certificate contains the public key, while the private key probably only exists on the Mac that created the original CSR.

You can either:

  1. Try to get the private key from the Mac that originally created the CSR. Exporting the PEM can be done from that Mac or you can copy the private key to another Mac.

or

  1. Create a new CSR, new SSL certificate, and this time back up the private key.

PHP preg_replace special characters

$newstr = preg_replace('/[^a-zA-Z0-9\']/', '_', "There wouldn't be any");
$newstr = str_replace("'", '', $newstr);

I put them on two separate lines to make the code a little more clear.

Note: If you're looking for Unicode support, see Filip's answer below. It will match all characters that register as letters in addition to A-z.

How to move mouse cursor using C#?

Take a look at the Cursor.Position Property. It should get you started.

private void MoveCursor()
{
   // Set the Current cursor, move the cursor's Position,
   // and set its clipping rectangle to the form. 

   this.Cursor = new Cursor(Cursor.Current.Handle);
   Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
   Cursor.Clip = new Rectangle(this.Location, this.Size);
}

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

I'm using Mojave with rbenv, this solution works for me:

$ vi ~/.bash_profile

Add this line into the file:

if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi

Allow docker container to connect to a local/host postgres database

The solution posted here does not work for me. Therefore, I am posting this answer to help someone facing similar issue.

OS: Ubuntu 18
PostgreSQL: 9.5 (Hosted on Ubuntu)
Docker: Server Application (which connects to PostgreSQL)

I am using docker-compose.yml to build application.

STEP 1: Please add host.docker.internal:<docker0 IP>

version: '3'
services:
  bank-server:
    ...
    depends_on:
      ....
    restart: on-failure
    ports:
      - 9090:9090
    extra_hosts:
      - "host.docker.internal:172.17.0.1"

To find IP of docker i.e. 172.17.0.1 (in my case) you can use:

$> ifconfig docker0
docker0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255

OR

$> ip a
1: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever

STEP 2: In postgresql.conf, change listen_addresses to listen_addresses = '*'

STEP 3: In pg_hba.conf, add this line

host    all             all             0.0.0.0/0               md5

STEP 4: Now restart postgresql service using, sudo service postgresql restart

STEP 5: Please use host.docker.internal hostname to connect database from Server Application.
Ex: jdbc:postgresql://host.docker.internal:5432/bankDB

Enjoy!!

How can I switch views programmatically in a view controller? (Xcode, iPhone)

Swift 3.0 Version

if you want to present new controller.

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "controllerIdentifier") as! YourController
self.present(viewController, animated: true, completion: nil)

and if you want to push to another controller (if it is in navigation)

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "controllerIdentifier") as! YourController
self.navigationController?.pushViewController(viewController, animated: true)

Could not install packages due to an EnvironmentError: [Errno 13]

I also had the same problem, I tried many different command lines, this one worked for me:

Try:

    conda install py-xgboost

That's what I got:

Collecting package metadata: done
Solving environment: done

## Package Plan ##

  environment location: /home/simplonco/anaconda3

  added / updated specs:
    - py-xgboost


The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    _py-xgboost-mutex-2.0      |            cpu_0           9 KB
    ca-certificates-2019.1.23  |                0         126 KB
    certifi-2018.11.29         |           py37_0         146 KB
    conda-4.6.2                |           py37_0         1.7 MB
    libxgboost-0.80            |       he6710b0_0         3.7 MB
    mkl-2019.1                 |              144       204.6 MB
    mkl_fft-1.0.10             |   py37ha843d7b_0         169 KB
    mkl_random-1.0.2           |   py37hd81dba3_0         405 KB
    numpy-1.15.4               |   py37h7e9f1db_0          47 KB
    numpy-base-1.15.4          |   py37hde5b4d6_0         4.2 MB
    py-xgboost-0.80            |   py37he6710b0_0         1.7 MB
    scikit-learn-0.20.2        |   py37hd81dba3_0         5.7 MB
    scipy-1.2.0                |   py37h7c811a0_0        17.7 MB
    ------------------------------------------------------------
                                           Total:       240.0 MB

The following NEW packages will be INSTALLED:

  _py-xgboost-mutex  pkgs/main/linux-64::_py-xgboost-mutex-2.0-cpu_0
  libxgboost         pkgs/main/linux-64::libxgboost-0.80-he6710b0_0
  py-xgboost         pkgs/main/linux-64::py-xgboost-0.80-py37he6710b0_0

The following packages will be UPDATED:

  ca-certificates     anaconda::ca-certificates-2018.12.5-0 --> pkgs/main::ca-certificates-2019.1.23-0
  mkl                                            2019.0-118 --> 2019.1-144
  mkl_fft                              1.0.4-py37h4414c95_1 --> 1.0.10-py37ha843d7b_0
  mkl_random                           1.0.1-py37h4414c95_1 --> 1.0.2-py37hd81dba3_0
  numpy                               1.15.1-py37h1d66e8a_0 --> 1.15.4-py37h7e9f1db_0
  numpy-base                          1.15.1-py37h81de0dd_0 --> 1.15.4-py37hde5b4d6_0
  scikit-learn                        0.19.2-py37h4989274_0 --> 0.20.2-py37hd81dba3_0
  scipy                                1.1.0-py37hfa4b5c9_1 --> 1.2.0-py37h7c811a0_0

The following packages will be SUPERSEDED by a higher-priority channel:

  certifi                                          anaconda --> pkgs/main
  conda                                            anaconda --> pkgs/main
  openssl                anaconda::openssl-1.1.1-h7b6447c_0 --> pkgs/main::openssl-1.1.1a-h7b6447c_0


Proceed ([y]/n)? y


Downloading and Extracting Packages
libxgboost-0.80      | 3.7 MB    | ##################################### | 100% 
mkl_random-1.0.2     | 405 KB    | ##################################### | 100% 
certifi-2018.11.29   | 146 KB    | ##################################### | 100% 
ca-certificates-2019 | 126 KB    | ##################################### | 100% 
conda-4.6.2          | 1.7 MB    | ##################################### | 100% 
mkl-2019.1           | 204.6 MB  | ##################################### | 100% 
mkl_fft-1.0.10       | 169 KB    | ##################################### | 100% 
numpy-1.15.4         | 47 KB     | ##################################### | 100% 
scipy-1.2.0          | 17.7 MB   | ##################################### | 100% 
scikit-learn-0.20.2  | 5.7 MB    | ##################################### | 100% 
py-xgboost-0.80      | 1.7 MB    | ##################################### | 100% 
_py-xgboost-mutex-2. | 9 KB      | ##################################### | 100% 
numpy-base-1.15.4    | 4.2 MB    | ##################################### | 100% 
Preparing transaction: done
Verifying transaction: done
Executing transaction: done

How to search a Git repository by commit message?

If the change is not too old, you can do,

git reflog

and then checkout the commit id

Implement paging (skip / take) functionality with this query

SQL 2008

Radim Köhler's answer works, but here is a shorter version:

select top 20 * from
(
select *,
ROW_NUMBER() OVER (ORDER BY columnid) AS ROW_NUM
from tablename
) x
where ROW_NUM>10

Source: https://forums.asp.net/post/4033909.aspx

How to resolve git stash conflict without commit?

git checkout stash -- .

worked for me.

Note: this can be dangerous since it doesn't try to merge the changes from the stash into your working copy, but overwrites it with the stashed files instead. So you can lose your uncommitted changes.

Is there a better way to do optional function parameters in JavaScript?

Folks -

After looking at these and other solutions, I tried a number of them out using a snippet of code originally from W3Schools as a base. You can find what works in the following. Each of the items commented out work as well and are that way to allow you to experiment simply by removing individual comments. To be clear, it is the "eyecolor" parameter that is not being defined.

function person(firstname, lastname, age, eyecolor)
{
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
this.eyecolor = eyecolor;
// if(null==eyecolor)
//   this.eyecolor = "unknown1";
//if(typeof(eyecolor)==='undefined') 
//   this.eyecolor = "unknown2";
// if(!eyecolor)
//   this.eyecolor = "unknown3";
this.eyecolor = this.eyecolor || "unknown4";
}

var myFather = new person("John", "Doe", 60);
var myMother = new person("Sally", "Rally", 48, "green");

var elem = document.getElementById("demo");
elem.innerHTML = "My father " +
              myFather.firstname + " " +
              myFather.lastname + " is " +
              myFather.age + " with " +
              myFather.eyecolor + " eyes.<br/>" +
              "My mother " +
              myMother.firstname + " " +
              myMother.lastname + " is " +
              myMother.age + " with " +
              myMother.eyecolor + " eyes."; 

"configuration file /etc/nginx/nginx.conf test failed": How do I know why this happened?

If you want to check syntax error for any nginx files, you can use the -c option.

[root@server ~]# sudo nginx -t -c /etc/nginx/my-server.conf
nginx: the configuration file /etc/nginx/my-server.conf syntax is ok
nginx: configuration file /etc/nginx/my-server.conf test is successful
[root@server ~]# 

Laravel view not found exception

This might be possible that your view is present even though it shows the error. So to solve this issue you need to stop the server and run this command on the terminal.

php artisan config:cache

then restart the server

How can I extract a number from a string in JavaScript?

I think this regular expression will serve your purpose:

var num = txt.replace(/[^0-9]/g,'');

Where txt is your string.

It basically rips off anything that is not a digit.

I think you can achieve the same thing by using this as well :

var num = txt.replace(/\D/g,'');

Freeing up a TCP/IP port?

Kill the process that is listening to the port in question. I believe netstat shows you process ids.

CSS/HTML: Create a glowing border around an Input Field

I combined two of the previous answers (jsfiddle).

input {
    /* round the corners */
    border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;    
}

input:focus { 
    outline:none;
    border: 1px solid #4195fc; 
    /* create a BIG glow */
    box-shadow: 0px 0px 14px #4195fc; 
    -moz-box-shadow: 0px 0px 14px #4195fc;
    -webkit-box-shadow: 0px 0px 14px #4195fc;  
}?

How can I iterate over an enum?

Extending @Eponymous's answer: It's great, but doesn't provide a general syntax. Here's what I came up with:

// Common/EnumTools.h
#pragma once

#include <array>

namespace Common {

// Here we forward-declare metafunction for mapping enums to their values.
// Since C++<23 doesn't have reflection, you have to populate it yourself :-(
// Usage: After declaring enum class E, add this overload in the namespace of E:
// inline constexpr auto allValuesArray(const E&, Commob::EnumAllValuesTag) { return std::array{E::foo, E::bar}; }
// Then `AllValues<NS::E>` will call `allValuesArray(NS::E{}, EnumAllValuesTag)` which will resolve
// by ADL.
// Just be sure to keep it sync'd with your enum!

// Here's what you want to use in, e.g., loops: "for (auto val : Common::AllValues<MyEnum>) {"

struct EnumAllValuesTag {}; // So your allValuesArray function is clearly associated with this header.

template <typename Enum>
static inline constexpr auto AllValues = allValuesArray(Enum{}, EnumAllValuesTag{});
// ^ Just "constexpr auto" or "constexpr std::array<Enum, allValuesArray(Enum{}, EnumAllValuesTag{}).size()>" didn't work on all compilers I'm using, but this did.

} // namespace Common

then in your namespace:

#include "Common/EnumTools.h"

namespace MyNamespace {

enum class MyEnum {
    foo,
    bar = 4,
    baz = 42,
};

// Making this not have to be in the `Common` namespace took some thinking,
// but is a critical feature since otherwise there's no hope in keeping it sync'd with the enum.
inline constexpr auto allValuesArray(const MyEnum&, Common::EnumAllValuesTag) {
    return std::array{ MyEnum::foo, MyEnum::bar, MyEnum::baz };
}

} // namespace MyNamespace

then wherever you need to use it:

for (const auto& e : Common::AllValues<MyNamespace::MyEnum>) { ... }

so even if you've typedef'd:

namespace YourNS {
using E = MyNamespace::MyEnum;
} // namespace YourNS

for (const auto& e : Common::AllValues<YourNS::E>) { ... }

I can't think of anything much better, short of the actual language feature everyone looking at this page want.

Future work:

  1. You should be able to add a constexpr function (and so a metafunction) that filters Common::AllValues<E> to provide a Common::AllDistinctValues<E> for the case of enums with repeated numerical values like enum { foo = 0, bar = 0 };.
  2. I bet there's a way to use the compiler's switch-covers-all-enum-values to write allValuesArray such that it errors if the enum has added a value.

How does java do modulus calculations with negative numbers?

According to section 15.17.3 of the JLS, "The remainder operation for operands that are integers after binary numeric promotion produces a result value such that (a/b)*b+(a%b) is equal to a. This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0)."

Hope that helps.

PHP header redirect 301 - what are the implications?

This is better:

<?php
//* Permanently redirect page
header("Location: new_page.php",TRUE,301);
?>

Just one call including code 301. Also notice the relative path to the file in the same directory (not "/dir/dir/new_page.php", etc.), which all modern browsers seem to support.

I think this is valid since PHP 5.1.2, possibly earlier.

How to assign the output of a command to a Makefile variable

Use the Make shell builtin like in MY_VAR=$(shell echo whatever)

me@Zack:~$make
MY_VAR IS whatever

me@Zack:~$ cat Makefile 
MY_VAR := $(shell echo whatever)

all:
    @echo MY_VAR IS $(MY_VAR)

How do I filter date range in DataTables?

Here is my solution, cobbled together from the range filter example in the datatables docs, and letting moment.js do the dirty work of comparing the dates.

HTML

<input 
    type="text" 
    id="min-date"
    class="date-range-filter"
    placeholder="From: yyyy-mm-dd">

<input 
    type="text" 
    id="max-date" 
    class="date-range-filter"
    placeholder="To: yyyy-mm-dd">

<table id="my-table">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Created At</th>
        </tr>
    </thead>
</table>

JS

Install Moment: npm install moment

// Assign moment to global namespace
window.moment = require('moment');

// Set up your table
table = $('#my-table').DataTable({
    // ... do your thing here.
});

// Extend dataTables search
$.fn.dataTable.ext.search.push(
    function( settings, data, dataIndex ) {
        var min  = $('#min-date').val();
        var max  = $('#max-date').val();
        var createdAt = data[2] || 0; // Our date column in the table

        if  ( 
                ( min == "" || max == "" )
                || 
                ( moment(createdAt).isSameOrAfter(min) && moment(createdAt).isSameOrBefore(max) ) 
            )
        {
            return true;
        }
        return false;
    }
);

// Re-draw the table when the a date range filter changes
$('.date-range-filter').change( function() {
    table.draw();
} );

JSFiddle Here

Notes

  • Using moment decouples the date comparison logic, and makes it easy to work with different formats. In my table, I used yyyy-mm-dd, but you could use mm/dd/yyyy as well. Be sure to reference moment's docs when parsing other formats, as you may need to modify what method you use.

SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)"

This is caused when the user's default database is set to a database they don't have permissions or its offline.

Just try to re add the user.Pleae have a look here too.

window.location.href and window.open () methods in JavaScript

window.open is a method; you can open new window, and can customize it. window.location.href is just a property of the current window.

Does Spring Data JPA have any way to count entites using method name resolving?

According to the issue DATAJPA-231 the feature is not implemented yet.

Removing empty rows of a data file in R

Alternative solution for rows of NAs using janitor package

myData %>% remove_empty("rows")

Percentage width in a RelativeLayout

PercentRelativeLayout is deprecated from Revision 26.0.0 of support Library.

Google introduced new Layout called ConstraintLayout.

Add the library as a dependency in your module-level build.gradle file:

     dependencies {
        compile 'com.android.support.constraint:constraint-layout:1.0.1'
      }

just add in a layout file:

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

Constraints

Constraints help you keep widgets aligned. You can use anchors, such as the constraint handles shown below, to determine alignment rules between various widgets.

  1. Wrap Content: The view expands as needed to fit its contents.
  2. Match Constraints: The view expands as needed to meet the definition of its constraints after accounting for margins. However, if the given dimension has only one constraint, then the view expands to fit its contents. Using this mode on either the height or width also allows you to set a size ratio.
  3. Fixed: You specify a specific dimension in the text box below or by resizing the view in the editor.
  4. Spread: The views are evenly distributed (after margins are accounted for). This is the default.
  5. Spread inside: The first and last view are affixed to the constraints on each end of the chain and the rest are evenly distributed.
  6. Weighted: When the chain is set to either spread or spread inside, you can fill the remaining space by setting one or more views to "match constraints" (0dp). By default, the space is evenly distributed between each view that's set to "match constraints," but you can assign a weight of importance to each view using the layout_constraintHorizontal_weight and layout_constraintVertical_weight attributes. If you're familiar with layout_weight in a linear layout, this works the same way. So the view with the highest weight value gets the most amount of space; views that have the same weight get the same amount of space.
  7. Packed: The views are packed together (after margins are accounted for). You can then adjust the whole chain's bias (left/right or up/down) by changing the chain's head view bias.
  8. Center Horizontally or Center Vertically: To create a chain of views quickly, select them all, right-click one of the views, and then select either Center Horizontally or Center Vertically, to create either a horizontal or vertical chain
  9. Baseline alignment: Align the text baseline of a view to the text baseline of another view.
  10. Constrain to a guideline: You can add a vertical or horizontal guideline to which you can constrain views, and the guideline will be invisible to app users. You can position the guideline within the layout based on either dp units or percent, relative to the layout's edge.
  11. Adjust the constraint bias: When you add a constraint to both sides of a view (and the view size for the same dimension is either "fixed" or "wrap content"), the view becomes centered between the two constraints with a bias of 50% by default. You can adjust the bias by dragging the bias slider in the Properties window
  12. Set size as a ratio: You can set the view size to a ratio such as 16:9 if at least one of the view dimensions is set to "match constraints" (0dp).

You can learn more from the official doc.

Convert Text to Date?

Besides other options, I confirm that using

c.Value = CDate(c.Value)

works (just tested with the description of your case, with Excel 2010). As for the reasons for you getting a type mismatch error, you may check (e.g.) this.

It might be a locale issue.

Python - Using regex to find multiple matches and print them out

Using regexes for this purpose is the wrong approach. Since you are using python you have a really awesome library available to extract parts from HTML documents: BeautifulSoup.

Dump a mysql database to a plaintext (CSV) backup from the command line

Here is the simplest command for it

mysql -h<hostname> -u<username> -p<password> -e 'select * from databaseName.tableNaame' | sed  's/\t/,/g' > output.csv

If there is a comma in the column value then we can generate .tsv instead of .csv with the following command

mysql -h<hostname> -u<username> -p<password> -e 'select * from databaseName.tableNaame' > output.csv

How can I have grep not print out 'No such file or directory' errors?

You can use the -s or --no-messages flag to suppress errors.

-s, --no-messages suppress error messages

grep pattern * -s -R -n

What exactly does stringstream do?

From C++ Primer:

The istringstream type reads a string, ostringstream writes a string, and stringstream reads and writes the string.

I come across some cases where it is both convenient and concise to use stringstream.

case 1

It is from one of the solutions for this leetcode problem. It demonstrates a very suitable case where the use of stringstream is efficient and concise.

Suppose a and b are complex numbers expressed in string format, we want to get the result of multiplication of a and b also in string format. The code is as follows:

string a = "1+2i", b = "1+3i";
istringstream sa(a), sb(b);
ostringstream out;

int ra, ia, rb, ib;
char buff;
// only read integer values to get the real and imaginary part of 
// of the original complex number
sa >> ra >> buff >> ia >> buff;
sb >> rb >> buff >> ib >> buff;

out << ra*rb-ia*ib << '+' << ra*ib+ia*rb << 'i';

// final result in string format
string result = out.str() 

case 2

It is also from a leetcode problem that requires you to simplify the given path string, one of the solutions using stringstream is the most elegant that I have seen:

string simplifyPath(string path) {
    string res, tmp;
    vector<string> stk;
    stringstream ss(path);
    while(getline(ss,tmp,'/')) {
        if (tmp == "" or tmp == ".") continue;
        if (tmp == ".." and !stk.empty()) stk.pop_back();
        else if (tmp != "..") stk.push_back(tmp);
    }
    for(auto str : stk) res += "/"+str;
    return res.empty() ? "/" : res; 
 }

Without the use of stringstream, it would be difficult to write such concise code.

The following artifacts could not be resolved: javax.jms:jms:jar:1.1

May not be the exactly same problem. but there is a nice article on the same line Here

Display all views on oracle database

Open a new worksheet on the related instance (Alt-F10) and run the following query

SELECT view_name, owner
FROM sys.all_views 
ORDER BY owner, view_name

Pagination using MySQL LIMIT, OFFSET

A dozen pages is not a big deal when using OFFSET. But when you have hundreds of pages, you will find that OFFSET is bad for performance. This is because all the skipped rows need to be read each time.

It is better to remember where you left off.

What are the -Xms and -Xmx parameters when starting JVM?

You can specify it in your IDE. For example, for Eclipse in Run Configurations ? VM arguments. You can enter -Xmx800m -Xms500m as

Enter image description here

How to obtain the start time and end time of a day?

private Date getStartOfDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int day = calendar.get(Calendar.DATE);
    calendar.setTimeInMillis(0);
    calendar.set(year, month, day, 0, 0, 0);
    return calendar.getTime();
    }

private Date getEndOfDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int day = calendar.get(Calendar.DATE);
    calendar.setTimeInMillis(0);
    calendar.set(year, month, day, 23, 59, 59);
    return calendar.getTime();
    }

calendar.setTimeInMillis(0); gives you accuracy upto milliseconds

How long do browsers cache HTTP 301s?

301 is a cacheable response per HTTP RFC and browsers will cache it depending on the HTTP caching headers you have on the response. Use FireBug or Charles to examine response headers to know the exact duration the response will be cached for.

If you would like to control the caching duration, you can use the the HTTP response headers Cache-Control and Expires to do the same. Alternatively, if you don't want to cache the 301 response at all, use the following headers.

Cache-Control: no-store, no-cache, must-revalidate
Expires: Thu, 01 Jan 1970 00:00:00 GMT

Add new item in existing array in c#.net

Arrays in C# are immutable, e.g. string[], int[]. That means you can't resize them. You need to create a brand new array.

Here is the code for Array.Resize:

public static void Resize<T>(ref T[] array, int newSize)
{
    if (newSize < 0)
    {
        throw new ArgumentOutOfRangeException("newSize", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
    }
    T[] sourceArray = array;
    if (sourceArray == null)
    {
        array = new T[newSize];
    }
    else if (sourceArray.Length != newSize)
    {
        T[] destinationArray = new T[newSize];
        Copy(sourceArray, 0, destinationArray, 0, (sourceArray.Length > newSize) ? newSize : sourceArray.Length);
        array = destinationArray;
    }
}

As you can see it creates a new array with the new size, copies the content of the source array and sets the reference to the new array. The hint for this is the ref keyword for the first parameter.

There are lists that can dynamically allocate new slots for new items. This is e.g. List<T>. These contain immutable arrays and resize them when needed (List<T> is not a linked list implementation!). ArrayList is the same thing without Generics (with Object array).

LinkedList<T> is a real linked list implementation. Unfortunately you can add just LinkListNode<T> elements to the list, so you must wrap your own list elements into this node type. I think its use is uncommon.

jQuery - Get Width of Element when Not Visible (Display: None)

Before take the width make the parent display show ,then take the width and finally make the parent display hide. Just like following

$('#parent').show();
var tableWidth = $('#parent').children('table').outerWidth();
 $('#parent').hide();
if (tableWidth > $('#parent').width())
{
    $('#parent').width() = tableWidth;
}

How to maintain page scroll position after a jquery event is carried out?

What you want to do is prevent the default action of the click event. To do this, you will need to modify your script like this:

$(document).ready(function() {
  $('.galleryicon').live("click", function(e) {

    $('#mainImage').hide();
    $('#cakebox').css('background-image', "url('ajax-loader.gif')");
    var i = $('<img />').attr('src',this.href).load(function() {
        $('#mainImage').attr('src', i.attr('src'));
        $('#cakebox').css('background-image', 'none');
        $('#mainImage').fadeIn();
    });
    return false; 
    e.preventDefault();
   });
 });

So, you're adding an "e" that represents the event in the line $('.galleryicon').live("click", function(e) { and you're adding the line e.preventDefault();

Use a.any() or a.all()

This should also work and is a closer answer to what is asked in the question:

for i in range(len(x)):
    if valeur.item(i) <= 0.6:
        print ("this works")
    else:   
        print ("valeur is too high")

Easiest way to copy a table from one database to another?

If your tables are on the same mysql server you can run the following

CREATE TABLE destination_db.my_table SELECT * FROM source_db.my_table;
ALTER TABLE destination_db.my_table ADD PRIMARY KEY (id); 
ALTER TABLE destination_db.my_table MODIFY COLUMN id INT AUTO_INCREMENT;

How to place div in top right hand corner of page

Try css:

.topcorner{
    position:absolute;
    top:10px;
    right: 10px;
 }

you can play with the top and right properties.

If you want to float the div even when you scroll down, just change position:absolute; to position:fixed;.

Hope it helps.

Eclipse does not start when I run the exe?

I looked online and found a person who had a similar problem.

It says on the forum

"You might need to download JRE 64 bit version"

But again, it depends on what OS you're using as well.

Undefined reference to pthread_create in Linux

I believe the proper way of adding pthread in CMake is with the following

find_package (Threads REQUIRED)

target_link_libraries(helloworld
    ${CMAKE_THREAD_LIBS_INIT}
)

Can pandas automatically recognize dates?

You should add parse_dates=True, or parse_dates=['column name'] when reading, thats usually enough to magically parse it. But there are always weird formats which need to be defined manually. In such a case you can also add a date parser function, which is the most flexible way possible.

Suppose you have a column 'datetime' with your string, then:

from datetime import datetime
dateparse = lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S')

df = pd.read_csv(infile, parse_dates=['datetime'], date_parser=dateparse)

This way you can even combine multiple columns into a single datetime column, this merges a 'date' and a 'time' column into a single 'datetime' column:

dateparse = lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S')

df = pd.read_csv(infile, parse_dates={'datetime': ['date', 'time']}, date_parser=dateparse)

You can find directives (i.e. the letters to be used for different formats) for strptime and strftime in this page.

How to find out which package version is loaded in R?

You can use packageVersion to see what version of a package is loaded

> packageVersion("snow")
[1] ‘0.3.9’

Although it sounds like you want to see what version of R you are running, in which case @Justin's sessionInfo suggestion is the way to go

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

If you want to return a format mm/dd/yyyy, then use 101 instead of 103: CONVERT(VARCHAR(10), [MyDate], 101)

ASP.NET Web Api: The requested resource does not support http method 'GET'

Have the same Setup as OP. One controller with many actions... less "messy" :-)

In my case i forgot the "[HttpGet]" when adding a new action.

[HttpGet]
public IEnumerable<string> TestApiCall()
{
    return new string[] { "aa", "bb" };
}

Adding null values to arraylist

Yes, you can always use null instead of an object. Just be careful because some methods might throw error.

It would be 1.

also nulls would be factored in in the for loop, but you could use

 for(Item i : itemList) {
        if (i!= null) {
               //code here
        }
 }

Print a list of all installed node.js modules

in any os

npm -g list

and thats it

Cannot use object of type stdClass as array?

Change it for

$results->fetch_array()

Go To Definition: "Cannot navigate to the symbol under the caret."

This weird bug happened to me while importing a Xamarin project into VS15. None of the solutions listed here worked for me. After a day of frustration I also ran into a problem similar to this: Visual Studio "Find" results in "No files were found to look in. Find stopped progress."

When clicking 'find all' in the search dialog, a popup informed me that other files could not be searched through. so i figured the reason 'go to definition' didn't work was due to the same bug, as looking for definitions in the same file did work.

the weird solution in the above link (pressing Ctrl+Scroll Lock or Ctrl+Break a few times) solved both problems for me.

Coloring of the code (which wasn't working when the 'Go to definition' functionality was broken) also immediately returned.

Sorting JSON by values

Solution working with different types and with upper and lower cases.
For example, without the toLowerCase statement, "Goodyear" will come before "doe" with an ascending sort. Run the code snippet at the bottom of my answer to view the different behaviors.

JSON DATA:

var people = [
{
    "f_name" : "john",
    "l_name" : "doe", // lower case
    "sequence": 0 // int
},
{
    "f_name" : "michael",
    "l_name" : "Goodyear", // upper case
    "sequence" : 1 // int
}];

JSON Sort Function:

function sortJson(element, prop, propType, asc) {
  switch (propType) {
    case "int":
      element = element.sort(function (a, b) {
        if (asc) {
          return (parseInt(a[prop]) > parseInt(b[prop])) ? 1 : ((parseInt(a[prop]) < parseInt(b[prop])) ? -1 : 0);
        } else {
          return (parseInt(b[prop]) > parseInt(a[prop])) ? 1 : ((parseInt(b[prop]) < parseInt(a[prop])) ? -1 : 0);
        }
      });
      break;
    default:
      element = element.sort(function (a, b) {
        if (asc) {
          return (a[prop].toLowerCase() > b[prop].toLowerCase()) ? 1 : ((a[prop].toLowerCase() < b[prop].toLowerCase()) ? -1 : 0);
        } else {
          return (b[prop].toLowerCase() > a[prop].toLowerCase()) ? 1 : ((b[prop].toLowerCase() < a[prop].toLowerCase()) ? -1 : 0);
        }
      });
  }
}

Usage:

sortJson(people , "l_name", "string", true);
sortJson(people , "sequence", "int", true);

_x000D_
_x000D_
var people = [{_x000D_
  "f_name": "john",_x000D_
  "l_name": "doe",_x000D_
  "sequence": 0_x000D_
}, {_x000D_
  "f_name": "michael",_x000D_
  "l_name": "Goodyear",_x000D_
  "sequence": 1_x000D_
}, {_x000D_
  "f_name": "bill",_x000D_
  "l_name": "Johnson",_x000D_
  "sequence": 4_x000D_
}, {_x000D_
  "f_name": "will",_x000D_
  "l_name": "malone",_x000D_
  "sequence": 2_x000D_
}, {_x000D_
  "f_name": "tim",_x000D_
  "l_name": "Allen",_x000D_
  "sequence": 3_x000D_
}];_x000D_
_x000D_
function sortJsonLcase(element, prop, asc) {_x000D_
  element = element.sort(function(a, b) {_x000D_
    if (asc) {_x000D_
      return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);_x000D_
    } else {_x000D_
      return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);_x000D_
    }_x000D_
  });_x000D_
}_x000D_
_x000D_
function sortJson(element, prop, propType, asc) {_x000D_
  switch (propType) {_x000D_
    case "int":_x000D_
      element = element.sort(function(a, b) {_x000D_
        if (asc) {_x000D_
          return (parseInt(a[prop]) > parseInt(b[prop])) ? 1 : ((parseInt(a[prop]) < parseInt(b[prop])) ? -1 : 0);_x000D_
        } else {_x000D_
          return (parseInt(b[prop]) > parseInt(a[prop])) ? 1 : ((parseInt(b[prop]) < parseInt(a[prop])) ? -1 : 0);_x000D_
        }_x000D_
      });_x000D_
      break;_x000D_
    default:_x000D_
      element = element.sort(function(a, b) {_x000D_
        if (asc) {_x000D_
          return (a[prop].toLowerCase() > b[prop].toLowerCase()) ? 1 : ((a[prop].toLowerCase() < b[prop].toLowerCase()) ? -1 : 0);_x000D_
        } else {_x000D_
          return (b[prop].toLowerCase() > a[prop].toLowerCase()) ? 1 : ((b[prop].toLowerCase() < a[prop].toLowerCase()) ? -1 : 0);_x000D_
        }_x000D_
      });_x000D_
  }_x000D_
}_x000D_
_x000D_
function sortJsonString() {_x000D_
  sortJson(people, 'l_name', 'string', $("#chkAscString").prop("checked"));_x000D_
  display();_x000D_
}_x000D_
_x000D_
function sortJsonInt() {_x000D_
  sortJson(people, 'sequence', 'int', $("#chkAscInt").prop("checked"));_x000D_
  display();_x000D_
}_x000D_
_x000D_
function sortJsonUL() {_x000D_
  sortJsonLcase(people, 'l_name', $('#chkAsc').prop('checked'));_x000D_
  display();_x000D_
}_x000D_
_x000D_
function display() {_x000D_
  $("#data").empty();_x000D_
  $(people).each(function() {_x000D_
    $("#data").append("<div class='people'>" + this.l_name + "</div><div class='people'>" + this.f_name + "</div><div class='people'>" + this.sequence + "</div><br />");_x000D_
  });_x000D_
}
_x000D_
body {_x000D_
  font-family: Arial;_x000D_
}_x000D_
.people {_x000D_
  display: inline-block;_x000D_
  width: 100px;_x000D_
  border: 1px dotted black;_x000D_
  padding: 5px;_x000D_
  margin: 5px;_x000D_
}_x000D_
.buttons {_x000D_
  border: 1px solid black;_x000D_
  padding: 5px;_x000D_
  margin: 5px;_x000D_
  float: left;_x000D_
  width: 20%;_x000D_
}_x000D_
ul {_x000D_
  margin: 5px 0px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="buttons" style="background-color: rgba(240, 255, 189, 1);">_x000D_
  Sort the JSON array <strong style="color: red;">with</strong> toLowerCase:_x000D_
  <ul>_x000D_
    <li>Type: string</li>_x000D_
    <li>Property: lastname</li>_x000D_
  </ul>_x000D_
  <button onclick="sortJsonString(); return false;">Sort JSON</button>_x000D_
  Asc Sort_x000D_
  <input id="chkAscString" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<div class="buttons" style="background-color: rgba(255, 214, 215, 1);">_x000D_
  Sort the JSON array <strong style="color: red;">without</strong> toLowerCase:_x000D_
  <ul>_x000D_
    <li>Type: string</li>_x000D_
    <li>Property: lastname</li>_x000D_
  </ul>_x000D_
  <button onclick="sortJsonUL(); return false;">Sort JSON</button>_x000D_
  Asc Sort_x000D_
  <input id="chkAsc" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<div class="buttons" style="background-color: rgba(240, 255, 189, 1);">_x000D_
  Sort the JSON array:_x000D_
  <ul>_x000D_
    <li>Type: int</li>_x000D_
    <li>Property: sequence</li>_x000D_
  </ul>_x000D_
  <button onclick="sortJsonInt(); return false;">Sort JSON</button>_x000D_
  Asc Sort_x000D_
  <input id="chkAscInt" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<br />_x000D_
<br />_x000D_
<div id="data" style="float: left; border: 1px solid black; width: 60%; margin: 5px;">Data</div>
_x000D_
_x000D_
_x000D_

How to center cell contents of a LaTeX table whose columns have fixed widths?

\usepackage{array} in the preamble

then this:

\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}

note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"

Convert a python dict to a string and back

I use yaml for that if needs to be readable (neither JSON nor XML are that IMHO), or if reading is not necessary I use pickle.

Write

from pickle import dumps, loads
x = dict(a=1, b=2)
y = dict(c = x, z=3)
res = dumps(y)
open('/var/tmp/dump.txt', 'w').write(res)

Read back

from pickle import dumps, loads
rev = loads(open('/var/tmp/dump.txt').read())
print rev

How to install numpy on windows using pip install?

As of March 2016, pip install numpy works on Windows without a Fortran compiler. See here.

pip install scipy still tries to use a compiler.

July 2018: mojoken reports pip install scipy working on Windows without a Fortran compiler.

Java Comparator class to sort arrays

The answer from @aioobe is excellent. I just want to add another way for Java 8.

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };

Arrays.sort(twoDim, (int[] o1, int[] o2) -> o2[0] - o1[0]);

System.out.println(Arrays.deepToString(twoDim));

For me it's intuitive and easy to remember with Java 8 syntax.

Execute specified function every X seconds

Use System.Windows.Forms.Timer.

private Timer timer1; 
public void InitTimer()
{
    timer1 = new Timer();
    timer1.Tick += new EventHandler(timer1_Tick);
    timer1.Interval = 2000; // in miliseconds
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    isonline();
}

You can call InitTimer() in Form1_Load().

How to find the day, month and year with moment.js

Here's an example that you could use :

 var myDateVariable= moment("01/01/2019").format("dddd Do MMMM YYYY")
  • dddd : Full day Name

  • Do : day of the Month

  • MMMM : Full Month name

  • YYYY : 4 digits Year

For more informations :

https://flaviocopes.com/momentjs/

LDAP server which is my base dn

Either you set LDAP_DOMAIN variable or you misconfigured it. Jump inside of ldap machine/container and run:

slapcat > backup.ldif

If it fails, check punctuation, quotes etc while you assigned variable "LDAP_DOMAIN" Otherwise you will find answer inside on backup.ldif file.

Make div scrollable

You should add overflow property like following:

.itemconfiguration
    {   
        height: 300px; 
        overflow-y:auto;
        width:215px;
        float:left;
        position:relative;
        margin-left:-5px;
    }