Programs & Examples On #Tracd

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

The package is not fully compatible with dotnetcore 2.0 for now.

eg, for 'Microsoft.AspNet.WebApi.Client' it maybe supported in version (5.2.4). See Consume new Microsoft.AspNet.WebApi.Client.5.2.4 package for details.

You could try the standard Client package as Federico mentioned.

If that still not work, then as a workaround you can only create a Console App (.Net Framework) instead of the .net core 2.0 console app.

Reference this thread: Microsoft.AspNet.WebApi.Client supported in .NET Core or not?

Animation CSS3: display + opacity

display: is not transitionable. You'll probably need to use jQuery to do what you want to do.

Characters allowed in a URL

I tested it by requesting my website (apache) with all available chars on my german keyboard as URL parameter:

http://example.com/?^1234567890ß´qwertzuiopü+asdfghjklöä#<yxcvbnm,.-°!"§$%&/()=? `QWERTZUIOPÜ*ASDFGHJKLÖÄ\'>YXCVBNM;:_²³{[]}\|µ@€~

These were not encoded:

^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,.-!/()=?`*;:_{}[]\|~

Not encoded after urlencode():

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_

Not encoded after rawurlencode():

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~

Note: Before PHP 5.3.0 rawurlencode() encoded ~ because of RFC 1738. But this was replaced by RFC 3986 so its safe to use, now. But I do not understand why for example {} are encoded through rawurlencode() because they are not mentioned in RFC 3986.

An additional test I made was regarding auto-linking in mail texts. I tested Mozilla Thunderbird, aol.com, outlook.com, gmail.com, gmx.de and yahoo.de and they fully linked URLs containing these chars:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~+#,%&=*;:@

Of course the ? was linked, too, but only if it was used once.

Some people would now suggest to use only the rawurlencode() chars, but did you ever hear that someone had problems to open these websites?

Asterisk
http://wayback.archive.org/web/*/http://google.com

Colon
https://en.wikipedia.org/wiki/Wikipedia:About

Plus
https://plus.google.com/+google

At sign, Colon, Comma and Exclamation mark
https://www.google.com/maps/place/USA/@36.2218457,...

Because of that these chars should be usable unencoded without problems. Of course you should not use &; because of encoding sequences like &amp;. The same reason is valid for % as it used to encode chars in general. And = as it assigns a value to a parameter name.

Finally I would say its ok to use these unencoded:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~!+,*:@

But if you expect randomly generated URLs you should not use .!, because those mark the end of a sentence and some mail apps will not auto-link the last char of the url. Example:

Visit http://example.com/foo=bar! !

XDocument or XmlDocument

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument. If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.

I've just started using LINQ to XML, and I love the way you create an XML document using functional construction. It's really nice. DOM is clunky in comparison.

Function to check if a string is a date

if (strtotime($date)>strtotime(0)) { echo 'it is a date' }

How do I space out the child elements of a StackPanel?

Following up on Sergey's suggestion, you can define and reuse a whole Style (with various property setters, including Margin) instead of just a Thickness object:

<Style x:Key="MyStyle" TargetType="SomeItemType">
  <Setter Property="Margin" Value="0,5,0,5" />
  ...
</Style>

...

  <StackPanel>
    <StackPanel.Resources>
      <Style TargetType="SomeItemType" BasedOn="{StaticResource MyStyle}" />
    </StackPanel.Resources>
  ...
  </StackPanel>

Note that the trick here is the use of Style Inheritance for the implicit style, inheriting from the style in some outer (probably merged from external XAML file) resource dictionary.

Sidenote:

At first, I naively tried to use the implicit style to set the Style property of the control to that outer Style resource (say defined with the key "MyStyle"):

<StackPanel>
  <StackPanel.Resources>
    <Style TargetType="SomeItemType">
      <Setter Property="Style" Value={StaticResource MyStyle}" />
    </Style>
  </StackPanel.Resources>
</StackPanel>

which caused Visual Studio 2010 to shut down immediately with CATASTROPHIC FAILURE error (HRESULT: 0x8000FFFF (E_UNEXPECTED)), as described at https://connect.microsoft.com/VisualStudio/feedback/details/753211/xaml-editor-window-fails-with-catastrophic-failure-when-a-style-tries-to-set-style-property#

What is the $? (dollar question mark) variable in shell scripting?

$? is used to find the return value of the last executed command. Try the following in the shell:

ls somefile
echo $?

If somefile exists (regardless whether it is a file or directory), you will get the return value thrown by the ls command, which should be 0 (default "success" return value). If it doesn't exist, you should get a number other then 0. The exact number depends on the program.

For many programs you can find the numbers and their meaning in the corresponding man page. These will usually be described as "exit status" and may have their own section.

How do I use regex in a SQLite query?

SQLite does not contain regular expression functionality by default.

It defines a REGEXP operator, but this will fail with an error message unless you or your framework define a user function called regexp(). How you do this will depend on your platform.

If you have a regexp() function defined, you can match an arbitrary integer from a comma-separated list like so:

... WHERE your_column REGEXP "\b" || your_integer || "\b";

But really, it looks like you would find things a whole lot easier if you normalised your database structure by replacing those groups within a single column with a separate row for each number in the comma-separated list. Then you could not only use the = operator instead of a regular expression, but also use more powerful relational tools like joins that SQL provides for you.

How to pass datetime from c# to sql correctly?

You've already done it correctly by using a DateTime parameter with the value from the DateTime, so it should already work. Forget about ToString() - since that isn't used here.

If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).

I have a table and the date-times in it are in the format: 2011-07-01 15:17:33.357

Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.

Is it possible to send a variable number of arguments to a JavaScript function?

There are two methods as of ES2015.

The arguments Object

This object is built into functions, and it refers to, appropriately, the arguments of a function. It is not technically an array, though, so typical array operations won't work on it. The suggested method is to use Array.from or the spread operator to create an array from it.

I've seen other answers mention using slice. Don't do that. It prevents optimizations (source: MDN).

Array.from(arguments)
[...arguments]

However, I would argue that arguments is problematic because it hides what a function accepts as input. An arguments function typically is written like this:

function mean(){
    let args = [...arguments];
    return args.reduce((a,b)=>a+b) / args.length;
}

Sometimes, the function header is written like the following to document the arguments in a C-like fashion:

function mean(/* ... */){ ... }

But that is rare.

As for why it is problematic, take C, for example. C is backwards compatible with an ancient pre-ANSI dialect of the language known as K&R C. K&R C allows function prototypes to have an empty arguments list.

int myFunction();
/* This function accepts unspecified parameters */

ANSI C provides a facility for varargs (...), and void to specify an empty arguments-list.

int myFunction(void);
/* This function accepts no parameters */

Many people inadvertently declare functions with an unspecified arguments list (int myfunction();), when they expect the function to take zero arguments. This is technically a bug because the function will accept arguments. Any number of them.

A proper varargs function in C takes the form:

int myFunction(int nargs, ...);

And JavaScript actually does have something similar to this.

Spread Operator / Rest Parameters

I've already shown you the spread operator, actually.

...name

It's pretty versatile, and can also be used in a function's argument-list ("rest parameters") to specify varargs in a nicely documented fashion:

function mean(...args){
    return args.reduce((a,b)=>a+b) / args.length;
}

Or as a lambda expression:

((...args)=>args.reduce((a,b)=>a+b) / args.length)(1,2,3,4,5); // 3

I much prefer the spread operator. It is clean and self-documenting.

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

You must declare the reportfile as variable for console.

Problem is all the Dokumentations you can find are not running so .. I was give 1 day of my live to find the right way ....

Example: for batch/console

cmd.exe /K set FFREPORT=file='C:\ffmpeg\proto\test.log':level=32 && C:\ffmpeg\bin\ffmpeg.exe -loglevel warning -report -i inputfile f outputfile

Exemple Javascript:

var reortlogfile = "cmd.exe /K set FFREPORT=file='C:\ffmpeg\proto\" + filename + ".log':level=32 && C:\ffmpeg\bin\ffmpeg.exe" .......;

You can change the dir and filename how ever you want.

Frank from Berlin

SQLite Reset Primary Key Field

Try this:

delete from your_table;    
delete from sqlite_sequence where name='your_table';

SQLite Autoincrement

SQLite keeps track of the largest ROWID that a table has ever held using the special SQLITE_SEQUENCE table. The SQLITE_SEQUENCE table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.

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

Use TO_TIMESTAMP function

TO_TIMESTAMP(date_string,'YYYY-MM-DD HH24:MI:SS')

How to count lines of Java code using IntelliJ IDEA?

Although it is not an IntelliJ option, you could use a simple Bash command (if your operating system is Linux/Unix). Go to your source directory and type:

find . -type f -name '*.java' | xargs cat | wc -l

How to loop over grouped Pandas dataframe?

Here is an example of iterating over a pd.DataFrame grouped by the column atable. For this sample, "create" statements for an SQL database are generated within the for loop:

import pandas as pd

df1 = pd.DataFrame({
    'atable':     ['Users', 'Users', 'Domains', 'Domains', 'Locks'],
    'column':     ['col_1', 'col_2', 'col_a', 'col_b', 'col'],
    'column_type':['varchar', 'varchar', 'int', 'varchar', 'varchar'],
    'is_null':    ['No', 'No', 'Yes', 'No', 'Yes'],
})

df1_grouped = df1.groupby('atable')

# iterate over each group
for group_name, df_group in df1_grouped:
    print('\nCREATE TABLE {}('.format(group_name))

    for row_index, row in df_group.iterrows():
        col = row['column']
        column_type = row['column_type']
        is_null = 'NOT NULL' if row['is_null'] == 'NO' else ''
        print('\t{} {} {},'.format(col, column_type, is_null))

    print(");")

Get week of year in JavaScript like in PHP

Jacob Wright's Date.format() library implements date formatting in the style of PHP's date() function and supports the ISO-8601 week number:

new Date().format('W');

It may be a bit overkill for just a week number, but it does support PHP style formatting and is quite handy if you'll be doing a lot of this.

php: how to get associative array key from numeric index?

$array = array( 'one' =>'value', 'two' => 'value2' );

$allKeys = array_keys($array);
echo $allKeys[0];

Which will output:

one

HTML anchor tag with Javascript onclick event

Use following code to show menu instead go to href addres

_x000D_
_x000D_
function show_more_menu(e) {_x000D_
  if( !confirm(`Go to ${e.target.href} ?`) ) e.preventDefault();_x000D_
}
_x000D_
<a href='more.php' onclick="show_more_menu(event)"> More >>> </a>
_x000D_
_x000D_
_x000D_

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

How do I get the name of a Ruby class?

Here's the correct answer, extracted from comments by Daniel Rikowski and pseidemann. I'm tired of having to weed through comments to find the right answer...

If you use Rails (ActiveSupport):

result.class.name.demodulize

If you use POR (plain-ol-Ruby):

result.class.name.split('::').last

List(of String) or Array or ArrayList

For those who are stuck maintaining old .net, here is one that works in .net framework 2.x:

Dim lstOfStrings As New List(of String)( new String(){"v1","v2","v3"} )

git rebase: "error: cannot stat 'file': Permission denied"

This can also happen when you're using SublimeText and the popup window asking you to buy the program is not closed.

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

adding mode:no-cors can avoid cors issue in the api.

fetch(sign_in, {
        mode: 'no-cors',
        credentials: 'include',
        method: 'POST',
        headers: headers
    })
    .then(response => response.json())
    .then(json => console.log(json))
    .catch(error => console.log('Authorization failed : ' + error.message));
}

Move branch pointer to different commit without checkout

Open the file .git/refs/heads/<your_branch_name>, and change the hash stored there to the one where you want to move the head of your branch. Just edit and save the file with any text editor. Just make sure that the branch to modify is not the current active one.

Disclaimer: Probably not an advisable way to do it, but gets the job done.

Convert hours:minutes:seconds into total minutes in excel

The only way is to use a formula or to format cells. The method i will use will be the following: Add another column next to these values. Then use the following formula:

=HOUR(A1)*60+MINUTE(A1)+SECOND(A1)/60

enter image description here

How to Execute a Python File in Notepad ++?

On the menu go to: "Run" --> "Run..." (or just press F5).

For Python 2 type in:

py -2 -i "$(FULL_CURRENT_PATH)"

For Python 3 type in:

py -3 -i "$(FULL_CURRENT_PATH)"

References:

To understand the py command better:

py -h

Another helpful link to understand the py command: How do I run python 2 and 3 in windows 7?

Thanks to Reshure for his answer that got me on the right track to figure this out.

How to specify the port an ASP.NET Core application is hosted on?

Follow up answer to help anyone doing this with the VS docker integration. I needed to change to port 8080 to run using the "flexible" environment in google appengine.

You'll need the following in your Dockerfile:

ENV ASPNETCORE_URLS=http://+:8080
EXPOSE 8080

and you'll need to modify the port in docker-compose.yml as well:

    ports:
      - "8080"

How to permanently remove few commits from remote branch

This might be too little too late but what helped me is the cool sounding 'nuclear' option. Basically using the command filter-branch you can remove files or change something over a large number of files throughout your entire git history.

It is best explained here.

How do I insert multiple checkbox values into a table?

I think this should work .. :)

<input type="checkbox" name="Days[]" value="Daily">Daily<br>
<input type="checkbox" name="Days[]" value="Sunday">Sunday<br>

Creating SVG graphics using Javascript?

There's a jQuery plugin that allows you to manipulate SVG via Javascript:

http://plugins.jquery.com/project/svg

From its intro:

Supported natively in Firefox, Opera, and Safari and via the Adobe SVG viewer or Renesis player in IE, SVG lets you display graphics within your Web pages. Now you can easily drive the SVG canvas from your JavaScript code.

How to remove "disabled" attribute using jQuery?

to remove disabled attribute use,

 $("#elementID").removeAttr('disabled');

and to add disabled attribute use,

$("#elementID").prop("disabled", true);

Enjoy :)

JavaScriptSerializer.Deserialize - how to change field names

Json.NET will do what you want (disclaimer: I'm the author of the package). It supports reading DataContract/DataMember attributes as well as its own to change the property names. Also there is the StringEnumConverter class for serializing enum values as the name rather than the number.

How do I convert a byte array to Base64 in Java?

In case you happen to be using Spring framework along with java, there is an easy way around.

  1. Import the following.

    import org.springframework.util.Base64Utils;
  2. Convert like this.

    byte[] bytearr ={0,1,2,3,4};
    String encodedText = Base64Utils.encodeToString(bytearr);
    

    To decode you can use the decodeToString method of the Base64Utils class.

How to get single value from this multi-dimensional PHP array

I think you want this:

foreach ($myarray as $key => $value) {
    echo "$key = $value\n";
}

How to create a new object instance from a Type

public AbstractType New
{
    get
    {
        return (AbstractType) Activator.CreateInstance(GetType());
    }
}

How to escape double quotes in a title attribute

The escape code &#34; can also be used instead of &quot;.

Deserialize json object into dynamic object using Json.net

Note: At the time I answered this question in 2010, there was no way to deserialize without some sort of type, this allowed you to deserialize without having go define the actual class and allowed an anonymous class to be used to do the deserialization.


You need to have some sort of type to deserialize to. You could do something along the lines of:

var product = new { Name = "", Price = 0 };
dynamic jsonResponse = JsonConvert.Deserialize(json, product.GetType());

My answer is based on a solution for .NET 4.0's build in JSON serializer. Link to deserialize to anonymous types is here:

http://blogs.msdn.com/b/alexghi/archive/2008/12/22/using-anonymous-types-to-deserialize-json-data.aspx

Finding current executable's path without /proc/self/exe

The whereami library by Gregory Pakosz implements this for a variety of platforms, using the APIs mentioned in mark4o's post. This is most interesting if you "just" need a solution that works for a portable project and are not interested in the peculiarities of the various platforms.

At the time of writing, supported platforms are:

  • Windows
  • Linux
  • Mac
  • iOS
  • Android
  • QNX Neutrino
  • FreeBSD
  • NetBSD
  • DragonFly BSD
  • SunOS

The library consists of whereami.c and whereami.h and is licensed under MIT and WTFPL2. Drop the files into your project, include the header and use it:

#include "whereami.h"

int main() {
  int length = wai_getExecutablePath(NULL, 0, NULL);
  char* path = (char*)malloc(length + 1);
  wai_getExecutablePath(path, length, &dirname_length);
  path[length] = '\0';

  printf("My path: %s", path);

  free(path);
  return 0;
}

JFrame background image

The best way to load an image is through the ImageIO API

BufferedImage img = ImageIO.read(new File("/path/to/some/image"));

There are a number of ways you can render an image to the screen.

You could use a JLabel. This is the simplest method if you don't want to modify the image in anyway...

JLabel background = new JLabel(new ImageIcon(img));

Then simply add it to your window as you see fit. If you need to add components to it, then you can simply set the label's layout manager to whatever you need and add your components.

If, however, you need something more sophisticated, need to change the image somehow or want to apply additional effects, you may need to use custom painting.

First cavert: Don't ever paint directly to a top level container (like JFrame). Top level containers aren't double buffered, so you may end up with some flashing between repaints, other objects live on the window, so changing it's paint process is troublesome and can cause other issues and frames have borders which are rendered inside the viewable area of the window...

Instead, create a custom component, extending from something like JPanel. Override it's paintComponent method and render your output to it, for example...

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(img, 0, 0, this);
}

Take a look at Performing Custom Painting and 2D Graphics for more details

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

jQuery find events handlers registered with an object

I combined some of the answers above and created this crazy looking but functional script that lists hopefully most of the event listeners on the given element. Feel free to optimize it here.

_x000D_
_x000D_
var element = $("#some-element");_x000D_
_x000D_
// sample event handlers_x000D_
element.on("mouseover", function () {_x000D_
  alert("foo");_x000D_
});_x000D_
_x000D_
$(".parent-element").on("mousedown", "span", function () {_x000D_
  alert("bar");_x000D_
});_x000D_
_x000D_
$(document).on("click", "span", function () {_x000D_
  alert("xyz");_x000D_
});_x000D_
_x000D_
var collection = element.parents()_x000D_
  .add(element)_x000D_
  .add($(document));_x000D_
collection.each(function() {_x000D_
  var currentEl = $(this) ? $(this) : $(document);_x000D_
  var tagName = $(this)[0].tagName ? $(this)[0].tagName : "DOCUMENT";_x000D_
  var events = $._data($(this)[0], "events");_x000D_
  var isItself = $(this)[0] === element[0]_x000D_
  if (!events) return;_x000D_
  $.each(events, function(i, event) {_x000D_
    if (!event) return;_x000D_
    $.each(event, function(j, h) {_x000D_
      var found = false;        _x000D_
      if (h.selector && h.selector.length > 0) {_x000D_
        currentEl.find(h.selector).each(function () {_x000D_
          if ($(this)[0] === element[0]) {_x000D_
            found = true;_x000D_
          }_x000D_
        });_x000D_
      } else if (!h.selector && isItself) {_x000D_
        found = true;_x000D_
      }_x000D_
_x000D_
      if (found) {_x000D_
        console.log("################ " + tagName);_x000D_
        console.log("event: " + i);_x000D_
        console.log("selector: '" + h.selector + "'");_x000D_
        console.log(h.handler);_x000D_
      }_x000D_
    });_x000D_
  });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="parent-element">_x000D_
  <span id="some-element"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Regular expression to match a word or its prefix

I test examples in js. Simplest solution - just add word u need inside / /:

var reg = /cat/;
reg.test('some cat here');//1 test
true // result
reg.test('acatb');//2 test
true // result

Now if u need this specific word with boundaries, not inside any other signs-letters. We use b marker:

var reg = /\bcat\b/
reg.test('acatb');//1 test 
false // result
reg.test('have cat here');//2 test
true // result

We have also exec() method in js, whichone returns object-result. It helps f.g. to get info about place/index of our word.

var matchResult = /\bcat\b/.exec("good cat good");
console.log(matchResult.index); // 5

If we need get all matched words in string/sentence/text, we can use g modifier (global match):

"cat good cat good cat".match(/\bcat\b/g).length
// 3 

Now the last one - i need not 1 specific word, but some of them. We use | sign, it means choice/or.

"bad dog bad".match(/\bcat|dog\b/g).length
// 1

HTML5 Canvas vs. SVG vs. div

Just my 2 cents regarding the divs option.

Famous/Infamous and SamsaraJS (and possibly others) use absolutely positioned non-nested divs (with non-trivial HTML/CSS content), combined with matrix2d/matrix3d for positioning and 2D/3D transformations, and achieve a stable 60FPS on moderate mobile hardware, so I'd argue against divs being a slow option.

There are plenty of screen recordings on Youtube and elsewhere, of high-performance 2D/3D stuff running in the browser with everything being an DOM element which you can Inspect Element on, at 60FPS (mixed with WebGL for certain effects, but not for the main part of the rendering).

Check if character is number?

Try:

function is_numeric(str){
        try {
           return isFinite(str)
        }
        catch(err) {
            return false
        }
    }

How to execute a command prompt command from python

You probably want to try something like this:

command = "cmd.exe /C dir C:\\"

I don't think you can pipe into cmd.exe... If you are coming from a unix background, well, cmd.exe has some ugly warts!

EDIT: According to Sven Marnach, you can pipe to cmd.exe. I tried following in a python shell:

>>> import subprocess
>>> proc = subprocess.Popen('cmd.exe', stdin = subprocess.PIPE, stdout = subprocess.PIPE)
>>> stdout, stderr = proc.communicate('dir c:\\')
>>> stdout
'Microsoft Windows [Version 6.1.7600]\r\nCopyright (c) 2009 Microsoft Corporatio
n.  All rights reserved.\r\n\r\nC:\\Python25>More? '

As you can see, you still have a bit of work to do (only the first line is returned), but you might be able to get this to work...

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

I have build a sample android studio project for this question.

output screen shots :-

enter image description here

enter image description here

enter image description here

Download full project source code Click here

Please note: you have to add your API key in Androidmanifest.xml

How to call a method in another class of the same package?

By calling method

public class a 
{
    void sum(int i,int k)
    {
        System.out.println("THe sum of the number="+(i+k));
    }
}
class b
{
    public static void main(String[] args)
    {
        a vc=new a();
        vc.sum(10 , 20);
    }
}

What's the best strategy for unit-testing database-driven applications?

I use the first (running the code against a test database). The only substantive issue I see you raising with this approach is the possibilty of schemas getting out of sync, which I deal with by keeping a version number in my database and making all schema changes via a script which applies the changes for each version increment.

I also make all changes (including to the database schema) against my test environment first, so it ends up being the other way around: After all tests pass, apply the schema updates to the production host. I also keep a separate pair of testing vs. application databases on my development system so that I can verify there that the db upgrade works properly before touching the real production box(es).

Disable firefox same origin policy

The cors-everywhere addon works for me until Firefox 68, after 68 I need to adjust 'privacy.file_unique_origin' -> false (by open 'about:config') to solve 'CORS request not HTTP' for new CORS same-origin rule introduced.

JUnit tests pass in Eclipse but fail in Maven Surefire

It is most likely that your configuration files are in src/main/resources, while they must be under src/test/resources to work properly under maven.

https://cwiki.apache.org/UIMA/differences-between-running-unit-tests-in-eclipse-and-in-maven.html

I'm replying this after two years 'cause I couldn't find this answer here and I think it is the right one.

How can I safely create a nested directory?

On Python = 3.5, use pathlib.Path.mkdir:

from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)

For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:

Try os.path.exists, and consider os.makedirs for the creation.

import os
if not os.path.exists(directory):
    os.makedirs(directory)

As noted in comments and elsewhere, there's a race condition – if the directory is created between the os.path.exists and the os.makedirs calls, the os.makedirs will fail with an OSError. Unfortunately, blanket-catching OSError and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.

One option would be to trap the OSError and examine the embedded error code (see Is there a cross-platform way of getting information from Python’s OSError):

import os, errno

try:
    os.makedirs(directory)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise

Alternatively, there could be a second os.path.exists, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled.

Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.

Modern versions of Python improve this code quite a bit, both by exposing FileExistsError (in 3.3+)...

try:
    os.makedirs("path/to/directory")
except FileExistsError:
    # directory already exists
    pass

...and by allowing a keyword argument to os.makedirs called exist_ok (in 3.2+).

os.makedirs("path/to/directory", exist_ok=True)  # succeeds even if directory exists.

Appending an element to the end of a list in Scala

That's because you shouldn't do it (at least with an immutable list). If you really really need to append an element to the end of a data structure and this data structure really really needs to be a list and this list really really has to be immutable then do eiher this:

(4 :: List(1,2,3).reverse).reverse

or that:

List(1,2,3) ::: List(4)

How do I generate a stream from a string?

Use the MemoryStream class, calling Encoding.GetBytes to turn your string into an array of bytes first.

Do you subsequently need a TextReader on the stream? If so, you could supply a StringReader directly, and bypass the MemoryStream and Encoding steps.

android start activity from service

I had the same problem, and want to let you know that none of the above worked for me. What worked for me was:

 Intent dialogIntent = new Intent(this, myActivity.class);
 dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 this.startActivity(dialogIntent);

and in one my subclasses, stored in a separate file I had to:

public static Service myService;

myService = this;

new SubService(myService);

Intent dialogIntent = new Intent(myService, myActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
myService.startActivity(dialogIntent);

All the other answers gave me a nullpointerexception.

C# MessageBox dialog result

This answer was not working for me so I went on to MSDN. There I found that now the code should look like this:

//var is of MessageBoxResult type
var result = MessageBox.Show(message, caption,
                             MessageBoxButtons.YesNo,
                             MessageBoxIcon.Question);

// If the no button was pressed ... 
if (result == DialogResult.No)
{
    ...
}

Hope it helps

How to change sa password in SQL Server 2008 express?

This is what worked for me:

  • Close all Sql Server referencing apps.
  • Open Services in Control Panel.
  • Find the "SQL Server (SQLEXPRESS)" entry and select properties.
  • Stop the service (all Sql Server services).
  • Enter "-m" at the Start parameters" fields.
  • Start the service (click on Start button on General Tab).
  • Open a Command Prompt (right click, Run as administrator if needed).
  • Enter the command:

    osql -S localhost\SQLEXPRESS -E

    (or change localhost to whatever your PC is called).

  • At the prompt type the following commands:

    CREATE LOGIN my_Login_here WITH PASSWORD = 'my_Password_here'

    go

    sp_addsrvrolemember 'my_Login_here', 'sysadmin'

    go

    quit

  • Stop the "SQL Server (SQLEXPRESS)" service.

  • Remove the "-m" from the Start parameters field (if still there).

  • Start the service.

  • In Management Studio, use the login and password you just created. This should give it admin permission.

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

Here's my 2 cents:

import sys

map the path where the module file is located. In my case it was the desktop

sys.path.append('/Users/John/Desktop')

Either import the whole mapping module BUT then you have to use the .notation to map the classes like mapping.Shipping()

import mapping #mapping.py is the name of my module file

shipit = mapping.Shipment() #Shipment is the name of the class I need to use in the mapping module

Or import the specific class from the mapping module

from mapping import Mapping

shipit = Shipment() #Now you don't have to use the .notation

What is the difference between DAO and Repository patterns?

A DAO allows for a simpler way to get data from storage, hiding the ugly queries.

Repository deals with data too and hides queries and all that but, a repository deals with business/domain objects.

A repository will use a DAO to get the data from the storage and uses that data to restore a business object.

For example, A DAO can contain some methods like that -

 public abstract class MangoDAO{
   abstract List<Mango>> getAllMangoes();
   abstract Mango getMangoByID(long mangoID);
}

And a Repository can contain some method like that -

   public abstract class MangoRepository{
       MangoDao mangoDao = new MangDao;

       Mango getExportQualityMango(){

       for(Mango mango:mangoDao.getAllMangoes()){
        /*Here some business logics are being applied.*/
        if(mango.isSkinFresh()&&mangoIsLarge(){
           mango.setDetails("It is an export quality mango");
            return mango;
           }
       }
    }
}

This tutorial helped me to get the main concept easily.

How do I make the return type of a method generic?

You have to convert the type of your return value of the method to the Generic type which you pass to the method during calling.

    public static T values<T>()
    {
        Random random = new Random();
        int number = random.Next(1, 4);
        return (T)Convert.ChangeType(number, typeof(T));
    }

You need pass a type that is type casteable for the value you return through that method.

If you would want to return a value which is not type casteable to the generic type you pass, you might have to alter the code or make sure you pass a type that is casteable for the return value of method. So, this approach is not reccomended.

Call removeView() on the child's parent first

Ok, call me paranoid but I suggest:

  final android.view.ViewParent parent = view.getParent ();

  if (parent instanceof android.view.ViewManager)
  {
     final android.view.ViewManager viewManager = (android.view.ViewManager) parent;

     viewManager.removeView (view);
  } // if

casting without instanceof just seems wrong. And (thanks IntelliJ IDEA for telling me) removeView is part of the ViewManager interface. And one should not cast to a concrete class when a perfectly suitable interface is available.

Python convert csv to xlsx

Simple two line code solution using pandas

  import pandas as pd

  read_file = pd.read_csv ('File name.csv')
  read_file.to_excel ('File name.xlsx', index = None, header=True)

What is the difference between 'java', 'javaw', and 'javaws'?

From http://publib.boulder.ibm.com/infocenter/javasdk/v6r0/index.jsp?topic=%2Fcom.ibm.java.doc.user.aix32.60%2Fuser%2Fjava.html:

The javaw command is identical to java, except that javaw has no associated console window. Use javaw when you do not want a command prompt window to be displayed. The javaw launcher displays a window with error information if it fails.

And javaws is for Java web start applications, applets, or something like that, I would suspect.

Best way to resolve file path too long exception

The best answer I can find, is in one of the comments here. Adding it to the answer so that someone won't miss the comment and should definitely try this out. It fixed the issue for me.

We need to map the solution folder to a drive using the "subst" command in command prompt- e.g., subst z:

And then open the solution from this drive (z in this case). This would shorten the path as much as possible and could solve the lengthy filename issue.

How to remove jar file from local maven repository which was added with install:install-file?

  1. cd ~/.m2
  2. git init
  3. git commit -am "some comments"
  4. cd /path/to/your/project
  5. mvn install
  6. cd ~/.m2
  7. git reset --hard

Wait one second in running program

Personally I think Thread.Sleep is a poor implementation. It locks the UI etc. I personally like timer implementations since it waits then fires.

Usage: DelayFactory.DelayAction(500, new Action(() => { this.RunAction(); }));

//Note Forms.Timer and Timer() have similar implementations. 

public static void DelayAction(int millisecond, Action action)
{
    var timer = new DispatcherTimer();
    timer.Tick += delegate

    {
        action.Invoke();
        timer.Stop();
    };

    timer.Interval = TimeSpan.FromMilliseconds(millisecond);
    timer.Start();
}

Support for "border-radius" in IE

The answer to this question has changed since it was asked a year ago. (This question is currently one of the top results for Googling "border-radius ie".)

IE9 will support border-radius.

There is a platform preview available which supports border-radius. You will need Windows Vista or Windows 7 to run the preview (and IE9 when it is released).

Spring CORS No 'Access-Control-Allow-Origin' header is present

public class TrackingSystemApplication {

    public static void main(String[] args) {
        SpringApplication.run(TrackingSystemApplication.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:4200").allowedMethods("PUT", "DELETE",
                        "GET", "POST");
            }
        };
    }

}

How to make a <svg> element expand or contract to its parent container?

The viewBox isn't the height of the container, it's the size of your drawing. Define your viewBox to be 100 units in width, then define your rect to be 10 units. After that, however large you scale the SVG, the rect will be 10% the width of the image.

How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

var val = yyy.First().Value;
return yyy.All(x=>x.Value == val) ? val : otherValue; 

Cleanest way I can think of. You can make it a one-liner by inlining val, but First() would be evaluated n times, doubling execution time.

To incorporate the "empty set" behavior specified in the comments, you simply add one more line before the two above:

if(yyy == null || !yyy.Any()) return otherValue;

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

are you using jquery and prototype on the same page by any chance?

If so, use jquery noConflict mode, otherwise you are overwriting prototypes $ function.

noConflict mode is activated by doing the following:

<script src="jquery.js"></script>
<script>jQuery.noConflict();</script>

Note: by doing this, the dollar sign variable no longer represents the jQuery object. To keep from rewriting all your jQuery code, you can use this little trick to create a dollar sign scope for jQuery:

jQuery(function ($) {
    // The dollar sign will equal jQuery in this scope
});

// Out here, the dollar sign still equals Prototype

How to import a module in Python with importlib.import_module

For relative imports you have to:

  • a) use relative name
  • b) provide anchor explicitly

    importlib.import_module('.c', 'a.b')
    

Of course, you could also just do absolute import instead:

importlib.import_module('a.b.c')

How to reposition Chrome Developer Tools

After I have placed my dock to the right (see older answers), I still found the panels split vertically.

To split the panels horizontally - and even got more from your screen width - go to Settings (bottom right corner), and remove the check on 'Split panels vertically when docked to right'.

Now, you have all panels from left to right :p

Allow only numeric value in textbox using Javascript

Here is a solution which blocks all non numeric input from being entered into the text-field.

html

<input type="text" id="numbersOnly" />

javascript

var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
    var k = e.which;
    /* numeric inputs can come from the keypad or the numeric row at the top */
    if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
        e.preventDefault();
        return false;
    }
};?

Find and copy files

i faced an issue something like this...

Actually, in two ways you can process find command output in copy command

  1. If find command's output doesn't contain any space i.e if file name doesn't contain space in it then you can use below mentioned command:

    Syntax: find <Path> <Conditions> | xargs cp -t <copy file path>

    Example: find -mtime -1 -type f | xargs cp -t inner/

  2. But most of the time our production data files might contain space in it. So most of time below mentioned command is safer:

    Syntax: find <path> <condition> -exec cp '{}' <copy path> \;

    Example find -mtime -1 -type f -exec cp '{}' inner/ \;

In the second example, last part i.e semi-colon is also considered as part of find command, that should be escaped before press the enter button. Otherwise you will get an error something like this

find: missing argument to `-exec'

In your case, copy command syntax is wrong in order to copy find file into /home/shantanu/tosend. The following command will work:

find /home/shantanu/processed/ -name '*2011*.xml' -exec cp  {} /home/shantanu/tosend \;

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

I had this problem in InteliJ. I went to: Edit -> Configuration -> Deployment -> EditArtifact:

enter image description here

Then there where yellow problems, I just clicked on fix two times and it works. I hope this will help someone.

How to get input text value on click in ReactJS

There are two ways to go about doing this.

  1. Create a state in the constructor that contains the text input. Attach an onChange event to the input box that updates state each time. Then onClick you could just alert the state object.

  2. handleClick: function() { alert(this.refs.myInput.value); },

SQL Server: SELECT only the rows with MAX(DATE)

And u can also use that select statement as left join query... Example :

... left join (select OrderNO,
   PartCode,
   Quantity from (select OrderNO,
         PartCode,
         Quantity,
         row_number() over(partition by OrderNO order by DateEntered desc) as rn
  from YourTable) as T where rn = 1 ) RESULT on ....

Hope this help someone that search for this :)

Page scroll when soft keyboard popped up

This only worked for me:

android:windowSoftInputMode="adjustPan"

Why is this rsync connection unexpectedly closed on Windows?

I had this problem, but only when I tried to rsync from a Linux (RH) server to a Solaris server. My fix was to make sure rsync had the same path on both boxes, and that the ownership of rsync was the same.

On the linux box, rsync path was /usr/bin, on Solaris box it was /usr/local/bin. So, on the Solaris box I did ln -s /usr/local/bin/rsync /usr/bin/rsync.

I still had the same problem, and noticed ownership differences. On linux it was root:root, on solaris it was bin:bin. Changing solaris to root:root fixed it.

What's the best way to dedupe a table?

This can dedupe the duplicated values in c1:

select * from foo
minus
select f1.* from foo f1, foo f2
where f1.c1 = f2.c1 and f1.c2 > f2.c2

Get current date in milliseconds

Use this to get the time in milliseconds (long)(NSTimeInterval)([[NSDate date] timeIntervalSince1970]).

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

You are trying to access an XLS file. However, you are using XSSFWorkbook and XSSFSheet class objects. These classes are mainly used for XLSX files.

For XLS file: HSSFWorkbook & HSSFSheet
For XLSX file: XSSFSheet & XSSFSheet

So in place of XSSFWorkbook use HSSFWorkbook and in place of XSSFSheet use HSSFSheet.

So your code should look like this after the changes are made:

HSSFWorkbook workbook = new HSSFWorkbook(file);

HSSFSheet sheet = workbook.getSheetAt(0);

How can I set the form action through JavaScript?

document.forms[0].action="http://..."

...assuming it is the first form on the page.

Two HTML tables side by side, centered on the page

Give your inner div a width.

EXAMPLE

Change your CSS:

<style>
#outer { text-align: center; }
#inner { text-align: left; margin: 0 auto; }
.t { float: left; }
table { border: 1px solid black; }
#clearit { clear: left; }
</style>

To this:

<style>
#outer { text-align: center; }
#inner { text-align: left; margin: 0 auto; width:500px }
.t { float: left; }
table { border: 1px solid black; }
#clearit { clear: left; }
</style>

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

I was trying to install react expo and apart from sudo I had to add --unsafe-perm

like this. This resolves my Issue

sudo npm install -g expo-cli --unsafe-perm

High CPU Utilization in java application - why?

If a profiler is not applicable in your setup, you may try to identify the thread following steps in this post.

Basically, there are three steps:

  1. run top -H and get PID of the thread with highest CPU.
  2. convert the PID to hex.
  3. look for thread with the matching HEX PID in your thread dump.

How Should I Set Default Python Version In Windows?

Try modifying the path in the windows registry (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment).

Caveat: Don't break the registry :)

How to change Format of a Cell to Text using VBA

Well this should change your format to text.

Worksheets("Sheetname").Activate
Worksheets("SheetName").Columns(1).Select 'or Worksheets("SheetName").Range("A:A").Select
Selection.NumberFormat = "@"

How to insert blank lines in PDF?

directly use

paragraph.add("\n");

to add an empty line.

How to call a parent method from child class in javascript?

While you can call the parent method by the prototype of the parent, you will need to pass the current child instance for using call, apply, or bind method. The bind method will create a new function so I doesn't recommend that if you care for performance except it only called once.

As an alternative you can replace the child method and put the parent method on the instance while calling the original child method.

_x000D_
_x000D_
function proxy(context, parent){
  var proto = parent.prototype;
  var list = Object.getOwnPropertyNames(proto);
  
  for(var i=0; i < list.length; i++){
    var key = list[i];

    // Create only when child have similar method name
    if(context[key] !== proto[key]){
      let currentMethod = context[key];
      let parentMethod = proto[key];
      
      context[key] = function(){
        context.super = parentMethod;
        return currentMethod.apply(context, arguments);
      }
    }
  }
}

// ========= The usage would be like this ==========

class Parent {
  first = "Home";

  constructor(){
    console.log('Parent created');
  }

  add(arg){
    return this.first + ", Parent "+arg;
  }
}

class Child extends Parent{
  constructor(b){
    super();
    proxy(this, Parent);
    console.log('Child created');
  }

  // Comment this to call method from parent only
  add(arg){
    return super.add(arg) + ", Child "+arg;
  }
}

var family = new Child();
console.log(family.add('B'));
_x000D_
_x000D_
_x000D_

TCPDF not render all CSS properties

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

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

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

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

Convert Mat to Array/Vector in OpenCV

cv::Mat m;
m.create(10, 10, CV_32FC3);

float *array = (float *)malloc( 3*sizeof(float)*10*10 );
cv::MatConstIterator_<cv::Vec3f> it = m.begin<cv::Vec3f>();
for (unsigned i = 0; it != m.end<cv::Vec3f>(); it++ ) {
    for ( unsigned j = 0; j < 3; j++ ) {
        *(array + i ) = (*it)[j];
        i++;
    }
}

Now you have a float array. In case of 8 bit, simply change float to uchar, Vec3f to Vec3b and CV_32FC3 to CV_8UC3.

Nested objects in javascript, best practices

If you know the settings in advance you can define it in a single statement:

var defaultsettings = {
                        ajaxsettings : { "ak1" : "v1", "ak2" : "v2", etc. },
                        uisettings : { "ui1" : "v1", "ui22" : "v2", etc }
                      };

If you don't know the values in advance you can just define the top level object and then add properties:

var defaultsettings = { };
defaultsettings["ajaxsettings"] = {};
defaultsettings["ajaxsettings"]["somekey"] = "some value";

Or half-way between the two, define the top level with nested empty objects as properties and then add properties to those nested objects:

var defaultsettings = {
                        ajaxsettings : {  },
                        uisettings : {  }
                      };

defaultsettings["ajaxsettings"]["somekey"] = "some value";
defaultsettings["uisettings"]["somekey"] = "some value";

You can nest as deep as you like using the above techniques, and anywhere that you have a string literal in the square brackets you can use a variable:

var keyname = "ajaxsettings";
var defaultsettings = {};
defaultsettings[keyname] = {};
defaultsettings[keyname]["some key"] = "some value";

Note that you can not use variables for key names in the { } literal syntax.

How to run php files on my computer

If you have apache running, put your file in server folder for html files and then call it from web-browser (Like http://localhost/myfile.php ).

After installing SQL Server 2014 Express can't find local db

Most probably, you didn't install any SQL Server Engine service. If no SQL Server engine is installed, no service will appear in the SQL Server Configuration Manager tool. Consider that the packages SQLManagementStudio_Architecture_Language.exe and SQLEXPR_Architecture_Language.exe, available in the Microsoft site contain, respectively only the Management Studio GUI Tools and the SQL Server engine.

If you want to have a full featured SQL Server installation, with the database engine and Management Studio, download the installer file of SQL Server with Advanced Services. Moreover, to have a sample database in order to perform some local tests, use the Adventure Works database.

Considering the package of SQL Server with Advanced Services, at the beginning at the installation you should see something like this (the screenshot below is about SQL Server 2008 Express, but the feature selection is very similar). The checkbox next to "Database Engine Services" must be checked. In the next steps, you will be able to configure the instance settings and other options.

Execute again the installation process and select the database engine services in the feature selection step. At the end of the installation, you should be able to see the SQL Server services in the SQL Server Configuration Manager.

enter image description here

mysqli_fetch_array while loop columns

I think this would be a more simpler way of outputting your results.

Sorry for using my own data should be easy to replace .

$query = "SELECT * FROM category ";

$result = mysqli_query($connection, $query);


    while($row = mysqli_fetch_assoc($result))
    {
        $cat_id = $row['cat_id'];
        $cat_title = $row['cat_title'];

        echo $cat_id . " " . $cat_title  ."<br>";
    }

This would output :

  • -ID Title
  • -1 Gary
  • -2 John
  • -3 Michaels

Choosing bootstrap vs material design

As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).

On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.

  1. Bootstrap = responsive page
  2. AngularJS = MVC
  3. Material Design = great UI/UX

You can check awesome material design components for AngularJS:

https://material.angularjs.org


enter image description here

Demo: https://material.angularjs.org/latest/demo/ enter image description here

set column width of a gridview in asp.net

<asp:GridView ID="GridView1" runat="server">
    <HeaderStyle Width="10%" />
    <RowStyle Width="10%" />
    <FooterStyle Width="10%" />
    <Columns>
        <asp:BoundField HeaderText="Name" DataField="LastName" 
            HeaderStyle-Width="10%" ItemStyle-Width="10%"
            FooterStyle-Width="10%" />
    </Columns>
</asp:GridView>

golang why don't we have a set datastructure

Partly, because Go doesn't have generics (so you would need one set-type for every type, or fall back on reflection, which is rather inefficient).

Partly, because if all you need is "add/remove individual elements to a set" and "relatively space-efficient", you can get a fair bit of that simply by using a map[yourtype]bool (and set the value to true for any element in the set) or, for more space efficiency, you can use an empty struct as the value and use _, present = the_setoid[key] to check for presence.

Creating Accordion Table with Bootstrap

In the accepted answer you get annoying spacing between the visible rows when the expandable row is hidden. You can get rid of that by adding this to css:

.collapse-row.collapsed + tr {
     display: none;
}

'+' is adjacent sibling selector, so if you want your expandable row to be the next row, this selects the next tr following tr named collapse-row.

Here is updated fiddle: http://jsfiddle.net/Nb7wy/2372/

How can I create C header files

Header files can contain any valid C code, since they are injected into the compilation unit by the pre-processor prior to compilation.

If a header file contains a function, and is included by multiple .c files, each .c file will get a copy of that function and create a symbol for it. The linker will complain about the duplicate symbols.

It is technically possible to create static functions in a header file for inclusion in multiple .c files. Though this is generally not done because it breaks from the convention that code is found in .c files and declarations are found in .h files.

See the discussions in C/C++: Static function in header file, what does it mean? for more explanation.

How to add an image to an svg container using D3.js

In SVG (contrasted with HTML), you will want to use <image> instead of <img> for elements.

Try changing your last block with:

var imgs = svg.selectAll("image").data([0]);
            imgs.enter()
            .append("svg:image")
            ...

How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Can someone help me with the exact syntax?

It's a three-step process, and it involves modifying the openssl.cnf file. You might be able to do it with only command line options, but I don't do it that way.

Find your openssl.cnf file. It is likely located in /usr/lib/ssl/openssl.cnf:

$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf

On my Debian system, /usr/lib/ssl/openssl.cnf is used by the built-in openssl program. On recent Debian systems it is located at /etc/ssl/openssl.cnf

You can determine which openssl.cnf is being used by adding a spurious XXX to the file and see if openssl chokes.


First, modify the req parameters. Add an alternate_names section to openssl.cnf with the names you want to use. There are no existing alternate_names sections, so it does not matter where you add it.

[ alternate_names ]

DNS.1        = example.com
DNS.2        = www.example.com
DNS.3        = mail.example.com
DNS.4        = ftp.example.com

Next, add the following to the existing [ v3_ca ] section. Search for the exact string [ v3_ca ]:

subjectAltName      = @alternate_names

You might change keyUsage to the following under [ v3_ca ]:

keyUsage = digitalSignature, keyEncipherment

digitalSignature and keyEncipherment are standard fare for a server certificate. Don't worry about nonRepudiation. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.

In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.


Second, modify the signing parameters. Find this line under the CA_default section:

# Extension copying option: use with caution.
# copy_extensions = copy

And change it to:

# Extension copying option: use with caution.
copy_extensions = copy

This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.


Third, generate your self-signed certificate:

$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...

Finally, examine the certificate:

$ openssl x509 -in certificate.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9647297427330319047 (0x85e215e5869042c7)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Validity
            Not Before: Feb  1 05:23:05 2014 GMT
            Not After : Feb  1 05:23:05 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (3072 bit)
                Modulus:
                    00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
                    ...
                    d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
                    72:1c:45:92:2c:88:a9:be:0b:f9
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
            X509v3 Authority Key Identifier:
                keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4

            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
    Signature Algorithm: sha256WithRSAEncryption
         3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
         ...
         71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
         8b:0a:bd:65:03:d1

VB.net Need Text Box to Only Accept Numbers

Copy this function in any module inside your vb.net project.

Public Function MakeTextBoxNumeric(kcode As Integer, shift As Boolean) As Boolean
    If kcode >= 96 And kcode <= 105 Then

    ElseIf kcode >= 48 And kcode <= 57
        If shift = True Then Return False
    ElseIf kcode = 8 Or kcode = 107 Then

    ElseIf kcode = 187 Then
        If shift = False Then Return False
    Else
        Return False
    End If
    Return True
End Function

Then use this function inside your textbox_keydown event like below:

Private Sub txtboxNumeric_KeyDown(sender As Object, e As KeyEventArgs) Handles txtboxNumeric.KeyDown
If MakeTextBoxNumeric(e.KeyCode, e.Shift) = False Then e.SuppressKeyPress = True
End Sub

And yes. It works 100% :)

How to get screen dimensions as pixels in Android

For who is searching for usable screen dimension without Status Bar and Action Bar (also thanks to Swapnil's answer):

DisplayMetrics dm = getResources().getDisplayMetrics();
float screen_w = dm.widthPixels;
float screen_h = dm.heightPixels;

int resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resId > 0) {
    screen_h -= getResources().getDimensionPixelSize(resId);
}

TypedValue typedValue = new TypedValue();
if(getTheme().resolveAttribute(android.R.attr.actionBarSize, typedValue, true)){
    screen_h -= getResources().getDimensionPixelSize(typedValue.resourceId);
}

filtering a list using LINQ

var result = projects.Where(p => filtedTags.All(t => p.Tags.Contains(t)));

Iterate over model instance field names and values in template

Ok, I know this is a bit late, but since I stumbled upon this before finding the correct answer so might someone else.

From the django docs:

# This list contains a Blog object.
>>> Blog.objects.filter(name__startswith='Beatles')
[<Blog: Beatles Blog>]

# This list contains a dictionary.
>>> Blog.objects.filter(name__startswith='Beatles').values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]

How to set the max size of upload file

These properties in spring boot application.properties makes the acceptable file size unlimited -

# To prevent maximum upload size limit exception
spring.servlet.multipart.max-file-size=-1
spring.servlet.multipart.max-request-size=-1

How to create an empty matrix in R?

To get rid of the first column of NAs, you can do it with negative indexing (which removes indices from the R data set). For example:

output = matrix(1:6, 2, 3) # gives you a 2 x 3 matrix filled with the numbers 1 to 6

# output = 
#           [,1] [,2] [,3]
#     [1,]    1    3    5
#     [2,]    2    4    6

output = output[,-1] # this removes column 1 for all rows

# output = 
#           [,1] [,2]
#     [1,]    3    5
#     [2,]    4    6

So you can just add output = output[,-1]after the for loop in your original code.

Solutions for INSERT OR UPDATE on SQL Server

I had tried below solution and it works for me, when concurrent request for insert statement occurs.

begin tran
if exists (select * from table with (updlock,serializable) where key = @key)
begin
   update table set ...
   where key = @key
end
else
begin
   insert table (key, ...)
   values (@key, ...)
end
commit tran

CardView background color always white

app:cardBackgroundColor="#488747"

use this in your card view and you can change a color of your card view

Storing data into list with class

This line is your problem:

lstemail.Add("JOhn","Smith","Los Angeles");

There is no direct cast from 3 strings to your custom class. The compiler has no way of figuring out what you're trying to do with this line. You need to Add() an instance of the class to lstemail:

lstemail.Add(new EmailData { FirstName = "JOhn", LastName = "Smith", Location = "Los Angeles" });

How to modify a specified commit?

Use the awesome interactive rebase:

git rebase -i @~9   # Show the last 9 commits in a text editor

Find the commit you want, change pick to e (edit), and save and close the file. Git will rewind to that commit, allowing you to either:

  • use git commit --amend to make changes, or
  • use git reset @~ to discard the last commit, but not the changes to the files (i.e. take you to the point you were at when you'd edited the files, but hadn't committed yet).

The latter is useful for doing more complex stuff like splitting into multiple commits.

Then, run git rebase --continue, and Git will replay the subsequent changes on top of your modified commit. You may be asked to fix some merge conflicts.

Note: @ is shorthand for HEAD, and ~ is the commit before the specified commit.

Read more about rewriting history in the Git docs.


Don't be afraid to rebase

ProTip™:   Don't be afraid to experiment with "dangerous" commands that rewrite history* — Git doesn't delete your commits for 90 days by default; you can find them in the reflog:

$ git reset @~3   # go back 3 commits
$ git reflog
c4f708b HEAD@{0}: reset: moving to @~3
2c52489 HEAD@{1}: commit: more changes
4a5246d HEAD@{2}: commit: make important changes
e8571e4 HEAD@{3}: commit: make some changes
... earlier commits ...
$ git reset 2c52489
... and you're back where you started

* Watch out for options like --hard and --force though — they can discard data.
* Also, don't rewrite history on any branches you're collaborating on.



On many systems, git rebase -i will open up Vim by default. Vim doesn't work like most modern text editors, so take a look at how to rebase using Vim. If you'd rather use a different editor, change it with git config --global core.editor your-favorite-text-editor.

Two versions of python on linux. how to make 2.7 the default

All OS comes with a default version of python and it resides in /usr/bin. All scripts that come with the OS (e.g. yum) point this version of python residing in /usr/bin. When you want to install a new version of python you do not want to break the existing scripts which may not work with new version of python.

The right way of doing this is to install the python as an alternate version.

e.g.
wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tar.bz2 
tar xf Python-2.7.3.tar.bz2
cd Python-2.7.3
./configure --prefix=/usr/local/
make && make altinstall

Now by doing this the existing scripts like yum still work with /usr/bin/python. and your default python version would be the one installed in /usr/local/bin. i.e. when you type python you would get 2.7.3

This happens because. $PATH variable has /usr/local/bin before usr/bin.

/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin

If python2.7 still does not take effect as the default python version you would need to do

export PATH="/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin"

How to set image width to be 100% and height to be auto in react native?

I've found a solution for width: "100%", height: "auto" if you know the aspectRatio (width / height) of the image.

Here's the code:

import { Image, StyleSheet, View } from 'react-native';

const image = () => (
    <View style={styles.imgContainer}>
        <Image style={styles.image} source={require('assets/images/image.png')} />
    </View>
);

const style = StyleSheet.create({
    imgContainer: {
        flexDirection: 'row'
    },
    image: {
        resizeMode: 'contain',
        flex: 1,
        aspectRatio: 1 // Your aspect ratio
    }
});

This is the most simplest way I could get it to work without using onLayout or Dimension calculations. You can even wrap it in a simple reusable component if needed. Give it a shot if anyone is looking for a simple implementation.

excel formula to subtract number of days from a date

Assuming the original date is in cell A1:

=A1-180

Works in at least Excel 2003 and 2010.

How to clear an ImageView in Android?

Can i just point out what you are all trying to set and int where its expecting a drawable.

should you not be doing the following?

imageview.setImageDrawable(this.getResources().getDrawable(R.drawable.icon_image));

imageview.setImageDrawable(getApplicationContext().getResources().getDrawable(R.drawable.icon_profile_image));

Looping through a hash, or using an array in PowerShell

A short traverse could be given too using the sub-expression operator $( ), which returns the result of one or more statements.

$hash = @{ a = 1; b = 2; c = 3}

forEach($y in $hash.Keys){
    Write-Host "$y -> $($hash[$y])"
}

Result:

a -> 1
b -> 2
c -> 3

how can I login anonymously with ftp (/usr/bin/ftp)?

As others point out, the user name is usually anonymous, and the password is usually your e-mail address, but this is not universally true, and has been found not to work for certain anonymous FTP sites. For example, at least some cPanel sites seem to deviate from the norm, and if given the traditional user name without domain, one of various errors may result:

If the server uses Pure-FTP as the FTP server:

421 Can't change directory to /var/ftp/ error message.

If the server uses ProFTP as the FTP server:

530 Login Authentication Failed error message.

When one of the aforementioned errors occurs when attempting anonymous access, try including a domain with the username. For example, where example.com is the domain used in your e-mail address:

User name: [email protected]

In the specific case of a cPanel site, the password value is unimportant, and may be left blank, but there is no harm in providing a "traditional" anonymous password formatted as an e-mail address.

For reference, this answer is based on content found on a documentation.cpanel.net Anonymous FTP page. At the time of this writing, it stated:

When users log in to FTP anonymously, they must format usernames as [email protected], where example.com represents the user's domain name. This requirement directs your server to the correct public_ftp directory.

How do you set a default value for a MySQL Datetime column?

For all who use the TIMESTAMP column as a solution i want to second the following limitation from the manual:

http://dev.mysql.com/doc/refman/5.0/en/datetime.html

"The TIMESTAMP data type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. It has varying properties, depending on the MySQL version and the SQL mode the server is running in. These properties are described later in this section. "

So this will obviously break your software in about 28 years.

I believe the only solution on the database side is to use triggers like mentioned in other answers.

How to use vertical align in bootstrap

I had to add width: 100%; to display table to fix some strange bahavior in IE and FF, when i used this example. IE and FF had some problems displaying the col-md-* tags at the right width

.display-table {
        display: table;
        table-layout: fixed;
        width: 100%;
}

.display-cell {
        display: table-cell;
        vertical-align: middle;
        float: none;
}

IntelliJ IDEA JDK configuration on Mac OS

Quite late to this party, today I had the same problem. The right answer on macOs I think is use jenv

brew install jenv openjdk@11
jenv add /usr/local/opt/openjdk@11

And then add into Intellij IDEA as new SDK the following path:

~/.jenv/versions/11/libexec/openjdk.jdk/Contents/Home/

Bootstrap col-md-offset-* not working

<div class="jumbotron">
        <div class="container">
            <div class="row">
                <div>
                    <h2 class="col-md-4 offset-md-4">Browse.</h2>
                    <h2 class="col-md-4 offset-md-4">create.</h2>
                    <h2 class="col-md-4 offset-md-4">share.</h2>
                </div>
            </div>
        </div>
    </div>

You can try this.

What does .class mean in Java?

When you write .class after a class name, it references the class literal - java.lang.Class object that represents information about given class.

For example, if your class is Print, then Print.class is an object that represents the class Print on runtime. It is the same object that is returned by the getClass() method of any (direct) instance of Print.

Print myPrint = new Print();
System.out.println(Print.class.getName());
System.out.println(myPrint.getClass().getName());

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

Open your mysql file any edit tool

find

/*!40101 SET NAMES utf8mb4 */;

change

/*!40101 SET NAMES utf8 */;

Save and upload ur mysql.

How to click or tap on a TextView text

in textView

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:onClick="onClick"
    android:clickable="true"

You must also implement View.OnClickListener and in On Click method can use intent

    Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
           intent.setData(Uri.parse("https://youraddress.com"));    
            startActivity(intent);

I tested this solution works fine.

Build the full path filename in Python

Um, why not just:

>>>> import os
>>>> os.path.join(dir_name, base_filename + "." + format)
'/home/me/dev/my_reports/daily_report.pdf'

Split text file into smaller multiple text file using command line

Syntax looks like:

$ split [OPTION] [INPUT [PREFIX]] 

where prefix is PREFIXaa, PREFIXab, ...

Just use proper one and youre done or just use mv for renameing. I think $ mv * *.txt should work but test it first on smaller scale.

:)

Repeat a task with a time delay?

To anyone interested, here's a class I created using inazaruk's code that creates everything needed (I called it UIUpdater because I use it to periodically update the UI, but you can call it anything you like):

import android.os.Handler;
/**
 * A class used to perform periodical updates,
 * specified inside a runnable object. An update interval
 * may be specified (otherwise, the class will perform the 
 * update every 2 seconds).
 * 
 * @author Carlos Simões
 */
public class UIUpdater {
        // Create a Handler that uses the Main Looper to run in
        private Handler mHandler = new Handler(Looper.getMainLooper());

        private Runnable mStatusChecker;
        private int UPDATE_INTERVAL = 2000;

        /**
         * Creates an UIUpdater object, that can be used to
         * perform UIUpdates on a specified time interval.
         * 
         * @param uiUpdater A runnable containing the update routine.
         */
        public UIUpdater(final Runnable uiUpdater) {
            mStatusChecker = new Runnable() {
                @Override
                public void run() {
                    // Run the passed runnable
                    uiUpdater.run();
                    // Re-run it after the update interval
                    mHandler.postDelayed(this, UPDATE_INTERVAL);
                }
            };
        }

        /**
         * The same as the default constructor, but specifying the
         * intended update interval.
         * 
         * @param uiUpdater A runnable containing the update routine.
         * @param interval  The interval over which the routine
         *                  should run (milliseconds).
         */
        public UIUpdater(Runnable uiUpdater, int interval){
            UPDATE_INTERVAL = interval;
            this(uiUpdater);
        }

        /**
         * Starts the periodical update routine (mStatusChecker 
         * adds the callback to the handler).
         */
        public synchronized void startUpdates(){
            mStatusChecker.run();
        }

        /**
         * Stops the periodical update routine from running,
         * by removing the callback.
         */
        public synchronized void stopUpdates(){
            mHandler.removeCallbacks(mStatusChecker);
        }
}

You can then create a UIUpdater object inside your class and use it like so:

...
mUIUpdater = new UIUpdater(new Runnable() {
         @Override 
         public void run() {
            // do stuff ...
         }
    });

// Start updates
mUIUpdater.startUpdates();

// Stop updates
mUIUpdater.stopUpdates();
...

If you want to use this as an activity updater, put the start call inside the onResume() method and the stop call inside the onPause(), so the updates start and stop according to the activity visibility.

Good way of getting the user's location in Android

Skyhook (http://www.skyhookwireless.com/) has a location provider that is much faster than the standard one Google provides. It might be what you're looking for. I'm not affiliated with them.

How do I update Homebrew?

  • cd /usr/local
  • git status
  • Discard all the changes (unless you actually want to try to commit to Homebrew - you probably don't)
  • git status til it's clean
  • brew update

Create new user in MySQL and give it full access to one database

Syntax

To create user in MySQL/MariaDB 5.7.6 and higher, use CREATE USER syntax:

CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'new_password';

then to grant all access to the database (e.g. my_db), use GRANT Syntax, e.g.

GRANT ALL ON my_db.* TO 'new_user'@'localhost';

Where ALL (priv_type) can be replaced with specific privilege such as SELECT, INSERT, UPDATE, ALTER, etc.

Then to reload newly assigned permissions run:

FLUSH PRIVILEGES;

Executing

To run above commands, you need to run mysql command and type them into prompt, then logout by quit command or Ctrl-D.

To run from shell, use -e parameter (replace SELECT 1 with one of above commands):

$ mysql -e "SELECT 1"

or print statement from the standard input:

$ echo "FOO STATEMENT" | mysql

If you've got Access denied with above, specify -u (for user) and -p (for password) parameters, or for long-term access set your credentials in ~/.my.cnf, e.g.

[client]
user=root
password=root

Shell integration

For people not familiar with MySQL syntax, here are handy shell functions which are easy to remember and use (to use them, you need to load the shell functions included further down).

Here is example:

$ mysql-create-user admin mypass
| CREATE USER 'admin'@'localhost' IDENTIFIED BY 'mypass'

$ mysql-create-db foo
| CREATE DATABASE IF NOT EXISTS foo

$ mysql-grant-db admin foo
| GRANT ALL ON foo.* TO 'admin'@'localhost'
| FLUSH PRIVILEGES

$ mysql-show-grants admin
| SHOW GRANTS FOR 'admin'@'localhost'
| Grants for admin@localhost                                                                                   
| GRANT USAGE ON *.* TO 'admin'@'localhost' IDENTIFIED BY PASSWORD '*6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4' |
| GRANT ALL PRIVILEGES ON `foo`.* TO 'admin'@'localhost'

$ mysql-drop-user admin
| DROP USER 'admin'@'localhost'

$ mysql-drop-db foo
| DROP DATABASE IF EXISTS foo

To use above commands, you need to copy&paste the following functions into your rc file (e.g. .bash_profile) and reload your shell or source the file. In this case just type source .bash_profile:

# Create user in MySQL/MariaDB.
mysql-create-user() {
  [ -z "$2" ] && { echo "Usage: mysql-create-user (user) (password)"; return; }
  mysql -ve "CREATE USER '$1'@'localhost' IDENTIFIED BY '$2'"
}

# Delete user from MySQL/MariaDB
mysql-drop-user() {
  [ -z "$1" ] && { echo "Usage: mysql-drop-user (user)"; return; }
  mysql -ve "DROP USER '$1'@'localhost';"
}

# Create new database in MySQL/MariaDB.
mysql-create-db() {
  [ -z "$1" ] && { echo "Usage: mysql-create-db (db_name)"; return; }
  mysql -ve "CREATE DATABASE IF NOT EXISTS $1"
}

# Drop database in MySQL/MariaDB.
mysql-drop-db() {
  [ -z "$1" ] && { echo "Usage: mysql-drop-db (db_name)"; return; }
  mysql -ve "DROP DATABASE IF EXISTS $1"
}

# Grant all permissions for user for given database.
mysql-grant-db() {
  [ -z "$2" ] && { echo "Usage: mysql-grand-db (user) (database)"; return; }
  mysql -ve "GRANT ALL ON $2.* TO '$1'@'localhost'"
  mysql -ve "FLUSH PRIVILEGES"
}

# Show current user permissions.
mysql-show-grants() {
  [ -z "$1" ] && { echo "Usage: mysql-show-grants (user)"; return; }
  mysql -ve "SHOW GRANTS FOR '$1'@'localhost'"
}

Note: If you prefer to not leave trace (such as passwords) in your Bash history, check: How to prevent commands to show up in bash history?

Align inline-block DIVs to top of container element

You need to add a vertical-align property to your two child div's.

If .small is always shorter, you need only apply the property to .small. However, if either could be tallest then you should apply the property to both .small and .big.

.container{ 
    border: 1px black solid;
    width: 320px;
    height: 120px;    
}

.small{
    display: inline-block;
    width: 40%;
    height: 30%;
    border: 1px black solid;
    background: aliceblue; 
    vertical-align: top;   
}

.big {
    display: inline-block;
    border: 1px black solid;
    width: 40%;
    height: 50%;
    background: beige; 
    vertical-align: top;   
}

Vertical align affects inline or table-cell box's, and there are a large nubmer of different values for this property. Please see https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align for more details.

What is the exact meaning of Git Bash?

At its core, Git is a set of command line utility programs that are designed to execute on a Unix style command-line environment. Modern operating systems like Linux and macOS both include built-in Unix command line terminals. This makes Linux and macOS complementary operating systems when working with Git. Microsoft Windows instead uses Windows command prompt, a non-Unix terminal environment.

What is Git Bash?

Git Bash is an application for Microsoft Windows environments which provides an emulation layer for a Git command line experience. Bash is an acronym for Bourne Again Shell. A shell is a terminal application used to interface with an operating system through written commands. Bash is a popular default shell on Linux and macOS. Git Bash is a package that installs Bash, some common bash utilities, and Git on a Windows operating system.

source : https://www.atlassian.com/git/tutorials/git-bash

How to represent matrices in python

((1,2,3,4),
 (5,6,7,8),
 (9,0,1,2))

Using tuples instead of lists makes it marginally harder to change the data structure in unwanted ways.

If you are going to do extensive use of those, you are best off wrapping a true number array in a class, so you can define methods and properties on them. (Or, you could NumPy, SciPy, ... if you are going to do your processing with those libraries.)

Big-O summary for Java Collections Framework implementations?

The Javadocs from Sun for each collection class will generally tell you exactly what you want. HashMap, for example:

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings).

TreeMap:

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

TreeSet:

This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

(emphasis mine)

Why declare unicode by string in python?

As others have said, # coding: specifies the encoding the source file is saved in. Here are some examples to illustrate this:

A file saved on disk as cp437 (my console encoding), but no encoding declared

b = 'über'
u = u'über'
print b,repr(b)
print u,repr(u)

Output:

  File "C:\ex.py", line 1
SyntaxError: Non-ASCII character '\x81' in file C:\ex.py on line 1, but no
encoding declared; see http://www.python.org/peps/pep-0263.html for details

Output of file with # coding: cp437 added:

über '\x81ber'
über u'\xfcber'

At first, Python didn't know the encoding and complained about the non-ASCII character. Once it knew the encoding, the byte string got the bytes that were actually on disk. For the Unicode string, Python read \x81, knew that in cp437 that was a ü, and decoded it into the Unicode codepoint for ü which is U+00FC. When the byte string was printed, Python sent the hex value 81 to the console directly. When the Unicode string was printed, Python correctly detected my console encoding as cp437 and translated Unicode ü to the cp437 value for ü.

Here's what happens with a file declared and saved in UTF-8:

++ber '\xc3\xbcber'
über u'\xfcber'

In UTF-8, ü is encoded as the hex bytes C3 BC, so the byte string contains those bytes, but the Unicode string is identical to the first example. Python read the two bytes and decoded it correctly. Python printed the byte string incorrectly, because it sent the two UTF-8 bytes representing ü directly to my cp437 console.

Here the file is declared cp437, but saved in UTF-8:

++ber '\xc3\xbcber'
++ber u'\u251c\u255dber'

The byte string still got the bytes on disk (UTF-8 hex bytes C3 BC), but interpreted them as two cp437 characters instead of a single UTF-8-encoded character. Those two characters where translated to Unicode code points, and everything prints incorrectly.

How to add icons to React Native app

This is helpful for people struggling to find better site to generate icons and splashscreen

How can I make a JPA OneToOne relation lazy

If the child entity is used readonly, then it's possible to simply lie and set optional=false. Then ensure that every use of that mapped entity is preloaded via queries.

public class App {
  ...
  @OneToOne(mappedBy = "app", fetch = FetchType.LAZY, optional = false)
  private Attributes additional;

and

String sql = " ... FROM App a LEFT JOIN FETCH a.additional aa ...";

... maybe even persisting would work...

Node.js - EJS - including a partial

In Express 4.x I used the following to load ejs:

  var path = require('path');

  // Set the default templating engine to ejs
  app.set('view engine', 'ejs');
  app.set('views', path.join(__dirname, 'views'));

  // The views/index.ejs exists in the app directory
  app.get('/hello', function (req, res) {
    res.render('index', {title: 'title'});
  });

Then you just need two files to make it work - views/index.ejs:

<%- include partials/navigation.ejs %>

And the views/partials/navigation.ejs:

<ul><li class="active">...</li>...</ul>

You can also tell Express to use ejs for html templates:

var path = require('path');
var EJS  = require('ejs');

app.engine('html', EJS.renderFile);

// Set the default templating engine to ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// The views/index.html exists in the app directory
app.get('/hello', function (req, res) {
  res.render('index.html', {title: 'title'});
});

Finally you can also use the ejs layout module:

var EJSLayout = require('express-ejs-layouts');
app.use(EJSLayout);

This will use the views/layout.ejs as your layout.

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

I think this is the simple answer you are looking for. It's from Shawn Wildermuth's blog:

// Add MVC services to the services container.
services.AddMvc()
  .AddJsonOptions(opts =>
  {
    opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  });

Hidden features of Python

Interactive Debugging of Scripts (and doctest strings)

I don't think this is as widely known as it could be, but add this line to any python script:

import pdb; pdb.set_trace()

will cause the PDB debugger to pop up with the run cursor at that point in the code. What's even less known, I think, is that you can use that same line in a doctest:

"""
>>> 1 in (1,2,3)   
Becomes
>>> import pdb; pdb.set_trace(); 1 in (1,2,3)
"""

You can then use the debugger to checkout the doctest environment. You can't really step through a doctest because the lines are each run autonomously, but it's a great tool for debugging the doctest globs and environment.

How to create a custom exception type in Java?

You should be able to create a custom exception class that extends the Exception class, for example:

class WordContainsException extends Exception
{
      // Parameterless Constructor
      public WordContainsException() {}

      // Constructor that accepts a message
      public WordContainsException(String message)
      {
         super(message);
      }
 }

Usage:

try
{
     if(word.contains(" "))
     {
          throw new WordContainsException();
     }
}
catch(WordContainsException ex)
{
      // Process message however you would like
}

Want to download a Git repository, what do I need (windows machine)?

To change working directory in GitMSYS's Git Bash you can just use cd

cd /path/do/directory

Note that:

  • Directory separators use the forward-slash (/) instead of backslash.
  • Drives are specified with a lower case letter and no colon, e.g. "C:\stuff" should be represented with "/c/stuff".
  • Spaces can be escaped with a backslash (\)
  • Command line completion is your friend. Press TAB at anytime to expand stuff, including Git options, branches, tags, and directories.

Also, you can right click in Windows Explorer on a directory and "Git Bash here".

module.exports vs. export default in Node.js and ES6

Felix Kling did a great comparison on those two, for anyone wondering how to do an export default alongside named exports with module.exports in nodejs

module.exports = new DAO()
module.exports.initDAO = initDAO // append other functions as named export

// now you have
let DAO = require('_/helpers/DAO');
// DAO by default is exported class or function
DAO.initDAO()

List comprehension with if statement

If you use sufficiently big list not in b clause will do a linear search for each of the item in a. Why not use set? Set takes iterable as parameter to create a new set object.

>>> a = ["a", "b", "c", "d", "e"]
>>> b = ["c", "d", "f", "g"]
>>> set(a).intersection(set(b))
{'c', 'd'}

SELECT data from another schema in oracle

In addition to grants, you can try creating synonyms. It will avoid the need for specifying the table owner schema every time.

From the connecting schema:

CREATE SYNONYM pi_int FOR pct.pi_int;

Then you can query pi_int as:

SELECT * FROM pi_int;

What is the maximum length of a URL in different browsers?

ASP.NET 2 and SQL Server reporting services 2005 have a limit of 2028. I found this out the hard way, where my dynamic URL generator would not pass over some parameters to a report beyond that point. This was under Internet Explorer 8.

Hibernate Annotations - Which is better, field or property access?

I favor field accessors. The code is much cleaner. All the annotations can be placed in one section of a class and the code is much easier to read.

I found another problem with property accessors: if you have getXYZ methods on your class that are NOT annotated as being associated with persistent properties, hibernate generates sql to attempt to get those properties, resulting in some very confusing error messages. Two hours wasted. I did not write this code; I have always used field accessors in the past and have never run into this issue.

Hibernate versions used in this app:

<!-- hibernate -->
<hibernate-core.version>3.3.2.GA</hibernate-core.version>
<hibernate-annotations.version>3.4.0.GA</hibernate-annotations.version>
<hibernate-commons-annotations.version>3.1.0.GA</hibernate-commons-annotations.version>
<hibernate-entitymanager.version>3.4.0.GA</hibernate-entitymanager.version>

Aborting a shell script if any command returns a non-zero value

An expression like

dosomething1 && dosomething2 && dosomething3

will stop processing when one of the commands returns with a non-zero value. For example, the following command will never print "done":

cat nosuchfile && echo "done"
echo $?
1

Java - Abstract class to contain variables?

I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin.

public abstract class ExternalScript extends Script {

    private String source;

    public void setSource(String file) {
        source = file;
    }

    public String getSource() {
        return source;
    }
}

Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code. There are a few other reasons to think about too:

  • If source was protected (so accessible by subclasses) then code gets messy: who's changing the variables? When it's an object it then becomes hard when you need to refactor, whereas a method tends to make this step easier.
  • If your getter/setter methods aren't getting and setting, then describe them as something else.

Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.

Auto number column in SharePoint list

If you want to control the formatting of the unique identifier you can create your own <FieldType> in SharePoint. MSDN also has a visual How-To. This basically means that you're creating a custom column.

WSS defines the Counter field type (which is what the ID column above is using). I've never had the need to re-use this or extend it, but it should be possible.

A solution might exist without creating a custom <FieldType>. For example: if you wanted unique IDs like CUST1, CUST2, ... it might be possible to create a Calculated column and use the value of the ID column in you formula (="CUST" & [ID]). I haven't tried this, but this should work :)

Disable LESS-CSS Overwriting calc()

The solutions of Fabricio works just fine.

A very common usecase of calc is add 100% width and adding some margin around the element.

One can do so with:

@someMarginVariable: 15px;

margin: @someMarginVariable;
width: calc(~"100% - "@someMarginVariable*2);
width: -moz-calc(~"100% - "@someMarginVariable*2);
width: -webkit-calc(~"100% - "@someMarginVariable*2);
width: -o-calc(~"100% - "@someMarginVariable*2);

Or can use a mixin like:

.fullWidthMinusMarginPaddingMixin(@marginSize,@paddingSize) {
  @minusValue: (@marginSize+@paddingSize)*2;
  padding: @paddingSize;
  margin: @marginSize;
  width: calc(~"100% - "@minusValue);
  width: -moz-calc(~"100% - "@minusValue);
  width: -webkit-calc(~"100% - "@minusValue);
  width: -o-calc(~"100% - "@minusValue);
}

Is there any way to configure multiple registries in a single npmrc file

I use Strongloop's cli tools for that; see https://strongloop.com/strongblog/switch-between-configure-public-and-private-npm-registry/ for more information

Switching between repositories is as easy as : slc registry use <name>

How, in general, does Node.js handle 10,000 concurrent requests?

Adding to slebetman's answer for more clarity on what happens while executing the code.

The internal thread pool in nodeJs just has 4 threads by default. and its not like the whole request is attached to a new thread from the thread pool the whole execution of request happens just like any normal request (without any blocking task) , just that whenever a request has any long running or a heavy operation like db call ,a file operation or a http request the task is queued to the internal thread pool which is provided by libuv. And as nodeJs provides 4 threads in internal thread pool by default every 5th or next concurrent request waits until a thread is free and once these operations are over the callback is pushed to the callback queue. and is picked up by event loop and sends back the response.

Now here comes another information that its not once single callback queue, there are many queues.

  1. NextTick queue
  2. Micro task queue
  3. Timers Queue
  4. IO callback queue (Requests, File ops, db ops)
  5. IO Poll queue
  6. Check Phase queue or SetImmediate
  7. close handlers queue

Whenever a request comes the code gets executing in this order of callbacks queued.

It is not like when there is a blocking request it is attached to a new thread. There are only 4 threads by default. So there is another queueing happening there.

Whenever in a code a blocking process like file read occurs , then calls a function which utilises thread from thread pool and then once the operation is done , the callback is passed to the respective queue and then executed in the order.

Everything gets queued based on the the type of callback and processed in the order mentioned above.

'Operation is not valid due to the current state of the object' error during postback

For ASP.NET 1.1, this is still due to someone posting more than 1000 form fields, but the setting must be changed in the registry rather than a config file. It should be added as a DWORD named MaxHttpCollectionKeys in the registry under

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\1.1.4322.0

for 32-bit editions of Windows, and

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\ASP.NET\1.1.4322.0

for 64-bit editions of Windows.

How do I check my gcc C++ compiler version for my Eclipse?

you can also use gcc -v command that works like gcc --version and if you would like to now where gcc is you can use whereis gcc command

I hope it'll be usefull

How to get row count in sqlite using Android?

Use android.database.DatabaseUtils to get number of count.

public long getTaskCount(long tasklist_Id) {
        return DatabaseUtils.queryNumEntries(readableDatabase, TABLE_NAME);
}

It is easy utility that has multiple wrapper methods to achieve database operations.

How to stop an unstoppable zombie job on Jenkins without restarting the server?

I guess it is too late to answer but my help some people.

  1. Install the monitoring plugin. (http://wiki.jenkins-ci.org/display/JENKINS/Monitoring)
  2. Go to jenkinsUrl/monitoring/nodes
  3. Go to the Threads section at the bottom
  4. Click on the details button on the left of the master
  5. Sort by User time (ms)
  6. Then look at the name of the thread, you will have the name and number of the build
  7. Kill it

I don't have enough reputation to post images sorry.

Hope it can help

How to import a JSON file in ECMAScript 6?

For NodeJS v12 and above, --experimental-json-modules would do the trick, without any help from babel.

https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_experimental_json_modules

But it is imported in commonjs form, so import { a, b } from 'c.json' is not yet supported.

But you can do:

import c from 'c.json';
const { a, b } = c;

How to convert string to date to string in Swift iOS?

//String to Date Convert

var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)


//CONVERT FROM NSDate to String  

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" 
var dateString = dateFormatter.stringFromDate(date)
println(dateString)  

Cannot install Aptana Studio 3.6 on Windows

Install NODE.JS on windows before installing aptana

Try the following link http://blueashes.com/2011/web-development/install-nodejs-on-windows/

Scrollable Menu with Bootstrap - Menu expanding its container when it should not

Do everything in the inline of UL tag

<ul class="dropdown-menu scrollable-menu" role="menu" style="height: auto;max-height: 200px; overflow-x: hidden;">
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
                <li><a href="#">Something else here</a></li>
                <li><a href="#">Action</a></li>
                ..
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
            </ul>

jquery change style of a div on click

$(document).ready(function() {
  $('#div_one').bind('click', function() {
    $('#div_two').addClass('large');
  });
});

If I understood your question.

Or you can modify css directly:

var $speech = $('div.speech');
var currentSize = $speech.css('fontSize');
$speech.css('fontSize', '10px');

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

The difference between them is that they use different pins. Seriously, that's it. The reason they both exist is that RTS/CTS wasn't supposed to ever be a flow control mechanism, originally; it was for half-duplex modems to coordinate who was sending and who was receiving. RTS and CTS got misused for flow control so often that it became standard.

Build a simple HTTP server in C

An HTTP server is conceptually simple:

  • Open port 80 for listening
  • When contact is made, gather a little information (get mainly - you can ignore the rest for now)
  • Translate the request into a file request
  • Open the file and spit it back at the client

It gets more difficult depending on how much of HTTP you want to support - POST is a little more complicated, scripts, handling multiple requests, etc.

But the base is very simple.

Run R script from command line

How to run Rmd in command with knitr and rmarkdown by multiple commands and then Upload an HTML file to RPubs

Here is a example: load two libraries and run a R command

R -e 'library("rmarkdown");library("knitr");rmarkdown::render("NormalDevconJuly.Rmd")'

R -e 'library("markdown");rpubsUpload("normalDev","NormalDevconJuly.html")'

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Just to add,

const foo = function(){ return "foo" } //this doesn't add a semicolon here.
(function (){
    console.log("aa");
})()

see this, using immediately invoked function expression(IIFE)

How do I set the timeout for a JAX-WS webservice client?

Here is my working solution :

// --------------------------
// SOAP Message creation
// --------------------------
SOAPMessage sm = MessageFactory.newInstance().createMessage();
sm.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
sm.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");

SOAPPart sp = sm.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
se.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
se.setAttribute("xmlns:SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/");
se.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
se.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");

SOAPBody sb = sm.getSOAPBody();
// 
// Add all input fields here ...
// 

SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
// -----------------------------------
// URL creation with TimeOut connexion
// -----------------------------------
URL endpoint = new URL(null,
                      "http://myDomain/myWebService.php",
                    new URLStreamHandler() { // Anonymous (inline) class
                    @Override
                    protected URLConnection openConnection(URL url) throws IOException {
                    URL clone_url = new URL(url.toString());
                    HttpURLConnection clone_urlconnection = (HttpURLConnection) clone_url.openConnection();
                    // TimeOut settings
                    clone_urlconnection.setConnectTimeout(10000);
                    clone_urlconnection.setReadTimeout(10000);
                    return(clone_urlconnection);
                    }
                });


try {
    // -----------------
    // Send SOAP message
    // -----------------
    SOAPMessage retour = connection.call(sm, endpoint);
}
catch(Exception e) {
    if ((e instanceof com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl) && (e.getCause()!=null) && (e.getCause().getCause()!=null) && (e.getCause().getCause().getCause()!=null)) {
        System.err.println("[" + e + "] Error sending SOAP message. Initial error cause = " + e.getCause().getCause().getCause());
    }
    else {
        System.err.println("[" + e + "] Error sending SOAP message.");

    }
}

How to get current instance name from T-SQL

How about this:

EXECUTE xp_regread @rootkey='HKEY_LOCAL_MACHINE',
                   @key='SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQl',
                   @value_name='MSSQLSERVER'

This will get the instance name as well. null means default instance:

SELECT SERVERPROPERTY ('InstanceName')

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

Link error "undefined reference to `__gxx_personality_v0'" and g++

If g++ still gives error Try using:

g++ file.c -lstdc++

Look at this post: What is __gxx_personality_v0 for?

Make sure -lstdc++ is at the end of the command. If you place it at the beginning (i.e. before file.c), you still can get this same error.

Display Last Saved Date on worksheet

May be this time stamp fit you better Code

Function LastInputTimeStamp() As Date
  LastInputTimeStamp = Now()
End Function

and each time you input data in defined cell (in my example below it is cell C36) you'll get a new constant time stamp. As an example in Excel file may use this

=IF(C36>0,LastInputTimeStamp(),"")

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

ASP.NET MVC Conditional validation

You can disable validators conditionally by removing errors from ModelState:

ModelState["DependentProperty"].Errors.Clear();

MySQL LEFT JOIN Multiple Conditions

Just move the extra condition into the JOIN ON criteria, this way the existence of b is not required to return a result

SELECT a.* FROM a 
    LEFT JOIN b ON a.group_id=b.group_id AND b.user_id!=$_SESSION{['user_id']} 
    WHERE a.keyword LIKE '%".$keyword."%' 
    GROUP BY group_id

String formatting in Python 3

Python 3.6 now supports shorthand literal string interpolation with PEP 498. For your use case, the new syntax is simply:

f"({self.goals} goals, ${self.penalties})"

This is similar to the previous .format standard, but lets one easily do things like:

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal('12.34567')
>>> f'result: {value:{width}.{precision}}'
'result:      12.35'

How to search contents of multiple pdf files?

Recoll is a fantastic full-text GUI search application for Unix/Linux that supports dozens of different formats, including PDF. It can even pass the exact page number and search term of a query to the document viewer and thus allows you to jump to the result right from its GUI.

Recoll also comes with a viable command-line interface and a web-browser interface.

Calculate difference between two dates (number of days)?

Use TimeSpan object which is the result of date substraction:

DateTime d1;
DateTime d2;
return (d1 - d2).TotalDays;

The source was not found, but some or all event logs could not be searched

Had the same exception. In my case, I had to run Command Prompt with Administrator Rights.

From the Start Menu, right click on Command Prompt, select "Run as administrator".

JPanel vs JFrame in Java

JFrame is the window; it can have one or more JPanel instances inside it. JPanel is not the window.

You need a Swing tutorial:

http://docs.oracle.com/javase/tutorial/uiswing/

How to mkdir only if a directory does not already exist?

If you don't want to show any error message:

[ -d newdir ] || mkdir newdir

If you want to show your own error message:

[ -d newdir ] && echo "Directory Exists" || mkdir newdir

Convert objective-c typedef to its string equivalent

I combined several approaches here. I like the idea of the preprocessor and the indexed list.

There's no extra dynamic allocation, and because of the inlining the compiler might be able to optimize the lookup.

typedef NS_ENUM(NSUInteger, FormatType) { FormatTypeJSON = 0, FormatTypeXML, FormatTypeAtom, FormatTypeRSS, FormatTypeCount };

NS_INLINE NSString *FormatTypeToString(FormatType t) {
  if (t >= FormatTypeCount)
    return nil;

#define FormatTypeMapping(value) [value] = @#value

  NSString *table[FormatTypeCount] = {FormatTypeMapping(FormatTypeJSON),
                                      FormatTypeMapping(FormatTypeXML),
                                      FormatTypeMapping(FormatTypeAtom),
                                      FormatTypeMapping(FormatTypeRSS)};

#undef FormatTypeMapping

  return table[t];
}

jQuery + client-side template = "Syntax error, unrecognized expression"

You can use

var modal_template_html = $.trim($('#modal_template').html());
var template = $(modal_template_html);

How can I enable the Windows Server Task Scheduler History recording?

Win 8.1 Pro

Brian Clark's answer above worked for me, but I'm posting here for those who may have to follow a slightly different sequence as I did.

When I ran Control Panel > Administrative Tools > Right Click Task Scheduler - 'Run as Administrator', I found the Actions pane to already contain the following action:

Disable All Tasks History

So my machine already had History enabled. But my machine needed to disable history first, then go back and 'Enable All Tasks History'. After that, my History showed up and I received no more errors. I'm assuming that action performed some type of initialization or setup that was never done properly from all the way back to OS installation.

I will also add that I had to exit Task Scheduler and reenter it before I could toggle the History Enable/Disable setting back and forth.

Java Mouse Event Right Click

Yes, take a look at this thread which talks about the differences between platforms.

How to detect right-click event for Mac OS

BUTTON3 is the same across all platforms, being equal to the right mouse button. BUTTON2 is simply ignored if the middle button does not exist.

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

I was getting this same warning everytime I was doing 'maven clean'. I found the solution :

Step - 1 Right click on your project in Eclipse

Step - 2 Click Properties

Step - 3 Select Maven in the left hand side list.

Step - 4 You will notice "pom.xml" in the Active Maven Profiles text box on the right hand side. Clear it and click Apply.

Below is the screen shot :

Properties dialog box

Hope this helps. :)

Common MySQL fields and their appropriate data types

Since you're going to be dealing with data of a variable length (names, email addresses), then you'd be wanting to use VARCHAR. The amount of space taken up by a VARCHAR field is [field length] + 1 bytes, up to max length 255, so I wouldn't worry too much about trying to find a perfect size. Take a look at what you'd imagine might be the longest length might be, then double it and set that as your VARCHAR limit. That said...:

I generally set email fields to be VARCHAR(100) - i haven't come up with a problem from that yet. Names I set to VARCHAR(50).

As the others have said, phone numbers and zip/postal codes are not actually numeric values, they're strings containing the digits 0-9 (and sometimes more!), and therefore you should treat them as a string. VARCHAR(20) should be well sufficient.

Note that if you were to store phone numbers as integers, many systems will assume that a number starting with 0 is an octal (base 8) number! Therefore, the perfectly valid phone number "0731602412" would get put into your database as the decimal number "124192010"!!

Using logging in multiple modules

Throwing in another solution.

In my module's init.py I have something like:

# mymodule/__init__.py
import logging

def get_module_logger(mod_name):
  logger = logging.getLogger(mod_name)
  handler = logging.StreamHandler()
  formatter = logging.Formatter(
        '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
  handler.setFormatter(formatter)
  logger.addHandler(handler)
  logger.setLevel(logging.DEBUG)
  return logger

Then in each module I need a logger, I do:

# mymodule/foo.py
from [modname] import get_module_logger
logger = get_module_logger(__name__)

When the logs are missed, you can differentiate their source by the module they came from.

Creating folders inside a GitHub repository without using Git

Another thing you can do is just drag a folder from your computer into the GitHub repository page. This folder does have to have at least 1 item in it, though.

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

To my knowledge, StackOverflow has lots of people asking this question in various ways, but nobody has answered it completely yet.

My spec called for the user to be able to choose email, twitter, facebook, or SMS, with custom text for each one. Here is how I accomplished that:

public void onShareClick(View v) {
    Resources resources = getResources();

    Intent emailIntent = new Intent();
    emailIntent.setAction(Intent.ACTION_SEND);
    // Native email client doesn't currently support HTML, but it doesn't hurt to try in case they fix it
    emailIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(resources.getString(R.string.share_email_native)));
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, resources.getString(R.string.share_email_subject));
    emailIntent.setType("message/rfc822");

    PackageManager pm = getPackageManager();
    Intent sendIntent = new Intent(Intent.ACTION_SEND);     
    sendIntent.setType("text/plain");


    Intent openInChooser = Intent.createChooser(emailIntent, resources.getString(R.string.share_chooser_text));

    List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
    List<LabeledIntent> intentList = new ArrayList<LabeledIntent>();        
    for (int i = 0; i < resInfo.size(); i++) {
        // Extract the label, append it, and repackage it in a LabeledIntent
        ResolveInfo ri = resInfo.get(i);
        String packageName = ri.activityInfo.packageName;
        if(packageName.contains("android.email")) {
            emailIntent.setPackage(packageName);
        } else if(packageName.contains("twitter") || packageName.contains("facebook") || packageName.contains("mms") || packageName.contains("android.gm")) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("text/plain");
            if(packageName.contains("twitter")) {
                intent.putExtra(Intent.EXTRA_TEXT, resources.getString(R.string.share_twitter));
            } else if(packageName.contains("facebook")) {
                // Warning: Facebook IGNORES our text. They say "These fields are intended for users to express themselves. Pre-filling these fields erodes the authenticity of the user voice."
                // One workaround is to use the Facebook SDK to post, but that doesn't allow the user to choose how they want to share. We can also make a custom landing page, and the link
                // will show the <meta content ="..."> text from that page with our link in Facebook.
                intent.putExtra(Intent.EXTRA_TEXT, resources.getString(R.string.share_facebook));
            } else if(packageName.contains("mms")) {
                intent.putExtra(Intent.EXTRA_TEXT, resources.getString(R.string.share_sms));
            } else if(packageName.contains("android.gm")) { // If Gmail shows up twice, try removing this else-if clause and the reference to "android.gm" above
                intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(resources.getString(R.string.share_email_gmail)));
                intent.putExtra(Intent.EXTRA_SUBJECT, resources.getString(R.string.share_email_subject));               
                intent.setType("message/rfc822");
            }

            intentList.add(new LabeledIntent(intent, packageName, ri.loadLabel(pm), ri.icon));
        }
    }

    // convert intentList to array
    LabeledIntent[] extraIntents = intentList.toArray( new LabeledIntent[ intentList.size() ]);

    openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
    startActivity(openInChooser);       
}

I found bits of how to do this in various places, but I haven't seen all of it in one place anywhere else.

Note that this method also hides all the silly options that I don't want, like sharing over wifi and bluetooth.

Hope this helps someone.

Edit: In a comment, I was asked to explain what this code is doing. Basically, it's creating an ACTION_SEND intent for the native email client ONLY, then tacking other intents onto the chooser. Making the original intent email-specific gets rid of all the extra junk like wifi and bluetooth, then I grab the other intents I want from a generic ACTION_SEND of type plain-text, and tack them on before showing the chooser.

When I grab the additional intents, I set custom text for each one.

Edit2: It's been awhile since I posted this, and things have changed a bit. If you are seeing gmail twice in the list of options, try removing the special handling for "android.gm" as suggested in a comment by @h_k below.

Since this one answer is the source of nearly all my stackoverflow reputation points, I have to at least try to keep it up to date.

Create a unique number with javascript time

Since milliseconds are not updated every millisecond in node, following is an answer. This generates a unique human readable ticket number. I am new to programming and nodejs. Please correct me if I am wrong.

function get2Digit(value) {
if (value.length == 1) return "0" + "" + value;
else return value;

}

function get3Digit(value) {
if (value.length == 1) return "00" + "" + value;
else return value;

}

function generateID() {
    var d = new Date();
    var year = d.getFullYear();
    var month = get2Digit(d.getMonth() + 1);
    var date = get2Digit(d.getDate());
    var hours = get2Digit(d.getHours());
    var minutes = get2Digit(d.getMinutes());
    var seconds = get2Digit(d.getSeconds());
    var millSeconds = get2Digit(d.getMilliseconds());
    var dateValue = year + "" + month + "" + date;
    var uniqueID = hours + "" + minutes + "" + seconds + "" + millSeconds;

    if (lastUniqueID == "false" || lastUniqueID < uniqueID) lastUniqueID = uniqueID;
    else lastUniqueID = Number(lastUniqueID) + 1;
    return dateValue + "" + lastUniqueID;
}

Equivalent of SQL ISNULL in LINQ?

Looks like the type is boolean and therefore can never be null and should be false by default.

Why do people write #!/usr/bin/env python on the first line of a Python script?

If you're running your script in a virtual environment, say venv, then executing which python while working on venv will display the path to the Python interpreter:

~/Envs/venv/bin/python

Note that the name of the virtual environment is embedded in the path to the Python interpreter. Therefore, hardcoding this path in your script will cause two problems:

  • If you upload the script to a repository, you're forcing other users to have the same virtual environment name. This is if they identify the problem first.
  • You won't be able to run the script across multiple virtual environments even if you had all required packages in other virtual environments.

Therefore, to add to Jonathan's answer, the ideal shebang is #!/usr/bin/env python, not just for portability across OSes but for portability across virtual environments as well!

What are the retransmission rules for TCP?

What exactly are the rules for requesting retransmission of lost data?

The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.

Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ

are detailed in the RFC 3366.

At what time frequency are the retransmission requests performed?

The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)

The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.

Is there an upper bound on the number?

Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.

Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?

The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)

How to disable anchor "jump" when loading a page?

See my answer here: Stackoverflow Answer

The trick is to just remove the hashtag ASAP and store its value for your own use:

It is important that you do not put that part of the code in the $() or $(window).load() functions as it would be too late and the browser already has moved to the tag.

// store the hash (DON'T put this code inside the $() function, it has to be executed 
// right away before the browser can start scrolling!
var target = window.location.hash,
    target = target.replace('#', '');

// delete hash so the page won't scroll to it
window.location.hash = "";

// now whenever you are ready do whatever you want
// (in this case I use jQuery to scroll to the tag after the page has loaded)
$(window).on('load', function() {
    if (target) {
        $('html, body').animate({
            scrollTop: $("#" + target).offset().top
        }, 700, 'swing', function () {});
    }
});

How to use sed to extract substring

sed 's/[^"]*"\([^"]*\).*/\1/'

does the job.

explanation of the part inside ' '

  • s - tells sed to substitute
  • / - start of regex string to search for
  • [^"]* - any character that is not ", any number of times. (matching parameter name=)
  • " - just a ".
  • ([^"]*) - anything inside () will be saved for reference to use later. The \ are there so the brackets are not considered as characters to search for. [^"]* means the same as above. (matching RemoteHost for example)
  • .* - any character, any number of times. (matching " access="readWrite"> /parameter)
  • / - end of the search regex, and start of the substitute string.
  • \1 - reference to that string we found in the brackets above.
  • / end of the substitute string.

basically s/search for this/replace with this/ but we're telling him to replace the whole line with just a piece of it we found earlier.

Laravel blade check empty foreach

Check the documentation for the best result:

@forelse($status->replies as $reply)
    <p>{{ $reply->body }}</p>
@empty
    <p>No replies</p>
@endforelse