Programs & Examples On #Caliburn.micro

A small, yet powerful framework, designed for building applications across all XAML platforms. Its strong support for MV* patterns will enable you to build your solution quickly, without the need to sacrifice code quality or testability.

Removing border from table cells

The HTML attribute for the purpose is rules=none (to be inserted into the table tag).

How to empty the message in a text area with jquery?

for set empty all input such textarea select and input run this code:

$('#message').val('').change();

XAMPP: Couldn't start Apache (Windows 10)

I found that running apache_start in gave me the exact error and on which line it was.

My error was that I left a space in between localhost: and the port.

What's the easiest way to escape HTML in Python?

In Python 3.2 a new html module was introduced, which is used for escaping reserved characters from HTML markup.

It has one function escape():

>>> import html
>>> html.escape('x > 2 && x < 7 single quote: \' double quote: "')
'x &gt; 2 &amp;&amp; x &lt; 7 single quote: &#x27; double quote: &quot;'

Rails 4 - passing variable to partial

Either

render partial: 'user', locals: {size: 30}

Or

render 'user', size: 30

To use locals, you need partial. Without the partial argument, you can just list variables directly (not within locals)

How can I get a precise time, for example in milliseconds in Objective-C?

NSDate and the timeIntervalSince* methods will return a NSTimeInterval which is a double with sub-millisecond accuracy. NSTimeInterval is in seconds, but it uses the double to give you greater precision.

In order to calculate millisecond time accuracy, you can do:

// Get a current time for where you want to start measuring from
NSDate *date = [NSDate date];

// do work...

// Find elapsed time and convert to milliseconds
// Use (-) modifier to conversion since receiver is earlier than now
double timePassed_ms = [date timeIntervalSinceNow] * -1000.0;

Documentation on timeIntervalSinceNow.

There are many other ways to calculate this interval using NSDate, and I would recommend looking at the class documentation for NSDate which is found in NSDate Class Reference.

Laravel - Eloquent or Fluent random row

Laravel >= 5.2:

User::inRandomOrder()->get();

or to get the specific number of records

// 5 indicates the number of records
User::inRandomOrder()->limit(5)->get();
// get one random record
User::inRandomOrder()->first();

or using the random method for collections:

User::all()->random();
User::all()->random(10); // The amount of items you wish to receive

Laravel 4.2.7 - 5.1:

User::orderByRaw("RAND()")->get();

Laravel 4.0 - 4.2.6:

User::orderBy(DB::raw('RAND()'))->get();

Laravel 3:

User::order_by(DB::raw('RAND()'))->get();

Check this article on MySQL random rows. Laravel 5.2 supports this, for older version, there is no better solution then using RAW Queries.

edit 1: As mentioned by Double Gras, orderBy() doesn't allow anything else then ASC or DESC since this change. I updated my answer accordingly.

edit 2: Laravel 5.2 finally implements a wrapper function for this. It's called inRandomOrder().

Difference between Dictionary and Hashtable

Simply, Dictionary<TKey,TValue> is a generic type, allowing:

  • static typing (and compile-time verification)
  • use without boxing

If you are .NET 2.0 or above, you should prefer Dictionary<TKey,TValue> (and the other generic collections)

A subtle but important difference is that Hashtable supports multiple reader threads with a single writer thread, while Dictionary offers no thread safety. If you need thread safety with a generic dictionary, you must implement your own synchronization or (in .NET 4.0) use ConcurrentDictionary<TKey, TValue>.

How to change the buttons text using javascript

innerText is the current correct answer for this. The other answers are outdated and incorrect.

document.getElementById('ShowButton').innerText = 'Show filter';

innerHTML also works, and can be used to insert HTML.

Multiple commands on a single line in a Windows batch file

Use:

echo %time% & dir & echo %time%

This is, from memory, equivalent to the semi-colon separator in bash and other UNIXy shells.

There's also && (or ||) which only executes the second command if the first succeeded (or failed), but the single ampersand & is what you're looking for here.


That's likely to give you the same time however since environment variables tend to be evaluated on read rather than execute.

You can get round this by turning on delayed expansion:

pax> cmd /v:on /c "echo !time! & ping 127.0.0.1 >nul: & echo !time!"
15:23:36.77
15:23:39.85

That's needed from the command line. If you're doing this inside a script, you can just use setlocal:

@setlocal enableextensions enabledelayedexpansion
@echo off
echo !time! & ping 127.0.0.1 >nul: & echo !time!
endlocal

How to convert a string Date to long millseconds

you can use the simpleDateFormat to parse the string date.

Combine multiple Collections into a single logical Collection?

Plain Java 8 solutions using a Stream.

Constant number

Assuming private Collection<T> c, c2, c3.

One solution:

public Stream<T> stream() {
    return Stream.concat(Stream.concat(c.stream(), c2.stream()), c3.stream());
}

Another solution:

public Stream<T> stream() {
    return Stream.of(c, c2, c3).flatMap(Collection::stream);
}

Variable number

Assuming private Collection<Collection<T>> cs:

public Stream<T> stream() {
    return cs.stream().flatMap(Collection::stream);
}

Can I change the viewport meta tag in mobile safari on the fly?

I realize this is a little old, but, yes it can be done. Some javascript to get you started:

viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0');

Just change the parts you need and Mobile Safari will respect the new settings.

Update:

If you don't already have the meta viewport tag in the source, you can append it directly with something like this:

var metaTag=document.createElement('meta');
metaTag.name = "viewport"
metaTag.content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"
document.getElementsByTagName('head')[0].appendChild(metaTag);

Or if you're using jQuery:

$('head').append('<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">');

how to send multiple data with $.ajax() jquery

I would recommend using a hash instead of a param string:

data = {id: id, name: name}

Search for a particular string in Oracle clob column

You can just CAST your CLOB value into a VARCHAR value and make your querie like a

How do you input command line arguments in IntelliJ IDEA?

You separate multiple program arguments with spaces. (this was not obvious to me)

Program arguments:Julia 52 Actress

TypeScript and React - children type?

React components should have a single wrapper node or return an array of nodes.

Your <Aux>...</Aux> component has two nodes div and main.

Try to wrap your children in a div in Aux component.

import * as React from 'react';

export interface AuxProps  { 
  children: React.ReactNode
}

const aux = (props: AuxProps) => (<div>{props.children}</div>);

export default aux;

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

Solution for HTTP Status 404 in NetBeans IDE: Right click on your project and go to your project properties, then click on run, then input your project relative URL like index.jsp.

  1. Project->Properties
  2. Click on Run
  3. Relative URL:/index.jsp (Select your project root URL)

enter image description here

Procedure or function !!! has too many arguments specified

You invoke the function with 2 parameters (@GenId and @Description):

EXEC etl.etl_M_Update_Promo @GenID, @Description

However you have declared the function to take 1 argument:

ALTER PROCEDURE [etl].[etl_M_Update_Promo]
    @GenId bigint = 0

SQL Server is telling you that [etl_M_Update_Promo] only takes 1 parameter (@GenId)

You can alter the procedure to take two parameters by specifying @Description.

ALTER PROCEDURE [etl].[etl_M_Update_Promo]
    @GenId bigint = 0,
    @Description NVARCHAR(50)
AS 

.... Rest of your code.

How to remove default chrome style for select Input?

In your CSS add this:

input {-webkit-appearance: none; box-shadow: none !important; }
:-webkit-autofill { color: #fff !important; }

Only for Chrome! :)

PHP7 : install ext-dom issue

First of all, read the warning! It says do not run composer as root! Secondly, you're probably using Xammp on your local which has the required php libraries as default.

But in your server you're missing ext-dom. php-xml has all the related packages you need. So, you can simply install it by running:

sudo apt-get update
sudo apt install php-xml

Most likely you are missing mbstring too. If you get the error, install this package as well with:

sudo apt-get install php-mbstring

Then run:

composer update
composer require cviebrock/eloquent-sluggable

Grep for beginning and end of line?

The tricky part is a regex that includes a dash as one of the valid characters in a character class. The dash has to come immediately after the start for a (normal) character class and immediately after the caret for a negated character class. If you need a close square bracket too, then you need the close square bracket followed by the dash. Mercifully, you only need dash, hence the notation chosen.

grep '^[-d]rwx.*[0-9]$' "$@"

See: Regular Expressions and grep for POSIX-standard details.

Explicitly set column value to null SQL Developer

It is clear that most people who haven't used SQL Server Enterprise Manager don't understand the question (i.e. Justin Cave).

I came upon this post when I wanted to know the same thing.

Using SQL Server, when you are editing your data through the MS SQL Server GUI Tools, you can use a KEYBOARD SHORTCUT to insert a NULL rather than having just an EMPTY CELL, as they aren't the same thing. An empty cell can have a space in it, rather than being NULL, even if it is technically empty. The difference is when you intentionally WANT to put a NULL in a cell rather than a SPACE or to empty it and NOT using a SQL statement to do so.

So, the question really is, how do I put a NULL value in the cell INSTEAD of a space to empty the cell?

I think the answer is, that the way the Oracle Developer GUI works, is as Laniel indicated above, And THAT should be marked as the answer to this question.

Oracle Developer seems to default to NULL when you empty a cell the way the op is describing it.

Additionally, you can force Oracle Developer to change how your null cells look by changing the color of the background color to further demonstrate when a cell holds a null:

Tools->Preferences->Advanced->Display Null Using Background Color

or even the VALUE it shows when it's null:

Tools->Preferences->Advanced->Display Null Value As

Hope that helps in your transition.

What is the difference between __dirname and ./ in node.js?

./ refers to the current working directory, except in the require() function. When using require(), it translates ./ to the directory of the current file called. __dirname is always the directory of the current file.

For example, with the following file structure

/home/user/dir/files/config.json

{
  "hello": "world"
}

/home/user/dir/files/somefile.txt

text file

/home/user/dir/dir.js

var fs = require('fs');

console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));

If I cd into /home/user/dir and run node dir.js I will get

{ hello: 'world' }
text file

But when I run the same script from /home/user/ I get

{ hello: 'world' }

Error: ENOENT, no such file or directory './files/somefile.txt'
    at Object.openSync (fs.js:228:18)
    at Object.readFileSync (fs.js:119:15)
    at Object.<anonymous> (/home/user/dir/dir.js:4:16)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Array.0 (module.js:470:10)
    at EventEmitter._tickCallback (node.js:192:40)

Using ./ worked with require but not for fs.readFileSync. That's because for fs.readFileSync, ./ translates into the cwd (in this case /home/user/). And /home/user/files/somefile.txt does not exist.

How to debug a GLSL shader?

Do offline rendering to a texture and evaluate the texture's data. You can find related code by googling for "render to texture" opengl Then use glReadPixels to read the output into an array and perform assertions on it (since looking through such a huge array in the debugger is usually not really useful).

Also you might want to disable clamping to output values that are not between 0 and 1, which is only supported for floating point textures.

I personally was bothered by the problem of properly debugging shaders for a while. There does not seem to be a good way - If anyone finds a good (and not outdated/deprecated) debugger, please let me know.

How to filter Pandas dataframe using 'in' and 'not in' like in SQL

I've been usually doing generic filtering over rows like this:

criterion = lambda row: row['countries'] not in countries
not_in = df[df.apply(criterion, axis=1)]

Is there an operator to calculate percentage in Python?

Very quickly and sortly-code implementation by using the lambda operator.

In [17]: percent = lambda part, whole:float(whole) / 100 * float(part)
In [18]: percent(5,400)
Out[18]: 20.0
In [19]: percent(5,435)
Out[19]: 21.75

Yes/No message box using QMessageBox

You can use the QMessage object to create a Message Box then add buttons :

QMessageBox msgBox;
msgBox.setWindowTitle("title");
msgBox.setText("Question");
msgBox.setStandardButtons(QMessageBox::Yes);
msgBox.addButton(QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
if(msgBox.exec() == QMessageBox::Yes){
  // do something
}else {
  // do something else
}

What is the 'instanceof' operator used for in Java?

The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface).

The instanceof in java is also known as type comparison operator as it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has null value, it returns false.

From JDK 14+ which includes JEP 305 we can also do "Pattern Matching" for instanceof

Patterns basically test that a value has a certain type, and can extract information from the value when it has the matching type. Pattern matching allows a more clear and efficient expression of common logic in a system, namely the conditional removal of components from objects.

Before Java 14

if (obj instanceof String) {
    String str = (String) obj; // need to declare and cast again the object
    .. str.contains(..) ..
}else{
     str = ....
}

Java 14 enhancements

if (!(obj instanceof String str)) {
    .. str.contains(..) .. // no need to declare str object again with casting
} else {
    .. str....
}

We can also combine the type check and other conditions together

if (obj instanceof String str && str.length() > 4) {.. str.contains(..) ..}

The use of pattern matching in instanceof should reduce the overall number of explicit casts in Java programs.

PS: instanceOf will only match when the object is not null, then only it can be assigned to str.

How can I parse String to Int in an Angular expression?

In your controller:

$scope.num_str = parseInt(num_str, 10);  // parseInt with radix

Can I make dynamic styles in React Native?

Yes, you can make dynamic styles. You can pass values from Components.

First create StyleSheetFactory.js

import { StyleSheet } from "react-native";
export default class StyleSheetFactory {
  static getSheet(backColor) {
    return StyleSheet.create({
      jewelStyle: {
        borderRadius: 10,
        backgroundColor: backColor,
        width: 20,
        height: 20,
      }
    })
  }
}

then use it in your component following way

import React from "react";
import { View } from "react-native";
import StyleSheetFactory from './StyleSheetFactory'
class Main extends React.Component {
  getRandomColor = () => {
    var letters = "0123456789ABCDEF";
    var color = "#";
    for (var i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
  };

  render() {
    return (
      <View>
        <View
          style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
        />
        <View
          style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
        />
        <View
          style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
        />
      </View>
    );
  }
}

Javascript (+) sign concatenates instead of giving sum of variables

Another alternative could be using:

divID = "question-" + (i - -1);

Subtracting a negative is the same as adding, and a minus cannot be used for concatenation

Edit: Forgot that brackets are still necessary since code is read from left to right.

Is there a cross-domain iframe height auto-resizer that works?

You have three alternatives:

1. Use iFrame-resizer

This is a simple library for keeping iFrames sized to their content. It uses the PostMessage and MutationObserver APIs, with fall backs for IE8-10. It also has options for the content page to request the containing iFrame is a certain size and can also close the iFrame when your done with it.

https://github.com/davidjbradshaw/iframe-resizer

2. Use Easy XDM (PostMessage + Flash combo)

Easy XDM uses a collection of tricks for enabling cross-domain communication between different windows in a number of browsers, and there are examples for using it for iframe resizing:

http://easyxdm.net/wp/2010/03/17/resize-iframe-based-on-content/

http://kinsey.no/blog/index.php/2010/02/19/resizing-iframes-using-easyxdm/

Easy XDM works by using PostMessage on modern browsers and a Flash based solution as fallback for older browsers.

See also this thread on Stackoverflow (there are also others, this is a commonly asked question). Also, Facebook would seem to use a similar approach.

3. Communicate via a server

Another option would be to send the iframe height to your server and then poll from that server from the parent web page with JSONP (or use a long poll if possible).

How to Extract Year from DATE in POSTGRESQL

You may try to_char(now()::date, 'yyyy')
If text, you've to cast your text to date to_char('2018-01-01'::date, 'yyyy')

See the PostgreSQL Documentation Data Type Formatting Functions

How to display a pdf in a modal window?

You can have a look at this library: https://github.com/mozilla/pdf.js it renders PDF document in a Web/HTML page

Also you can use Flash to embed the document into any HTML page like that:

<object data="your_file.pdf#view=Fit" type="application/pdf" width="100%" height="850">
    <p>
        It appears your Web browser is not configured to display PDF files. No worries, just <a href="your_file.pdf">click here to download the PDF file.</a>
    </p>
</object>

How to export dataGridView data Instantly to Excel on button click?

I did not intend to steal @Jake and @Cornelius's answer, so i tried editing it. but it was rejected. Anyways, the only improvement I have to point out is about avoiding extra blank column in excel after paste. Adding one line dataGridView1.RowHeadersVisible = false; hides so called "Row Header" which appears on the left most part of DataGridView, and so it is not selected and copied to clipboard when you do dataGridView1.SelectAll();

private void copyAlltoClipboard()
    {
        //to remove the first blank column from datagridview
        dataGridView1.RowHeadersVisible = false;
        dataGridView1.SelectAll();
        DataObject dataObj = dataGridView1.GetClipboardContent();
        if (dataObj != null)
            Clipboard.SetDataObject(dataObj);
    }
    private void button3_Click_1(object sender, EventArgs e)
    {
        copyAlltoClipboard();
        Microsoft.Office.Interop.Excel.Application xlexcel;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        xlexcel = new Excel.Application();
        xlexcel.Visible = true;
        xlWorkBook = xlexcel.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
        CR.Select();
        xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);          
    }

SmartGit Installation and Usage on Ubuntu

You can add a PPA that provides a relatively current version of SmartGit(as well as SmartGitHg, the predecessor of SmartGit).

To add the PPA run:

sudo add-apt-repository ppa:eugenesan/ppa
sudo apt-get update

To install smartgit (after adding the PPA) run:

sudo apt-get install smartgit

To install smartgithg (after adding the PPA) run:

sudo apt-get install smartgithg

This should add a menu option for you

For more information, see Eugene San PPA.

This repository contains collection of customized, updated, ported and backported packages for two last LTS releases and latest pre-LTS release

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

Based on the other answer by @Mechanical Snail, except without the use of python, which I found to be wildly overkill. Add this to your ~/.gitconfig:

[github]
    user = "your-name-here"
[alias]
    hub-new-repo = "!REPO=$(basename $PWD) GHUSER=$(git config --get github.user); curl -u $GHUSER https://api.github.com/user/repos -d {\\\"name\\\":\\\"$REPO\\\"} --fail; git remote add origin [email protected]:$GHUSER/$REPO.git; git push origin master"

Detect if user is scrolling

You just said javascript in your tags, so @Wampie Driessen post could helps you.

I want also to contribute, so you can use the following when using jQuery if you need it.

 //Firefox
 $('#elem').bind('DOMMouseScroll', function(e){
     if(e.detail > 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

 //IE, Opera, Safari
 $('#elem').bind('mousewheel', function(e){
     if(e.wheelDelta< 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

Another example:

$(function(){
    var _top = $(window).scrollTop();
    var _direction;
    $(window).scroll(function(){
        var _cur_top = $(window).scrollTop();
        if(_top < _cur_top)
        {
            _direction = 'down';
        }
        else
        {
            _direction = 'up';
        }
        _top = _cur_top;
        console.log(_direction);
    });
});?

How do I filter ForeignKey choices in a Django ModelForm?

To do this with a generic view, like CreateView...

class AddPhotoToProject(CreateView):
    """
    a view where a user can associate a photo with a project
    """
    model = Connection
    form_class = CreateConnectionForm


    def get_context_data(self, **kwargs):
        context = super(AddPhotoToProject, self).get_context_data(**kwargs)
        context['photo'] = self.kwargs['pk']
        context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)
        return context
    def form_valid(self, form):
        pobj = Photo.objects.get(pk=self.kwargs['pk'])
        obj = form.save(commit=False)
        obj.photo = pobj
        obj.save()

        return_json = {'success': True}

        if self.request.is_ajax():

            final_response = json.dumps(return_json)
            return HttpResponse(final_response)

        else:

            messages.success(self.request, 'photo was added to project!')
            return HttpResponseRedirect(reverse('MyPhotos'))

the most important part of that...

    context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)

, read my post here

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

Is this a console program project or a Windows project? I'm asking because for a Win32 and similar project, the entry point is WinMain().

  1. Right-click the Project (not the Solution) on the left side.
  2. Then click Properties -> Configuration Properties -> Linker -> System

If it says Subsystem Windows your entry point should be WinMain(), i.e.

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd)
{
   your code here ...
}

Besides, speaking of the comments. This is a compile (or more precisely a Link) error, not a run-time error. When you start to debug, the compiler needs to make a complete program (not just to compile your module) and that is when the error occurs.

It does not even get to the point being loaded and run.

How can I tell if a DOM element is visible in the current viewport?

As simple as it can get, IMO:

function isVisible(elem) {
  var coords = elem.getBoundingClientRect();
  return Math.abs(coords.top) <= coords.height;
}

How to redirect in a servlet filter?

In Filter the response is of ServletResponse rather than HttpServletResponse. Hence do the cast to HttpServletResponse.

HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.sendRedirect("/login.jsp");

If using a context path:

httpResponse.sendRedirect(req.getContextPath() + "/login.jsp");

Also don't forget to call return; at the end.

In MVC, how do I return a string result?

You can also just return string if you know that's the only thing the method will ever return. For example:

public string MyActionName() {
  return "Hi there!";
}

Hashcode and Equals for Hashset

I think your questions will all be answered if you understand how Sets, and in particular HashSets work. A set is a collection of unique objects, with Java defining uniqueness in that it doesn't equal anything else (equals returns false).

The HashSet takes advantage of hashcodes to speed things up. It assumes that two objects that equal eachother will have the same hash code. However it does not assume that two objects with the same hash code mean they are equal. This is why when it detects a colliding hash code, it only compares with other objects (in your case one) in the set with the same hash code.

Section vs Article HTML5

Sounds like you should wrap each of the "sections" (as you call them) in <article> tags and entries in the article in <section> tags.

The HTML5 spec says (Section):

The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading. [...]

Examples of sections would be chapters, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A Web site's home page could be split into sections for an introduction, news items, and contact information.

Note: Authors are encouraged to use the article element instead of the section element when it would make sense to syndicate the contents of the element.

And for Article

The article element represents a self-contained composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.

I think what you call "sections" in the OP fit the definition of article as I can see them being independently distributable or reusable.

Update: Some minor text changes for article in the latest editors draft for HTML 5.1 (changes in italic):

The article element represents a complete, or self-contained, composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.

Also, discussion on the Public HTML mailing list about article in January and February of 2013.

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

I had the same error and ended up solving it by upgrading my Oracle ojdbc driver to a version compatible with the Oracle database version

How to access Spring MVC model object in javascript file?

Here is an example of how i made a list object available for javascript:

var listForJavascript = [];
<c:forEach items="${MyListFromJava}" var="listItem">
  var arr = [];

  arr.push("<c:out value="${listItem.param1}" />");
  arr.push("<c:out value="${listItem.param2}" />");

  listForJavascript.push(arr);
</c:forEach>

How do I truncate a .NET string?

I know this is an old question, but here is a nice solution:

public static string Truncate(this string text, int maxLength, string suffix = "...")
{
    string str = text;
    if (maxLength > 0)
    {
        int length = maxLength - suffix.Length;
        if (length <= 0)
        {
            return str;
        }
        if ((text != null) && (text.Length > maxLength))
        {
            return (text.Substring(0, length).TrimEnd(new char[0]) + suffix);
        }
    }
    return str;
}

var myString = "hello world"
var myTruncatedString = myString.Truncate(4);

Returns: hello...

How to remove margin space around body or clear default css styles

try removing the padding/margins from the body tag.

body{
padding:0px;
margin:0px;
}

uint8_t vs unsigned char

The whole point is to write implementation-independent code. unsigned char is not guaranteed to be an 8-bit type. uint8_t is (if available).

Don't reload application when orientation changes

You just have to go to the AndroidManifest.xml and inside or in your activities labels, you have to type this line of code as someone up there said:

android:configChanges="orientation|screenSize"

So, you'll have something like this:

<activity android:name="ActivityMenu"
android:configChanges="orientation|screenSize">
</activity>

Hope it works!

How to align entire html body to the center?

Just write

<body>
   <center>
            *Your Code Here*
   </center></body>

function is not defined error in Python

It works for me:

>>> def pyth_test (x1, x2):
...     print x1 + x2
...
>>> pyth_test(1,2)
3

Make sure you define the function before you call it.

How to get store information in Magento?

In Magento 1.9.4.0 and maybe all versions in 1.x use:

Mage::getStoreConfig('general/store_information/address');

and the following params, it depends what you want to get:

  • general/store_information/name
  • general/store_information/phone
  • general/store_information/merchant_country
  • general/store_information/address
  • general/store_information/merchant_vat_number

File path to resource in our war/WEB-INF folder?

I know this is late, but this is how I normally do it,

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();           
InputStream stream = classLoader.getResourceAsStream("../test/foo.txt");

Convert array of strings into a string in Java

String[] strings = new String[25000];
for (int i = 0; i < 25000; i++) strings[i] = '1234567';

String result;
result = "";
for (String s : strings) result += s;
//linear +: 5s

result = "";
for (String s : strings) result = result.concat(s);
//linear .concat: 2.5s

result = String.join("", strings);
//Java 8 .join: 3ms

Public String join(String delimiter, String[] s)
{
    int ls = s.length;
    switch (ls)
    {
        case 0: return "";
        case 1: return s[0];
        case 2: return s[0].concat(delimiter).concat(s[1]);
        default:
            int l1 = ls / 2;
            String[] s1 = Arrays.copyOfRange(s, 0, l1); 
            String[] s2 = Arrays.copyOfRange(s, l1, ls); 
            return join(delimiter, s1).concat(delimiter).concat(join(delimiter, s2));
    }
}
result = join("", strings);
// Divide&Conquer join: 7ms

If you don't have the choise but to use Java 6 or 7 then you should use Divide&Conquer join.

Excel Formula: Count cells where value is date

Here is how I was able to trick Excel to count expired certifications in a list. I didn't have a set date, or date range, just current date. "TODAY()" doesn't work in these for Excel 2013. It sees it as text or condition, not the date value. So these previous didn't work for me. So the word problem/scenario: How many people are expired in this list?

Use: =IFERROR(D5-TODAY(),0) Where D5 is the date to be interrogated.

Then use: =IF(J5>=1,1,0) Where J5 is the cell where the first equation is producing either a positive or negative number. This set, I have hidden on the side of the visible sheet, then I just sum the total for the number of unexpired members.

How can I use std::maps with user-defined types as key?

The right solution is to Specialize std::less for your class/Struct.

• Basically maps in cpp are implemented as Binary Search Trees.

  1. BSTs compare elements of nodes to determine the organization of the tree.
  2. Nodes who's element compares less than that of the parent node are placed on the left of the parent and nodes whose elements compare greater than the parent nodes element are placed on the right. i.e.

For each node, node.left.key < node.key < node.right.key

Every node in the BST contains Elements and in case of maps its KEY and a value, And keys are supposed to be ordered. More About Map implementation : The Map data Type.

In case of cpp maps , keys are the elements of the nodes and values does not take part in the organization of the tree its just a supplementary data .

So It means keys should be compatible with std::less or operator< so that they can be organized. Please check map parameters.

Else if you are using user defined data type as keys then need to give meaning full comparison semantics for that data type.

Solution : Specialize std::less:

The third parameter in map template is optional and it is std::less which will delegate to operator< ,

So create a new std::less for your user defined data type. Now this new std::less will be picked by std::map by default.

namespace std
{
    template<> struct  less<MyClass>
    {
        bool operator() (const MyClass& lhs, const MyClass& rhs) const
        {
            return lhs.anyMemen < rhs.age;
        }
    };

}

Note: You need to create specialized std::less for every user defined data type(if you want to use that data type as key for cpp maps).

Bad Solution: Overloading operator< for your user defined data type. This solution will also work but its very bad as operator < will be overloaded universally for your data type/class. which is undesirable in client scenarios.

Please check answer Pavel Minaev's answer

How to resolve symbolic links in a shell script

function realpath {
    local r=$1; local t=$(readlink $r)
    while [ $t ]; do
        r=$(cd $(dirname $r) && cd $(dirname $t) && pwd -P)/$(basename $t)
        t=$(readlink $r)
    done
    echo $r
}

#example usage
SCRIPT_PARENT_DIR=$(dirname $(realpath "$0"))/..

Share data between html pages

possibly if you want to just transfer data to be used by JavaScript then you can use Hash Tags like this

http://localhost/project/index.html#exist

so once when you are done retriving the data show the message and change the window.location.hash to a suitable value.. now whenever you ll refresh the page the hashtag wont be present
NOTE: when you will use this instead ot query strings the data being sent cannot be retrived/read by the server

How to use both onclick and target="_blank"

onclick="window.open('your_html', '_blank')"

Darken CSS background image?

You can use the CSS3 Linear Gradient property along with your background-image like this:

#landing-wrapper {
    display:table;
    width:100%;
    background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
    background-position:center top;
    height:350px;
}

Here's a demo:

_x000D_
_x000D_
#landing-wrapper {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
  background-position: center top;_x000D_
  height: 350px;_x000D_
  color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
_x000D_
_x000D_

How to make a new List in Java

Using Google Collections, you could use the following methods in the Lists class

import com.google.common.collect.Lists;

// ...

List<String> strings = Lists.newArrayList();

List<Integer> integers = Lists.newLinkedList();

There are overloads for varargs initialization and initialising from an Iterable<T>.

The advantage of these methods is that you don't need to specify the generic parameter explicitly as you would with the constructor - the compiler will infer it from the type of the variable.

google chrome extension :: console.log() from background page?

You can still use console.log(), but it gets logged into a separate console. In order to view it - right click on the extension icon and select "Inspect popup".

How to add a jar in External Libraries in android studio

If you dont see option "Add as Library", make sure you extract (unzip) your file so that you have mail.jar and not mail.zip.

Then right click your file, and you can see the option "Add as library".

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

wsHttpBinding is a problem because silverlight doesn't support it!

Git: "Corrupt loose object"

Try

git stash

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

How do I change the JAVA_HOME for ant?

Though the environment variable JAVA_HOME set correctly, the ant may use the configured JRE within the each build.xml or any build files.

To check what version of the JRE the ant is using, right click on the build file -> select the build ant which displays the details about the tasks to choose etc, select the JRE which you want to use.

Its advisable to use the project level settings or just at the workspace level.

Genymotion Android emulator - adb access?

My working solution is:

cd /opt/genymobile/genymotion/tools
./adb shell

You have to use its own adb tool.

How to wrap async function calls into a sync function in Node.js or Javascript?

You shouldn't be looking at what happens around the call that creates the fiber but rather at what happens inside the fiber. Once you are inside the fiber you can program in sync style. For example:

function f1() {
    console.log('wait... ' + new Date);
    sleep(1000);
    console.log('ok... ' + new Date);   
}

function f2() {
    f1();
    f1();
}

Fiber(function() {
    f2();
}).run();

Inside the fiber you call f1, f2 and sleep as if they were sync.

In a typical web application, you will create the Fiber in your HTTP request dispatcher. Once you've done that you can write all your request handling logic in sync style, even if it calls async functions (fs, databases, etc.).

How to remove and clear all localStorage data

localStorage.clear();

should work.

How can I determine the direction of a jQuery scroll event?

Existing Solution

There could be 3 solution from this posting and other answer.

Solution 1

    var lastScrollTop = 0;
    $(window).on('scroll', function() {
        st = $(this).scrollTop();
        if(st < lastScrollTop) {
            console.log('up 1');
        }
        else {
            console.log('down 1');
        }
        lastScrollTop = st;
    });

Solution 2

    $('body').on('DOMMouseScroll', function(e){
        if(e.originalEvent.detail < 0) {
            console.log('up 2');
        }
        else {
            console.log('down 2');
        }
    });

Solution 3

    $('body').on('mousewheel', function(e){
        if(e.originalEvent.wheelDelta > 0) {
            console.log('up 3');
        }
        else {
            console.log('down 3');
        }
    });

Multi Browser Test

I couldn't tested it on Safari

chrome 42 (Win 7)

  • Solution 1
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll
  • Solution 2
    • Up : Not working
    • Down : Not working
  • Solution 3
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll

Firefox 37 (Win 7)

  • Solution 1
    • Up : 20 events per 1 scroll
    • Down : 20 events per 1 scroll
  • Solution 2
    • Up : Not working
    • Down : 1 event per 1 scroll
  • Solution 3
    • Up : Not working
    • Down : Not working

IE 11 (Win 8)

  • Solution 1
    • Up : 10 events per 1 scroll (side effect : down scroll occured at last)
    • Down : 10 events per 1 scroll
  • Solution 2
    • Up : Not working
    • Down : Not working
  • Solution 3
    • Up : Not working
    • Down : 1 event per 1 scroll

IE 10 (Win 7)

  • Solution 1
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll
  • Solution 2
    • Up : Not working
    • Down : Not working
  • Solution 3
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll

IE 9 (Win 7)

  • Solution 1
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll
  • Solution 2
    • Up : Not working
    • Down : Not working
  • Solution 3
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll

IE 8 (Win 7)

  • Solution 1
    • Up : 2 events per 1 scroll (side effect : down scroll occured at last)
    • Down : 2~4 events per 1 scroll
  • Solution 2
    • Up : Not working
    • Down : Not working
  • Solution 3
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll

Combined Solution

I checked that side effect from IE 11 and IE 8 is come from if else statement. So, I replaced it with if else if statement as following.

From the multi browser test, I decided to use Solution 3 for common browsers and Solution 1 for firefox and IE 11.

I referred this answer to detect IE 11.

    // Detect IE version
    var iev=0;
    var ieold = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
    var trident = !!navigator.userAgent.match(/Trident\/7.0/);
    var rv=navigator.userAgent.indexOf("rv:11.0");

    if (ieold) iev=new Number(RegExp.$1);
    if (navigator.appVersion.indexOf("MSIE 10") != -1) iev=10;
    if (trident&&rv!=-1) iev=11;

    // Firefox or IE 11
    if(typeof InstallTrigger !== 'undefined' || iev == 11) {
        var lastScrollTop = 0;
        $(window).on('scroll', function() {
            st = $(this).scrollTop();
            if(st < lastScrollTop) {
                console.log('Up');
            }
            else if(st > lastScrollTop) {
                console.log('Down');
            }
            lastScrollTop = st;
        });
    }
    // Other browsers
    else {
        $('body').on('mousewheel', function(e){
            if(e.originalEvent.wheelDelta > 0) {
                console.log('Up');
            }
            else if(e.originalEvent.wheelDelta < 0) {
                console.log('Down');
            }
        });
    }

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

From other stackoverflow thread:

"Second. Make sure that you have MySQL JDBC Driver aka Connector/J in JMeter's classpath. If you don't - download it, unpack and drop mysql-connector-java-x.xx.xx-bin.jar to JMeter's /lib folder. JMeter restart will be required to pick the library up"

Please be sure that .jar file is added directly to the lib folder.

jQuery - Redirect with post data

This would redirect with posted data

$(function() {
       $('<form action="url.php" method="post"><input type="hidden" name="name" value="value1"></input></form>').appendTo('body').submit().remove();
    });

    }

the .submit() function does the submit to url automatically
the .remove() function kills the form after submitting

Java integer list

code that works, but output is:

10
20
30
40
50

so:

    List<Integer> myCoords = new ArrayList<Integer>();
    myCoords.add(10);
    myCoords.add(20);
    myCoords.add(30);
    myCoords.add(40);
    myCoords.add(50);
    for (Integer number : myCoords) {
        System.out.println(number);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

Objective-C: Calling selectors with multiple arguments

iOS users also expect autocapitalization: In a standard text field, the first letter of a sentence in a case-sensitive language is automatically capitalized.

You can decide whether or not to implement such features; there is no dedicated API for any of the features just listed, so providing them is a competitive advantage.

Apple document is saying there is no API available for this feature and some other expected feature in a customkeyboard. so you need to find out your own logic to implement this.

How to read data from excel file using c#

CSharpJExcel for reading Excel 97-2003 files (XLS), ExcelPackage for reading Excel 2007/2010 files (Office Open XML format, XLSX), and ExcelDataReader that seems to have the ability to handle both formats

Good luck!

form_for but to post to a different action

new syntax

<%= form_for :user, url: custom_user_path, method: :post do |f|%>
<%end%>

How to replace all double quotes to single quotes using jquery?

Use double quote to enclose the quote or escape it.

newTemp = mystring.replace(/"/g, "'");

or

newTemp = mystring.replace(/"/g, '\'');

Best Practice: Software Versioning

As Mahesh says: I would use x.y.z kind of versioning

x - major release y - minor release z - build number

you may want to add a datetime, maybe instead of z.

You increment the minor release when you have another release. The major release will probably stay 0 or 1, you change that when you really make major changes (often when your software is at a point where its not backwards compatible with previous releases, or you changed your entire framework)

Configuring Git over SSH to login once

If you have cloned using HTTPS (recommended) then:-

git config --global credential.helper cache

and then

git config --global credential.helper 'cache --timeout=2592000'
  • timeout=2592000 (30 Days in seconds) to enable caching for 30 days (or whatever suites you).

  • Now run a simple git command that requires your username and password.

  • Enter your credentials once and now caching is enabled for 30 Days.

  • Try again with any git command and now you don't need any credentials.

  • For more info :- Caching your GitHub password in Git

Note : You need Git 1.7.10 or newer to use the credential helper. On system restart, we might have to enter the password again.

Update #1:

If you are receiving this error git: 'credential-cache' is not a git command. See 'get --help'

then replace git config --global credential.helper 'cache --timeout=2592000'

with git config --global credential.helper 'store --file ~/.my-credentials'

Update #2:

If you keep getting the prompt of username and password and getting this issue:

Logon failed, use ctrl+c to cancel basic credential prompt.

Reinstalling the latest version of git worked for me.

e.printStackTrace equivalent in python

There is also logging.exception.

import logging

...

try:
    g()
except Exception as ex:
    logging.exception("Something awful happened!")
    # will print this message followed by traceback

Output:

ERROR 2007-09-18 23:30:19,913 error 1294 Something awful happened!
Traceback (most recent call last):
  File "b.py", line 22, in f
    g()
  File "b.py", line 14, in g
    1/0
ZeroDivisionError: integer division or modulo by zero

(From http://blog.tplus1.com/index.php/2007/09/28/the-python-logging-module-is-much-better-than-print-statements/ via How to print the full traceback without halting the program?)

How to run an android app in background?

As apps run in the background anyway. I’m assuming what your really asking is how do you make apps do stuff in the background. The solution below will make your app do stuff in the background after opening the app and after the system has rebooted.

Below, I’ve added a link to a fully working example (in the form of an Android Studio Project)

This subject seems to be out of the scope of the Android docs, and there doesn’t seem to be any one comprehensive doc on this. The information is spread across a few docs.

The following docs tell you indirectly how to do this: https://developer.android.com/reference/android/app/Service.html

https://developer.android.com/reference/android/content/BroadcastReceiver.html

https://developer.android.com/guide/components/bound-services.html

In the interests of getting your usage requirements correct, the important part of this above doc to read carefully is: #Binder, #Messenger and the components link below:

https://developer.android.com/guide/components/aidl.html

Here is the link to a fully working example (in Android Studio format): http://developersfound.com/BackgroundServiceDemo.zip

This project will start an Activity which binds to a service; implementing the AIDL.

This project is also useful to re-factor for the purpose of IPC across different apps.

This project is also developed to start automatically when Android restarts (provided the app has been run at least one after installation and app is not installed on SD card)

When this app/project runs after reboot, it dynamically uses a transparent view to make it look like no app has started but the service of the associated app starts cleanly.

This code is written in such a way that it’s very easy to tweak to simulate a scheduled service.

This project is developed in accordance to the above docs and is subsequently a clean solution.

There is however a part of this project which is not clean being: I have not found a way to start a service on reboot without using an Activity. If any of you guys reading this post have a clean way to do this please post a comment.

Push JSON Objects to array in localStorage

One thing I can suggest you is to extend the storage object to handle objects and arrays.

LocalStorage can handle only strings so you can achieve that using these methods

Storage.prototype.setObj = function(key, obj) {
    return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
    return JSON.parse(this.getItem(key))
}

Using it every values will be converted to json string on set and parsed on get

ECONNREFUSED error when connecting to mongodb from node.js

very strange, but in my case, i switch wifi connection...

I use some public wifi and switch to my phone connection

Iterating through directories with Python

From python >= 3.5 onward, you can use **, glob.iglob(path/**, recursive=True) and it seems the most pythonic solution, i.e.:

import glob, os

for filename in glob.iglob('/pardadox-music/**', recursive=True):
    if os.path.isfile(filename): # filter dirs
        print(filename)

Output:

/pardadox-music/modules/her1.mod
/pardadox-music/modules/her2.mod
...

Notes:
1 - glob.iglob

glob.iglob(pathname, recursive=False)

Return an iterator which yields the same values as glob() without actually storing them all simultaneously.

2 - If recursive is True, the pattern '**' will match any files and zero or more directories and subdirectories.

3 - If the directory contains files starting with . they won’t be matched by default. For example, consider a directory containing card.gif and .card.gif:

>>> import glob
>>> glob.glob('*.gif') ['card.gif'] 
>>> glob.glob('.c*')['.card.gif']

4 - You can also use rglob(pattern), which is the same as calling glob() with **/ added in front of the given relative pattern.

Embedding SVG into ReactJS

If you just have a static svg string you want to include, you can use dangerouslySetInnerHTML:

render: function() {
    return <span dangerouslySetInnerHTML={{__html: "<svg>...</svg>"}} />;
}

and React will include the markup directly without processing it at all.

How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

UIImage is a wrapper the bytes are CGImage or CIImage

According the the Apple Reference on UIImage the object is immutable and you have no access to the backing bytes. While it is true that you can access the CGImage data if you populated the UIImage with a CGImage (explicitly or implicitly), it will return NULL if the UIImage is backed by a CIImage and vice-versa.

Image objects not provide direct access to their underlying image data. However, you can retrieve the image data in other formats for use in your app. Specifically, you can use the cgImage and ciImage properties to retrieve versions of the image that are compatible with Core Graphics and Core Image, respectively. You can also use the UIImagePNGRepresentation(:) and UIImageJPEGRepresentation(:_:) functions to generate an NSData object containing the image data in either the PNG or JPEG format.

Common tricks to getting around this issue

As stated your options are

  • UIImagePNGRepresentation or JPEG
  • Determine if image has CGImage or CIImage backing data and get it there

Neither of these are particularly good tricks if you want output that isn't ARGB, PNG, or JPEG data and the data isn't already backed by CIImage.

My recommendation, try CIImage

While developing your project it might make more sense for you to avoid UIImage altogether and pick something else. UIImage, as a Obj-C image wrapper, is often backed by CGImage to the point where we take it for granted. CIImage tends to be a better wrapper format in that you can use a CIContext to get out the format you desire without needing to know how it was created. In your case, getting the bitmap would be a matter of calling

- render:toBitmap:rowBytes:bounds:format:colorSpace:

As an added bonus you can start doing nice manipulations to the image by chaining filters onto the image. This solves a lot of the issues where the image is upside down or needs to be rotated/scaled etc.

Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'

Here is my response to the problem described in the question.

in cmd write:

php artisan cache:clear

then try to do this code in your terminal

php artisan serve

note: this will start again the server

how to avoid extra blank page at end while printing?

First, emulate the print stylesheet via your browser's devtools. Instructions can be found here.

Then you'll want to look for extra padding, margin, borders, etc that could be extending the dimensions of your pages beyond the 8.5in x 11in. Pay special attention to whitespace as this will be impossible to detect via the print preview dialog. If there is whitespace that shouldn't be there, right-clicking and inspecting the element under the cursor should highlight the issue (unless it's a margin causing it).

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

Visual Studio Post Build Event - Copy to Relative Directory Location

If none of the TargetDir or other macros point to the right place, use the ".." directory to go backwards up the folder hierarchy.

ie. Use $(SolutionDir)\..\.. to get your base directory.


For list of all macros, see here:

http://msdn.microsoft.com/en-us/library/c02as0cs.aspx

How to get current timestamp in milliseconds since 1970 just the way Java gets

Since C++11 you can use std::chrono:

  • get current system time: std::chrono::system_clock::now()
  • get time since epoch: .time_since_epoch()
  • translate the underlying unit to milliseconds: duration_cast<milliseconds>(d)
  • translate std::chrono::milliseconds to integer (uint64_t to avoid overflow)
#include <chrono>
#include <cstdint>
#include <iostream>

uint64_t timeSinceEpochMillisec() {
  using namespace std::chrono;
  return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}

int main() {
  std::cout << timeSinceEpochMillisec() << std::endl;
  return 0;
}

How do I add records to a DataGridView in VB.Net?

When I try to cast data source from datagridview that used bindingsource it error accor cannot casting:

----------Solution------------

'I changed casting from bindingsource that bind with datagridview

'Code here

Dim dtdata As New DataTable()

dtdata = CType(bndsData.DataSource, DataTable)

Spring Boot without the web server

You can create something like this:

@SpringBootApplication
public class Application {
  public static void main(String[] args) {
    new SpringApplicationBuilder(Application.class).web(false).run(args);
  }
}

And

@Component
public class CommandLiner implements CommandLineRunner {

  @Override
  public void run(String... args) throws Exception {
    // Put your logic here
  }

}

The dependency is still there though but not used.

What is the meaning of "__attribute__((packed, aligned(4))) "

  • packed means it will use the smallest possible space for struct Ball - i.e. it will cram fields together without padding
  • aligned means each struct Ball will begin on a 4 byte boundary - i.e. for any struct Ball, its address can be divided by 4

These are GCC extensions, not part of any C standard.

How do I extract data from JSON with PHP?

The acepted Answer is very detailed and correct in most of the cases.

I just want to add that i was getting an error while attempting to load a JSON text file encoded with UTF8, i had a well formatted JSON but the 'json_decode' always returned me with NULL, it was due the BOM mark.

To solve it, i made this PHP function:

function load_utf8_file($filePath)
{
    $response = null;
    try
    {
        if (file_exists($filePath)) {
            $text = file_get_contents($filePath);
            $response = preg_replace("/^\xEF\xBB\xBF/", '', $text);          
        }     
    } catch (Exception $e) {
      echo 'ERROR: ',  $e->getMessage(), "\n";
   }
   finally{  }
   return $response;
}

Then i use it like this to load a JSON file and get a value from it:

$str = load_utf8_file('appconfig.json'); 
$json = json_decode($str, true); 
//print_r($json);
echo $json['prod']['deploy']['hostname'];

Matplotlib: "Unknown projection '3d'" error

I encounter the same problem, and @Joe Kington and @bvanlew's answer solve my problem.

but I should add more infomation when you use pycharm and enable auto import.

when you format the code, the code from mpl_toolkits.mplot3d import Axes3D will auto remove by pycharm.

so, my solution is

from mpl_toolkits.mplot3d import Axes3D
Axes3D = Axes3D  # pycharm auto import
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

and it works well!

An error occurred while collecting items to be installed (Access is denied)

I just solved this problem by unchecking Read only checkbox of the Program Files/eclipse folder on win7.

Apply to all files and folders.

Serialize and Deserialize Json and Json Array in Unity

Assume you got a JSON like this

[
    {
        "type": "qrcode",
        "symbol": [
            {
                "seq": 0,
                "data": "HelloWorld9887725216",
                "error": null
            }
        ]
    }
]

To parse the above JSON in unity, you can create JSON model like this.

[System.Serializable]
public class QrCodeResult
{
    public QRCodeData[] result;
}

[System.Serializable]
public class Symbol
{
    public int seq;
    public string data;
    public string error;
}

[System.Serializable]
public class QRCodeData
{
    public string type;
    public Symbol[] symbol;
}

And then simply parse in the following manner...

var myObject = JsonUtility.FromJson<QrCodeResult>("{\"result\":" + jsonString.ToString() + "}");

Now you can modify the JSON/CODE according to your need. https://docs.unity3d.com/Manual/JSONSerialization.html

How can I convert an RGB image into grayscale in Python?

Using this formula

Y' = 0.299 R + 0.587 G + 0.114 B 

We can do

import imageio
import numpy as np
import matplotlib.pyplot as plt

pic = imageio.imread('(image)')
gray = lambda rgb : np.dot(rgb[... , :3] , [0.299 , 0.587, 0.114]) 
gray = gray(pic)  
plt.imshow(gray, cmap = plt.get_cmap(name = 'gray'))

However, the GIMP converting color to grayscale image software has three algorithms to do the task.

Change the background color in a twitter bootstrap modal?

It gets a little bit more complicated if you want to add the background to a specific modal. One way of solving that is to add and call something like this function instead of showing the modal directly:

function showModal(selector) {
    $(selector).modal('show');
    $('.modal-backdrop').addClass('background-backdrop');
}

Any css can then be applied to the background-backdrop class.

How do I configure the proxy settings so that Eclipse can download new plugins?

Just to add to the thread as a POSSIBLE solution, I faced a similar issue when developing on a Linux system that was behind a company firewall. However, using a Windows XP machine, Eclipse was able to access different update sites just fine as both the manual and native network connection providers worked just fine using the company proxy.

After stumbling around for some time, I came across a discussion about using NTLMv2 and an implementation to be found at http://cntlm.sourceforge.net/. To whomever posted this, I give much credit to as it helped me get past the issue running on Linux. As a side note, I was using Eclipse 3.6.2 / Helios on both the Linux and Windows distros.

Best of luck on finding a solution!

Pull new updates from original GitHub repository into forked GitHub repository

You have to add the original repository (the one you forked) as a remote.

From the GitHub documentation on forking a repository:

Screenshot of the old GitHub interface with a rectangular lens around the "Fork" button

Once the clone is complete your repo will have a remote named “origin” that points to your fork on GitHub.
Don’t let the name confuse you, this does not point to the original repo you forked from. To help you keep track of that repo we will add another remote named “upstream”:

$ cd PROJECT_NAME
$ git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git
$ git fetch upstream

# then: (like "git pull" which is fetch + merge)
$ git merge upstream/master master

# or, better, replay your local work on top of the fetched branch
# like a "git pull --rebase"
$ git rebase upstream/master

There's also a command-line tool (hub) which can facilitate the operations above.

Here's a visual of how it works:

Flowchart on the result after the commands are executed

See also "Are Git forks actually Git clones?".

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

I'm using Studio 3.3.1 Build from Jan 28.

For me I was getting the "error android resource linking failed" pointing to a line in a layout file using ConstraintLayout that had been working correctly until today when the only change to my app level gradle file was to update the versions of:

android.arch.navigation:navigation-fragment
android.arch.navigation:navigation-ui

from 1.0.0-rc01 to 1.0.0-rc02.

The error message said something about not recognizing layout_constraintTop_toTopOf which of course is silly because it had been compiling quite happily for months.

I am already on 28.0.3 of build tools and compileSdkVersion of 28. I've been using androidx.appcompat everywhere for a while now (converted this project months back to androidx).

I first went through a project clean (no help), and invalidating cache/restart (no help). The layout in question had been originally defined using

<TextView>, <EditText> and <ImageView> components (which had been working fine until today).

But after reading the above answers I thought maybe somehow there was confusion being caused here so I changed the layout to use:

<androidx.appcompat.widget

versions of all the various components. No change - still got the error.

I then deleted the <androidx.appcompat.widget.AppCompatTextView block that was causing the compilation error. I changed all references to it in the other widgets to refer to "parent" instead. Did a Make. This time the compile completed without error.

So something strange in that widget definition I thought....here is what it was:

<androidx.appcompat.widget.AppCompatTextView
    android:id="@+id/contact_firstname_label"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="@string/contact_fname_label"
    android:gravity="end"
    android:textAppearance="@android:style/TextAppearance.Material.Small"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@+id/contact_detail_fname"
    app:layout_constraintBaseline_toBaselineOf="@+id/contact_detail_fname"/>

I then pasted back the block I had Ctrl-V cut previously and changed the references back to that ID in the other components that reference it in the layout. Compile failed.

I cut the block again and pasted it to WordPad. Then reading from the WordPad paste, I actually typed it back in (i.e. I didn't copy/paste this time) - line by line, doing a make on the project after I typed in the minimal definition, and then again thereafter when I put in each new line. Each time the project compiled cleanly!

I don't know what to make of this. Perhaps some spurious invisible character was in the file originally?

Node.js https pem error: routines:PEM_read_bio:no start line

If you log the

var options = {
  key: fs.readFileSync('./key.pem', 'utf8'),
  cert: fs.readFileSync('./csr.pem', 'utf8')
};

You might notice there are invalid characters due to improper encoding.

Reading rather large json files in Python

The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.

The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.

The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.

Edit: Also worth a look - kashif's comment about json-streamer and Henrik Heino's comment about bigjson.

Create a BufferedImage from file and make it TYPE_INT_ARGB

Create a BufferedImage from file and make it TYPE_INT_RGB

import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
    public static void main(String args[]){
        try{
            BufferedImage img = new BufferedImage( 
                500, 500, BufferedImage.TYPE_INT_RGB );
            File f = new File("MyFile.png");
            int r = 5;
            int g = 25; 
            int b = 255;
            int col = (r << 16) | (g << 8) | b;
            for(int x = 0; x < 500; x++){
                for(int y = 20; y < 300; y++){
                    img.setRGB(x, y, col);
                }
            }
            ImageIO.write(img, "PNG", f); 
        }
        catch(Exception e){ 
            e.printStackTrace();
        }
    }
}

This paints a big blue streak across the top.

If you want it ARGB, do it like this:

    try{
        BufferedImage img = new BufferedImage( 
            500, 500, BufferedImage.TYPE_INT_ARGB );
        File f = new File("MyFile.png");
        int r = 255;
        int g = 10;
        int b = 57;
        int alpha = 255;
        int col = (alpha << 24) | (r << 16) | (g << 8) | b;
        for(int x = 0; x < 500; x++){
            for(int y = 20; y < 30; y++){
                img.setRGB(x, y, col);
            }
        }
        ImageIO.write(img, "PNG", f);
    }
    catch(Exception e){
        e.printStackTrace();
    }

Open up MyFile.png, it has a red streak across the top.

Using Linq to group a list of objects into a new grouped list of list of objects

Still an old one, but answer from Lee did not give me the group.Key as result. Therefore, I am using the following statement to group a list and return a grouped list:

public IOrderedEnumerable<IGrouping<string, User>> groupedCustomerList;

groupedCustomerList =
        from User in userList
        group User by User.GroupID into newGroup
        orderby newGroup.Key
        select newGroup;

Each group now has a key, but also contains an IGrouping which is a collection that allows you to iterate over the members of the group.

Multiple modals overlay

Each modal should be given a different id and each link should be targeted to a different modal id. So it should be something like that:

<a href="#myModal" data-toggle="modal">
...
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
...
<a href="#myModal2" data-toggle="modal">
...
<div id="myModal2" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
...

Delete terminal history in Linux

If you use bash, then the terminal history is saved in a file called .bash_history. Delete it, and history will be gone.

However, for MySQL the better approach is not to enter the password in the command line. If you just specify the -p option, without a value, then you will be prompted for the password and it won't be logged.

Another option, if you don't want to enter your password every time, is to store it in a my.cnf file. Create a file named ~/.my.cnf with something like:

[client]
user = <username>
password = <password>

Make sure to change the file permissions so that only you can read the file.

Of course, this way your password is still saved in a plaintext file in your home directory, just like it was previously saved in .bash_history.

Master Page Weirdness - "Content controls have to be top-level controls in a content page or a nested master page that references a master page."

When you created the WebForm, did you select the Master page it is attached to in the "Add New Item" dialog itself ? Or did you attach it manually using the MasterPageFile attribute of the @Page directive ? If it was the latter, it might explain the error message you receive.

VS automatically inserts certain markup in each kind of page. If you select the MasterPage at the time of page creation itself, it does not generate any markup except the @Page declaration and the top level Content control.

Getting Image from URL (Java)

Directly calling a URL to get an image may concern with major security issues. You need to ensure that you have sufficient rights to access that resource. However You can use ByteOutputStream to read image file. This is an example (Its just an example, you need to do necessary changes as per your requirement.)

ByteArrayOutputStream bis = new ByteArrayOutputStream();
InputStream is = null;
try {
  is = url.openStream ();
  byte[] bytebuff = new byte[4096]; 
  int n;

  while ( (n = is.read(bytebuff)) > 0 ) {
    bis.write(bytebuff, 0, n);
  }
}

How do I express "if value is not empty" in the VBA language?

Why not just use the built-in Format() function?

Dim vTest As Variant
vTest = Empty ' or vTest = null or vTest = ""

If Format(vTest) = vbNullString Then
    doSomethingWhenEmpty() 
Else
   doSomethingElse() 
End If

Format() will catch empty variants as well as null ones and transforms them in strings. I use it for things like null/empty validations and to check if an item has been selected in a combobox.

Creating a simple configuration file and parser in C++

In general, it's easiest to parse such typical config files in two stages: first read the lines, and then parse those one by one.
In C++, lines can be read from a stream using std::getline(). While by default it will read up to the next '\n' (which it will consume, but not return), you can pass it some other delimiter, too, which makes it a good candidate for reading up-to-some-char, like = in your example.

For simplicity, the following presumes that the = are not surrounded by whitespace. If you want to allow whitespaces at these positions, you will have to strategically place is >> std::ws before reading the value and remove trailing whitespaces from the keys. However, IMO the little added flexibility in the syntax is not worth the hassle for a config file reader.

const char config[] = "url=http://example.com\n"
                      "file=main.exe\n"
                      "true=0";

std::istringstream is_file(config);

std::string line;
while( std::getline(is_file, line) )
{
  std::istringstream is_line(line);
  std::string key;
  if( std::getline(is_line, key, '=') )
  {
    std::string value;
    if( std::getline(is_line, value) ) 
      store_line(key, value);
  }
}

(Adding error handling is left as an exercise to the reader.)

How to add custom validation to an AngularJS form?

I extended @Ben Lesh's answer with an ability to specify whether the validation is case sensitive or not (default)

use:

<input type="text" name="fruitName" ng-model="data.fruitName" blacklist="Coconuts,Bananas,Pears" caseSensitive="true" required/>

code:

angular.module('crm.directives', []).
directive('blacklist', [
    function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            scope: {
                'blacklist': '=',
            },
            link: function ($scope, $elem, $attrs, modelCtrl) {

                var check = function (value) {
                    if (!$attrs.casesensitive) {
                        value = (value && value.toUpperCase) ? value.toUpperCase() : value;

                        $scope.blacklist = _.map($scope.blacklist, function (item) {
                            return (item.toUpperCase) ? item.toUpperCase() : item
                        })
                    }

                    return !_.isArray($scope.blacklist) || $scope.blacklist.indexOf(value) === -1;
                }

                //For DOM -> model validation
                modelCtrl.$parsers.unshift(function (value) {
                    var valid = check(value);
                    modelCtrl.$setValidity('blacklist', valid);

                    return value;
                });
                //For model -> DOM validation
                modelCtrl.$formatters.unshift(function (value) {
                    modelCtrl.$setValidity('blacklist', check(value));
                    return value;
                });
            }
        };
    }
]);

How to throw a C++ exception

Wanted to ADD to the other answers described here an additional note, in the case of custom exceptions.

In the case where you create your own custom exception, that derives from std::exception, when you catch "all possible" exceptions types, you should always start the catch clauses with the "most derived" exception type that may be caught. See the example (of what NOT to do):

#include <iostream>
#include <string>

using namespace std;

class MyException : public exception
{
public:
    MyException(const string& msg) : m_msg(msg)
    {
        cout << "MyException::MyException - set m_msg to:" << m_msg << endl;
    }

   ~MyException()
   {
        cout << "MyException::~MyException" << endl;
   }

   virtual const char* what() const throw () 
   {
        cout << "MyException - what" << endl;
        return m_msg.c_str();
   }

   const string m_msg;
};

void throwDerivedException()
{
    cout << "throwDerivedException - thrown a derived exception" << endl;
    string execptionMessage("MyException thrown");
    throw (MyException(execptionMessage));
}

void illustrateDerivedExceptionCatch()
{
    cout << "illustrateDerivedExceptionsCatch - start" << endl;
    try 
    {
        throwDerivedException();
    }
    catch (const exception& e)
    {
        cout << "illustrateDerivedExceptionsCatch - caught an std::exception, e.what:" << e.what() << endl;
        // some additional code due to the fact that std::exception was thrown...
    }
    catch(const MyException& e)
    {
        cout << "illustrateDerivedExceptionsCatch - caught an MyException, e.what::" << e.what() << endl;
        // some additional code due to the fact that MyException was thrown...
    }

    cout << "illustrateDerivedExceptionsCatch - end" << endl;
}

int main(int argc, char** argv)
{
    cout << "main - start" << endl;
    illustrateDerivedExceptionCatch();
    cout << "main - end" << endl;
    return 0;
}

NOTE:

0) The proper order should be vice-versa, i.e.- first you catch (const MyException& e) which is followed by catch (const std::exception& e).

1) As you can see, when you run the program as is, the first catch clause will be executed (which is probably what you did NOT wanted in the first place).

2) Even though the type caught in the first catch clause is of type std::exception, the "proper" version of what() will be called - cause it is caught by reference (change at least the caught argument std::exception type to be by value - and you will experience the "object slicing" phenomena in action).

3) In case that the "some code due to the fact that XXX exception was thrown..." does important stuff WITH RESPECT to the exception type, there is misbehavior of your code here.

4) This is also relevant if the caught objects were "normal" object like: class Base{}; and class Derived : public Base {}...

5) g++ 7.3.0 on Ubuntu 18.04.1 produces a warning that indicates the mentioned issue:

In function ‘void illustrateDerivedExceptionCatch()’: item12Linux.cpp:48:2: warning: exception of type ‘MyException’ will be caught catch(const MyException& e) ^~~~~

item12Linux.cpp:43:2: warning: by earlier handler for ‘std::exception’ catch (const exception& e) ^~~~~

Again, I will say, that this answer is only to ADD to the other answers described here (I thought this point is worth mention, yet could not depict it within a comment).

Insert Unicode character into JavaScript

The answer is correct, but you don't need to declare a variable. A string can contain your character:

"This string contains omega, that looks like this: \u03A9"

Unfortunately still those codes in ASCII are needed for displaying UTF-8, but I am still waiting (since too many years...) the day when UTF-8 will be same as ASCII was, and ASCII will be just a remembrance of the past.

What are NR and FNR and what does "NR==FNR" imply?

Assuming you have Files a.txt and b.txt with

cat a.txt
a
b
c
d
1
3
5
cat b.txt
a
1
2
6
7

Keep in mind NR and FNR are awk built-in variables. NR - Gives the total number of records processed. (in this case both in a.txt and b.txt) FNR - Gives the total number of records for each input file (records in either a.txt or b.txt)

awk 'NR==FNR{a[$0];}{if($0 in a)print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
a.txt 1 1 a
a.txt 2 2 b
a.txt 3 3 c
a.txt 4 4 d
a.txt 5 5 1
a.txt 6 6 3
a.txt 7 7 5
b.txt 8 1 a
b.txt 9 2 1

lets Add "next" to skip the first matched with NR==FNR

in b.txt and in a.txt

awk 'NR==FNR{a[$0];next}{if($0 in a)print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
b.txt 8 1 a
b.txt 9 2 1

in b.txt but not in a.txt

 awk 'NR==FNR{a[$0];next}{if(!($0 in a))print FILENAME " " NR " " FNR " " $0}' a.txt b.txt
b.txt 10 3 2
b.txt 11 4 6
b.txt 12 5 7

awk 'NR==FNR{a[$0];next}!($0 in a)' a.txt b.txt
2
6
7

How can I get the request URL from a Java Filter?

Building on another answer on this page,

public static String getCurrentUrlFromRequest(ServletRequest request)
{
   if (! (request instanceof HttpServletRequest))
       return null;

   return getCurrentUrlFromRequest((HttpServletRequest)request);
}

public static String getCurrentUrlFromRequest(HttpServletRequest request)
{
    StringBuffer requestURL = request.getRequestURL();
    String queryString = request.getQueryString();

    if (queryString == null)
        return requestURL.toString();

    return requestURL.append('?').append(queryString).toString();
}

Why can't I set text to an Android TextView?

In your XML, you had used Textview, But in Java Code you had used EditText instead of TextView. If you change it into TextView you can set Text to to your TextView Object.

text = (TextView) findViewById(R.id.this_is_the_id_of_textview);
text.setText("TEST");

hope it will work.

bootstrap multiselect get selected values

$('#multiselect1').on('change', function(){
    var selected = $(this).find("option:selected");    
    var arrSelected = [];

    // selected.each(function(){
    //   arrSelected.push($(this).val());
    // });

    // The problem with the above selected.each statement is that  
    // there is no iteration value.
    // $(this).val() is all selected items, not an iterative item value.
    // With each iteration the selected items will be appended to 
    // arrSelected like so    
    //
    // arrSelected [0]['item0','item1','item2']
    // arrSelected [1]['item0','item1','item2'] 

    // You need to get the iteration value. 
    //
    selected.each((idx, val) => {
        arrSelected.push(val.value);
    });
    // arrSelected [0]['item0'] 
    // arrSelected [1]['item1']
    // arrSelected [2]['item2']
});

Fatal error: Call to undefined function mb_strlen()

This worked for me on Debian stretch

sudo apt-get update
sudo apt install php-mbstring
service apache2 restart

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

Many answer above are correct but same time convoluted with other aspects of authN/authZ. What actually resolves the exception in question is this line:

services.AddScheme<YourAuthenticationOptions, YourAuthenticationHandler>(YourAuthenticationSchemeName, options =>
    {
        options.YourProperty = yourValue;
    })

Can I load a UIImage from a URL?

The way using a Swift Extension to UIImageView (source code here):

Creating Computed Property for Associated UIActivityIndicatorView

import Foundation
import UIKit
import ObjectiveC

private var activityIndicatorAssociationKey: UInt8 = 0

extension UIImageView {
    //Associated Object as Computed Property
    var activityIndicator: UIActivityIndicatorView! {
        get {
            return objc_getAssociatedObject(self, &activityIndicatorAssociationKey) as? UIActivityIndicatorView
        }
        set(newValue) {
            objc_setAssociatedObject(self, &activityIndicatorAssociationKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
        }
    }

    private func ensureActivityIndicatorIsAnimating() {
        if (self.activityIndicator == nil) {
            self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
            self.activityIndicator.hidesWhenStopped = true
            let size = self.frame.size;
            self.activityIndicator.center = CGPoint(x: size.width/2, y: size.height/2);
            NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                self.addSubview(self.activityIndicator)
                self.activityIndicator.startAnimating()
            })
        }
    }

Custom Initializer and Setter

    convenience init(URL: NSURL, errorImage: UIImage? = nil) {
        self.init()
        self.setImageFromURL(URL)
    }

    func setImageFromURL(URL: NSURL, errorImage: UIImage? = nil) {
        self.ensureActivityIndicatorIsAnimating()
        let downloadTask = NSURLSession.sharedSession().dataTaskWithURL(URL) {(data, response, error) in
            if (error == nil) {
                NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                    self.activityIndicator.stopAnimating()
                    self.image = UIImage(data: data)
                })
            }
            else {
                self.image = errorImage
            }
        }
        downloadTask.resume()
    }
}

sql delete statement where date is greater than 30 days

Although the DATEADD is probably the most transparrent way of doing this, it is worth noting that simply getdate()-30 will also suffice.

Also, are you looking for 30 days from now, i.e. including hours, minutes, seconds, etc? Or 30 days from midnight today (e.g. 12/06/2010 00:00:00.000). In which case, you might consider:

SELECT * 
FROM Results 
WHERE convert(varchar(8), [Date], 112) >= convert(varchar(8), getdate(), 112)

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

If i can help you, you have to go in the Project Properties, and in the JDK location field check Use embedded JSD (recommended) eneable.

Android Min SDK Version vs. Target SDK Version

If you get some compile errors for example:

<uses-sdk
            android:minSdkVersion="10"
            android:targetSdkVersion="15" />

.

private void methodThatRequiresAPI11() {
        BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Config.ARGB_8888;  // API Level 1          
                options.inSampleSize = 8;    // API Level 1
                options.inBitmap = bitmap;   // **API Level 11**
        //...
    }

You get compile error:

Field requires API level 11 (current min is 10): android.graphics.BitmapFactory$Options#inBitmap

Since version 17 of Android Development Tools (ADT) there is one new and very useful annotation @TargetApi that can fix this very easily. Add it before the method that is enclosing the problematic declaration:

@TargetApi
private void methodThatRequiresAPI11() {            
  BitmapFactory.Options options = new BitmapFactory.Options();
      options.inPreferredConfig = Config.ARGB_8888;  // API Level 1          
      options.inSampleSize = 8;    // API Level 1

      // This will avoid exception NoSuchFieldError (or NoSuchMethodError) at runtime. 
      if (Integer.valueOf(android.os.Build.VERSION.SDK) >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        options.inBitmap = bitmap;   // **API Level 11**
            //...
      }
    }

No compile errors now and it will run !

EDIT: This will result in runtime error on API level lower than 11. On 11 or higher it will run without problems. So you must be sure you call this method on an execution path guarded by version check. TargetApi just allows you to compile it but you run it on your own risk.

Simplest way to download and unzip files in Node.js cross-platform?

You can simply extract the existing zip files also by using "unzip". It will work for any size files and you need to add it as a dependency from npm.

_x000D_
_x000D_
fs.createReadStream(filePath).pipe(unzip.Extract({path:moveIntoFolder})).on('close', function(){_x000D_
        //To do after unzip_x000D_
    callback();_x000D_
  });
_x000D_
_x000D_
_x000D_

Best practices with STDIN in Ruby?

while STDIN.gets
  puts $_
end

while ARGF.gets
  puts $_
end

This is inspired by Perl:

while(<STDIN>){
  print "$_\n"
}

Execute method on startup in Spring

Posted another solution that implements WebApplicationInitializer and is called much before any spring bean is instantiated, in case someone has that use case

Initialize default Locale and Timezone with Spring configuration

Equivalent of Math.Min & Math.Max for Dates?

// Two different dates
var date1 = new Date(2013, 05, 13); 
var date2 = new Date(2013, 04, 10) ;
// convert both dates in milliseconds and use Math.min function
var minDate = Math.min(date1.valueOf(), date2.valueOf());
// convert minDate to Date
var date = new Date(minDate); 

http://jsfiddle.net/5CR37/

Sharing a variable between multiple different threads

  1. Making it static could fix this issue.
  2. Reference to the main thread in other thread and making that variable visible

Is it possible to validate the size and type of input=file in html5

    <form  class="upload-form">
        <input class="upload-file" data-max-size="2048" type="file" >
        <input type=submit>
    </form>
    <script>
$(function(){
    var fileInput = $('.upload-file');
    var maxSize = fileInput.data('max-size');
    $('.upload-form').submit(function(e){
        if(fileInput.get(0).files.length){
            var fileSize = fileInput.get(0).files[0].size; // in bytes
            if(fileSize>maxSize){
                alert('file size is more then' + maxSize + ' bytes');
                return false;
            }else{
                alert('file size is correct- '+fileSize+' bytes');
            }
        }else{
            alert('choose file, please');
            return false;
        }

    });
});
    </script>

http://jsfiddle.net/9bhcB/2/

Scala how can I count the number of occurrences in a list

Short answer:

import scalaz._, Scalaz._
xs.foldMap(x => Map(x -> 1))

Long answer:

Using Scalaz, given.

import scalaz._, Scalaz._

val xs = List('a, 'b, 'c, 'c, 'a, 'a, 'b, 'd)

then all of these (in the order of less simplified to more simplified)

xs.map(x => Map(x -> 1)).foldMap(identity)
xs.map(x => Map(x -> 1)).foldMap()
xs.map(x => Map(x -> 1)).suml
xs.map(_ -> 1).foldMap(Map(_))
xs.foldMap(x => Map(x -> 1))

yield

Map('b -> 2, 'a -> 3, 'c -> 2, 'd -> 1)

The filename, directory name, or volume label syntax is incorrect inside batch

set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
  • The single quotes do not indicate a string, they make it starts: 'C:\ instead of C:\ so

  • %name% is the usual syntax for expanding a variable, the !name! syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION first, or by running the command prompt with CMD /V:ON.

  • Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4 to keep the current PATH content, and add something to the end.

How to write log base(2) in c/c++

As stated on http://en.wikipedia.org/wiki/Logarithm:

logb(x) = logk(x) / logk(b)

Which means that:

log2(x) = log10(x) / log10(2)

How to enable Google Play App Signing

This guide is oriented to developers who already have an application in the Play Store. If you are starting with a new app the process it's much easier and you can follow the guidelines of paragraph "New apps" from here

Prerequisites that 99% of developers already have :

  1. Android Studio

  2. JDK 8 and after installation you need to setup an environment variable in your user space to simplify terminal commands. In Windows x64 you need to add this : C:\Program Files\Java\{JDK_VERSION}\bin to the Path environment variable. (If you don't know how to do this you can read my guide to add a folder to the Windows 10 Path environment variable).

Step 0: Open Google Play developer console, then go to Release Management -> App Signing.

enter image description here

Accept the App Signing TOS.

enter image description here

Step 1: Download PEPK Tool clicking the button identical to the image below

enter image description here

Step 2: Open a terminal and type:

java -jar PATH_TO_PEPK --keystore=PATH_TO_KEYSTORE --alias=ALIAS_YOU_USE_TO_SIGN_APK --output=PATH_TO_OUTPUT_FILE --encryptionkey=GOOGLE_ENCRYPTION_KEY

Legend:

  • PATH_TO_PEPK = Path to the pepk.jar you downloaded in Step 1, could be something like C:\Users\YourName\Downloads\pepk.jar for Windows users.
  • PATH_TO_KEYSTORE = Path to keystore which you use to sign your release APK. Could be a file of type *.keystore or *.jks or without extension. Something like C:\Android\mykeystore or C:\Android\mykeystore.keystore etc...
  • ALIAS_YOU_USE_TO_SIGN_APK = The name of the alias you use to sign the release APK.
  • PATH_TO_OUTPUT_FILE = The path of the output file with .pem extension, something like C:\Android\private_key.pem
  • GOOGLE_ENCRYPTION_KEY = This encryption key should be always the same. You can find it in the App Signing page, copy and paste it. Should be in this form: eb10fe8f7c7c9df715022017b00c6471f8ba8170b13049a11e6c09ffe3056a104a3bbe4ac5a955f4ba4fe93fc8cef27558a3eb9d2a529a2092761fb833b656cd48b9de6a

Example:

java -jar "C:\Users\YourName\Downloads\pepk.jar" --keystore="C:\Android\mykeystore" --alias=myalias --output="C:\Android\private_key.pem" --encryptionkey=eb10fe8f7c7c9df715022017b00c6471f8ba8170b13049a11e6c09ffe3056a104a3bbe4ac5a955f4ba4fe93fc8cef27558a3eb9d2a529a2092761fb833b656cd48b9de6a

Press Enter and you will need to provide in order:

  1. The keystore password
  2. The alias password

If everything has gone OK, you now will have a file in PATH_TO_OUTPUT_FILE folder called private_key.pem.

Step 3: Upload the private_key.pem file clicking the button identical to the image below

enter image description here

Step 4: Create a new keystore file using Android Studio.

YOU WILL NEED THIS KEYSTORE IN THE FUTURE TO SIGN THE NEXT RELEASES OF YOUR APP, DON'T FORGET THE PASSWORDS

Open one of your Android projects (choose one at random). Go to Build -> Generate Signed APK and press Create new.

enter image description here

Now you should fill the required fields.

Key store path represent the new keystore you will create, choose a folder and a name using the 3 dots icon on the right, i choosed C:\Android\upload_key.jks (.jks extension will be added automatically)

NOTE: I used upload as the new alias name but if you previously used the same keystore with different aliases to sign different apps, you should choose the same aliases name you had previously in the original keystore.

enter image description here

Press OK when finished, and now you will have a new upload_key.jks keystore. You can close Android Studio now.

Step 5: We need to extract the upload certificate from the newly created upload_key.jks keystore. Open a terminal and type:

keytool -export -rfc -keystore UPLOAD_KEYSTORE_PATH -alias UPLOAD_KEYSTORE_ALIAS -file PATH_TO_OUTPUT_FILE

Legend:

  • UPLOAD_KEYSTORE_PATH = The path of the upload keystore you just created. In this case was C:\Android\upload_key.jks.
  • UPLOAD_KEYSTORE_ALIAS = The new alias associated with the upload keystore. In this case was upload.
  • PATH_TO_OUTPUT_FILE = The path to the output file with .pem extension. Something like C:\Android\upload_key_public_certificate.pem.

Example:

keytool -export -rfc -keystore "C:\Android\upload_key.jks" -alias upload -file "C:\Android\upload_key_public_certificate.pem"

Press Enter and you will need to provide the keystore password.

Now if everything has gone OK, you will have a file in the folder PATH_TO_OUTPUT_FILE called upload_key_public_certificate.pem.

Step 6: Upload the upload_key_public_certificate.pem file clicking the button identical to the image below

enter image description here

Step 7: Click ENROLL button at the end of the App Signing page.

enter image description here

Now every new release APK must be signed with the upload_key.jks keystore and aliases created in Step 4, prior to be uploaded in the Google Play Developer console.

More Resources:

Q&A

Q: When i upload the APK signed with the new upload_key keystore, Google Play show an error like : You uploaded an unsigned APK. You need to create a signed APK.

A: Check to sign the APK with both signatures (V1 and V2) while building the release APK. Read here for more details.

UPDATED

The step 4,5,6 are to create upload key which is optional for existing apps

"Upload key (optional for existing apps): A new key you generate during your enrollment in the program. You will use the upload key to sign all future APKs prior to uploading them to the Play Console." https://support.google.com/googleplay/android-developer/answer/7384423

How do I break out of a loop in Perl?

Additional data (in case you have more questions):

FOO: {
       for my $i ( @listone ){
          for my $j ( @listtwo ){
                 if ( cond( $i,$j ) ){

                    last FOO;  # --->
                                   # |
                 }                 # |
          }                        # |
       }                           # |
 } # <-------------------------------

How do I import material design library to Android Studio?

Goto

  1. File (Top Left Corner)
  2. Project Structure
  3. Under Module. Find the Dependence tab
  4. press plus button (+) at top right.
  5. You will find all the dependencies

Move to another EditText when Soft Keyboard Next is clicked on Android

add your editText

android:imeOptions="actionNext"
android:singleLine="true"

add property to activity in manifest

    android:windowSoftInputMode="adjustResize|stateHidden"

in layout file ScrollView set as root or parent layout all ui

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.ukuya.marketplace.activity.SignInActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

       <!--your items-->

    </ScrollView>

</LinearLayout>

if you do not want every time it adds, create style: add style in values/style.xml

default/style:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="editTextStyle">@style/AppTheme.CustomEditText</item>
    </style>

<style name="AppTheme.CustomEditText"     parent="android:style/Widget.EditText">
        //...
        <item name="android:imeOptions">actionNext</item>
        <item name="android:singleLine">true</item>
    </style>

Drop view if exists

your exists syntax is wrong and you should seperate DDL with go like below

if exists(select 1 from sys.views where name='tst' and type='v')
drop view tst;
go

create view tst
as
select * from test

you also can check existence test, with object_id like below

if object_id('tst','v') is not null
drop view tst;
go

create view tst
as
select * from test

In SQL 2016,you can use below syntax to drop

Drop view  if exists dbo.tst

From SQL2016 CU1,you can do below

create or alter view vwTest
as
 select 1 as col;
go

Can't operator == be applied to generic types in C#?

In general, EqualityComparer<T>.Default.Equals should do the job with anything that implements IEquatable<T>, or that has a sensible Equals implementation.

If, however, == and Equals are implemented differently for some reason, then my work on generic operators should be useful; it supports the operator versions of (among others):

  • Equal(T value1, T value2)
  • NotEqual(T value1, T value2)
  • GreaterThan(T value1, T value2)
  • LessThan(T value1, T value2)
  • GreaterThanOrEqual(T value1, T value2)
  • LessThanOrEqual(T value1, T value2)

How to find files modified in last x minutes (find -mmin does not work as expected)

this command may be help you sir

find -type f -mtime -60

Animate element transform rotate

To add to the answers of Ryley and atonyc, you don't actually have to use a real CSS property, like text-index or border-spacing, but instead you can specify a fake CSS property, like rotation or my-awesome-property. It might be a good idea to use something that does not risk becoming an actual CSS property in the future.

Also, somebody asked how to animate other things at the same time. This can be done as usual, but remember that the step function is called for every animated property, so you'll have to check for your property, like so:

$('#foo').animate(
    {
        opacity: 0.5,
        width: "100px",
        height: "100px",
        myRotationProperty: 45
    },
    {
        step: function(now, tween) {
            if (tween.prop === "myRotationProperty") {
                $(this).css('-webkit-transform','rotate('+now+'deg)');
                $(this).css('-moz-transform','rotate('+now+'deg)'); 
                // add Opera, MS etc. variants
                $(this).css('transform','rotate('+now+'deg)');  
            }
        }
    });

(Note: I can't find the documentation for the "Tween" object in the jQuery documentation; from the animate documentation page there is a link to http://api.jquery.com/Types#Tween which is a section that doesn't appear to exist. You can find the code for the Tween prototype on Github here).

How to get records randomly from the oracle database?

SELECT column FROM
( SELECT column, dbms_random.value FROM table ORDER BY 2 )
where rownum <= 20;

Converting user input string to regular expression

I suggest you also add separate checkboxes or a textfield for the special flags. That way it is clear that the user does not need to add any //'s. In the case of a replace, provide two textfields. This will make your life a lot easier.

Why? Because otherwise some users will add //'s while other will not. And some will make a syntax error. Then, after you stripped the //'s, you may end up with a syntactically valid regex that is nothing like what the user intended, leading to strange behaviour (from the user's perspective).

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

  1. @SpringBootApplication: checked, didn't work.
  2. spring-boot-starter-web in Pom file: checked, didn't work.
  3. Switch from IntelliJ CE to IntelliJ Ultimate, problem solved.

Check if an object exists

the boolean value of an empty QuerySet is also False, so you could also just do...

...
if not user_object:
   do insert or whatever etc.

How to get Latitude and Longitude of the mobile device in android?

Above solutions is also correct, but some time if location is null then it crash the app or not working properly. The best way to get Latitude and Longitude of android is:

 Geocoder geocoder;
     String bestProvider;
     List<Address> user = null;
     double lat;
     double lng;

    LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);

     Criteria criteria = new Criteria();
     bestProvider = lm.getBestProvider(criteria, false);
     Location location = lm.getLastKnownLocation(bestProvider);

     if (location == null){
         Toast.makeText(activity,"Location Not found",Toast.LENGTH_LONG).show();
      }else{
        geocoder = new Geocoder(activity);
        try {
            user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        lat=(double)user.get(0).getLatitude();
        lng=(double)user.get(0).getLongitude();
        System.out.println(" DDD lat: " +lat+",  longitude: "+lng);

        }catch (Exception e) {
                e.printStackTrace();
        }
    }

Python debugging tips

If you don't like spending time in debuggers (and don't appreciate poor usability of pdb command line interface), you can dump execution trace and analyze it later. For example:

python -m trace -t setup.py install > execution.log

This will dump all source line of setup.py install execution to execution.log.

To make it easier to customize trace output and write your own tracers, I put together some pieces of code into xtrace module (public domain).

How to check a string for a special character?

You can use string.punctuation and any function like this

import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
    print "Invalid"
else:
    print "Valid"

With this line

invalidChars = set(string.punctuation.replace("_", ""))

we are preparing a list of punctuation characters which are not allowed. As you want _ to be allowed, we are removing _ from the list and preparing new set as invalidChars. Because lookups are faster in sets.

any function will return True if atleast one of the characters is in invalidChars.

Edit: As asked in the comments, this is the regular expression solution. Regular expression taken from https://stackoverflow.com/a/336220/1903116

word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"

Make WPF Application Fullscreen (Cover startmenu)

If you want user to change between WindowStyle.SingleBorderWindow and WindowStyle.None at runtime you can bring this at code behind:

Make application fullscreen:

RootWindow.Visibility = Visibility.Collapsed;
RootWindow.WindowStyle = WindowStyle.None;
RootWindow.ResizeMode = ResizeMode.NoResize;
RootWindow.WindowState = WindowState.Maximized;
RootWindow.Topmost = true;
RootWindow.Visibility = Visibility.Visible;

Return to single border style:

RootWindow.WindowStyle = WindowStyle.SingleBorderWindow;
RootWindow.ResizeMode = ResizeMode.CanResize;
RootWindow.Topmost = false;

Note that without RootWindow.Visibility property your window will not cover start menu, however you can skip this step if you making application fullscreen once at startup.

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

Why am I getting the error "connection refused" in Python? (Sockets)

Assume s = socket.socket() The server can be bound by following methods: Method 1:

host = socket.gethostname()
s.bind((host, port))

Method 2:

host = socket.gethostbyname("localhost")  #Note the extra letters "by"
s.bind((host, port))

Method 3:

host = socket.gethostbyname("192.168.1.48")
s.bind((host, port))

If you do not exactly use same method on the client side, you will get the error: socket.error errno 111 connection refused.

So, you have to use on the client side exactly same method to get the host, as you do on the server. For example, in case of client, you will correspondingly use following methods:

Method 1:

host = socket.gethostname() 
s.connect((host, port))

Method 2:

host = socket.gethostbyname("localhost") # Get local machine name
s.connect((host, port))

Method 3:

host = socket.gethostbyname("192.168.1.48") # Get local machine name
s.connect((host, port))

Hope that resolves the problem.

How to format current time using a yyyyMMddHHmmss format?

import("time")

layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)
if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

gives:

>> 2014-11-12 11:45:26.371 +0000 UTC

Get url without querystring

Try this:

urlString=Request.RawUrl.ToString.Substring(0, Request.RawUrl.ToString.IndexOf("?"))

from this: http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye you'll get this: mypage.aspx

How to reenable event.preventDefault?

I had a similar problem recently. I had a form and PHP function that to be run once the form is submitted. However, I needed to run a javascript first.

        // This variable is used in order to determine if we already did our js fun
        var window.alreadyClicked = "NO"
        $("form:not('#press')").bind("submit", function(e){
            // Check if we already run js part
            if(window.alreadyClicked == "NO"){
                // Prevent page refresh
                e.preventDefault();
                // Change variable value so next time we submit the form the js wont run
                window.alreadyClicked = "YES"
                // Here is your actual js you need to run before doing the php part
                xxxxxxxxxx

                // Submit the form again but since we changed the value of our variable js wont be run and page can reload (and php can do whatever you told it to)
                $("form:not('#press')").submit()
            } 
        });

What is the difference between connection and read timeout for sockets?

  1. What is the difference between connection and read timeout for sockets?

The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read call, a read timeout error will be raised.

  1. What does connection timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?

It means that the connection attempt can potentially block for ever. There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket. (A Thread.interrupt() call may also do the trick ... not sure.)

  1. What does read timeout set to "infinity" mean? In what situation can it remain in an infinite loop? What can trigger that the infinite loop to end?

It means that a call to read on the socket stream may block for ever. Once again there is no infinite loop, but the read can be unblocked by a Thread.interrupt() call, closing the socket, and (of course) the other end sending data or closing the connection.


1 - It is not ... as one commenter thought ... the timeout on how long a socket can be open, or idle.

How do you create different variable names while in a loop?

Don't do this use a dictionary

import sys
this = sys.modules[__name__] # this is now your current namespace
for x in range(0,9):
    setattr(this, 'string%s' % x, 'Hello')

print string0
print string1
print string2
print string3
print string4
print string5
print string6
print string7
print string8

don't do this use a dict

globals() has risk as it gives you what the namespace is currently pointing to but this can change and so modifying the return from globals() is not a good idea

Properties file with a list as the value for an individual key

Create a wrapper around properties and assume your A value has keys A.1, A.2, etc. Then when asked for A your wrapper will read all the A.* items and build the list. HTH

How to generate serial version UID in Intellij

Without any plugins:

You just need to enable highlight: (Idea v.2016, 2017 and 2018, previous versions may have same or similar settings)

File -> Settings -> Editor -> Inspections -> Java -> Serialization issues -> Serializable class without 'serialVersionUID' - set flag and click 'OK'. (For Macs, Settings is under IntelliJ IDEA -> Preferences...)

Now, if your class implements Serializable, you will see highlight and alt+Enter on class name will ask you to generate private static final long serialVersionUID.

UPD: a faster way to find this setting - you might use hotkey Ctrl+Shift+A (find action), type Serializable class without 'serialVersionUID' - the first is the one.

Highlight label if checkbox is checked

I like Andrew's suggestion, and in fact the CSS rule only needs to be:

:checked + label {
   font-weight: bold;
}

I like to rely on implicit association of the label and the input element, so I'd do something like this:

<label>
   <input type="checkbox"/>
   <span>Bah</span>
</label>

with CSS:

:checked + span {
    font-weight: bold;
}

Example: http://jsfiddle.net/wrumsby/vyP7c/

Sort an array of objects in React and render them

this.state.data.sort((a, b) => a.item.timeM > b.item.timeM).map(
    (item, i) => <div key={i}> {item.matchID} {item.timeM} {item.description}</div>
)

How do I show a console output/window in a forms application?

If you are not worrying about opening a console on-command, you can go into the properties for your project and change it to Console Application

screenshot of changing the project type.

This will still show your form as well as popping up a console window. You can't close the console window, but it works as an excellent temporary logger for debugging.

Just remember to turn it back off before you deploy the program.

Creating and returning Observable from Angular 2 Service

In the service.ts file -

a. import 'of' from observable/of
b. create a json list
c. return json object using Observable.of()
Ex. -

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

@Injectable()
export class ClientListService {
    private clientList;

    constructor() {
        this.clientList = [
            {name: 'abc', address: 'Railpar'},
            {name: 'def', address: 'Railpar 2'},
            {name: 'ghi', address: 'Panagarh'},
            {name: 'jkl', address: 'Panagarh 2'},
        ];
    }

    getClientList () {
        return Observable.of(this.clientList);
    }
};

In the component where we are calling the get function of the service -

this.clientListService.getClientList().subscribe(res => this.clientList = res);

Setting table column width

Try this instead.

<table style="width: 100%">
    <tr>
        <th style="width: 20%">
           column 1
        </th>
        <th style="width: 40%">
           column 2
        </th>
        <th style="width: 40%">
           column 3
        </th>
    </tr>
    <tr>
        <td style="width: 20%">
           value 1
        </td>
        <td style="width: 40%">
           value 2
        </td>
        <td style="width: 40%">
           value 3
        </td>
    </tr>
</table>

Why is this program erroneously rejected by three C++ compilers?

OCR Says:

N lml_?e <loJ+_e__}

.lnt Mk.,n ( ln+ _rSC Lhc_yh )
h_S_
_l

s_l . co__ <, " H llo uo/_d ! '` << s l? . ena_ .
TP__rn _ |
_|

Which is pretty damn good, to be fair.

Where do alpha testers download Google Play Android apps?

You can use a Google Group and have your alpha testers just join the group. Everything else should just be handled through the Google Play Store App.

Problem in running .net framework 4.0 website on iis 7.0

  1. Go to the IIS Manager.
  2. open the server name like (PC-Name)\.
  3. then double click on the ISAPI and CGI Restriction.
  4. then select ASP.NET v4.0.30319(32-bit) Restriction allowed.

Datetime format Issue: String was not recognized as a valid DateTime

Below code worked for me:

string _stDate = Convert.ToDateTime(DateTime.Today.AddMonths(-12)).ToString("MM/dd/yyyy");
String format ="MM/dd/yyyy";
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
DateTime _Startdate = DateTime.ParseExact(_stDate, format, culture);

Why has it failed to load main-class manifest attribute from a JAR file?

  1. set the classpath and compile

    javac -classpath "C:\Program Files\Java\jdk1.6.0_updateVersion\tools.jar" yourApp.java

  2. create manifest.txt

    Main-Class: yourApp newline

  3. create yourApp.jar

    jar cvf0m yourApp.jar manifest.txt yourApp.class

  4. run yourApp.jar

    java -jar yourApp.jar

how to calculate binary search complexity

Here a more mathematical way of seeing it, though not really complicated. IMO much clearer as informal ones:

The question is, how many times can you divide N by 2 until you have 1? This is essentially saying, do a binary search (half the elements) until you found it. In a formula this would be this:

1 = N / 2x

multiply by 2x:

2x = N

now do the log2:

log2(2x)    = log2 N
x * log2(2) = log2 N
x * 1         = log2 N

this means you can divide log N times until you have everything divided. Which means you have to divide log N ("do the binary search step") until you found your element.

How to set a fixed width column with CSS flexbox

You should use the flex or flex-basis property rather than width. Read more on MDN.

.flexbox .red {
  flex: 0 0 25em;
}

The flex CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:

flex-grow: 0;     /* do not grow   - initial value: 0 */
flex-shrink: 0;   /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height  - initial value: auto */

A simple demo shows how to set the first column to 50px fixed width.

_x000D_
_x000D_
.flexbox {_x000D_
  display: flex;_x000D_
}_x000D_
.red {_x000D_
  background: red;_x000D_
  flex: 0 0 50px;_x000D_
}_x000D_
.green {_x000D_
  background: green;_x000D_
  flex: 1;_x000D_
}_x000D_
.blue {_x000D_
  background: blue;_x000D_
  flex: 1;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
  <div class="red">1</div>_x000D_
  <div class="green">2</div>_x000D_
  <div class="blue">3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


See the updated codepen based on your code.

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

It looks like you are calling a non static member (a property or method, specifically setTextboxText) from a static method (specifically SumData). You will need to either:

  1. Make the called member static also:

    static void setTextboxText(int result)
    {
        // Write static logic for setTextboxText.  
        // This may require a static singleton instance of Form1.
    }
    
  2. Create an instance of Form1 within the calling method:

    private static void SumData(object state)
    {
        int result = 0;
        //int[] icount = (int[])state;
        int icount = (int)state;
    
        for (int i = icount; i > 0; i--)
        {
            result += i;
            System.Threading.Thread.Sleep(1000);
        }
        Form1 frm1 = new Form1();
        frm1.setTextboxText(result);
    }
    

    Passing in an instance of Form1 would be an option also.

  3. Make the calling method a non-static instance method (of Form1):

    private void SumData(object state)
    {
        int result = 0;
        //int[] icount = (int[])state;
        int icount = (int)state;
    
        for (int i = icount; i > 0; i--)
        {
            result += i;
            System.Threading.Thread.Sleep(1000);
        }
        setTextboxText(result);
    }
    

More info about this error can be found on MSDN.

How can I use optional parameters in a T-SQL stored procedure?

Dynamically changing searches based on the given parameters is a complicated subject and doing it one way over another, even with only a very slight difference, can have massive performance implications. The key is to use an index, ignore compact code, ignore worrying about repeating code, you must make a good query execution plan (use an index).

Read this and consider all the methods. Your best method will depend on your parameters, your data, your schema, and your actual usage:

Dynamic Search Conditions in T-SQL by by Erland Sommarskog

The Curse and Blessings of Dynamic SQL by Erland Sommarskog

If you have the proper SQL Server 2008 version (SQL 2008 SP1 CU5 (10.0.2746) and later), you can use this little trick to actually use an index:

Add OPTION (RECOMPILE) onto your query, see Erland's article, and SQL Server will resolve the OR from within (@LastName IS NULL OR LastName= @LastName) before the query plan is created based on the runtime values of the local variables, and an index can be used.

This will work for any SQL Server version (return proper results), but only include the OPTION(RECOMPILE) if you are on SQL 2008 SP1 CU5 (10.0.2746) and later. The OPTION(RECOMPILE) will recompile your query, only the verison listed will recompile it based on the current run time values of the local variables, which will give you the best performance. If not on that version of SQL Server 2008, just leave that line off.

CREATE PROCEDURE spDoSearch
    @FirstName varchar(25) = null,
    @LastName varchar(25) = null,
    @Title varchar(25) = null
AS
    BEGIN
        SELECT ID, FirstName, LastName, Title
        FROM tblUsers
        WHERE
                (@FirstName IS NULL OR (FirstName = @FirstName))
            AND (@LastName  IS NULL OR (LastName  = @LastName ))
            AND (@Title     IS NULL OR (Title     = @Title    ))
        OPTION (RECOMPILE) ---<<<<use if on for SQL 2008 SP1 CU5 (10.0.2746) and later
    END

Can't use modulus on doubles?

The % operator is for integers. You're looking for the fmod() function.

#include <cmath>

int main()
{
    double x = 6.3;
    double y = 2.0;
    double z = std::fmod(x,y);

}

How can I recursively find all files in current and subfolders based on wildcard matching?

find will find all files that match a pattern:

find . -name "*foo"

However, if you want a picture:

tree -P "*foo"

Hope this helps!

Get the name of an object's type

The closest you can get is typeof, but it only returns "object" for any sort of custom type. For those, see Jason Bunting.

Edit, Jason's deleted his post for some reason, so just use Object's constructor property.

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

INSERT INTO AM_PROGRAM_TUNING_EVENT_TMP1 
VALUES(TO_DATE('2012-03-28 11:10:00','yyyy/mm/dd hh24:mi:ss'));

http://www.sqlfiddle.com/#!4/22115/1

In laymans terms, what does 'static' mean in Java?

Above points are correct and I want to add some more important points about Static keyword.

Internally what happening when you are using static keyword is it will store in permanent memory(that is in heap memory),we know that there are two types of memory they are stack memory(temporary memory) and heap memory(permanent memory),so if you are not using static key word then will store in temporary memory that is in stack memory(or you can call it as volatile memory).

so you will get a doubt that what is the use of this right???

example: static int a=10;(1 program)

just now I told if you use static keyword for variables or for method it will store in permanent memory right.

so I declared same variable with keyword static in other program with different value.

example: static int a=20;(2 program)

the variable 'a' is stored in heap memory by program 1.the same static variable 'a' is found in program 2 at that time it won`t create once again 'a' variable in heap memory instead of that it just replace value of a from 10 to 20.

In general it will create once again variable 'a' in stack memory(temporary memory) if you won`t declare 'a' as static variable.

overall i can say that,if we use static keyword
  1.we can save memory
  2.we can avoid duplicates
  3.No need of creating object in-order to access static variable with the help of class name you can access it.

document.getElementById().value and document.getElementById().checked not working for IE

Have a look at jQuery, a cross-browser library that will make your life a lot easier.

var msg = 'abc';
$('#msg').val(msg);
$('#sp_100').attr('checked', 'checked');

How can I check for IsPostBack in JavaScript?

Create a global variable in and apply the value

<script>
       var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;
</script>

Then you can reference it from elsewhere

How do I parse JSON into an int?

I use a combination of json.get() and instanceof to read in values that might be either integers or integer strings.

These three test cases illustrate:

int val;
Object obj;
JSONObject json = new JSONObject();
json.put("number", 1);
json.put("string", "10");
json.put("other", "tree");

obj = json.get("number");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
System.out.println(val);

obj = json.get("string");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
System.out.println(val);

try {
    obj = json.get("other");
    val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
} catch (Exception e) {
    // throws exception
}

Unzip files programmatically in .net

We have used SharpZipLib successfully on many projects. I know it's a third party tool, but source code is included and could provide some insight if you chose to reinvent the wheel here.

How to change the order of DataFrame columns?

Just flipping helps often.

df[df.columns[::-1]]

Or just shuffle for a look.

import random
cols = list(df.columns)
random.shuffle(cols)
df[cols]

How do I compare two strings in python?

This is a pretty basic example, but after the logical comparisons (==) or string1.lower() == string2.lower(), maybe can be useful to try some of the basic metrics of distances between two strings.

You can find examples everywhere related to these or some other metrics, try also the fuzzywuzzy package (https://github.com/seatgeek/fuzzywuzzy).

import Levenshtein
import difflib

print(Levenshtein.ratio('String1', 'String2'))
print(difflib.SequenceMatcher(None, 'String1', 'String2').ratio())

Simplest way to do a recursive self-join?

The Quassnoi query with a change for large table. Parents with more childs then 10: Formating as str(5) the row_number()

WITH    q AS 
        (
        SELECT  m.*, CAST(str(ROW_NUMBER() OVER (ORDER BY m.ordernum),5) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN AS bc
        FROM    #t m
        WHERE   ParentID =0
        UNION ALL
        SELECT  m.*,  q.bc + '.' + str(ROW_NUMBER()  OVER (PARTITION BY m.ParentID ORDER BY m.ordernum),5) COLLATE Latin1_General_BIN
        FROM    #t m
        JOIN    q
        ON      m.parentID = q.DBID
        )
SELECT  *
FROM    q
ORDER BY
        bc

How to Convert the value in DataTable into a string array in c#

    private string[] GetPrimaryKeysofTable(string TableName)
    {
        string stsqlCommand = "SELECT column_name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE " +
                              "WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1" +
                              "AND table_name = '" +TableName+ "'";
        SqlCommand command = new SqlCommand(stsqlCommand, Connection);
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = command;

        DataTable table = new DataTable();
        table.Locale = System.Globalization.CultureInfo.InvariantCulture;

        adapter.Fill(table);

        string[] result = new string[table.Rows.Count];
        int i = 0;
        foreach (DataRow dr in table.Rows)
        {
            result[i++] = dr[0].ToString();
        }

        return result;
    }

How to write a simple Java program that finds the greatest common divisor between two numbers?

private static void GCD(int a, int b) {

    int temp;
    // make a greater than b
    if (b > a) {
         temp = a;
         a = b;
         b = temp;
    }

    while (b !=0) {
        // gcd of b and a%b
        temp = a%b;
        // always make a greater than bf
        a =b;
        b =temp;

    }
    System.out.println(a);
}

Pass Method as Parameter using C#

Here is an example Which can help you better to understand how to pass a function as a parameter.

Suppose you have Parent page and you want to open a child popup window. In the parent page there is a textbox that should be filled basing on child popup textbox.

Here you need to create a delegate.

Parent.cs // declaration of delegates public delegate void FillName(String FirstName);

Now create a function which will fill your textbox and function should map delegates

//parameters
public void Getname(String ThisName)
{
     txtname.Text=ThisName;
}

Now on button click you need to open a Child popup window.

  private void button1_Click(object sender, RoutedEventArgs e)
  {
        ChildPopUp p = new ChildPopUp (Getname) //pass function name in its constructor

         p.Show();

    }

IN ChildPopUp constructor you need to create parameter of 'delegate type' of parent //page

ChildPopUp.cs

    public  Parent.FillName obj;
    public PopUp(Parent.FillName objTMP)//parameter as deligate type
    {
        obj = objTMP;
        InitializeComponent();
    }



   private void OKButton_Click(object sender, RoutedEventArgs e)
    {


        obj(txtFirstName.Text); 
        // Getname() function will call automatically here
        this.DialogResult = true;
    }

ValueError when checking if variable is None or numpy.array

You can see if object has shape or not

def check_array(x):
    try:
        x.shape
        return True
    except:
        return False

Git Ignores and Maven targets

The .gitignore file in the root directory does apply to all subdirectories. Mine looks like this:

.classpath
.project
.settings/
target/

This is in a multi-module maven project. All the submodules are imported as individual eclipse projects using m2eclipse. I have no further .gitignore files. Indeed, if you look in the gitignore man page:

Patterns read from a .gitignore file in the same directory as the path, or in any parent directory

So this should work for you.