Programs & Examples On #Email processing

Trim spaces from start and end of string

Here is some methods I've been used in the past to trim strings in js:

String.prototype.ltrim = function( chars ) {
    chars = chars || "\\s*";
    return this.replace( new RegExp("^[" + chars + "]+", "g"), "" );
}

String.prototype.rtrim = function( chars ) {
    chars = chars || "\\s*";
    return this.replace( new RegExp("[" + chars + "]+$", "g"), "" );
}
String.prototype.trim = function( chars ) {
    return this.rtrim(chars).ltrim(chars);
}

How to change the output color of echo in Linux

to show the message output with diffrent color you can make :

echo -e "\033[31;1mYour Message\033[0m"

-Black 0;30 Dark Gray 1;30

-Red 0;31 Light Red 1;31

-Green 0;32 Light Green 1;32

-Brown/Orange 0;33 Yellow 1;33

-Blue 0;34 Light Blue 1;34

-Purple 0;35 Light Purple 1;35

-Cyan 0;36 Light Cyan 1;36

-Light Gray 0;37 White 1;37

iOS - Dismiss keyboard when touching outside of UITextField

Just to add to the list here my version of how to dismiss a keyboard on outside touch.

viewDidLoad:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleTap];

Anywhere:

-(void)handleSingleTap:(UITapGestureRecognizer *)sender{
    [textFieldName resignFirstResponder];
    puts("Dismissed the keyboard");
}

Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID

As Rahul stated, it is a common Chrome and an OSX bug. I was having similar issues in the past. In fact I finally got tired of making the 2 [yes I know it is not many] additional clicks when testing a local site for work.

As for a possible workaround to this issue [using Windows], I would using one of the many self signing certificate utilities available.

Recommended Steps:

  1. Create a Self Signed Cert
  2. Import Certificate into Windows Certificate Manager
  3. Import Certificate in Chrome Certificate Manager
    NOTE: Step 3 will resolve the issue experienced once Google addresses the bug...considering the time in has been stale there is no ETA in the foreseeable future.**

    As much as I prefer to use Chrome for development, I have found myself in Firefox Developer Edition lately. which does not have this issue.

    Hope this helps :)

SPA best practices for authentication and session management

This question has been addressed, in a slightly different form, at length, here:

RESTful Authentication

But this addresses it from the server-side. Let's look at this from the client-side. Before we do that, though, there's an important prelude:

Javascript Crypto is Hopeless

Matasano's article on this is famous, but the lessons contained therein are pretty important:

https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/

To summarize:

  • A man-in-the-middle attack can trivially replace your crypto code with <script> function hash_algorithm(password){ lol_nope_send_it_to_me_instead(password); }</script>
  • A man-in-the-middle attack is trivial against a page that serves any resource over a non-SSL connection.
  • Once you have SSL, you're using real crypto anyways.

And to add a corollary of my own:

  • A successful XSS attack can result in an attacker executing code on your client's browser, even if you're using SSL - so even if you've got every hatch battened down, your browser crypto can still fail if your attacker finds a way to execute any javascript code on someone else's browser.

This renders a lot of RESTful authentication schemes impossible or silly if you're intending to use a JavaScript client. Let's look!

HTTP Basic Auth

First and foremost, HTTP Basic Auth. The simplest of schemes: simply pass a name and password with every request.

This, of course, absolutely requires SSL, because you're passing a Base64 (reversibly) encoded name and password with every request. Anybody listening on the line could extract username and password trivially. Most of the "Basic Auth is insecure" arguments come from a place of "Basic Auth over HTTP" which is an awful idea.

The browser provides baked-in HTTP Basic Auth support, but it is ugly as sin and you probably shouldn't use it for your app. The alternative, though, is to stash username and password in JavaScript.

This is the most RESTful solution. The server requires no knowledge of state whatsoever and authenticates every individual interaction with the user. Some REST enthusiasts (mostly strawmen) insist that maintaining any sort of state is heresy and will froth at the mouth if you think of any other authentication method. There are theoretical benefits to this sort of standards-compliance - it's supported by Apache out of the box - you could store your objects as files in folders protected by .htaccess files if your heart desired!

The problem? You are caching on the client-side a username and password. This gives evil.ru a better crack at it - even the most basic of XSS vulnerabilities could result in the client beaming his username and password to an evil server. You could try to alleviate this risk by hashing and salting the password, but remember: JavaScript Crypto is Hopeless. You could alleviate this risk by leaving it up to the Browser's Basic Auth support, but.. ugly as sin, as mentioned earlier.

HTTP Digest Auth

Is Digest authentication possible with jQuery?

A more "secure" auth, this is a request/response hash challenge. Except JavaScript Crypto is Hopeless, so it only works over SSL and you still have to cache the username and password on the client side, making it more complicated than HTTP Basic Auth but no more secure.

Query Authentication with Additional Signature Parameters.

Another more "secure" auth, where you encrypt your parameters with nonce and timing data (to protect against repeat and timing attacks) and send the. One of the best examples of this is the OAuth 1.0 protocol, which is, as far as I know, a pretty stonking way to implement authentication on a REST server.

http://tools.ietf.org/html/rfc5849

Oh, but there aren't any OAuth 1.0 clients for JavaScript. Why?

JavaScript Crypto is Hopeless, remember. JavaScript can't participate in OAuth 1.0 without SSL, and you still have to store the client's username and password locally - which puts this in the same category as Digest Auth - it's more complicated than HTTP Basic Auth but it's no more secure.

Token

The user sends a username and password, and in exchange gets a token that can be used to authenticate requests.

This is marginally more secure than HTTP Basic Auth, because as soon as the username/password transaction is complete you can discard the sensitive data. It's also less RESTful, as tokens constitute "state" and make the server implementation more complicated.

SSL Still

The rub though, is that you still have to send that initial username and password to get a token. Sensitive information still touches your compromisable JavaScript.

To protect your user's credentials, you still need to keep attackers out of your JavaScript, and you still need to send a username and password over the wire. SSL Required.

Token Expiry

It's common to enforce token policies like "hey, when this token has been around too long, discard it and make the user authenticate again." or "I'm pretty sure that the only IP address allowed to use this token is XXX.XXX.XXX.XXX". Many of these policies are pretty good ideas.

Firesheeping

However, using a token Without SSL is still vulnerable to an attack called 'sidejacking': http://codebutler.github.io/firesheep/

The attacker doesn't get your user's credentials, but they can still pretend to be your user, which can be pretty bad.

tl;dr: Sending unencrypted tokens over the wire means that attackers can easily nab those tokens and pretend to be your user. FireSheep is a program that makes this very easy.

A Separate, More Secure Zone

The larger the application that you're running, the harder it is to absolutely ensure that they won't be able to inject some code that changes how you process sensitive data. Do you absolutely trust your CDN? Your advertisers? Your own code base?

Common for credit card details and less common for username and password - some implementers keep 'sensitive data entry' on a separate page from the rest of their application, a page that can be tightly controlled and locked down as best as possible, preferably one that is difficult to phish users with.

Cookie (just means Token)

It is possible (and common) to put the authentication token in a cookie. This doesn't change any of the properties of auth with the token, it's more of a convenience thing. All of the previous arguments still apply.

Session (still just means Token)

Session Auth is just Token authentication, but with a few differences that make it seem like a slightly different thing:

  • Users start with an unauthenticated token.
  • The backend maintains a 'state' object that is tied to a user's token.
  • The token is provided in a cookie.
  • The application environment abstracts the details away from you.

Aside from that, though, it's no different from Token Auth, really.

This wanders even further from a RESTful implementation - with state objects you're going further and further down the path of plain ol' RPC on a stateful server.

OAuth 2.0

OAuth 2.0 looks at the problem of "How does Software A give Software B access to User X's data without Software B having access to User X's login credentials."

The implementation is very much just a standard way for a user to get a token, and then for a third party service to go "yep, this user and this token match, and you can get some of their data from us now."

Fundamentally, though, OAuth 2.0 is just a token protocol. It exhibits the same properties as other token protocols - you still need SSL to protect those tokens - it just changes up how those tokens are generated.

There are two ways that OAuth 2.0 can help you:

  • Providing Authentication/Information to Others
  • Getting Authentication/Information from Others

But when it comes down to it, you're just... using tokens.

Back to your question

So, the question that you're asking is "should I store my token in a cookie and have my environment's automatic session management take care of the details, or should I store my token in Javascript and handle those details myself?"

And the answer is: do whatever makes you happy.

The thing about automatic session management, though, is that there's a lot of magic happening behind the scenes for you. Often it's nicer to be in control of those details yourself.

I am 21 so SSL is yes

The other answer is: Use https for everything or brigands will steal your users' passwords and tokens.

How to get the previous url using PHP

But you could make an own link for every from url.

Example: http://example.com?auth=holasite

In this example your site is: example.com

If somebody open that link it's give you the holasite value for the auth variable.

Then just $_GET['auth'] and you have the variable. But you should have a database to store it, and to authorize.

Like: $holasite = http://holasite.com (You could use mysql too..)

And just match it, and you have the url.

This method is a little bit more complicated, but it works. This method is good for a referral system authentication. But where is the site name, you should write an id, and works with that id.

How to set image to UIImage

Try this code to 100% work....

UIImageView * imageview = [[UIImageView alloc] initWithFrame:CGRectMake(20,100, 80, 80)];
imageview.image = [UIImage imageNamed:@"myimage.jpg"];
[self.view  addSubview:imageview];

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

I tried the steps mentioned by @bcmoney but for me the current version was already set to the latest version. In my it was Java8.

I had various versions of java installed (java6, java7 and java8). I got the same error but instead of 1.5 and 1.7 i got 1.7 and 1.8. I uninstalled java6 on my windows 8.1 machine. After which i tried java -version in command prompt and the error did not appear.

I am not sure whether this is the right answer but it worked for me so i thought it would help the community too.

How do I spool to a CSV formatted file using SQLPLUS?

I know this is an old thread, however I noticed that no one mentioned the underline option, which can remove the underlines under the column headings.

set pagesize 50000--50k is the max as of 12c
set linesize 10000   
set trimspool on  --remove trailing blankspaces
set underline off --remove the dashes/underlines under the col headers
set colsep ~

select * from DW_TMC_PROJECT_VW;

Class has been compiled by a more recent version of the Java Environment

I had a similar issue from the console after building a Jar in Intellij. Using the Java configuration to update to a newer version (Windows -> Configure Java -> Update -> Update Now) didn't work and stuck at version 1.8 (Java 8).

To switch to a more recent version locally I had to install the Java 15 JDK from https://www.oracle.com/uk/java/technologies/javase-jdk15-downloads.html and add that to my Java runtime environment settings.

Java Runtime Environment Settings

How to activate a specific worksheet in Excel?

An alternative way to (not dynamically) link a text to activate a worksheet without macros is to make the selected string an actual link. You can do this by selecting the cell that contains the text and press CTRL+K then select the option/tab 'Place in this document' and select the tab you want to activate. If you would click the text (that is now a link) the configured sheet will become active/selected.

How can I control Chromedriver open window size?

If you're using the Facebook language binding for php try this:

$driver->manage()->window()->setSize(new WebDriverDimension(1024,768));

Enterprise app deployment doesn't work on iOS 7.1

Our team uses dropbox for ad-hoc distribution which uses https but still our app was failing to install. After much trouble-shooting we realized that the title field is required too. Whenever we sent out a link without this field safari ignored the link and did not prompt the user to install. Sometimes for quick development tests we skipped over the title node in the xml and not populate it. In case this is helpful for anyone having this issue make sure that your .plist contains the following nodes populated:

      ....
     <string>software</string>
    <key>title</key>
     <string>Your App Name</string>
      ...

How to create cron job using PHP?

Create a cronjob like this to work on every minute

*       *       *       *       *       /usr/bin/php path/to/cron.php &> /dev/null

Refresh/reload the content in Div using jquery/ajax

I always use this, works perfect.

$(document).ready(function(){
        $(function(){
        $('#ideal_form').submit(function(e){
                e.preventDefault();
                var form = $(this);
                var post_url = form.attr('action');
                var post_data = form.serialize();
                $('#loader3', form).html('<img src="../../images/ajax-loader.gif" />       Please wait...');
                $.ajax({
                    type: 'POST',
                    url: post_url, 
                    data: post_data,
                    success: function(msg) {
                        $(form).fadeOut(800, function(){
                            form.html(msg).fadeIn().delay(2000);

                        });
                    }
                });
            });
        });
         });

Mysql select distinct

You can use DISTINCT like that

mysql_query("SELECT DISTINCT(ticket_id), column1, column2, column3 
FROM temp_tickets 
ORDER BY ticket_id");

How to read a file in reverse order?

for line in reversed(open("file").readlines()):
    print line.rstrip()

If you are on linux, you can use tac command.

$ tac file

2 recipes you can find in ActiveState here and here

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

Here is another way you can change the selected option of a <select> element in javascript. You can use

document.getElementById('salesperson').selectedIndex=1;

Setting it to 1 will make the second element of the dropdown selected. The select element index start from 0.

Here is a sample code. Check if you can use this type of approach:

<html>
<head>
<script language="javascript">

function changeSelected() { 
document.getElementById('salesperson').selectedIndex=1;

} 

</script>
</head>
<body>
<form name="f1">

<select id="salesperson" > 
   <option value"">james</option>
   <option value"">john</option>  
</select> 
<input type="button" value="Change Selected" onClick="changeSelected();">

</form>
</body>
</html>

XCOPY switch to create specified directory if it doesn't exist?

I tried this on the command line using

D:\>xcopy myfile.dat xcopytest\test\

and the target directory was properly created.

If not you can create the target dir using the mkdir command with cmd's command extensions enabled like

cmd /x /c mkdir "$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules\"

('/x' enables command extensions in case they're not enabled by default on your system, I'm not that familiar with cmd)

use

cmd /? 
mkdir /?
xcopy /?

for further information :)

fatal error LNK1169: one or more multiply defined symbols found in game programming

The two int variables are defined in the header file. This means that every source file which includes the header will contain their definition (header inclusion is purely textual). The of course leads to multiple definition errors.

You have several options to fix this.

  1. Make the variables static (static int WIDTH = 1024;). They will still exist in each source file, but their definitions will not be visible outside of the source file.

  2. Turn their definitions into declarations by using extern (extern int WIDTH;) and put the definition into one source file: int WIDTH = 1024;.

  3. Probably the best option: make the variables const (const int WIDTH = 1024;). This makes them static implicitly, and also allows them to be used as compile-time constants, allowing the compiler to use their value directly instead of issuing code to read it from the variable etc.

How to enable explicit_defaults_for_timestamp?

On Windows you can run server with option key, no need to change ini files.

"C:\mysql\bin\mysqld.exe" --explicit_defaults_for_timestamp=1

Where to get this Java.exe file for a SQL Developer installation

You must install the latest Java SE Development Kit (note not the Java SE Runtime Environment ) and provide the path ex C:\Program Files\Java\jdk1.6.0_41

How to import data from one sheet to another

VLookup

You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4". VLOOKUP example

External Reference

To reference a cell of the same Workbook use the following pattern:

<Sheetname>!<Cell>

Example:

Table1!A1

To reference a cell of a different Workbook use this pattern:

[<Workbook_name>]<Sheetname>!<Cell>

Example:

[MyWorkbook]Table1!A1

Multiple variables in a 'with' statement?

I think you want to do this instead:

from __future__ import with_statement

with open("out.txt","wt") as file_out:
    with open("in.txt") as file_in:
        for line in file_in:
            file_out.write(line)

jQuery textbox change event doesn't fire until textbox loses focus?

if you write anything in your textbox, the event gets fired.
code as follows :

HTML:

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

JS:

<script type="text/javascript">
  $(function () {
      $("#textbox").bind('input', function() {
      alert("letter entered");
      });
   });
</script>

Know relationships between all the tables of database in SQL Server

select * from information_schema.REFERENTIAL_CONSTRAINTS where 
UNIQUE_CONSTRAINT_SCHEMA = 'TABLE_NAME' 

This will list the column with TABLE_NAME and REFERENCED_COLUMN_NAME.

Print page numbers on pages when printing html

Can you try this, you can use content: counter(page);

     @page {
       @bottom-left {
            content: counter(page) "/" counter(pages);
        }
     }

Ref: http://www.w3.org/TR/CSS21/generate.html#counters

http://www.princexml.com/doc/9.0/page-numbers/

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

How to retrieve GET parameters from JavaScript

You can use the search function available in the location object. The search function gives the parameter part of the URL. Details can be found in Location Object.

You will have to parse the resulting string for getting the variables and their values, e.g. splitting them on '='.

HTML table with fixed headers?

I've just completed putting together a jQuery plugin that will take valid single table using valid HTML (have to have a thead and tbody) and will output a table that has fixed headers, optional fixed footer that can either be a cloned header or any content you chose (pagination, etc.). If you want to take advantage of larger monitors it will also resize the table when the browser is resized. Another added feature is being able to side scroll if the table columns can not all fit in view.

http://fixedheadertable.com/

on github: http://markmalek.github.com/Fixed-Header-Table/

It's extremely easy to setup and you can create your own custom styles for it. It also uses rounded corners in all browsers. Keep in mind I just released it, so it's still technically beta and there are very few minor issues I'm ironing out.

It works in Internet Explorer 7, Internet Explorer 8, Safari, Firefox and Chrome.

Image height and width not working?

http://www.markrafferty.com/wp-content/w3tc/min/7415c412.e68ae1.css

Line 11:

.postItem img {
    height: auto;
    width: 450px;
}

You can either edit your CSS, or you can listen to Mageek and use INLINE STYLING to override the CSS styling that's happening:

<img src="theSource" style="width:30px;" />

Avoid setting both width and height, as the image itself might not be scaled proportionally. But you can set the dimensions to whatever you want, as per Mageek's example.

jQuery.click() vs onClick

Most of the time, native JavaScript methods are a better choice over jQuery when performance is the only criteria, but jQuery makes use of JavaScript and makes the development easy. You can use jQuery as it does not degrade performance too much. In your specific case, the difference of performance is ignorable.

How To Launch Git Bash from DOS Command Line?

The answer by Endoro has aged and I'm unable to comment;

# if you want to launch from a batch file or the command line:

start "" "%ProgramFiles%\Git\bin\sh.exe" --login

How to get file extension from string in C++

If you consider the extension as the last dot and the possible characters after it, but only if they don't contain the directory separator character, the following function returns the extension starting index, or -1 if no extension found. When you have that you can do what ever you want, like strip the extension, change it, check it etc.

long get_extension_index(string path, char dir_separator = '/') {
    // Look from the end for the first '.',
    // but give up if finding a dir separator char first
    for(long i = path.length() - 1; i >= 0; --i) {
        if(path[i] == '.') {
            return i;
        }
        if(path[i] == dir_separator) {
            return -1;
        }
    }
    return -1;
}

Best XML Parser for PHP

It depends on what you are trying to do with the XML files. If you are just trying to read the XML file (like a configuration file), The Wicked Flea is correct in suggesting SimpleXML since it creates what amounts to nested ArrayObjects. e.g. value will be accessible by $xml->root->child.

If you are looking to manipulate the XML files you're probably best off using DOM XML

Oracle : how to subtract two dates and get minutes of the result

When you subtract two dates in Oracle, you get the number of days between the two values. So you just have to multiply to get the result in minutes instead:

SELECT (date2 - date1) * 24 * 60 AS minutesBetween
FROM ...

Excel: Search for a list of strings within a particular string using array formulas?

This will return the matching word or an error if no match is found. For this example I used the following.

List of words to search for: G1:G7
Cell to search in: A1

=INDEX(G1:G7,MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*(ROW(G1:G7)-ROW(G1)+1)))

Enter as an array formula by pressing Ctrl+Shift+Enter.

This formula works by first looking through the list of words to find matches, then recording the position of the word in the list as a positive value if it is found or as a negative value if it is not found. The largest value from this array is the position of the found word in the list. If no word is found, a negative value is passed into the INDEX() function, throwing an error.

To return the row number of a matching word, you can use the following:

=MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*ROW(G1:G7))

This also must be entered as an array formula by pressing Ctrl+Shift+Enter. It will return -1 if no match is found.

JavaScript Chart Library

It maybe not exactly what you are looking for, but
Google's Chart API is pretty cool and easy to use.

Is there a Subversion command to reset the working copy?

Very quick and simple and does exactly what you want

svn status | awk '{if($2 !~ /(config|\.ini)/ && !system("test -e \"" $2 "\"")) {print $2; system("rm -Rf \"" $2 "\"");}}'

The /(config|.ini)/ is for my own purposes.

And might be a good idea to add --no-ignore to the svn command

How to use mongoimport to import csv

I was perplexed with a similar problem where mongoimport did not give me an error but would report importing 0 records. I had saved my file that didn't work using the OSX Excel for Mac 2011 version using the default "Save as.." "xls as csv" without specifying "Windows Comma Separated(.csv)" format specifically. After researching this site and trying the "Save As again using "Windows Comma Separated (.csv)" format, mongoimport worked fine. I think mongoimport expects a newline character on each line and the default Mac Excel 2011 csv export didn't provide that character at the end of each line.

extract part of a string using bash/cut/split

What about sed? That will work in a single command:

sed 's#.*/\([^:]*\).*#\1#' <<<$string
  • The # are being used for regex dividers instead of / since the string has / in it.
  • .*/ grabs the string up to the last backslash.
  • \( .. \) marks a capture group. This is \([^:]*\).
    • The [^:] says any character _except a colon, and the * means zero or more.
  • .* means the rest of the line.
  • \1 means substitute what was found in the first (and only) capture group. This is the name.

Here's the breakdown matching the string with the regular expression:

        /var/cpanel/users/           joebloggs  :DNS9=domain.com joebloggs
sed 's#.*/                          \([^:]*\)   .*              #\1       #'

Spaces in URLs?

A URL must not contain a literal space. It must either be encoded using the percent-encoding or a different encoding that uses URL-safe characters (like application/x-www-form-urlencoded that uses + instead of %20 for spaces).

But whether the statement is right or wrong depends on the interpretation: Syntactically, a URI must not contain a literal space and it must be encoded; semantically, a %20 is not a space (obviously) but it represents a space.

How to do sed like text replace with python?

You could do something like:

p = re.compile("^\# *deb", re.MULTILINE)
text = open("sources.list", "r").read()
f = open("sources.list", "w")
f.write(p.sub("deb", text))
f.close()

Alternatively (imho, this is better from organizational standpoint) you could split your sources.list into pieces (one entry/one repository) and place them under /etc/apt/sources.list.d/

'AND' vs '&&' as operator

Another nice example using if statements without = assignment operations.

if (true || true && false); // is the same as:
if (true || (true && false)); // TRUE

and

if (true || true AND false); // is the same as:
if ((true || true) && false); // FALSE

because AND has a lower precedence and thus || a higher precedence.

These are different in the cases of true, false, false and true, true, false. See https://ideone.com/lsqovs for en elaborate example.

How to access PHP session variables from jQuery function in a .js file?

If you want to maintain a clearer separation of PHP and JS (it makes syntax highlighting and checking in IDEs easier) then you can create jquery plugins for your code and then pass the $_SESSION['param'] as a variable.

So in page.php:

<script src="my_progress_bar.js"></script>
<script>
$(function () {
    var percent = <?php echo $_SESSION['percent']; ?>;
    $.my_progress_bar(percent);
});
</script>

Then in my_progress_bar.js:

(function ($) {
    $.my_progress_bar = function(percent) {
        $( "#progressbar" ).progressbar({
            value: percent
        });
    };
})(jQuery);

Show Image View from file path?

private void showImage(ImageView img, String absolutePath) {
  
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 8;
    Bitmap bitmapPicture = BitmapFactory.decodeFile(absolutePath);
    img.setImageBitmap(bitmapPicture);

}

How do I rename a repository on GitHub?

If you are the only person working on the project, it's not a big problem, because you only have to do #2.

Let's say your username is someuser and your project is called someproject.

Then your project's URL will be1

[email protected]:someuser/someproject.git

If you rename your project, it will change the someproject part of the URL, e.g.

[email protected]:someuser/newprojectname.git

(see footnote if your URL does not look like this).

Your working copy of Git uses this URL when you do a push or pull.

So after you rename your project, you will have to tell your working copy the new URL.

You can do that in two steps:

Firstly, cd to your local Git directory, and find out what remote name(s) refer to that URL:

$ git remote -v
origin  [email protected]:someuser/someproject.git

Then, set the new URL

$ git remote set-url origin [email protected]:someuser/newprojectname.git

Or in older versions of Git, you might need:

$ git remote rm origin
$ git remote add origin [email protected]:someuser/newprojectname.git

(origin is the most common remote name, but it might be called something else.)

But if there are lots of people who are working on your project, they will all need to do the above steps, and maybe you don't even know how to contact them all to tell them. That's what #1 is about.

Further reading:

Footnotes:

1 The exact format of your URL depends on which protocol you are using, e.g.

How do I grab an INI value within a shell script?

The explanation to the answer for the one-liner sed.

[section1]
param1=123
param2=345
param3=678

[section2]
param1=abc
param2=def
param3=ghi

[section3]
param1=000
param2=111
param3=222
sed -nr "/^\[section2\]/ { :l /^\s*[^#].*/ p; n; /^\[/ q; b l; }" ./file.ini

To understand, it will be easier to format the line like this:

sed -nr "
      # start processing when we found the word \"section2\"
      /^\[section2\]/  { #the set of commands inside { } will be executed
          #create a label \"l\"  (https://www.grymoire.com/Unix/Sed.html#uh-58)
          :l /^\s*[^#].*/ p; 
          # move on to the next line. For the first run it is the \"param1=abc\"
          n; 
          # check if this line is beginning of new section. If yes - then exit.
          /^\[/ q
          #otherwise jump to the label \"l\"
          b l
          }

" file.ini

Python Write bytes to file

If you want to write bytes then you should open the file in binary mode.

f = open('/tmp/output', 'wb')

How to retrieve the hash for the current commit in Git?

Here is another direct-access implementation:

head="$(cat ".git/HEAD")"
while [ "$head" != "${head#ref: }" ]; do
  head="$(cat ".git/${head#ref: }")"
done

This also works over http which is useful for local package archives (I know: for public web sites it's not recommended to make the .git directory accessable):

head="$(curl -s "$baseurl/.git/HEAD")"
while [ "$head" != "${head#ref: }" ]; do
  head="$(curl -s "$baseurl/.git/${head#ref: }")"
done

Pandas - Compute z-score for all columns

Build a list from the columns and remove the column you don't want to calculate the Z score for:

In [66]:
cols = list(df.columns)
cols.remove('ID')
df[cols]

Out[66]:
   Age  BMI  Risk  Factor
0    6   48  19.3       4
1    8   43  20.9     NaN
2    2   39  18.1       3
3    9   41  19.5     NaN
In [68]:
# now iterate over the remaining columns and create a new zscore column
for col in cols:
    col_zscore = col + '_zscore'
    df[col_zscore] = (df[col] - df[col].mean())/df[col].std(ddof=0)
df
Out[68]:
   ID  Age  BMI  Risk  Factor  Age_zscore  BMI_zscore  Risk_zscore  \
0  PT    6   48  19.3       4   -0.093250    1.569614    -0.150946   
1  PT    8   43  20.9     NaN    0.652753    0.074744     1.459148   
2  PT    2   39  18.1       3   -1.585258   -1.121153    -1.358517   
3  PT    9   41  19.5     NaN    1.025755   -0.523205     0.050315   

   Factor_zscore  
0              1  
1            NaN  
2             -1  
3            NaN  

Why doesn't the Scanner class have a nextChar method?

To get a definitive reason, you'd need to ask the designer(s) of that API.

But one possible reason is that the intent of a (hypothetical) nextChar would not fit into the scanning model very well.

  • If nextChar() to behaved like read() on a Reader and simply returned the next unconsumed character from the scanner, then it is behaving inconsistently with the other next<Type> methods. These skip over delimiter characters before they attempt to parse a value.

  • If nextChar() to behaved like (say) nextInt then:

    • the delimiter skipping would be "unexpected" for some folks, and

    • there is the issue of whether it should accept a single "raw" character, or a sequence of digits that are the numeric representation of a char, or maybe even support escaping or something1.

No matter what choice they made, some people wouldn't be happy. My guess is that the designers decided to stay away from the tarpit.


1 - Would vote strongly for the raw character approach ... but the point is that there are alternatives that need to be analysed, etc.

What is the official name for a credit card's 3 digit code?

It's got a number of names. Most likely you've heard it as either Card Security Code (CSC) or Card Verification Value (CVV).

Card Security Code

Difference between logical addresses, and physical addresses?

This answer is by no means exhaustive but it may explain it enough to make things click.

In virtual memory systems, there is a disconnect between logical and physical addresses.

An application can be given a virtual address space of (let's say) 4G. This is its usable memory and it's free to use it as it sees fit. It's a nice contiguous block of memory (from the point of view of the application).

However, it is not the only application running, and the OS has to mediate between them all. Underneath that nice contiguous model, there is a lot of mapping going on to convert logical to physical addresses.

With this mapping, the OS and hardware (I'll just call these the lower layers from here on in) is free to put the application pages anywhere it wants (either in physical memory or swapped out to secondary storage).

When the application tries to access memory at logical address 50, the lower levels can translate that to a physical address using translation tables. And, if it tries to access logical memory that's been swapped out to disk, a page fault is raised and the lower levels can bring the relevant data back into memory, at whatever physical address it wants.

In the bad old days when physical addresses were all you had, code had to be relocatable (or fixed up on load) since it could load anywhere. With virtual memory, that code (and data) can be at logical memory location 50 in a dozen different processes at the same time - it's actual physical address will be different however.

It can even be shared so that one physical copy exists in the address space of many processes at once. This is the crux of shared code (so we don't use more physical memory than we need) and shared memory to allow easy inter-process communication).

It is, of course, less efficient than a pure physical-address environment but the CPU manufacturers try to make it as insanely efficient as possible, since it's used heavily. The advantages far outweigh the disadvantages.

How can I send an email through the UNIX mailx command?

mailx -s "subjec_of_mail" [email protected] < file_name

through mailx utility we can send a file from unix to mail server. here in above code we can see first parameter is -s "subject of mail" the second parameter is mail ID and the last parameter is name of file which we want to attach

How do I compile the asm generated by GCC?

nasm -f bin -o 2_hello 2_hello.asm

Show diff between commits

To see the difference between two different commits (let's call them a and b), use

git diff a..b
  • Note that the difference between a and b is opposite from b and a.

To see the difference between your last commit and not yet committed changes, use

git diff

If you want to be able to come back to the difference later, you can save it in a file.

git diff a..b > ../project.diff

The transaction log for the database is full

Is this a one time script, or regularly occurring job?

In the past, for special projects that temporarily require lots of space for the log file, I created a second log file and made it huge. Once the project is complete we then removed the extra log file.

How to use Git for Unity3D source control?

We now have seamless integration to unity with Github to Unity extension... https://unity.github.com/

The new GitHub for Unity extension brings the GitHub workflow and more to Unity, providing support for large files with Git LFS and file locking.

At the time of writing the project is in alpha, but is still usable for personal projects.

Random shuffling of an array

Simplest code to shuffle:

import java.util.*;
public class ch {
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        ArrayList<Integer> l=new ArrayList<Integer>(10);
        for(int i=0;i<10;i++)
            l.add(sc.nextInt());
        Collections.shuffle(l);
        for(int j=0;j<10;j++)
            System.out.println(l.get(j));       
    }
}

Pythonically add header to a csv file

The DictWriter() class expects dictionaries for each row. If all you wanted to do was write an initial header, use a regular csv.writer() and pass in a simple row for the header:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.writer(outcsv)
    writer.writerow(["Date", "temperature 1", "Temperature 2"])

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row + [0.0] for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)

The alternative would be to generate dictionaries when copying across your data:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])
    writer.writeheader()

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': row[1], 'temperature 2': 0.0} for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': 0.0, 'temperature 2': row[1]} for row in reader)

batch file to copy files to another location?

@echo off
xcopy ...

Replace ... with the appropriate xcopy arguments to copy what you want copied.

Is there a Google Voice API?

I needed a C# API and after spending hours looking for it (all I found was outdated and non-working) and unsuccessfully trying to port the PHP/Python/Java versions listed here (none worked either) I decided to create my own. It's SMS-only for now...

https://bitbucket.org/jitbit/sharpgooglevoice/wiki/Home

How to set image button backgroundimage for different state?

if you want pressed image button then image should be change from normal to pressed

But I best way will be to customize the RadioButton and use them in a group. I have see an example of that. Sorry I did not remember that link.

but if you want to avoid that. You need to add this to your selector.xml

Once Done. Just got to your code and add this

public void onClick ( View v ) {
    myImageButton.setSelected ( true ) ;
 }

You will see the result. But you have to mange the states which button was recently press. So that you can set

  myOLDImageButton.setSelected ( false ) ;

I suggest you to put all button reference in a array.

Build error: You must add a reference to System.Runtime

Adding a reference to this System.Runtime.dll assembly fixed the issue:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1\Facades\System.Runtime.dll

Though that file in that explicit path doesn't exist on the build server.

I will post back with more information once I've found some documentation on PCL and these Facades.

Update

Yeah pretty much nothing on facade assemblies on the whole internet.

Google:

(Facades OR Facade) Portable Library site:microsoft.com

How to center a window on the screen in Tkinter?

Tk provides a helper function that can do this as tk::PlaceWindow, but I don't believe it has been exposed as a wrapped method in Tkinter. You would center a widget using the following:

from tkinter import *

app = Tk()
app.eval('tk::PlaceWindow %s center' % app.winfo_pathname(app.winfo_id()))
app.mainloop()

This function should deal with multiple displays correctly as well. It also has options to center over another widget or relative to the pointer (used for placing popup menus), so that they don't fall off the screen.

How to compare 2 files fast using .NET?

Yet another answer, derived from @chsh. MD5 with usings and shortcuts for file same, file not exists and differing lengths:

/// <summary>
/// Performs an md5 on the content of both files and returns true if
/// they match
/// </summary>
/// <param name="file1">first file</param>
/// <param name="file2">second file</param>
/// <returns>true if the contents of the two files is the same, false otherwise</returns>
public static bool IsSameContent(string file1, string file2)
{
    if (file1 == file2)
        return true;

    FileInfo file1Info = new FileInfo(file1);
    FileInfo file2Info = new FileInfo(file2);

    if (!file1Info.Exists && !file2Info.Exists)
       return true;
    if (!file1Info.Exists && file2Info.Exists)
        return false;
    if (file1Info.Exists && !file2Info.Exists)
        return false;
    if (file1Info.Length != file2Info.Length)
        return false;

    using (FileStream file1Stream = file1Info.OpenRead())
    using (FileStream file2Stream = file2Info.OpenRead())
    { 
        byte[] firstHash = MD5.Create().ComputeHash(file1Stream);
        byte[] secondHash = MD5.Create().ComputeHash(file2Stream);
        for (int i = 0; i < firstHash.Length; i++)
        {
            if (i>=secondHash.Length||firstHash[i] != secondHash[i])
                return false;
        }
        return true;
    }
}

List all the files and folders in a Directory with PHP recursive function

I improved with one check iteration the good code of Hors Sujet to avoid including folders in the result array:

function getDirContents($dir, &$results = array()){

    $files = scandir($dir);

    foreach($files as $key => $value){
        $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
        if(is_dir($path) == false) {
            $results[] = $path;
        }
        else if($value != "." && $value != "..") {
            getDirContents($path, $results);
            if(is_dir($path) == false) {
                $results[] = $path;
            }   
        }
    }
    return $results;

}

How to get access to raw resources that I put in res folder?

In some situations we have to get image from drawable or raw folder using image name instead if generated id

// Image View Object 
        mIv = (ImageView) findViewById(R.id.xidIma);
// create context Object for  to Fetch  image from resourse 
Context mContext=getApplicationContext();

// getResources().getIdentifier("image_name","res_folder_name", package_name);

// find out below example 
    int i = mContext.getResources().getIdentifier("ic_launcher","raw", mContext.getPackageName());

// now we will get contsant id for that image       
        mIv.setBackgroundResource(i);

How to set image for bar button with swift?

Only two Lines of code required for this

Swift 3.0

let closeButtonImage = UIImage(named: "ic_close_white")
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: closeButtonImage, style: .plain, target: self, action:  #selector(ResetPasswordViewController.barButtonDidTap(_:)))

func barButtonDidTap(_ sender: UIBarButtonItem) 
{

}

Create own colormap using matplotlib and plot color scale

There is an illustrative example of how to create custom colormaps here. The docstring is essential for understanding the meaning of cdict. Once you get that under your belt, you might use a cdict like this:

cdict = {'red':   ((0.0, 1.0, 1.0), 
                   (0.1, 1.0, 1.0),  # red 
                   (0.4, 1.0, 1.0),  # violet
                   (1.0, 0.0, 0.0)), # blue

         'green': ((0.0, 0.0, 0.0),
                   (1.0, 0.0, 0.0)),

         'blue':  ((0.0, 0.0, 0.0),
                   (0.1, 0.0, 0.0),  # red
                   (0.4, 1.0, 1.0),  # violet
                   (1.0, 1.0, 0.0))  # blue
          }

Although the cdict format gives you a lot of flexibility, I find for simple gradients its format is rather unintuitive. Here is a utility function to help generate simple LinearSegmentedColormaps:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors


def make_colormap(seq):
    """Return a LinearSegmentedColormap
    seq: a sequence of floats and RGB-tuples. The floats should be increasing
    and in the interval (0,1).
    """
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)


c = mcolors.ColorConverter().to_rgb
rvb = make_colormap(
    [c('red'), c('violet'), 0.33, c('violet'), c('blue'), 0.66, c('blue')])
N = 1000
array_dg = np.random.uniform(0, 10, size=(N, 2))
colors = np.random.uniform(-2, 2, size=(N,))
plt.scatter(array_dg[:, 0], array_dg[:, 1], c=colors, cmap=rvb)
plt.colorbar()
plt.show()

enter image description here


By the way, the for-loop

for i in range(0, len(array_dg)):
  plt.plot(array_dg[i], markers.next(),alpha=alpha[i], c=colors.next())

plots one point for every call to plt.plot. This will work for a small number of points, but will become extremely slow for many points. plt.plot can only draw in one color, but plt.scatter can assign a different color to each dot. Thus, plt.scatter is the way to go.

How to use a filter in a controller?

AngularJs lets you to use filters inside template or inside Controller, Directive etc..

in template you can use this syntax

{{ variable | MyFilter: ... : ... }}

and inside controller you can use injecting the $filter service

angular.module('MyModule').controller('MyCtrl',function($scope, $filter){
    $filter('MyFilter')(arg1, arg2);
})

If you need more with Demo example here is a link

AngularJs filter examples and demo

Passing data from controller to view in Laravel

Can you give this a try,

return View::make("user/regprofile", compact('students')); OR
return View::make("user/regprofile")->with(array('students'=>$students));

While, you can set multiple variables something like this,

$instructors="";
$instituitions="";

$compactData=array('students', 'instructors', 'instituitions');
$data=array('students'=>$students, 'instructors'=>$instructors, 'instituitions'=>$instituitions);

return View::make("user/regprofile", compact($compactData));
return View::make("user/regprofile")->with($data);

How to insert the current timestamp into MySQL database using a PHP insert query

Don't like any of those solutions.

this is how i do it:

$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='" 
            . sqlEsc($somename) . "' ;";

then i use my own sqlEsc function:

function sqlEsc($val) 
{
    global $mysqli;
    return mysqli_real_escape_string($mysqli, $val);
}

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

Here's my take experience with E7 async/await:

In case you have an async helperFunction() called from your test... (one explicilty with the ES7 async keyword, I mean)

? make sure, you call that as await helperFunction(whateverParams) (well, yeah, naturally, once you know...)

And for that to work (to avoid ‘await is a reserved word’), your test-function must have an outer async marker:

it('my test', async () => { ...

Adding subscribers to a list using Mailchimp's API v3

If you Want to run Batch Subscribe on a List using Mailchimp API . Then you can use the below function.

    /**
     * Mailchimp API- List Batch Subscribe added function
     *
     * @param array  $data   Passed you data as an array format.
     * @param string $apikey your mailchimp api key.
     *
     * @return mixed
     */
    function batchSubscribe(array $data, $apikey)
    {
        $auth          = base64_encode('user:' . $apikey);
        $json_postData = json_encode($data);
        $ch            = curl_init();
        $dataCenter    = substr($apikey, strpos($apikey, '-') + 1);
        $curlopt_url   = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/batches/';
        curl_setopt($ch, CURLOPT_URL, $curlopt_url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
            'Authorization: Basic ' . $auth));
        curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_postData);
        $result = curl_exec($ch);
        return $result;
    }

Function Use And Data format for Batch Operations:

<?php
$apikey  = 'Your MailChimp Api Key';
$list_id = 'Your list ID';
$servername = 'localhost';
$username   = 'Youre DB username';
$password   = 'Your DB password';
$dbname     = 'Your DB Name';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}
$sql       = 'SELECT * FROM emails';// your SQL Query goes here
$result    = $conn->query($sql);
$finalData = [];
if ($result->num_rows > 0) {
    // output data of each row
    while ($row = $result->fetch_assoc()) {
        $individulData = array(
            'apikey'        => $apikey,
            'email_address' => $row['email'],
            'status'        => 'subscribed',
            'merge_fields'  => array(
                'FNAME' => 'eastwest',
                'LNAME' => 'rehab',
            )
        );
        $json_individulData        = json_encode($individulData);
        $finalData['operations'][] =
            array(
                "method" => "POST",
                "path"   => "/lists/$list_id/members/",
                "body"   => $json_individulData
            );
    }
}
$api_response = batchSubscribe($finalData, $apikey);
print_r($api_response);
$conn->close();

Also, You can found this code in my Github gist. GithubGist Link

Reference Documentation: Official

RecyclerView vs. ListView

Simple answer: You should use RecyclerView in a situation where you want to show a lot of items, and the number of them is dynamic. ListView should only be used when the number of items is always the same and is limited to the screen size.

You find it harder because you are thinking just with the Android library in mind.

Today there exists a lot of options that help you build your own adapters, making it easy to build lists and grids of dynamic items that you can pick, reorder, use animation, dividers, add footers, headers, etc, etc.

Don't get scared and give a try to RecyclerView, you can starting to love it making a list of 100 items downloaded from the web (like facebook news) in a ListView and a RecyclerView, you will see the difference in the UX (user experience) when you try to scroll, probably the test app will stop before you can even do it.

I recommend you to check this two libraries for making easy adapters:

FastAdapter by mikepenz

FlexibleAdapter by davideas

Print "\n" or newline characters as part of the output on terminal

Use repr

>>> string = "abcd\n"
>>> print(repr(string))
'abcd\n'

View/edit ID3 data for MP3 files

ID3.NET implemented ID3v1.x and ID3v2.3 and supports read/write operations on the ID3 section in MP3 files. There's also a NuGet package available.

FFT in a single C-file

Your best bet is KissFFT - as its name implies it's simple, but it's still quite respectably fast, and a lot more lightweight than FFTW. It's also free, wheras FFTW requires a hefty licence fee if you want to include it in a commercial product.

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

One can also receive this error if using the new (so far webkit only) notification feature before getting permission.

First run:

<!-- Get permission -->
<button onclick="webkitNotifications.requestPermission();">Enable Notifications</button>

Later run:

// Display Notification:
window.webkitNotifications.createNotification('image', 'Title', 'Body').show();

The request permission functions needs to be triggered from an event caused by the user, otherwise it won't be displayed.

What does the explicit keyword mean?

Suppose, you have a class String:

class String {
public:
    String(int n); // allocate n bytes to the String object
    String(const char *p); // initializes object with char *p
};

Now, if you try:

String mystring = 'x';

The character 'x' will be implicitly converted to int and then the String(int) constructor will be called. But, this is not what the user might have intended. So, to prevent such conditions, we shall define the constructor as explicit:

class String {
public:
    explicit String (int n); //allocate n bytes
    String(const char *p); // initialize sobject with string p
};

What does the question mark and the colon (?: ternary operator) mean in objective-c?

I just learned something new about the ternary operator. The short form that omits the middle operand is truly elegant, and is one of the many reasons that C remains relevant. FYI, I first really got my head around this in the context of a routine implemented in C#, which also supports the ternary operator. Since the ternary operator is in C, it stands to reason that it would be in other languages that are essentially extensions thereof (e. g., Objective-C, C#).

What is the difference between a HashMap and a TreeMap?

HashMap is implemented by Hash Table while TreeMap is implemented by Red-Black tree. The main difference between HashMap and TreeMap actually reflect the main difference between a Hash and a Binary Tree , that is, when iterating, TreeMap guarantee can the key order which is determined by either element's compareTo() method or a comparator set in the TreeMap's constructor.

Take a look at following diagram.

enter image description here

How can I String.Format a TimeSpan object with a custom format in .NET?

Personally, I like this approach:

TimeSpan ts = ...;
string.Format("{0:%d}d {0:%h}h {0:%m}m {0:%s}s", ts);

You can make this as custom as you like with no problems:

string.Format("{0:%d}days {0:%h}hours {0:%m}min {0:%s}sec", ts);
string.Format("{0:%d}d {0:%h}h {0:%m}' {0:%s}''", ts);

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

There's some sort of bogus character at the end of that source. Try deleting the last line and adding it back.

I can't figure out exactly what's there, yet ...

edit — I think it's a zero-width space, Unicode 200B. Seems pretty weird and I can't be sure of course that it's not a Stackoverflow artifact, but when I copy/paste that last function including the complete last line into the Chrome console, I get your error.

A notorious source of such characters are websites like jsfiddle. I'm not saying that there's anything wrong with them — it's just a side-effect of something, maybe the use of content-editable input widgets.

If you suspect you've got a case of this ailment, and you're on MacOS or Linux/Unix, the od command line tool can show you (albeit in a fairly ugly way) the numeric values in the characters of the source code file. Some IDEs and editors can show "funny" characters as well. Note that such characters aren't always a problem. It's perfectly OK (in most reasonable programming languages, anyway) for there to be embedded Unicode characters in string constants, for example. The problems start happening when the language parser encounters the characters when it doesn't expect them.

Creating a new ArrayList in Java

Do this: List<Class> myArray= new ArrayList<Class>();

Setting maxlength of textbox with JavaScript or jQuery

set the attribute, not a property

$("#ms_num").attr("maxlength", 6);

How to write an async method with out parameter?

Here's the code of @dcastro's answer modified for C# 7.0 with named tuples and tuple deconstruction, which streamlines the notation:

public async void Method1()
{
    // Version 1, named tuples:
    // just to show how it works
    /*
    var tuple = await GetDataTaskAsync();
    int op = tuple.paramOp;
    int result = tuple.paramResult;
    */

    // Version 2, tuple deconstruction:
    // much shorter, most elegant
    (int op, int result) = await GetDataTaskAsync();
}

public async Task<(int paramOp, int paramResult)> GetDataTaskAsync()
{
    //...
    return (1, 2);
}

For details about the new named tuples, tuple literals and tuple deconstructions see: https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/

JavaScript: replace last occurrence of text in a string

Simple solution would be to use substring method. Since string is ending with list element, we can use string.length and calculate end index for substring without using lastIndexOf method

str = str.substring(0, str.length - list[i].length) + "finish"

Parse rfc3339 date strings in Python?

You should have a look at moment which is a python port of the excellent js lib momentjs.

One advantage of it is the support of ISO 8601 strings formats, as well as a generic "% format" :

import moment
time_string='2012-10-09T19:00:55Z'

m = moment.date(time_string, '%Y-%m-%dT%H:%M:%SZ')
print m.format('YYYY-M-D H:M')
print m.weekday

Result:

2012-10-09 19:10
2

Extracting extension from filename in Python

worth adding a lower in there so you don't find yourself wondering why the JPG's aren't showing up in your list.

os.path.splitext(filename)[1][1:].strip().lower()

What is the meaning of "operator bool() const"

operator bool() const 
{
    return col != 0;
}

Defines how the class is convertable to a boolean value, the const after the () is used to indicate this method does not mutate (change the members of this class).

You would usually use such operators as follows:

airplaysdk sdkInstance;
if (sdkInstance) {
    std::cout << "Instance is active" << std::endl;
} else {
    std::cout << "Instance is in-active error!" << std::endl;
}

php search array key and get value

The key is already the ... ehm ... key

echo $array[20120504];

If you are unsure, if the key exists, test for it

$key = 20120504;
$result = isset($array[$key]) ? $array[$key] : null;

Minor addition:

$result = @$array[$key] ?: null;

One may argue, that @ is bad, but keep it serious: This is more readable and straight forward, isn't?

Update: With PHP7 my previous example is possible without the error-silencer

$result = $array[$key] ?? null;

how to avoid a new line with p tag?

The <p> paragraph tag is meant for specifying paragraphs of text. If you don't want the text to start on a new line, I would suggest you're using the <p> tag incorrectly. Perhaps the <span> tag more closely fits what you want to achieve...?

how to log in to mysql and query the database from linux terminal

I had the same exact issue on my ArchLinux VPS today.

mysql -u root -p just didn't work, whereas mysql -u root -pmypassword did.

It turned out I had a broken /dev/tty device file (most likely after a udev upgrade), so mysql couldn't use it for an interactive login.

I ended up removing /dev/tty and recreating it with mknod /dev/tty c 5 1 and chmod 666 /dev/tty. That solved the mysql problem and some other issues too.

Remove #N/A in vlookup result

To avoid errors in any excel function, use the Error Handling functions that start with IS* in Excel. Embed your function with these error handing functions and avoid the undesirable text in your results. More info in OfficeTricks Page

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

As mentioned in the earlier comment, stacked bar chart does the trick, though the data needs to be setup differently.(See image below)

Duration column = End - Start

  1. Once done, plot your stacked bar chart using the entire data.
  2. Mark start and end range to no fill.
  3. Right click on the X Axis and change Axis options manually. (This did cause me some issues, till I realized I couldn't manipulate them to enter dates, :) yeah I am newbie, excel masters! :))

enter image description here

What's the fastest way to loop through an array in JavaScript?

Try this:

var myarray =[],
i = myarray.lenght;
while(i--){
// do somthing
}

Detecting attribute change of value of an attribute I made

You would have to watch the DOM node changes. There is an API called MutationObserver, but it looks like the support for it is very limited. This SO answer has a link to the status of the API, but it seems like there is no support for it in IE or Opera so far.

One way you could get around this problem is to have the part of the code that modifies the data-select-content-val attribute dispatch an event that you can listen to.

For example, see: http://jsbin.com/arucuc/3/edit on how to tie it together.

The code here is

$(function() {  
  // Here you register for the event and do whatever you need to do.
  $(document).on('data-attribute-changed', function() {
    var data = $('#contains-data').data('mydata');
    alert('Data changed to: ' + data);
  });

  $('#button').click(function() {
    $('#contains-data').data('mydata', 'foo');
    // Whenever you change the attribute you will user the .trigger
    // method. The name of the event is arbitrary
    $(document).trigger('data-attribute-changed');
  });

   $('#getbutton').click(function() {
    var data = $('#contains-data').data('mydata');
    alert('Data is: ' + data);
  });
});

How to configure Fiddler to listen to localhost?

Go to proxy settings in Firefox and choose "Use system proxy" but be sure to check if there is no exception for localhost in "no proxy for" field.

enter image description here enter image description here

Disable click outside of bootstrap modal area to close modal

Another option if you do not know if the modal has already been opened or not yet and you need to configure the modal options:

Bootstrap 3.4

var $modal = $('#modal');
var keyboard = false; // Prevent to close by ESC
var backdrop = 'static'; // Prevent to close on click outside the modal

if(typeof $modal.data('bs.modal') === 'undefined') { // Modal did not open yet
    $modal.modal({
        keyboard: keyboard,
        backdrop: backdrop
    });
} else { // Modal has already been opened
    $modal.data('bs.modal').options.keyboard = keyboard;
    $modal.data('bs.modal').options.backdrop = backdrop;

    if(keyboard === false) { 
        $modal.off('keydown.dismiss.bs.modal'); // Disable ESC
    } else { // 
        $modal.data('bs.modal').escape(); // Resets ESC
    }
}

Bootstrap 4.3+

var $modal = $('#modal');
var keyboard = false; // Prevent to close by ESC
var backdrop = 'static'; // Prevent to close on click outside the modal

if(typeof $modal.data('bs.modal') === 'undefined') { // Modal did not open yet
    $modal.modal({
        keyboard: keyboard,
        backdrop: backdrop
    });
} else { // Modal has already been opened
    $modal.data('bs.modal')._config.keyboard = keyboard;
    $modal.data('bs.modal')._config.backdrop = backdrop;

    if(keyboard === false) { 
        $modal.off('keydown.dismiss.bs.modal'); // Disable ESC
    } else { // 
        $modal.data('bs.modal').escape(); // Resets ESC
    }
}

Change options to _config

Version vs build in Xcode

(Just leaving this here for my own reference.) This will show version and build for the "version" and "build" fields you see in an Xcode target:

- (NSString*) version {
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    return [NSString stringWithFormat:@"%@ build %@", version, build];
}

In Swift

func version() -> String {
    let dictionary = NSBundle.mainBundle().infoDictionary!
    let version = dictionary["CFBundleShortVersionString"] as? String
    let build = dictionary["CFBundleVersion"] as? String
    return "\(version) build \(build)"
}

What is a callback in java

Strictly speaking, the concept of a callback function does not exist in Java, because in Java there are no functions, only methods, and you cannot pass a method around, you can only pass objects and interfaces. So, whoever has a reference to that object or interface may invoke any of its methods, not just one method that you might wish them to.

However, this is all fine and well, and we often speak of callback objects and callback interfaces, and when there is only one method in that object or interface, we may even speak of a callback method or even a callback function; we humans tend to thrive in inaccurate communication.

(Actually, perhaps the best approach is to just speak of "a callback" without adding any qualifications: this way, you cannot possibly go wrong. See next sentence.)

One of the most famous examples of using a callback in Java is when you call an ArrayList object to sort itself, and you supply a comparator which knows how to compare the objects contained within the list.

Your code is the high-level layer, which calls the lower-level layer (the standard java runtime list object) supplying it with an interface to an object which is in your (high level) layer. The list will then be "calling back" your object to do the part of the job that it does not know how to do, namely to compare elements of the list. So, in this scenario the comparator can be thought of as a callback object.

How to convert webpage into PDF by using Python

You also can use pdfkit:

Usage

import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')

Install

MacOS: brew install Caskroom/cask/wkhtmltopdf

Debian/Ubuntu: apt-get install wkhtmltopdf

Windows: choco install wkhtmltopdf

See official documentation for MacOS/Ubuntu/other OS: https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf

Get GPS location via a service in Android

All these answers doesn't work from M - to - Android"O" - 8, Due to Dozer mode that restrict the service - whatever service or any background operation that requires discrete things in background would be no longer able to run.

So the approach would be listening to the system FusedLocationApiClient through BroadCastReciever that always listening the location and work even in Doze mode.

Posting the link would be pointless, please search FusedLocation with Broadcast receiver.

Thanks

Tab space instead of multiple non-breaking spaces ("nbsp")?

There really isn't any easy way to insert multiple spaces inside (or in the middle) of a paragraph. Those suggesting you use CSS are missing the point. You may not always be trying to indent a paragraph from a side but, in fact, trying to put extra spaces in a particular spot of it.

In essence, in this case, the spaces become the content and not the style. I don't know why so many people don't see that. I guess the rigidity with which they try to enforce the separation of style and content rule (HTML was designed to do both from the beginning - there is nothing wrong with occasionally defining style of an unique element using appropriate tags without having to spend a lot more time on creating CSS style sheets and there is absolutely nothing unreadable about it when it's used in moderation. There is also something to be said for being able to do something quickly.) translates to how they can only consider whitespace characters as being used only for style and indentation.

And when there is no graceful way to insert spaces without having to rely on &emsp; and &nbsp; tags, I would argue that the resulting code becomes far more unreadible than if there was an appropriately named tag that would have allowed you to quickly insert a large number of spaces (or if, you know, spaces weren't needlessly consumed in the first place).

As it is though, as was said above, your best bet would be to use &emsp; to insert   in the correct place.

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

I notice many answers just try to increase the amount of memory given to a script which has its place but more often than not it means that something is being too liberal with memory due to an unforseen amount of volume or size. Obviously if your not the author of a script your at the mercy of the author unless your feeling ambitious :) The PHP docs even say memory issues are due to "poorly written scripts"

It should be mentioned that ini_set('memory_limit', '-1'); (no limit) can cause server instability as 0 bytes free = bad things. Instead, find a reasonable balance by what your script is trying to do and the amount of available memory on a machine.

A better approach: If you are the author of the script (or ambitious) you can debug such memory issues with xdebug. The latest version (2.6.0 - released 2018-01-29) brought back memory profiling that shows you what function calls are consuming large amounts of memory. It exposes issues in the script that are otherwise hard to find. Usually, the inefficiencies are in a loop that isn't expecting the volume it's receiving, but each case will be left as an exercise to the reader :)

The xdebug documentation is helpful, but it boils down to 3 steps:

  1. Install It - Available through apt-get and yum etc
  2. Configure it - xdebug.ini: xdebug.profiler_enable = 1, xdebug.profiler_output_dir = /where/ever/
  3. View the profiles in a tool like QCacheGrind, KCacheGrind

RadioGroup: How to check programmatically

I use this code piece while working with getId() for radio group:

radiogroup.check(radiogroup.getChildAt(0).getId());

set position as per your design of RadioGroup

hope this will help you!

The input is not a valid Base-64 string as it contains a non-base 64 character

Check if your image data contains some header information at the beginning:

imageCode = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAABkC...

This will cause the above error.

Just remove everything in front of and including the first comma, and you good to go.

imageCode = "iVBORw0KGgoAAAANSUhEUgAAAMgAAABkC...

Getting Raw XML From SOAPMessage in Java

Using Transformer Factory:-

public static String printSoapMessage(final SOAPMessage soapMessage) throws TransformerFactoryConfigurationError,
            TransformerConfigurationException, SOAPException, TransformerException
    {
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();

        // Format it
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        final Source soapContent = soapMessage.getSOAPPart().getContent();

        final ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
        final StreamResult result = new StreamResult(streamOut);
        transformer.transform(soapContent, result);

        return streamOut.toString();
    }

How to remove "Server name" items from history of SQL Server Management Studio

Over on this duplicate question @arcticdev posted some code that will get rid of individual entries (as opposed to all entries being delete the bin file). I have wrapped it in a very ugly UI and put it here: http://ssmsmru.codeplex.com/

PyCharm import external library

I wanted to add an import path, for another project elsewhere in my workspace. MacOS Catalina 10.15.5 PyCharm Community 2020.1.1

PyCharm - Preferences - Project interpreter - Cog symbol - Show All

At the bottom of that dialog, it shows 5 buttons: Plus, Minus, Pencil, Funnel, and Directory tree.

Click Directory tree. You can now use the Plus button in the new dialog to add your 'external library' search path.

If successful, you should now see the directory name in the "External Libraries" pane in the Project panel.

How to resolve a Java Rounding Double issue

Save the number of cents rather than dollars, and just do the format to dollars when you output it. That way you can use an integer which doesn't suffer from the precision issues.

Using Python's os.path, how do I go up one directory?

Go up a level from the work directory

import os
os.path.dirname(os.getcwd())

or from the current directory

import os
os.path.dirname('current path')

Going through a text file line by line in C

Say you're dealing with some other delimiter, such as a \t tab, instead of a \n newline.

A more general approach to delimiters is the use of getc(), which grabs one character at a time.

Note that getc() returns an int, so that we can test for equality with EOF.

Secondly, we define an array line[BUFFER_MAX_LENGTH] of type char, in order to store up to BUFFER_MAX_LENGTH-1 characters on the stack (we have to save that last character for a \0 terminator character).

Use of an array avoids the need to use malloc and free to create a character pointer of the right length on the heap.

#define BUFFER_MAX_LENGTH 1024

int main(int argc, char* argv[])
{
    FILE *file = NULL;
    char line[BUFFER_MAX_LENGTH];
    int tempChar;
    unsigned int tempCharIdx = 0U;

    if (argc == 2)
         file = fopen(argv[1], "r");
    else {
         fprintf(stderr, "error: wrong number of arguments\n"
                         "usage: %s textfile\n", argv[0]);
         return EXIT_FAILURE;
    }

    if (!file) {
         fprintf(stderr, "error: could not open textfile: %s\n", argv[1]);
         return EXIT_FAILURE;
    }

    /* get a character from the file pointer */
    while(tempChar = fgetc(file))
    {
        /* avoid buffer overflow error */
        if (tempCharIdx == BUFFER_MAX_LENGTH) {
            fprintf(stderr, "error: line is too long. increase BUFFER_MAX_LENGTH.\n");
            return EXIT_FAILURE;
        }

        /* test character value */
        if (tempChar == EOF) {
            line[tempCharIdx] = '\0';
            fprintf(stdout, "%s\n", line);
            break;
        }
        else if (tempChar == '\n') {
            line[tempCharIdx] = '\0';
            tempCharIdx = 0U;
            fprintf(stdout, "%s\n", line);
            continue;
        }
        else
            line[tempCharIdx++] = (char)tempChar;
    }

    return EXIT_SUCCESS;
}

If you must use a char *, then you can still use this code, but you strdup() the line[] array, once it is filled up with a line's worth of input. You must free this duplicated string once you're done with it, or you'll get a memory leak:

#define BUFFER_MAX_LENGTH 1024

int main(int argc, char* argv[])
{
    FILE *file = NULL;
    char line[BUFFER_MAX_LENGTH];
    int tempChar;
    unsigned int tempCharIdx = 0U;
    char *dynamicLine = NULL;

    if (argc == 2)
         file = fopen(argv[1], "r");
    else {
         fprintf(stderr, "error: wrong number of arguments\n"
                         "usage: %s textfile\n", argv[0]);
         return EXIT_FAILURE;
    }

    if (!file) {
         fprintf(stderr, "error: could not open textfile: %s\n", argv[1]);
         return EXIT_FAILURE;
    }

    while(tempChar = fgetc(file))
    {
        /* avoid buffer overflow error */
        if (tempCharIdx == BUFFER_MAX_LENGTH) {
            fprintf(stderr, "error: line is too long. increase BUFFER_MAX_LENGTH.\n");
            return EXIT_FAILURE;
        }

        /* test character value */
        if (tempChar == EOF) {
            line[tempCharIdx] = '\0';
            dynamicLine = strdup(line);
            fprintf(stdout, "%s\n", dynamicLine);
            free(dynamicLine);
            dynamicLine = NULL;
            break;
        }
        else if (tempChar == '\n') {
            line[tempCharIdx] = '\0';
            tempCharIdx = 0U;
            dynamicLine = strdup(line);
            fprintf(stdout, "%s\n", dynamicLine);
            free(dynamicLine);
            dynamicLine = NULL;
            continue;
        }
        else
            line[tempCharIdx++] = (char)tempChar;
    }

    return EXIT_SUCCESS;
}

How to Get the Query Executed in Laravel 5? DB::getQueryLog() Returning Empty Array

If all you really care about is the actual query (the last one run) for quick debugging purposes:

DB::enableQueryLog();

# your laravel query builder goes here

$laQuery = DB::getQueryLog();

$lcWhatYouWant = $laQuery[0]['query']; # <-------

# optionally disable the query log:
DB::disableQueryLog();

do a print_r() on $laQuery[0] to get the full query, including the bindings. (the $lcWhatYouWant variable above will have the variables replaced with ??)

If you're using something other than the main mysql connection, you'll need to use these instead:

DB::connection("mysql2")->enableQueryLog();

DB::connection("mysql2")->getQueryLog();

(with your connection name where "mysql2" is)

How to rebuild docker container in docker-compose.yml?

The problem is:

$ docker-compose stop nginx

didn't work (you said it is still running). If you are going to rebuild it anyway, you can try killing it:

$ docker-compose kill nginx

If it still doesn't work, try to stop it with docker directly:

$ docker stop nginx

or delete it

$ docker rm -f nginx

If that still doesn't work, check your version of docker, you might want to upgrade.

It might be a bug, you could check if one matches your system/version. Here are a couple, for ex: https://github.com/docker/docker/issues/10589

https://github.com/docker/docker/issues/12738

As a workaround, you could try to kill the process.

$ ps aux | grep docker 
$ kill 225654 # example process id

How to change the background color on a Java panel?

I am assuming that we are dealing with a JFrame? The visible portion in the content pane - you have to use jframe.getContentPane().setBackground(...);

How do I set cell value to Date and apply default Excel date format?

http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells

CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
    createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

typesafe select onChange event using reactjs and typescript

In addition to @thoughtrepo's answer:

Until we do not have definitely typed events in React it might be useful to have a special target interface for input controls:

export interface FormControlEventTarget extends EventTarget{
    value: string;
}

And then in your code cast to this type where is appropriate to have IntelliSense support:

 import {FormControlEventTarget} from "your.helper.library"

 (event.target as FormControlEventTarget).value;

How to add key,value pair to dictionary?

If you want to add a new record in the form

newRecord = [4L, 1L, u'DDD', 1689544L, datetime.datetime(2010, 9, 21, 21, 45), u'jhhjjh']

to messageName where messageName in the form X_somemessage can, but does not have to be in your dictionary, then do it this way:

myDict.setdefault(messageName, []).append(newRecord)

This way it will be appended to an existing messageName or a new list will be created for a new messageName.

How to refresh or show immediately in datagridview after inserting?

Only need to fill datagrid again like this:

this.XXXTableAdapter.Fill(this.DataSet.XXX);

If you use automaticlly connect from dataGridView this code create automaticlly in Form_Load()

VS 2017 Metadata file '.dll could not be found

In my case I was facing same error. One of my project solution was referring an assembly from different NuGet location. I just changed it to correct location to solve this error and rebuild. and wow the project get build successfully and all other error gone away.

Java rounding up to an int using Math.ceil

You are doing 157/32 which is dividing two integers with each other, which always result in a rounded down integer. Therefore the (int) Math.ceil(...) isn't doing anything. There are three possible solutions to achieve what you want. I recommend using either option 1 or option 2. Please do NOT use option 0.

Option 0

Convert a and b to a double, and you can use the division and Math.ceil as you wanted it to work. However I strongly discourage the use of this approach, because double division can be imprecise. To read more about imprecision of doubles see this question.

int n = (int) Math.ceil((double) a / b));

Option 1

int n = a / b + ((a % b == 0) ? 0 : 1); 

You do a / b with always floor if a and b are both integers. Then you have an inline if-statement witch checks whether or not you should ceil instead of floor. So +1 or +0, if there is a remainder with the division you need +1. a % b == 0 checks for the remainder.

Option 2

This option is very short, but maybe for some less intuitive. I think this less intuitive approach would be faster than the double division and comparison approach:
Please note that this doesn't work for b < 0.

int n = (a + b - 1) / b;

To reduce the chance of overflow you could use the following. However please note that it doesn't work for a = 0 and b < 1.

int n = (a - 1) / b + 1;

Explanation behind the "less intuitive approach"

Since dividing two integer in Java (and most other programming languages) will always floor the result. So:

int a, b;
int result = a/b (is the same as floor(a/b) )

But we don't want floor(a/b), but ceil(a/b), and using the definitions and plots from Wikipedia: enter image description here

With these plots of the floor and ceil function you can see the relationship.

Floor function Ceil function

You can see that floor(x) <= ceil(x). We need floor(x + s) = ceil(x). So we need to find s. If we take 1/2 <= s < 1 it will be just right (try some numbers and you will see it does, I find it hard myself to prove this). And 1/2 <= (b-1) / b < 1, so

ceil(a/b) = floor(a/b + s)
          = floor(a/b + (b-1)/b)
          = floor( (a+b-1)/b) )

This is not a real proof, but I hope your are satisfied with it. If someone can explain it better I would appreciate it too. Maybe ask it on MathOverflow.

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

If someone is using AFHTTPSessionManager then one can do like this to solve the issue,

I subclassed AFHTTPSessionManager where I'm doing like this,

NSMutableSet *contentTypes = [[NSMutableSet alloc] initWithSet:self.responseSerializer.acceptableContentTypes];
[contentTypes addObject:@"text/html"];
self.responseSerializer.acceptableContentTypes = contentTypes;

Create session factory in Hibernate 4

Yes, they have deprecated the previous buildSessionFactory API, and it's quite easy to do well.. you can do something like this..

EDIT : ServiceRegistryBuilder is deprecated. you must use StandardServiceRegistryBuilder

public void testConnection() throws Exception {

            logger.info("Trying to create a test connection with the database.");
            Configuration configuration = new Configuration();
            configuration.configure("hibernate_sp.cfg.xml");
            StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
            SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb.build());
            Session session = sessionFactory.openSession();
            logger.info("Test connection with the database created successfuly.");
    }

For more reference and in depth detail, you can check the hibernate's official test case at https://github.com/hibernate/hibernate-orm/blob/master/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseCoreFunctionalTestCase.java function (buildSessionFactory()).

final keyword in method parameters

final keyword in the method input parameter is not needed. Java creates a copy of the reference to the object, so putting final on it doesn't make the object final but just the reference, which doesn't make sense

Add CSS to iFrame

Based on solution You've already found How to apply CSS to iframe?:

var cssLink = document.createElement("link") 
cssLink.href = "file://path/to/style.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 
frames['iframe'].document.body.appendChild(cssLink);

or more jqueryish (from Append a stylesheet to an iframe with jQuery):

var $head = $("iframe").contents().find("head");                
$head.append($("<link/>", 
    { rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));

as for security issues: Disabling same-origin policy in Safari

GroupBy pandas DataFrame and select most common value

The two top answers here suggest:

df.groupby(cols).agg(lambda x:x.value_counts().index[0])

or, preferably

df.groupby(cols).agg(pd.Series.mode)

However both of these fail in simple edge cases, as demonstrated here:

df = pd.DataFrame({
    'client_id':['A', 'A', 'A', 'A', 'B', 'B', 'B', 'C'],
    'date':['2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01'],
    'location':['NY', 'NY', 'LA', 'LA', 'DC', 'DC', 'LA', np.NaN]
})

The first:

df.groupby(['client_id', 'date']).agg(lambda x:x.value_counts().index[0])

yields IndexError (because of the empty Series returned by group C). The second:

df.groupby(['client_id', 'date']).agg(pd.Series.mode)

returns ValueError: Function does not reduce, since the first group returns a list of two (since there are two modes). (As documented here, if the first group returned a single mode this would work!)

Two possible solutions for this case are:

import scipy
x.groupby(['client_id', 'date']).agg(lambda x: scipy.stats.mode(x)[0])

And the solution given to me by cs95 in the comments here:

def foo(x): 
    m = pd.Series.mode(x); 
    return m.values[0] if not m.empty else np.nan
df.groupby(['client_id', 'date']).agg(foo)

However, all of these are slow and not suited for large datasets. A solution I ended up using which a) can deal with these cases and b) is much, much faster, is a lightly modified version of abw33's answer (which should be higher):

def get_mode_per_column(dataframe, group_cols, col):
    return (dataframe.fillna(-1)  # NaN placeholder to keep group 
            .groupby(group_cols + [col])
            .size()
            .to_frame('count')
            .reset_index()
            .sort_values('count', ascending=False)
            .drop_duplicates(subset=group_cols)
            .drop(columns=['count'])
            .sort_values(group_cols)
            .replace(-1, np.NaN))  # restore NaNs

group_cols = ['client_id', 'date']    
non_grp_cols = list(set(df).difference(group_cols))
output_df = get_mode_per_column(df, group_cols, non_grp_cols[0]).set_index(group_cols)
for col in non_grp_cols[1:]:
    output_df[col] = get_mode_per_column(df, group_cols, col)[col].values

Essentially, the method works on one col at a time and outputs a df, so instead of concat, which is intensive, you treat the first as a df, and then iteratively add the output array (values.flatten()) as a column in the df.

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

I just opened the dump.sql file in Notepad++ and hit CTRL+H to find and replace the string "utf8mb4_0900_ai_ci" and replaced it with "utf8mb4_general_ci". Source link https://www.freakyjolly.com/resolved-when-i-faced-1273-unknown-collation-utf8mb4_0900_ai_ci-error/

Regex to match 2 digits, optional decimal, two digits

^(\d{0,2}\\.)?\d{1,2}$

\d{1,2}$ matches a 1-2 digit number with nothing after it (3, 33, etc.), (\d{0,2}\.)? matches optionally a number 0-2 digits long followed by a period (3., 44., ., etc.). Put them together and you've got your regex.

JavaScript - Hide a Div at startup (load)

Why not add "display: none;" to the divs style attribute? Thats all JQuery's .hide() function does.

Place a button right aligned

Which alignment technique you use depends on your circumstances but the basic one is float: right;:

<input type="button" value="Click Me" style="float: right;">

You'll probably want to clear your floats though but that can be done with overflow:hidden on the parent container or an explicit <div style="clear: both;"></div> at the bottom of the container.

For example: http://jsfiddle.net/ambiguous/8UvVg/

Floated elements are removed from the normal document flow so they can overflow their parent's boundary and mess up the parent's height, the clear:both CSS takes care of that (as does overflow:hidden). Play around with the JSFiddle example I added to see how floating and clearing behave (you'll want to drop the overflow:hidden first though).

How to programmatically get iOS status bar height

For iOS 13 you can use:

UIApplication.shared.keyWindow?.windowScene?.statusBarManager?.statusBarFrame.height

What does the shrink-to-fit viewport meta attribute do?

As stats on iOS usage, indicating that iOS 9.0-9.2.x usage is currently at 0.17%. If these numbers are truly indicative of global use of these versions, then it’s even more likely to be safe to remove shrink-to-fit from your viewport meta tag.

After 9.2.x. IOS remove this tag check on its' browser.

You can check this page https://www.scottohara.me/blog/2018/12/11/shrink-to-fit.html

PHP - get base64 img string decode and save as jpg (resulting empty image )

Client need to send base64 to server.

And above answer described code is work perfectly:

$imageData = base64_decode($imageData);
$source = imagecreatefromstring($imageData);
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);

Thanks

How do I remove the space between inline/inline-block elements?

Try this snippet:

span {
    display: inline-block;
    width: 100px;
    background: blue;
    font-size: 30px;
    color: white;
    text-align: center;
    margin-right: -3px;
}

Working demo: http://jsfiddle.net/dGHFV/2784/

orderBy multiple fields in Angular

I wrote this handy piece to sort by multiple columns / properties of an object. With each successive column click, the code stores the last column clicked and adds it to a growing list of clicked column string names, placing them in an array called sortArray. The built-in Angular "orderBy" filter simply reads the sortArray list and orders the columns by the order of column names stored there. So the last clicked column name becomes the primary ordered filter, the previous one clicked the next in precedence, etc. The reverse order affects all columns order at once and toggles ascending/descending for the complete array list set:

<script>
    app.controller('myCtrl', function ($scope) {
        $scope.sortArray = ['name'];
        $scope.sortReverse1 = false;
        $scope.searchProperty1 = '';
        $scope.addSort = function (x) {
            if ($scope.sortArray.indexOf(x) === -1) {
                $scope.sortArray.splice(0,0,x);//add to front
            }
            else {
                $scope.sortArray.splice($scope.sortArray.indexOf(x), 1, x);//remove
                $scope.sortArray.splice(0, 0, x);//add to front again
            }
        };
        $scope.sushi = [
        { name: 'Cali Roll', fish: 'Crab', tastiness: 2 },
        { name: 'Philly', fish: 'Tuna', tastiness: 2 },
        { name: 'Tiger', fish: 'Eel', tastiness: 7 },
        { name: 'Rainbow', fish: 'Variety', tastiness: 6 },
        { name: 'Salmon', fish: 'Misc', tastiness: 2 }
        ];
    });
</script>
<table style="border: 2px solid #000;">
<thead>
    <tr>
        <td><a href="#" ng-click="addSort('name');sortReverse1=!sortReverse1">NAME<span ng-show="sortReverse1==false">&#9660;</span><span ng-show="sortReverse1==true">&#9650;</span></a></td>
        <td><a href="#" ng-click="addSort('fish');sortReverse1=!sortReverse1">FISH<span ng-show="sortReverse1==false">&#9660;</span><span ng-show="sortReverse1==true">&#9650;</span></a></td>
        <td><a href="#" ng-click="addSort('tastiness');sortReverse1=!sortReverse1">TASTINESS<span ng-show="sortReverse1==false">&#9660;</span><span ng-show="sortReverse1==true">&#9650;</span></a></td>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="s in sushi | orderBy:sortArray:sortReverse1 | filter:searchProperty1">
        <td>{{ s.name }}</td>
        <td>{{ s.fish }}</td>
        <td>{{ s.tastiness }}</td>
    </tr>
</tbody>
</table>

Spring Boot application.properties value not populating

Using Environment class we can get application. Properties values

@Autowired,

private Environment env;

and access using

String password =env.getProperty(your property key);

How do I run Python code from Sublime Text 2?

I ran into the same problem today. And here is how I managed to run python code in Sublime Text 3:

  1. Press Ctrl + B (for Mac, ? + B) to start build system. It should execute the file now.
  2. Follow this answer to understand how to customise build system.

What you need to do next is replace the content in Python.sublime-build to

{
    "cmd": ["/usr/local/bin/python", "-u", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python",
}

You can of course further customise it to something that works for you.

Return Boolean Value on SQL Select Statement

Notice another equivalent problem: Creating an SQL query that returns (1) if the condition is satisfied and an empty result otherwise. Notice that a solution to this problem is more general and can easily be used with the above answers to achieve the question that you asked. Since this problem is more general, I am proving its solution in addition to the beautiful solutions presented above to your problem.

SELECT DISTINCT 1 AS Expr1
FROM [User]
WHERE (UserID = 20070022)

Textarea to resize based on content length

Use this function:

function adjustHeight(el){
    el.style.height = (el.scrollHeight > el.clientHeight) ? (el.scrollHeight)+"px" : "60px";
}

Use this html:

<textarea onkeyup="adjustHeight(this)"></textarea>

And finally use this css:

textarea {
min-height: 60px;
overflow-y: auto;
word-wrap:break-word
}

The solution simply is letting the scrollbar appears to detect that height needs to be adjusted, and whenever the scrollbar appears in your text area, it adjusts the height just as much as to hide the scrollbar again.

exit application when click button - iOS

You can use exit method to quit an ios app :

exit(0);

You should say same alert message and ask him to quit

Another way is by using [[NSThread mainThread] exit]

However you should not do this way

According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.

How to make an HTTP request + basic auth in Swift

swift 4:

let username = "username"
let password = "password"
let loginString = "\(username):\(password)"

guard let loginData = loginString.data(using: String.Encoding.utf8) else {
    return
}
let base64LoginString = loginData.base64EncodedString()

request.httpMethod = "GET"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

C string append

man page of strcat says that arg1 and arg2 are appended to arg1.. and returns the pointer of s1. If you dont want disturb str1,str2 then you have write your own function.

char * my_strcat(const char * str1, const char * str2)
{
   char * ret = malloc(strlen(str1)+strlen(str2));

   if(ret!=NULL)
   {
     sprintf(ret, "%s%s", str1, str2);
     return ret;
   }
   return NULL;    
}

Hope this solves your purpose

How to center the elements in ConstraintLayout

add these tag in your view

    app:layout_constraintCircleRadius="0dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"

and you can right click in design mode and choose center.

Change windows hostname from command line

The previously mentioned wmic command is the way to go, as it is installed by default in recent versions of Windows.

Here is my small improvement to generalize it, by retrieving the current name from the environment:

wmic computersystem where name="%COMPUTERNAME%" 
     call rename name="NEW-NAME"

NOTE: The command must be given in one line, but I've broken it into two to make scrolling unnecessary. As @rbeede mentions you'll have to reboot to complete the update.

AJAX cross domain call

after doing some research, the only "solution" to this problem is to call:

if($.browser.mozilla)
   netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');

this will ask an user if he allows a website to continue. After he confirmed that, all ajax calls regardless of it's datatype will get executed.

This works for mozilla browsers, in IE < 8, an user has to allow a cross domain call in a similar way, some version need to get configured within browser options.

chrome/safari: I didn't find a config flag for those browsers so far.

using JSONP as datatype would be nice, but in my case I don't know if a domain I need to access supports data in that format.

Another shot is to use HTML5 postMessage which works cross-domain aswell, but I can't afford to doom my users to HTML5 browsers.

How do I commit only some files?

Get a list of files you want to commit

$ git status

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

modified:   file1
modified:   file2
modified:   file3
modified:   file4

Add the files to staging

$ git add file1 file2

Check to see what you are committing

$ git status

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    modified:   file1
    modified:   file2

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   file3
    modified:   file4

Commit the files with a commit message

$ git commit -m "Fixed files 1 and 2"

If you accidentally commit the wrong files

$ git reset --soft HEAD~1

If you want to unstage the files and start over

$ git reset

Unstaged changes after reset:
M file1
M file2
M file3
M file4

HTML table needs spacing between columns, not rows

This can be achieved by putting padding between the columns using CSS. You can either add padding to the left of all columns except the first, or add padding to the right of all columns except the last. You should avoid adding padding to the right of the last column or to the left of the first as this will insert redundant white space. You should also avoid being too prescriptive with classes to specify which columns should have the additional padding as this will make maintenance harder if you later add a new column.

The 'lobotomised owl selector' allows you to select all siblings, regardless of if they are a th, td or something else.

_x000D_
_x000D_
tr > * + * {
  padding-left: 4em;
}
_x000D_
<table>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Data 1</td>
      <td>Data 2</td>
      <td>Data 3</td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

Converting from signed char to unsigned char and back again?

I'm not 100% sure that I understand your question, so tell me if I'm wrong.

If I got it right, you are reading jbytes that are technically signed chars, but really pixel values ranging from 0 to 255, and you're wondering how you should handle them without corrupting the values in the process.

Then, you should do the following:

  • convert jbytes to unsigned char before doing anything else, this will definetly restore the pixel values you are trying to manipulate

  • use a larger signed integer type, such as int while doing intermediate calculations, this to make sure that over- and underflows can be detected and dealt with (in particular, not casting to a signed type could force to compiler to promote every type to an unsigned type in which case you wouldn't be able to detect underflows later on)

  • when assigning back to a jbyte, you'll want to clamp your value to the 0-255 range, convert to unsigned char and then convert again to signed char: I'm not certain the first conversion is strictly necessary, but you just can't be wrong if you do both

For example:

inline int fromJByte(jbyte pixel) {
    // cast to unsigned char re-interprets values as 0-255
    // cast to int will make intermediate calculations safer
    return static_cast<int>(static_cast<unsigned char>(pixel));
}

inline jbyte fromInt(int pixel) {
    if(pixel < 0)
        pixel = 0;

    if(pixel > 255)
        pixel = 255;

    return static_cast<jbyte>(static_cast<unsigned char>(pixel));
}

jbyte in = ...
int intermediate = fromJByte(in) + 30;
jbyte out = fromInt(intermediate);

Angular ReactiveForms: Producing an array of checkbox values?

If you want to use an Angular reactive form (https://angular.io/guide/reactive-forms).

You can use one form control to manage the outputted value of the group of checkboxes.

component

import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { flow } from 'lodash';
import { flatMap, filter } from 'lodash/fp';

@Component({
  selector: 'multi-checkbox',
  templateUrl: './multi-checkbox.layout.html',
})
export class MultiChecboxComponent  {

  checklistState = [ 
      {
        label: 'Frodo Baggins',
        value: 'frodo_baggins',
        checked: false
      },
      {
        label: 'Samwise Gamgee',
        value: 'samwise_gamgee',
        checked: true,
      },
      {
        label: 'Merry Brandybuck',
        value: 'merry_brandybuck',
        checked: false
      }
    ];

  form = new FormGroup({
    checklist : new FormControl(this.flattenValues(this.checklistState)),
  });


  checklist = this.form.get('checklist');

  onChecklistChange(checked, checkbox) {
    checkbox.checked = checked;
    this.checklist.setValue(this.flattenValues(this.checklistState));
  }

  flattenValues(checkboxes) {
    const flattenedValues = flow([
      filter(checkbox => checkbox.checked),
      flatMap(checkbox => checkbox.value )
    ])(checkboxes)
    return flattenedValues.join(',');
  }
}

html

<form [formGroup]="form">
    <label *ngFor="let checkbox of checklistState" class="checkbox-control">
    <input type="checkbox" (change)="onChecklistChange($event.target.checked, checkbox)" [checked]="checkbox.checked" [value]="checkbox.value" /> {{ checkbox.label }}
  </label>
</form>

checklistState

Manages the model/state of the checklist inputs. This model allows you to map the current state to whatever value format you need.

Model:

{
   label: 'Value 1',
   value: 'value_1',
   checked: false
},
{
  label: 'Samwise Gamgee',
  value: 'samwise_gamgee',
  checked: true,
},
{
  label: 'Merry Brandybuck',
  value: 'merry_brandybuck',
  checked: false
}

checklist Form Control

This control stores the value would like to save as e.g

value output: "value_1,value_2"

See demo at https://stackblitz.com/edit/angular-multi-checklist

How to get a time zone from a location using latitude and longitude coordinates?

Try this code for use Google Time Zone API from Java with current NTP Time Client and correct UTC_Datetime_from_timestamp convert:

String get_xml_server_reponse(String server_url){

    URL xml_server = null;

    String xmltext = "";

    InputStream input;


    try {
        xml_server = new URL(server_url);


        try {
            input = xml_server.openConnection().getInputStream();


            final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            final StringBuilder sBuf = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null) 
                {
                    sBuf.append(line);
                }
               } 
            catch (IOException e) 
              {
                    Log.e(e.getMessage(), "XML parser, stream2string 1");
              } 
            finally {
                try {
                    input.close();
                    }
                catch (IOException e) 
                {
                    Log.e(e.getMessage(), "XML parser, stream2string 2");
                }
            }

            xmltext =  sBuf.toString();

        } catch (IOException e1) {

                e1.printStackTrace();
            }


        } catch (MalformedURLException e1) {

          e1.printStackTrace();
        }

     return  xmltext;

  }     


 private String get_UTC_Datetime_from_timestamp(long timeStamp){

    try{

        Calendar cal = Calendar.getInstance();
        TimeZone tz = cal.getTimeZone();

        int tzt = tz.getOffset(System.currentTimeMillis());

        timeStamp -= tzt;

        // DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
        DateFormat sdf = new SimpleDateFormat();
        Date netDate = (new Date(timeStamp));
        return sdf.format(netDate);
    }
    catch(Exception ex){
        return "";
     }
    } 

 class NTP_UTC_Time
 {
     private static final String TAG = "SntpClient";

     private static final int RECEIVE_TIME_OFFSET = 32;
     private static final int TRANSMIT_TIME_OFFSET = 40;
     private static final int NTP_PACKET_SIZE = 48;

     private static final int NTP_PORT = 123;
     private static final int NTP_MODE_CLIENT = 3;
     private static final int NTP_VERSION = 3;

     // Number of seconds between Jan 1, 1900 and Jan 1, 1970
     // 70 years plus 17 leap days
     private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;

     private long mNtpTime;

     public boolean requestTime(String host, int timeout) {
         try {
             DatagramSocket socket = new DatagramSocket();
             socket.setSoTimeout(timeout);
             InetAddress address = InetAddress.getByName(host);
             byte[] buffer = new byte[NTP_PACKET_SIZE];
             DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);

             buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);

             writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET);

             socket.send(request);

             // read the response
             DatagramPacket response = new DatagramPacket(buffer, buffer.length);
             socket.receive(response);          
             socket.close();

             mNtpTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);            
         } catch (Exception e) {
           //  if (Config.LOGD) Log.d(TAG, "request time failed: " + e);
             return false;
         }

         return true;
     }


     public long getNtpTime() {
         return mNtpTime;
     }


     /**
      * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
      */
     private long read32(byte[] buffer, int offset) {
         byte b0 = buffer[offset];
         byte b1 = buffer[offset+1];
         byte b2 = buffer[offset+2];
         byte b3 = buffer[offset+3];

         // convert signed bytes to unsigned values
         int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
         int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
         int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
         int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);

         return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
     }

     /**
      * Reads the NTP time stamp at the given offset in the buffer and returns 
      * it as a system time (milliseconds since January 1, 1970).
      */    
     private long readTimeStamp(byte[] buffer, int offset) {
         long seconds = read32(buffer, offset);
         long fraction = read32(buffer, offset + 4);
         return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);        
     }

     /**
      * Writes 0 as NTP starttime stamp in the buffer. --> Then NTP returns Time OFFSET since 1900
      */    
     private void writeTimeStamp(byte[] buffer, int offset) {        
         int ofs =  offset++;

         for (int i=ofs;i<(ofs+8);i++)
           buffer[i] = (byte)(0);             
     }

 }

 String get_time_zone_time(GeoPoint gp){

        String erg = "";
        String raw_offset = "";
        String dst_offset = "";

        double Longitude = gp.getLongitudeE6()/1E6;
        double Latitude = gp.getLatitudeE6()/1E6;



        long tsLong = 0; // System.currentTimeMillis()/1000;

        NTP_UTC_Time client = new NTP_UTC_Time();

        if (client.requestTime("pool.ntp.org", 2000)) {              
          tsLong = client.getNtpTime();
        }

        if (tsLong != 0)
        {

        tsLong = tsLong  / 1000;

        // https://maps.googleapis.com/maps/api/timezone/xml?location=39.6034810,-119.6822510&timestamp=1331161200&sensor=false

        String request = "https://maps.googleapis.com/maps/api/timezone/xml?location="+Latitude+","+ Longitude+ "&timestamp="+tsLong +"&sensor=false";

        String xmltext = get_xml_server_reponse(request);

        if(xmltext.compareTo("")!= 0)
        {

         int startpos = xmltext.indexOf("<TimeZoneResponse");
         xmltext = xmltext.substring(startpos);



        XmlPullParser parser;
        try {
            parser = XmlPullParserFactory.newInstance().newPullParser();


             parser.setInput(new StringReader (xmltext));

             int eventType = parser.getEventType();  

             String tagName = "";


             while(eventType != XmlPullParser.END_DOCUMENT) {
                 switch(eventType) {

                     case XmlPullParser.START_TAG:

                           tagName = parser.getName();

                         break;


                     case XmlPullParser.TEXT :


                        if  (tagName.equalsIgnoreCase("raw_offset"))
                          if(raw_offset.compareTo("")== 0)                               
                            raw_offset = parser.getText();  

                        if  (tagName.equalsIgnoreCase("dst_offset"))
                          if(dst_offset.compareTo("")== 0)
                            dst_offset = parser.getText();  


                        break;   

                 }

                 try {
                        eventType = parser.next();
                    } catch (IOException e) {

                        e.printStackTrace();
                    }

                }

                } catch (XmlPullParserException e) {

                    e.printStackTrace();
                    erg += e.toString();
                }

        }      

        int ro = 0;
        if(raw_offset.compareTo("")!= 0)
        { 
            float rof = str_to_float(raw_offset);
            ro = (int)rof;
        }

        int dof = 0;
        if(dst_offset.compareTo("")!= 0)
        { 
            float doff = str_to_float(dst_offset);
            dof = (int)doff;
        }

        tsLong = (tsLong + ro + dof) * 1000;



        erg = get_UTC_Datetime_from_timestamp(tsLong);
        }


  return erg;

}

And use it with:

GeoPoint gp = new GeoPoint(39.6034810,-119.6822510);
String Current_TimeZone_Time = get_time_zone_time(gp);

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Unfortunately this error is not descriptive for a range of different problems related to the same issue - a binding error. It also does not specify where the error is, and so your problem is not necessarily in the execution, but the sql statement that was already 'prepared'.

These are the possible errors and their solutions:

  1. There is a parameter mismatch - the number of fields does not match the parameters that have been bound. Watch out for arrays in arrays. To double check - use var_dump($var). "print_r" doesn't necessarily show you if the index in an array is another array (if the array has one value in it), whereas var_dump will.

  2. You have tried to bind using the same binding value, for example: ":hash" and ":hash". Every index has to be unique, even if logically it makes sense to use the same for two different parts, even if it's the same value. (it's similar to a constant but more like a placeholder)

  3. If you're binding more than one value in a statement (as is often the case with an "INSERT"), you need to bindParam and then bindValue to the parameters. The process here is to bind the parameters to the fields, and then bind the values to the parameters.

    // Code snippet
    $column_names = array();
    $stmt->bindParam(':'.$i, $column_names[$i], $param_type);
    $stmt->bindValue(':'.$i, $values[$i], $param_type);
    $i++;
    //.....
    
  4. When binding values to column_names or table_names you can use `` but its not necessary, but make sure to be consistent.

  5. Any value in '' single quotes is always treated as a string and will not be read as a column/table name or placeholder to bind to.

Windows command to get service status?

Well i see "Nick Kavadias" telling this:

"according to this http://www.computerhope.com/nethlp.htm it should be NET START /LIST ..."

If you type in Windows XP this:

NET START /LIST

you will get an error, just type instead

NET START

The /LIST is only for Windows 2000... If you fully read such web you would see the /LIST is only on Windows 2000 section.

Hope this helps!!!

Python: Assign Value if None Exists

You should initialize variables to None and then check it:

var1 = None
if var1 is None:
    var1 = 4

Which can be written in one line as:

var1 = 4 if var1 is None else var1

or using shortcut (but checking against None is recommended)

var1 = var1 or 4

alternatively if you will not have anything assigned to variable that variable name doesn't exist and hence using that later will raise NameError, and you can also use that knowledge to do something like this

try:
    var1
except NameError:
    var1 = 4

but I would advise against that.

What does iterator->second mean?

I'm sure you know that a std::vector<X> stores a whole bunch of X objects, right? But if you have a std::map<X, Y>, what it actually stores is a whole bunch of std::pair<const X, Y>s. That's exactly what a map is - it pairs together the keys and the associated values.

When you iterate over a std::map, you're iterating over all of these std::pairs. When you dereference one of these iterators, you get a std::pair containing the key and its associated value.

std::map<std::string, int> m = /* fill it */;
auto it = m.begin();

Here, if you now do *it, you will get the the std::pair for the first element in the map.

Now the type std::pair gives you access to its elements through two members: first and second. So if you have a std::pair<X, Y> called p, p.first is an X object and p.second is a Y object.

So now you know that dereferencing a std::map iterator gives you a std::pair, you can then access its elements with first and second. For example, (*it).first will give you the key and (*it).second will give you the value. These are equivalent to it->first and it->second.

isPrime Function for Python Language

def is_prime(x):  
    if x < 2:  
        return False  
    for n in range(2, (x) - 1):  
        if x % n == 0:  
            return False  
    return True

How to force reloading php.ini file?

TL;DR; If you're still having trouble after restarting apache or nginx, also try restarting the php-fpm service.

The answers here don't always satisfy the requirement to force a reload of the php.ini file. On numerous occasions I've taken these steps to be rewarded with no update, only to find the solution I need after also restarting the php-fpm service. So if restarting apache or nginx doesn't trigger a php.ini update although you know the files are updated, try restarting php-fpm as well.

To restart the service:

Note: prepend sudo if not root

Using SysV Init scripts directly:

/etc/init.d/php-fpm restart        # typical
/etc/init.d/php5-fpm restart       # debian-style
/etc/init.d/php7.0-fpm restart     # debian-style PHP 7

Using service wrapper script

service php-fpm restart        # typical
service php5-fpm restart       # debian-style
service php7.0-fpm restart.    # debian-style PHP 7

Using Upstart (e.g. ubuntu):

restart php7.0-fpm         # typical (ubuntu is debian-based) PHP 7
restart php5-fpm           # typical (ubuntu is debian-based)
restart php-fpm            # uncommon

Using systemd (newer servers):

systemctl restart php-fpm.service        # typical
systemctl restart php5-fpm.service       # uncommon
systemctl restart php7.0-fpm.service     # uncommon PHP 7

Or whatever the equivalent is on your system.

The above commands taken directly from this server fault answer

How to set environment variable for everyone under my linux system?

As well as /etc/profile which others have mentioned, some Linux systems now use a directory /etc/profile.d/; any .sh files in there will be sourced by /etc/profile. It's slightly neater to keep your custom environment stuff in these files than to just edit /etc/profile.

C++ - struct vs. class

The other difference is that

template<class T> ...

is allowed, but

template<struct T> ...

is not.

Setting the number of map tasks and reduce tasks

From what I understand reading above, it depends on the input files. If Input Files are 100 means - Hadoop will create 100 map tasks. However, it depends on the Node configuration on How Many can be run at one point of time. If a node is configured to run 10 map tasks - only 10 map tasks will run in parallel by picking 10 different input files out of the 100 available. Map tasks will continue to fetch more files as and when it completes processing of a file.

Merge Cell values with PHPExcel - PHP

$this->excel->setActiveSheetIndex(0)->mergeCells("A".($p).":B".($p)); for dynamic merging of cells

Check whether a variable is a string in Ruby

You can do:

foo.instance_of?(String)

And the more general:

foo.kind_of?(String)

How to install Cmake C compiler and CXX compiler

Those errors :

"CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage

CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage"

means you haven't installed mingw32-base.

Go to http://sourceforge.net/projects/mingw/files/latest/download?source=files

and then make sure you select "mingw32-base"

Make sure you set up environment variables correctly in PATH section. "C:\MinGW\bin"

After that open CMake and Select Installation --> Delete Cache.

And click configure button again. I solved the problem this way, hope you solve the problem.

Laravel Fluent Query Builder Join with subquery

I can't comment because my reputation is not high enough. @Franklin Rivero if you are using Laravel 5.2 you can set the bindings on the main query instead of the join using the setBindings method.

So the main query in @ph4r05's answer would look something like this:

$q = DnsResult::query()
    ->from($dnsTable . ' AS s')
    ->join(
        DB::raw('(' . $qqSql. ') AS ss'),
        function(JoinClause $join) {
            $join->on('s.watch_id', '=', 'ss.watch_id')
                 ->on('s.last_scan_at', '=', 'ss.last_scan');
        })
    ->setBindings($subq->getBindings());

Java Pass Method as Parameter

I did not found any solution here that show how to pass method with parameters bound to it as a parameter of a method. Bellow is example of how you can pass a method with parameter values already bound to it.

  1. Step 1: Create two interfaces one with return type, another without. Java has similar interfaces but they are of little practical use because they do not support Exception throwing.


    public interface Do {
    void run() throws Exception;
    }


    public interface Return {
        R run() throws Exception;
    }

  1. Example of how we use both interfaces to wrap method call in transaction. Note that we pass method with actual parameters.


    //example - when passed method does not return any value
    public void tx(final Do func) throws Exception {
        connectionScope.beginTransaction();
        try {
            func.run();
            connectionScope.commit();
        } catch (Exception e) {
            connectionScope.rollback();
            throw e;
        } finally {
            connectionScope.close();
        }
    }

    //Invoke code above by 
    tx(() -> api.delete(6));

Another example shows how to pass a method that actually returns something



        public  R tx(final Return func) throws Exception {
    R r=null;
    connectionScope.beginTransaction();
    try {
                r=func.run();
                connectionScope.commit();
            } catch (Exception e) {
                connectionScope.rollback();
                throw e;
            } finally {
                connectionScope.close();
            }
        return r;
        }
        //Invoke code above by 
        Object x= tx(() -> api.get(id));

Generate a random letter in Python

My overly complicated piece of code:

import random

letter = (random.randint(1,26))
if letter == 1:
   print ('a')
elif letter == 2:
    print ('b')
elif letter == 3:
    print ('c')
elif letter == 4:
    print ('d')
elif letter == 5:
    print ('e')
elif letter == 6:
    print ('f')
elif letter == 7:
    print ('g')
elif letter == 8:
    print ('h')
elif letter == 9:
    print ('i')
elif letter == 10:
    print ('j')
elif letter == 11:
    print ('k')
elif letter == 12:
    print ('l')
elif letter == 13:
    print ('m')
elif letter == 14:
    print ('n')
elif letter == 15:
    print ('o')
elif letter == 16:
    print ('p')
elif letter == 17:
    print ('q')
elif letter == 18:
    print ('r')
elif letter == 19:
    print ('s')
elif letter == 20:
    print ('t')
elif letter == 21:
    print ('u')
elif letter == 22:
    print ('v')
elif letter == 23:
    print ('w')
elif letter == 24:
    print ('x')
elif letter == 25:
    print ('y')
elif letter == 26:
    print ('z')

It basically generates a random number out of 26 and then converts into its corresponding letter. This could defiantly be improved but I am only a beginner and I am proud of this piece of code.

How to check if Receiver is registered in Android?

Personally I use the method of calling unregisterReceiver and swallowing the exception if it's thrown. I agree this is ugly but the best method currently provided.

I've raised a feature request to get a boolean method to check if a receiver is registered added to the Android API. Please support it here if you want to see it added: https://code.google.com/p/android/issues/detail?id=73718

Java Refuses to Start - Could not reserve enough space for object heap

It seems that for 32-bit servers there is a JVM limitation that cannot be overcome (unless you find a special 32-bit JVM that does not impose a 2GB limit or less).

This thread on The Server Side has more details including several people who tested out various JVMs on 32-bit architectures. IBM's JVM seems to allow 100 more MB but that's not really going to get you what you want.

http://www.theserverside.com/discussions/thread.tss?thread_id=26347

The "real" solution is to use a 64-bit server with a 64-bit JVM to get heaps larger than 2GB per process. However, it's important to also consider the impact of increasing your address size (not just the addressable space) by using a 64-bit JVM. There will likely be performance and memory impacts for processing using less than 4GB of memory.

Food for thought: do each of these jobs really require 2GB of memory? Is there any way for the jobs to be modified to run within 1.8GB so this limit is not a problem?

Ruby/Rails: converting a Date to a UNIX timestamp

The code date.to_time.to_i should work fine. The Rails console session below shows an example:

>> Date.new(2009,11,26).to_time
=> Thu Nov 26 00:00:00 -0800 2009
>> Date.new(2009,11,26).to_time.to_i
=> 1259222400
>> Time.at(1259222400)
=> Thu Nov 26 00:00:00 -0800 2009

Note that the intermediate DateTime object is in local time, so the timestamp might be a several hours off from what you expect. If you want to work in UTC time, you can use the DateTime's method "to_utc".

When to use StringBuilder in Java

For two strings concat is faster, in other cases StringBuilder is a better choice, see my explanation in concatenation operator (+) vs concat()

force browsers to get latest js and css files in asp.net application

ASP.NET MVC will handle this for you if you use bundles for your JS/CSS. It will automatically append a version number in the form of a GUID to your bundles and only update this GUID when the bundle is updated (aka any of the source files have changes).

This also helps if you have a ton of JS/CSS files as it can greatly improve content load times!

See Here

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

UPDATE  table
SET     columnx = CASE WHEN condition THEN 25 ELSE columnx END,
        columny = CASE WHEN condition THEN columny ELSE 25 END

HTML input file selection event not firing upon selecting the same file

In this article, under the title "Using form input for selecting"

http://www.html5rocks.com/en/tutorials/file/dndfiles/

<input type="file" id="files" name="files[]" multiple />

<script>
function handleFileSelect(evt) {

    var files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    var output = [];
    for (var i = 0, f; f = files[i]; i++) {
     // Code to execute for every file selected
    }
    // Code to execute after that

}

document.getElementById('files').addEventListener('change', 
                                                  handleFileSelect, 
                                                  false);
</script>

It adds an event listener to 'change', but I tested it and it triggers even if you choose the same file and not if you cancel.

Stock ticker symbol lookup API

Your best bets are probably going with one of the other lookup services (still screen-scraping), and checking whether they don't require CAPTCHAs.

The last appears the least likely to require a CAPTCHA at any point, but it's worth checking all three.

Fastest method of screen capturing on Windows

I wrote a class that implemented the GDI method for screen capture. I too wanted extra speed so, after discovering the DirectX method (via GetFrontBuffer) I tried that, expecting it to be faster.

I was dismayed to find that GDI performs about 2.5x faster. After 100 trials capturing my dual monitor display, the GDI implementation averaged 0.65s per screen capture, while the DirectX method averaged 1.72s. So GDI is definitely faster than GetFrontBuffer, according to my tests.

I was unable to get Brandrew's code working to test DirectX via GetRenderTargetData. The screen copy came out purely black. However, it could copy that blank screen super fast! I'll keep tinkering with that and hope to get a working version to see real results from it.

Java: get greatest common divisor

Those GCD functions provided by Commons-Math and Guava have some differences.

  • Commons-Math throws an ArithematicException.class only for Integer.MIN_VALUE or Long.MIN_VALUE.
    • Otherwise, handles the value as an absolute value.
  • Guava throws an IllegalArgumentException.class for any negative values.

Reduce git repository size

git gc --aggressive is one way to force the prune process to take place (to be sure: git gc --aggressive --prune=now). You have other commands to clean the repo too. Don't forget though, sometimes git gc alone can increase the size of the repo!

It can be also used after a filter-branch, to mark some directories to be removed from the history (with a further gain of space); see here. But that means nobody is pulling from your public repo. filter-branch can keep backup refs in .git/refs/original, so that directory can be cleaned too.

Finally, as mentioned in this comment and this question; cleaning the reflog can help:

git reflog expire --all --expire=now
git gc --prune=now --aggressive

An even more complete, and possibly dangerous, solution is to remove unused objects from a git repository


Update Feb. 2021, eleven years later: the new git maintenance command (man page) should supersede git gc, and can be scheduled.

What are the First and Second Level caches in (N)Hibernate?

There's a pretty good explanation of first level caching on the Streamline Logic blog.

Basically, first level caching happens on a per session basis where as second level caching can be shared across multiple sessions.

How do I add to the Windows PATH variable using setx? Having weird problems

I was having such trouble managing my computer labs when the %PATH% environment variable approached 1024 characters that I wrote a Powershell script to fix it.

You can download the code here: https://gallery.technet.microsoft.com/scriptcenter/Edit-and-shorten-PATH-37ef3189

You can also use it as a simple way to safely add, remove and parse PATH entries. Enjoy.

Jackson overcoming underscores in favor of camel-case

If its a spring boot application, In application.properties file, just use

spring.jackson.property-naming-strategy=SNAKE_CASE

Or Annotate the model class with this annotation.

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)

REST response code for invalid data

400 is the best choice in both cases. If you want to further clarify the error you can either change the Reason Phrase or include a body to explain the error.

412 - Precondition failed is used for conditional requests when using last-modified date and ETags.

403 - Forbidden is used when the server wishes to prevent access to a resource.

The only other choice that is possible is 422 - Unprocessable entity.

OS X Bash, 'watch' command

You can emulate the basic functionality with the shell loop:

while :; do clear; your_command; sleep 2; done

That will loop forever, clear the screen, run your command, and wait two seconds - the basic watch your_command implementation.

You can take this a step further and create a watch.sh script that can accept your_command and sleep_duration as parameters:

#!/bin/bash
# usage: watch.sh <your_command> <sleep_duration>

while :; 
  do 
  clear
  date
  $1
  sleep $2
done

Angular2 - Input Field To Accept Only Numbers

I know this is an old question, but since this is a common funcionality, I want to share the modifications I've made:

  • Custom decimal separator (point or comma)
  • Support for integers only or integer and decimals
  • Support for positive numbers only or positives and negatives
  • Validate minus sign(-) is in the beginning
  • Support to mouse pasting (with some limitation though https://caniuse.com/#feat=clipboard)
  • Support for Mac command key
  • Replace strings like ".33" and "33." for the correct versions: 0.33 and 33.0

    import { Directive, ElementRef, HostListener, Input } from '@angular/core';
    
    @Directive({ selector: '[NumbersOnly]' })
    export class NumbersOnly { 
    
        @Input() allowDecimals: boolean = true;
        @Input() allowSign: boolean = false;
        @Input() decimalSeparator: string = '.';
    
        previousValue: string = '';
    
        // --------------------------------------
        //  Regular expressions
        integerUnsigned: string = '^[0-9]*$';
        integerSigned: string = '^-?[0-9]+$';
        decimalUnsigned: string = '^[0-9]+(.[0-9]+)?$';
        decimalSigned: string = '^-?[0-9]+(.[0-9]+)?$';
    
        /**
         * Class constructor
         * @param hostElement
         */
        constructor(private hostElement: ElementRef) { }
    
        /**
         * Event handler for host's change event
         * @param e
         */
        @HostListener('change', ['$event']) onChange(e) {
    
                this.validateValue(this.hostElement.nativeElement.value);
    }
    
    /**
     * Event handler for host's paste event
     * @param e
     */
    @HostListener('paste', ['$event']) onPaste(e) {
    
        // get and validate data from clipboard
        let value = e.clipboardData.getData('text/plain');
        this.validateValue(value);
        e.preventDefault();
    }
    
    /**
     * Event handler for host's keydown event
     * @param event
     */
    @HostListener('keydown', ['$event']) onKeyDown(e: KeyboardEvent) {
    
        let cursorPosition: number = e.target['selectionStart'];
        let originalValue: string = e.target['value'];
        let key: string = this.getName(e);
        let controlOrCommand = (e.ctrlKey === true || e.metaKey === true);
        let signExists = originalValue.includes('-');
        let separatorExists = originalValue.includes(this.decimalSeparator);
    
        // allowed keys apart from numeric characters
        let allowedKeys = [
            'Backspace', 'ArrowLeft', 'ArrowRight', 'Escape', 'Tab'
        ];
    
        // when decimals are allowed, add
        // decimal separator to allowed codes when
        // its position is not close to the the sign (-. and .-)
        let separatorIsCloseToSign = (signExists && cursorPosition <= 1);
        if (this.allowDecimals && !separatorIsCloseToSign && !separatorExists) {
    
            if (this.decimalSeparator == '.')
                allowedKeys.push('.');
            else
                allowedKeys.push(',');
        }
    
        // when minus sign is allowed, add its
        // key to allowed key only when the
        // cursor is in the first position, and
        // first character is different from
        // decimal separator
        let firstCharacterIsSeparator = (originalValue.charAt(0) != this.decimalSeparator);
        if (this.allowSign && !signExists &&
            firstCharacterIsSeparator && cursorPosition == 0) {
    
            allowedKeys.push('-');
        }
    
        // allow some non-numeric characters
        if (allowedKeys.indexOf(key) != -1 ||
            // Allow: Ctrl+A and Command+A
            (key == 'a' && controlOrCommand) ||
            // Allow: Ctrl+C and Command+C
            (key == 'c' && controlOrCommand) ||
            // Allow: Ctrl+V and Command+V
            (key == 'v' && controlOrCommand) ||
            // Allow: Ctrl+X and Command+X
            (key == 'x' && controlOrCommand)) {
            // let it happen, don't do anything
            return;
        }
    
        // save value before keydown event
        this.previousValue = originalValue;
    
        // allow number characters only
        let isNumber = (new RegExp(this.integerUnsigned)).test(key);
        if (isNumber) return; else e.preventDefault();
    }
    
    /**
     * Test whether value is a valid number or not
     * @param value
     */
    validateValue(value: string): void {
    
        // choose the appropiate regular expression
        let regex: string;
        if (!this.allowDecimals && !this.allowSign) regex = this.integerUnsigned;
        if (!this.allowDecimals && this.allowSign) regex = this.integerSigned;
        if (this.allowDecimals && !this.allowSign) regex = this.decimalUnsigned;
        if (this.allowDecimals &&  this.allowSign) regex = this.decimalSigned;
    
        // when a numbers begins with a decimal separator,
        // fix it adding a zero in the beginning
        let firstCharacter = value.charAt(0);
        if (firstCharacter == this.decimalSeparator)
            value = 0 + value;
    
        // when a numbers ends with a decimal separator,
        // fix it adding a zero in the end
        let lastCharacter = value.charAt(value.length-1);
        if (lastCharacter == this.decimalSeparator)
            value = value + 0;
    
        // test number with regular expression, when
        // number is invalid, replace it with a zero
        let valid: boolean = (new RegExp(regex)).test(value);
        this.hostElement.nativeElement['value'] = valid ? value : 0;
    }
    
    /**
     * Get key's name
     * @param e
     */
    getName(e): string {
    
        if (e.key) {
    
            return e.key;
    
        } else {
    
            // for old browsers
            if (e.keyCode && String.fromCharCode) {
    
                switch (e.keyCode) {
                    case   8: return 'Backspace';
                    case   9: return 'Tab';
                    case  27: return 'Escape';
                    case  37: return 'ArrowLeft';
                    case  39: return 'ArrowRight';
                    case 188: return ',';
                    case 190: return '.';
                    case 109: return '-'; // minus in numbpad
                    case 173: return '-'; // minus in alphabet keyboard in firefox
                    case 189: return '-'; // minus in alphabet keyboard in chrome
                    default: return String.fromCharCode(e.keyCode);
                }
            }
        }
    }
    

Usage:

 <input NumbersOnly
        [allowDecimals]="true"
        [allowSign]="true"
        type="text">

Running a command as Administrator using PowerShell?

To append the output of the command to a text filename which includes the current date you can do something like this:

$winupdfile = 'Windows-Update-' + $(get-date -f MM-dd-yyyy) + '.txt'
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -Command `"Get-WUInstall -AcceptAll | Out-File $env:USERPROFILE\$winupdfile -Append`"" -Verb RunAs; exit } else { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -Command `"Get-WUInstall -AcceptAll | Out-File $env:USERPROFILE\$winupdfile -Append`""; exit }

Getting Spring Application Context

If you use a web-app there is also another way to access the application context without using singletons by using a servletfilter and a ThreadLocal. In the filter you can access the application context using WebApplicationContextUtils and store either the application context or the needed beans in the TheadLocal.

Caution: if you forget to unset the ThreadLocal you will get nasty problems when trying to undeploy the application! Thus, you should set it and immediately start a try that unsets the ThreadLocal in the finally-part.

Of course, this still uses a singleton: the ThreadLocal. But the actual beans do not need to be anymore. The can even be request-scoped, and this solution also works if you have multiple WARs in an Application with the libaries in the EAR. Still, you might consider this use of ThreadLocal as bad as the use of plain singletons. ;-)

Perhaps Spring already provides a similar solution? I did not find one, but I don't know for sure.

Count number of rows by group using dplyr

another approach is to use the double colons:

mtcars %>% 
  dplyr::group_by(cyl, gear) %>%
  dplyr::summarise(length(gear))

Best practices for SQL varchar column length

No DBMS I know of has any "optimization" that will make a VARCHAR with a 2^n length perform better than one with a max length that is not a power of 2.

I think early SQL Server versions actually treated a VARCHAR with length 255 differently than one with a higher maximum length. I don't know if this is still the case.

For almost all DBMS, the actual storage that is required is only determined by the number of characters you put into it, not the max length you define. So from a storage point of view (and most probably a performance one as well), it does not make any difference whether you declare a column as VARCHAR(100) or VARCHAR(500).

You should see the max length provided for a VARCHAR column as a kind of constraint (or business rule) rather than a technical/physical thing.

For PostgreSQL the best setup is to use text without a length restriction and a CHECK CONSTRAINT that limits the number of characters to whatever your business requires.

If that requirement changes, altering the check constraint is much faster than altering the table (because the table does not need to be re-written)

The same can be applied for Oracle and others - in Oracle it would be VARCHAR(4000) instead of text though.

I don't know if there is a physical storage difference between VARCHAR(max) and e.g. VARCHAR(500) in SQL Server. But apparently there is a performance impact when using varchar(max) as compared to varchar(8000).

See this link (posted by Erwin Brandstetter as a comment)

Edit 2013-09-22

Regarding bigown's comment:

In Postgres versions before 9.2 (which was not available when I wrote the initial answer) a change to the column definition did rewrite the whole table, see e.g. here. Since 9.2 this is no longer the case and a quick test confirmed that increasing the column size for a table with 1.2 million rows indeed only took 0.5 seconds.

For Oracle this seems to be true as well, judging by the time it takes to alter a big table's varchar column. But I could not find any reference for that.

For MySQL the manual says "In most cases, ALTER TABLE makes a temporary copy of the original table". And my own tests confirm that: running an ALTER TABLE on a table with 1.2 million rows (the same as in my test with Postgres) to increase the size of a column took 1.5 minutes. In MySQL however you can not use the "workaround" to use a check constraint to limit the number of characters in a column.

For SQL Server I could not find a clear statement on this but the execution time to increase the size of a varchar column (again the 1.2 million rows table from above) indicates that no rewrite takes place.

Edit 2017-01-24

Seems I was (at least partially) wrong about SQL Server. See this answer from Aaron Bertrand that shows that the declared length of a nvarchar or varchar columns makes a huge difference for the performance.

React JSX: selecting "selected" on selected <select> option

I've had a problem with <select> tags not updating to the correct <option> when the state changes. My problem seemed to be that if you render twice in quick succession, the first time with no pre-selected <option> but the second time with one, then the <select> tag doesn't update on the second render, but stays on the default first .

I found a solution to this using refs. You need to get a reference to your <select> tag node (which might be nested in some component), and then manually update the value property on it, in the componentDidUpdate hook.

componentDidUpdate(){
  let selectNode = React.findDOMNode(this.refs.selectingComponent.refs.selectTag);
  selectNode.value = this.state.someValue;
}

Is there any way to return HTML in a PHP function? (without building the return value as a string)

Yes, there is: you can capture the echoed text using ob_start:

<?php function TestBlockHTML($replStr) {
    ob_start(); ?>
    <html>
    <body><h1><?php echo($replStr) ?></h1>
    </html>
<?php
    return ob_get_clean();
} ?>

How to deserialize a list using GSON or another JSON library in Java?

I recomend this one-liner

List<Video> videos = Arrays.asList(new Gson().fromJson(json, Video[].class));

Warning: the list of videos, returned by Arrays.asList is immutable - you can't insert new values. If you need to modify it, wrap in new ArrayList<>(...).


Reference:

  1. Method Arrays#asList
  2. Constructor Gson
  3. Method Gson#fromJson (source json may be of type JsonElement, Reader, or String)
  4. Interface List
  5. JLS - Arrays
  6. JLS - Generic Interfaces

Creating Accordion Table with Bootstrap

This seems to be already asked before:

This might help:

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

UPDATE:

Your fiddle wasn't loading jQuery, so anything worked.

<table class="table table-hover">
<thead>
  <tr>
    <th></th>
    <th></th>
    <th></th>
  </tr>
</thead>

<tbody>
    <tr data-toggle="collapse" data-target="#accordion" class="clickable">
        <td>Some Stuff</td>
        <td>Some more stuff</td>
        <td>And some more</td>
    </tr>
    <tr>
        <td colspan="3">
            <div id="accordion" class="collapse">Hidden by default</div>
        </td>
    </tr>
</tbody>
</table>

Try this one: http://jsfiddle.net/Nb7wy/2/

I also added colspan='2' to the details row. But it's essentially your fiddle with jQuery loaded (in frameworks in the left column)

Android: Clear Activity Stack

For Xamarin Developers, you can use:

intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);

How to call javascript function from code-behind

If the order of the execution is not important and you need both some javascript AND some codebehind to be fired on an asp element, heres what you can do.

What you can take away from my example: I have a div covering the ASP control that I want both javascript and codebehind to be ran from. The div's onClick method AND the calendar's OnSelectionChanged event both get fired this way.

In this example, i am using an ASP Calendar control, and im controlling it from both javascript and codebehind:

Front end code:

        <div onclick="showHideModal();">
            <asp:Calendar 
                OnSelectionChanged="DatepickerDateChange" ID="DatepickerCalendar" runat="server" 
                BorderWidth="1px" DayNameFormat="Shortest" Font-Names="Verdana" 
                Font-Size="8pt" ShowGridLines="true" BackColor="#B8C9E1" BorderColor="#003E51" Width="100%"> 
                <OtherMonthDayStyle ForeColor="#6C5D34"> </OtherMonthDayStyle> 
                <DayHeaderStyle  ForeColor="black" BackColor="#D19000"> </DayHeaderStyle>
                <TitleStyle BackColor="#B8C9E1" ForeColor="Black"> </TitleStyle> 
                <DayStyle BackColor="White"> </DayStyle> 
                <SelectedDayStyle BackColor="#003E51" Font-Bold="True"> </SelectedDayStyle> 
            </asp:Calendar>
        </div>

Codebehind:

        protected void DatepickerDateChange(object sender, EventArgs e)
        {
            if (toFromPicked.Value == "MainContent_fromDate")
            {
                fromDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
            }
            else
            {
                toDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
            }
        }