Programs & Examples On #Fcgid

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

I came across this one while debugging a virtualmin/apache related error.

In my case, I am running virtualmin and had in my virtual machine's php.ini safe_mode=On.

In my Virtual Machine's error log, I was getting the fcgi Connection reset by peer: mod_fcgid: error reading data from FastCGI server

In my main apache error log I was getting: PHP Fatal error: Directive 'safe_mode' is no longer available in PHP in Unknown on line 0

In my case, I simply set safe_mode = Off in my php.ini and restarted apache.

stackoverflow.com/questions/18683177/where-to-start-with-deprecated-directive-safe-mode-on-line-0-in-apache-error

PHP Fatal Error Failed opening required File

If you have SELinux running, you might have to grant httpd permission to read from /home dir using:

 sudo setsebool httpd_read_user_content=1

Wordpress 403/404 Errors: You don't have permission to access /wp-admin/themes.php on this server

Just to follow up, problem solved! I mentioned mod_sec settings for my server as being the possible culprit as suggested and they were able to fix this issue. Here's what the tech agent said to tell them when you go to support:

Just let them know you need the rule 340163 whitelisted for domain.com as its hitting a mod_sec rule.

Apparently you will need to do this for each domain that is having the issue, but it works. Thanks for all the suggestions everyone!

Enter triggers button click

Where ever you use a <button> element by default it considers that button type="submit" so if you define the button type="button" then it won't consider that <button> as submit button.

How to parse a String containing XML in Java and retrieve the value of the root node?

One of the above answer states to convert XML String to bytes which is not needed. Instead you can can use InputSource and supply it with StringReader.

String xmlStr = "<message>HELLO!</message>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xmlStr)));
System.out.println(doc.getFirstChild().getNodeValue());

Java check to see if a variable has been initialized

Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.

Now if you know that once assigned, the value will never reassigned a value of null, you can use:

if (box != null) {
    box.removeFromCanvas();
}

(and that also avoids a possible NullPointerException) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:

if (box != null) {
    box.removeFromCanvas();
    // Forget about the box - we don't want to try to remove it again
    box = null;
}

The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):

// Won't compile
String x;
System.out.println(x);

// Will compile, prints null
String y = null;
System.out.println(y);

How do I add target="_blank" to a link within a specified div?

/* here are two different ways to do this */
//using jquery:
$(document).ready(function(){
  $('#link_other a').attr('target', '_blank');
});

// not using jquery
window.onload = function(){
  var anchors = document.getElementById('link_other').getElementsByTagName('a');
  for (var i=0; i<anchors.length; i++){
    anchors[i].setAttribute('target', '_blank');
  }
}
// jquery is prettier. :-)

You could also add a title tag to notify the user that you are doing this, to warn them, because as has been pointed out, it's not what users expect:

$('#link_other a').attr('target', '_blank').attr('title','This link will open in a new window.');

How do I send a POST request as a JSON?

I recommend using the incredible requests module.

http://docs.python-requests.org/en/v0.10.7/user/quickstart/#custom-headers

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

response = requests.post(url, data=json.dumps(payload), headers=headers)

Changing plot scale by a factor in matplotlib

To set the range of the x-axis, you can use set_xlim(left, right), here are the docs

Update:

It looks like you want an identical plot, but only change the 'tick values', you can do that by getting the tick values and then just changing them to whatever you want. So for your need it would be like this:

ticks = your_plot.get_xticks()*10**9
your_plot.set_xticklabels(ticks)

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

If your file idea/workspace.xml is added to .gitignore (or its parent folder) just add it manually to git version control. Also you can add it using TortoiseGit. After the next push you will see, that your problem is solved.

Add to git versioning using TortoiseGit

iOS detect if user is on an iPad

There are quite a few ways to check if a device is an iPad. This is my favorite way to check whether the device is in fact an iPad:

if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad )
{
    return YES; /* Device is iPad */
}

The way I use it

#define IDIOM    UI_USER_INTERFACE_IDIOM()
#define IPAD     UIUserInterfaceIdiomPad

if ( IDIOM == IPAD ) {
    /* do something specifically for iPad. */
} else {
    /* do something specifically for iPhone or iPod touch. */
}   

Other Examples

if ( [(NSString*)[UIDevice currentDevice].model hasPrefix:@"iPad"] ) {
    return YES; /* Device is iPad */
}

#define IPAD     (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
if ( IPAD ) 
     return YES;

For a Swift solution, see this answer: https://stackoverflow.com/a/27517536/2057171

How to clear or stop timeInterval in angularjs?

var interval = $interval(function() {
  console.log('say hello');
}, 1000);

$interval.cancel(interval);

Multiprocessing a for loop?

You can use multiprocessing.Pool:

from multiprocessing import Pool
class Engine(object):
    def __init__(self, parameters):
        self.parameters = parameters
    def __call__(self, filename):
        sci = fits.open(filename + '.fits')
        manipulated = manipulate_image(sci, self.parameters)
        return manipulated

try:
    pool = Pool(8) # on 8 processors
    engine = Engine(my_parameters)
    data_outputs = pool.map(engine, data_inputs)
finally: # To make sure processes are closed in the end, even if errors happen
    pool.close()
    pool.join()

How to decrypt hash stored by bcrypt

You can use the password_verify function with the PHP. It verifies that a password matches with the hash

password_verify ( string $password , string $hash ) : bool

more details: https://www.php.net/manual/en/function.password-verify.php

redistributable offline .NET Framework 3.5 installer for Windows 8

Try this command:

Dism.exe /online /enable-feature /featurename:NetFX3 /Source:I:\Sources\sxs /LimitAccess

I: partition of your Windows DVD.

How to scroll to top of the page in AngularJS?

You can use $anchorScroll.

Just inject $anchorScroll as a dependency, and call $anchorScroll() whenever you want to scroll to top.

How to pass arguments to Shell Script through docker run

With Docker, the proper way to pass this sort of information is through environment variables.

So with the same Dockerfile, change the script to

#!/bin/bash
echo $FOO

After building, use the following docker command:

docker run -e FOO="hello world!" test

Converting an int to a binary string representation in Java?

You should really use Integer.toBinaryString() (as shown above), but if for some reason you want your own:

// Like Integer.toBinaryString, but always returns 32 chars
public static String asBitString(int value) {
  final char[] buf = new char[32];
  for (int i = 31; i >= 0; i--) {
    buf[31 - i] = ((1 << i) & value) == 0 ? '0' : '1';
  }
  return new String(buf);
}

Ruby String to Date Conversion

Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")

Should be:

Date.strptime(updated, '%a, %d %b %Y %H:%M:%S %Z')

Center Triangle at Bottom of Div

Can't you just set left to 50% and then have margin-left set to -25px to account for it's width: http://jsfiddle.net/9AbYc/

.hero:after {
    content:'';
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -50px;
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

or if you needed a variable width you could use: http://jsfiddle.net/9AbYc/1/

.hero:after {
    content:'';
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    margin: 0 auto;
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

Counting number of occurrences in column?

Just adding some extra sorting if needed

=QUERY(A2:A,"select A, count(A) where A is not null group by A order by count(A) DESC label A 'Name', count(A) 'Count'",-1)

enter image description here

Counting null and non-null values in a single query

if its mysql, you can try something like this.

select 
   (select count(*) from TABLENAME WHERE a = 'null') as total_null, 
   (select count(*) from TABLENAME WHERE a != 'null') as total_not_null
FROM TABLENAME

Convert wchar_t to char

assert is for ensuring that something is true in a debug mode, without it having any effect in a release build. Better to use an if statement and have an alternate plan for characters that are outside the range, unless the only way to get characters outside the range is through a program bug.

Also, depending on your character encoding, you might find a difference between the Unicode characters 0x80 through 0xff and their char version.

Select data from "show tables" MySQL query

You can create a stored procedure and put the table names in a cursor, then loop through your table names to show the data.

Getting started with stored procedure: http://www.mysqltutorial.org/getting-started-with-mysql-stored-procedures.aspx

Creating a cursor: http://www.mysqltutorial.org/mysql-cursor/

For example,

CREATE PROCEDURE `ShowFromTables`()
BEGIN

DECLARE v_finished INTEGER DEFAULT 0;
DECLARE c_table varchar(100) DEFAULT "";

DECLARE table_cursor CURSOR FOR 
SELECT table_name FROM information_schema.tables WHERE table_name like 'wp_1%';

DECLARE CONTINUE HANDLER 
    FOR NOT FOUND SET v_finished = 1;

OPEN table_cursor;

get_data: LOOP

FETCH table_cursor INTO c_table;

IF v_finished = 1 THEN 
LEAVE get_data;
END IF;

SET @s=CONCAT("SELECT * FROM ",c_table,";");

PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

END LOOP get_data;

CLOSE table_cursor;

END

Then call the stored procedure:

CALL ShowFromTables();

spring PropertyPlaceholderConfigurer and context:property-placeholder

First, you don't need to define both of those locations. Just use classpath:config/properties/database.properties. In a WAR, WEB-INF/classes is a classpath entry, so it will work just fine.

After that, I think what you mean is you want to use Spring's schema-based configuration to create a configurer. That would go like this:

<context:property-placeholder location="classpath:config/properties/database.properties"/>

Note that you don't need to "ignoreResourceNotFound" anymore. If you need to define the properties separately using util:properties:

<context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>

There's usually not any reason to define them separately, though.

ASP.NET 4.5 has not been registered on the Web server

If you've installed .NET framework 4.6, you may see this error due to a VS bug. Workarounds and resolutions here:

http://blogs.msdn.com/b/webdev/archive/2014/11/11/dialog-box-may-be-displayed-to-users-when-opening-projects-in-microsoft-visual-studio-after-installation-of-microsoft-net-framework-4-6.aspx

EDIT:

As noted in some of the comments, this can happen behind the scenes after upgrading to Windows 10 or Visual Studio 2015.

How do the likely/unlikely macros in the Linux kernel work and what is their benefit?

As per the comment by Cody, this has nothing to do with Linux, but is a hint to the compiler. What happens will depend on the architecture and compiler version.

This particular feature in Linux is somewhat mis-used in drivers. As osgx points out in semantics of hot attribute, any hot or cold function called with in a block can automatically hint that the condition is likely or not. For instance, dump_stack() is marked cold so this is redundant,

 if(unlikely(err)) {
     printk("Driver error found. %d\n", err);
     dump_stack();
 }

Future versions of gcc may selectively inline a function based on these hints. There have also been suggestions that it is not boolean, but a score as in most likely, etc. Generally, it should be preferred to use some alternate mechanism like cold. There is no reason to use it in any place but hot paths. What a compiler will do on one architecture can be completely different on another.

How to compile multiple java source files in command line

OR you could just use javac file1.java and then also use javac file2.java afterwards.

Blur effect on a div element

Try using this library: https://github.com/jakiestfu/Blur.js-II

That should do it for ya.

ASP.NET set hiddenfield a value in Javascript

My understanding is if you set controls.Visible = false during initial page load, it doesn't get rendered in the client response. My suggestion to solve your problem is

Don't use placeholder, judging from the scenario, you don't really need a placeholder, unless you need to dynamically add controls on the server side. Use div, without runat=server. You can always controls the visiblity of that div using css. If you need to add controls dynamically later, use placeholder, but don't set visible = false. Placeholder won't have any display anyway, Set the visibility of that placeholder using css. Here's how to do it programmactically :

placeholderId.Attributes["style"] = "display:none";

Anyway, as other have stated, your problems occurs because once you set control.visible = false, it doesn't get rendered in the client response.

What is the location of mysql client ".my.cnf" in XAMPP for Windows?

Look in the MySQL config file C:\xampp\mysql\bin\my.ini.

At the top of that file are some comments:

# You can copy this file to
# C:/xampp/mysql/bin/my.cnf to set global options,
# mysql-data-dir/my.cnf to set server-specific options (in this
# installation this directory is C:/xampp/mysql/data) or
# ~/.my.cnf to set user-specific options.

There it tells you where to find your .my.cnf file.

Storyboard - refer to ViewController in AppDelegate

    UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Tutorial" bundle:nil];
    self.window.rootViewController = [storyboard instantiateInitialViewController];

Remove a string from the beginning of a string

Nice speed, but this is hard-coded to depend on the needle ending with _. Is there a general version? – toddmo Jun 29 at 23:26

A general version:

$parts = explode($start, $full, 2);
if ($parts[0] === '') {
    $end = $parts[1];
} else {
    $fail = true;
}

Some benchmarks:

<?php

$iters = 100000;
$start = "/aaaaaaa/bbbbbbbbbb";
$full = "/aaaaaaa/bbbbbbbbbb/cccccccccc/dddddddddd/eeeeeeeeee";
$end = '';

$fail = false;

$t0 = microtime(true);
for ($i = 0; $i < $iters; $i++) {
    if (strpos($full, $start) === 0) {
        $end = substr($full, strlen($start));
    } else {
        $fail = true;
    }
}
$t = microtime(true) - $t0;
printf("%16s : %f s\n", "strpos+strlen", $t);

$t0 = microtime(true);
for ($i = 0; $i < $iters; $i++) {
    $parts = explode($start, $full, 2);
    if ($parts[0] === '') {
        $end = $parts[1];
    } else {
        $fail = true;
    }
}
$t = microtime(true) - $t0;
printf("%16s : %f s\n", "explode", $t);

On my quite old home PC:

$ php bench.php

Outputs:

   strpos+strlen : 0.158388 s
         explode : 0.126772 s

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Can't add a comment to the solution but that didn't work for me. The solution that worked for me was to use:

var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass)); 
return des.data.Count.ToString();

Deserializing JSON array into strongly typed .NET object

Python 3 turn range to a list

In fact, this is a retro-gradation of Python3 as compared to Python2. Certainly, Python2 which uses range() and xrange() is more convenient than Python3 which uses list(range()) and range() respectively. The reason is because the original designer of Python3 is not very experienced, they only considered the use of the range function by many beginners to iterate over a large number of elements where it is both memory and CPU inefficient; but they neglected the use of the range function to produce a number list. Now, it is too late for them to change back already.

If I was to be the designer of Python3, I will:

  1. use irange to return a sequence iterator
  2. use lrange to return a sequence list
  3. use range to return either a sequence iterator (if the number of elements is large, e.g., range(9999999) or a sequence list (if the number of elements is small, e.g., range(10))

That should be optimal.

Convert string to title case with JavaScript

A slightly more elegant way, adapting Greg Dean's function:

String.prototype.toProperCase = function () {
    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

Call it like:

"pascal".toProperCase();

How do I use LINQ Contains(string[]) instead of Contains(string)

Try the following.

string input = "someString";
string[] toSearchFor = GetSearchStrings();
var containsAll = toSearchFor.All(x => input.Contains(x));

ORA-28001: The password has expired

Try to connect with the users in SQL Plus, whose password has expired. it will prompt for the new password. Enter the new password and confirm password.

It will work

SQL Plus output image

create a white rgba / CSS3

I believe

rgba( 0, 0, 0, 0.8 )

is equivalent in shade with #333.

Live demo: http://jsfiddle.net/8MVC5/1/

What is the difference between match_parent and fill_parent?

match_parent is used in place of fill_parent and sets it to go as far as the parent goes. Just use match_parent and forget about fill_parent. I completely ditched fill_parent and everything is perfect as usual.

Check here for more.

How to send image to PHP file using Ajax?

Post both multiple text inputs plus multiple files via Ajax in one Ajax request

HTML

<form class="form-horizontal" id="myform" enctype="multipart/form-data">
<input type="text" name="name" class="form-control">
<input type="text" name="email" class="form-control">
<input type="file" name="image" class="form-control">
<input type="file" name="anotherFile" class="form-control">

Jquery Code

$(document).on('click','#btnSendData',function (event) {
    event.preventDefault();
    var form = $('#myform')[0];
    var formData = new FormData(form);
    // Set header if need any otherwise remove setup part
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="token"]').attr('value')
        }
    });
    $.ajax({
        url: "{{route('sendFormWithImage')}}",// your request url
        data: formData,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function (data) {
            console.log(data);
        },
        error: function () {

        }
    });

});

how to include js file in php?

Pekka has the correct answer (hence my making this answer a Community Wiki): Use src, not href, to specify the file.

Regarding:

When i try it this way:

<script type="text/javascript">
    document.write('<script type="text/javascript" src="datetimepicker_css.js"></script>');
</script>

the first tag in the document.write function closes
what is the correct way to do this?

You don't want or need document.write for this, but just in case you ever do need to put the characters </script> inside a script tag for some other reason: You do that by ensuring that the HTML parser (which doesn't understand JavaScript) doesn't see a literal </script>. There are a couple of ways of doing that. One way is to escape the / even though you don't need to:

<script type='text/javascript'>
alert("<\/script>"); // Works, HTML parser doesn't see this as a closing script tag
//      ^--- note the seemingly-unnecessary backslash
</script>

Or if you're feeling more paranoid:

<script type='text/javascript'>
alert("</scr" + "ipt>"); // Works, HTML parser doesn't see this as a closing script tag
</script>

...since in each case, JavaScript sees the string as </script> but the HTML parser doesn't.

How to get textLabel of selected row in swift?

Maintain an array which stores data in the cellforindexPath method itself :-

[arryname objectAtIndex:indexPath.row];

Using same code in the didselectaAtIndexPath method too.. Good luck :)

Difference between object and class in Scala

Scala class same as Java Class but scala not gives you any entry method in class, like main method in java. The main method associated with object keyword. You can think of the object keyword as creating a singleton object of a class that is defined implicitly.

more information check this article class and object keyword in scala programming

Prevent flex items from overflowing a container

Instead of flex: 1 0 auto just use flex: 1

_x000D_
_x000D_
main, aside, article {_x000D_
  margin: 10px;_x000D_
  border: solid 1px #000;_x000D_
  border-bottom: 0;_x000D_
  height: 50px;_x000D_
}_x000D_
main {_x000D_
  display: flex;_x000D_
}_x000D_
aside {_x000D_
  flex: 0 0 200px;_x000D_
}_x000D_
article {_x000D_
  flex: 1;_x000D_
}
_x000D_
<main>_x000D_
  <aside>x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </aside>_x000D_
  <article>don't let flex item overflow container.... y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y </article>_x000D_
</main>
_x000D_
_x000D_
_x000D_

Django - what is the difference between render(), render_to_response() and direct_to_template()?

Just one note I could not find in the answers above. In this code:

context_instance = RequestContext(request)
return render_to_response(template_name, user_context, context_instance)

What the third parameter context_instance actually does? Being RequestContext it sets up some basic context which is then added to user_context. So the template gets this extended context. What variables are added is given by TEMPLATE_CONTEXT_PROCESSORS in settings.py. For instance django.contrib.auth.context_processors.auth adds variable user and variable perm which are then accessible in the template.

Do I need to compile the header files in a C program?

In some systems, attempts to speed up the assembly of fully resolved '.c' files call the pre-assembly of include files "compiling header files". However, it is an optimization technique that is not necessary for actual C development.

Such a technique basically computed the include statements and kept a cache of the flattened includes. Normally the C toolchain will cut-and-paste in the included files recursively, and then pass the entire item off to the compiler. With a pre-compiled header cache, the tool chain will check to see if any of the inputs (defines, headers, etc) have changed. If not, then it will provide the already flattened text file snippets to the compiler.

Such systems were intended to speed up development; however, many such systems were quite brittle. As computers sped up, and source code management techniques changed, fewer of the header pre-compilers are actually used in the common project.

Until you actually need compilation optimization, I highly recommend you avoid pre-compiling headers.

How to disable sort in DataGridView?

It's very simple:

foreach (DataGridViewColumn dgvc in dataGridView1.Columns)
{
    dgvc.SortMode = DataGridViewColumnSortMode.NotSortable;
}

What is a C++ delegate?

Very simply, a delegate provides functionality for how a function pointer SHOULD work. There are many limitations of function pointers in C++. A delegate uses some behind-the-scenes template nastyness to create a template-class function-pointer-type-thing that works in the way you might want it to.

ie - you can set them to point at a given function and you can pass them around and call them whenever and wherever you like.

There are some very good examples here:

How to get day of the month?

Take a look at GregorianCalendar, something like:

final Calendar now = GregorianCalendar.getInstance()
final int dayNumber = now.get(Calendar.DAY_OF_MONTH);

How to use ArrayList.addAll()?

Use Arrays class in Java which will return you an ArrayList :

final List<String> characters = Arrays.asList("+","-");

You will need a bit more work if you need a List<Character>.

How do I call a SQL Server stored procedure from PowerShell?

Here is a function I use to execute sql commands. You just have to change $sqlCommand.CommandText to the name of your sproc and $SqlCommand.CommandType to CommandType.StoredProcedure.

function execute-Sql{
    param($server, $db, $sql )
    $sqlConnection = new-object System.Data.SqlClient.SqlConnection
    $sqlConnection.ConnectionString = 'server=' + $server + ';integrated security=TRUE;database=' + $db 
    $sqlConnection.Open()
    $sqlCommand = new-object System.Data.SqlClient.SqlCommand
    $sqlCommand.CommandTimeout = 120
    $sqlCommand.Connection = $sqlConnection
    $sqlCommand.CommandText= $sql
    $text = $sql.Substring(0, 50)
    Write-Progress -Activity "Executing SQL" -Status "Executing SQL => $text..."
    Write-Host "Executing SQL => $text..."
    $result = $sqlCommand.ExecuteNonQuery()
    $sqlConnection.Close()
}

java.lang.RuntimeException: Uncompilable source code - what can cause this?

I had the same issue with one of my netbeans project.

Check whether you have correctly put the package name on all the classes. I got the same error message because i forgot to put the package name of a certain class (which was copied from another project).

How to avoid precompiled headers

The .cpp file is configured to use precompiled header, therefore it must be included first (before iostream). For Visual Studio, it's name is usually "stdafx.h".

If there are no stdafx* files in your project, you need to go to this file's options and set it as “Not using precompiled headers”.

How do I remove the last comma from a string using PHP?

Try the below code:

$my_string = "'name', 'name2', 'name3',";
echo substr(trim($my_string), 0, -1);

Use this code to remove the last character of the string.

git undo all uncommitted or unsaved changes

Another option to undo changes that weren't staged for commit is to run:

git restore <file>

To discard changes in the working directory.

Python POST binary data

You can use unirest, It provides easy method to post request. `

import unirest
 
def callback(response):
 print "code:"+ str(response.code)
 print "******************"
 print "headers:"+ str(response.headers)
 print "******************"
 print "body:"+ str(response.body)
 print "******************"
 print "raw_body:"+ str(response.raw_body)
 
# consume async post request
def consumePOSTRequestASync():
 params = {'test1':'param1','test2':'param2'}
 
 # we need to pass a dummy variable which is open method
 # actually unirest does not provide variable to shift between
 # application-x-www-form-urlencoded and
 # multipart/form-data
  
 params['dummy'] = open('dummy.txt', 'r')
 url = 'http://httpbin.org/post'
 headers = {"Accept": "application/json"}
 # call get service with headers and params
 unirest.post(url, headers = headers,params = params, callback = callback)
 
 
# post async request multipart/form-data
consumePOSTRequestASync()

JavaScript validation for empty input field

I would like to add required attribute in case user disabled javascript:

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

It works on all modern browsers.

Notify ObservableCollection when Item changes

I know it's late, but maybe this helps others. I have created a class NotifyObservableCollection, that solves the problem of missing notification to item itself, when a property of the item changes. The usage is as simple as ObservableCollection.

public class NotifyObservableCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
    private void Handle(object sender, PropertyChangedEventArgs args)
    {
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset, null));
    }

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null) {
            foreach (object t in e.NewItems) {
                ((T) t).PropertyChanged += Handle;
            }
        }
        if (e.OldItems != null) {
            foreach (object t in e.OldItems) {
                ((T) t).PropertyChanged -= Handle;
            }
        }
        base.OnCollectionChanged(e);
    }

While Items are added or removed the class forwards the items PropertyChanged event to the collections PropertyChanged event.

usage:

public abstract class ParameterBase : INotifyPropertyChanged
{
    protected readonly CultureInfo Ci = new CultureInfo("en-US");
    private string _value;

    public string Value {
        get { return _value; }
        set {
            if (value == _value) return;
            _value = value;
            OnPropertyChanged();
        }
    }
}

public class AItem {
    public NotifyObservableCollection<ParameterBase> Parameters {
        get { return _parameters; }
        set {
            NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
            if (_parameters != null) _parameters.CollectionChanged -= cceh;
            _parameters = value;
            //needed for Binding to AItem at xaml directly
            _parameters.CollectionChanged += cceh; 
        }
    }

    public NotifyObservableCollection<ParameterBase> DefaultParameters {
        get { return _defaultParameters; }
        set {
            NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
            if (_defaultParameters != null) _defaultParameters.CollectionChanged -= cceh;
            _defaultParameters = value;
            //needed for Binding to AItem at xaml directly
            _defaultParameters.CollectionChanged += cceh;
        }
    }


public class MyViewModel {
    public NotifyObservableCollection<AItem> DataItems { get; set; }
}

If now a property of an item in DataItems changes, the following xaml will get a notification, though it binds to Parameters[0] or to the item itself except to the changing property Value of the item (Converters at Triggers are called reliable on every change).

<DataGrid CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding DataItems}">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Parameters[0].Value}" Header="P1">
            <DataGridTextColumn.CellStyle>
                <Style TargetType="DataGridCell">
                    <Setter Property="Background" Value="Aqua" />
                    <Style.Triggers>
                        <DataTrigger Value="False">
                            <!-- Bind to Items with changing properties -->
                            <DataTrigger.Binding>
                                <MultiBinding Converter="{StaticResource ParameterCompareConverter}">
                                    <Binding Path="DefaultParameters[0]" />
                                    <Binding Path="Parameters[0]" />
                                </MultiBinding>
                            </DataTrigger.Binding>
                            <Setter Property="Background" Value="DeepPink" />
                        </DataTrigger>
                        <!-- Binds to AItem directly -->
                        <DataTrigger Value="True" Binding="{Binding Converter={StaticResource CheckParametersConverter}}">
                            <Setter Property="FontWeight" Value="ExtraBold" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </DataGridTextColumn.CellStyle>
        </DataGridTextColumn>

PHP: Split a string in to an array foreach char

You can access characters in strings in the same way as you would access an array index, e.g.

$length = strlen($string);
$thisWordCodeVerdeeld = array();
for ($i=0; $i<$length; $i++) {
    $thisWordCodeVerdeeld[$i] = $string[$i];
}

You could also do:

$thisWordCodeVerdeeld = str_split($string);

However you might find it is easier to validate the string as a whole string, e.g. using regular expressions.

Installed SSL certificate in certificate store, but it's not in IIS certificate list

when you have one certificate and 2 different web servers here how I fixed it:

  1. List item
  2. You should generate certificate at one of the servers as usually in IIS Then at that server you can also complete the certificate in IIS.
  3. Run the program DigiCertUtil and export that working certificate
  4. Go to the other web server in IIS in security certificates Import that file from step 3.
  5. Then use that certificate to create the Binding.

Mongoose's find method with $or condition does not work properly

I solved it through googling:

var ObjectId = require('mongoose').Types.ObjectId;
var objId = new ObjectId( (param.length < 12) ? "123456789012" : param );
// You should make string 'param' as ObjectId type. To avoid exception, 
// the 'param' must consist of more than 12 characters.

User.find( { $or:[ {'_id':objId}, {'name':param}, {'nickname':param} ]}, 
  function(err,docs){
    if(!err) res.send(docs);
});

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

I know this is an old question, and most people have replied with good answers. But for reference and hopefully saving somebody else's time. Check if your function:

$(document).ready(function(){}

is being called after you have loaded the JQuery library

How can I tell which button was clicked in a PHP form submit?

Are you asking in php or javascript.

If it is in php, give the name of that and use the post or get method, after that you can use the option of isset or that particular button name is checked to that value.

If it is in js, use getElementById for that

Using quotation marks inside quotation marks

When you have several words like this which you want to concatenate in a string, I recommend using format or f-strings which increase readability dramatically (in my opinion).

To give an example:

s = "a word that needs quotation marks"
s2 = "another word"

Now you can do

print('"{}" and "{}"'.format(s, s2))

which will print

"a word that needs quotation marks" and "another word"

As of Python 3.6 you can use:

print(f'"{s}" and "{s2}"')

yielding the same output.

How to access Spring MVC model object in javascript file?

Another solution could be using in JSP: <input type="hidden" id="jsonBom" value='${jsonBom}'/>

and getting the value in Javascript with jQuery:

var jsonBom = $('#jsonBom').val();

ToString() function in Go

When you have own struct, you could have own convert-to-string function.

package main

import (
    "fmt"
)

type Color struct {
    Red   int `json:"red"`
    Green int `json:"green"`
    Blue  int `json:"blue"`
}

func (c Color) String() string {
    return fmt.Sprintf("[%d, %d, %d]", c.Red, c.Green, c.Blue)
}

func main() {
    c := Color{Red: 123, Green: 11, Blue: 34}
    fmt.Println(c) //[123, 11, 34]
}

How to display a json array in table format?

using jquery $.each you can access all data and also set in table like this

<table style="width: 100%">
     <thead>
          <tr>
               <th>Id</th>
               <th>Name</th>
               <th>Category</th>
               <th>Color</th>
           </tr>
     </thead>
     <tbody id="tbody">
     </tbody>
</table>

$.each(data, function (index, item) {
     var eachrow = "<tr>"
                 + "<td>" + item[1] + "</td>"
                 + "<td>" + item[2] + "</td>"
                 + "<td>" + item[3] + "</td>"
                 + "<td>" + item[4] + "</td>"
                 + "</tr>";
     $('#tbody').append(eachrow);
});

How to pass command-line arguments to a PowerShell ps1 file

Maybe you can wrap the PowerShell invocation in a .bat file like so:

rem ps.bat
@echo off
powershell.exe -command "%*"

If you then placed this file under a folder in your PATH, you could call PowerShell scripts like this:

ps foo 1 2 3

Quoting can get a little messy, though:

ps write-host """hello from cmd!""" -foregroundcolor green

How do I fix the npm UNMET PEER DEPENDENCY warning?

EDIT 2020

From npm v7.0.0, npm automatically installs peer dependencies. It is one of the reasons to upgrade to v7.

https://github.blog/2020-10-13-presenting-v7-0-0-of-the-npm-cli/

Also this page explains the rationale of peer dependencies very well. https://github.com/npm/rfcs/blob/latest/implemented/0025-install-peer-deps.md


This answer doesn’t apply all cases, but if you can’t solve the error by simply typing npm install , this steps might help.

Let`s say you got this error.

UNMET PEER DEPENDENCY [email protected]

npm WARN [email protected] requires a peer of packageA@^3.1.0 but none was installed.

This means you installed version 4.2.0 of packageA, but [email protected] needs version 3.x.x of pakageA. (explanation of ^)

So you can resolve this error by downgrading packageA to 3.x.x, but usually you don`t want to downgrade the package.
Good news is that in some cases, packageB is just not keeping up with packageA and maintainer of packageB is trying hard to raise the peer dependency of packageA to 4.x.x.
In that case, you can check if there is a higher version of packageB that requires version 4.2.0 of packageA in the npm or github.

For example, Go to release pageenter image description here

Oftentimes you can find breaking change about dependency like this.

packageB v4.0.0-beta.0

BREAKING CHANGE
package: requires packageA >= v4.0.0

If you don’t find anything on release page, go to issue page and search issue by keyword like peer. You may find useful information.

enter image description here

At this point, you have two options.

  1. Upgrade to the version you want
  2. Leave error for the time being, wait until stable version is released.

If you choose option1:
In many cases, the version does not have latest tag thus not stable. So you have to check what has changed in this update and make sure anything won`t break.

If you choose option2:
If upgrade of pakageA from version 3 to 4 is trivial, or if maintainer of pakageB didn’t test version 4 of pakageA yet but says it should be no problem, you may consider leaving the error.

In both case, it is best to thoroughly test if it does not break anything.

Lastly, if you wanna know why you have to manually do such a thing, this link explains well.

Hook up Raspberry Pi via Ethernet to laptop without router?

Configure static ip for your laptop and raspberry pi. On the rapberryPI configure it as following.

pi@rpi>sudo nano /etc/network/interfaces

Then configure following as required to connect to your laptop.

iface eth0 inet static

address 192.168.1.81

netmask 255.255.255.0

broadcast 192.168.1.255

Preventing SQL injection in Node.js

The easiest way is to handle all of your database interactions in its own module that you export to your routes. If your route has no context of the database then SQL can't touch it anyway.

Why should I use IHttpActionResult instead of HttpResponseMessage?

// this will return HttpResponseMessage as IHttpActionResult
return ResponseMessage(httpResponseMessage); 

How to use Bootstrap 4 in ASP.NET Core

As others already mentioned, the package manager Bower, that was usually used for dependencies like this in application that do not rely on heavy client-side scripting, is on the way out and actively recommending to move to other solutions:

..psst! While Bower is maintained, we recommend yarn and webpack for new front-end projects!

So although you can still use it right now, Bootstrap has also announced to drop support for it. As a result, the built-in ASP.NET Core templates are slowly being edited to move away from it too.

Unfortunately, there is no clear path forward. This is mostly due to the fact that web applications are continuously moving further into the client-side, requiring complex client-side build systems and many dependencies. So if you are building something like that, you might already know how to solve this then, and you can expand your existing build process to simply also include Bootstrap and jQuery there.

But there are still many web applications out there that are not that heavy on the client-side, where the application still runs mainly on the server and the server serves static views as a result. Bower previously filled this by making it easy to just publish client-side dependencies without that much of a process.

In the .NET world we also have NuGet and with previous ASP.NET versions, we could use NuGet as well to add dependencies to some client-side dependencies since NuGet would just place the content into our project correctly. Unfortunately, with the new .csproj format and the new NuGet, installed packages are located outside of our project, so we cannot simply reference those.

This leaves us with a few options how to add our dependencies:

One-time installation

This is what the ASP.NET Core templates, that are not single-page applications, are currently doing. When you use those to create a new application, the wwwroot folder simply contains a folder lib that contains the dependencies:

wwwroot folder contains lib folder with static dependencies

If you look closely at the files currently, you can see that they were originally placed there with Bower to create the template, but that is likely to change soon. The basic idea is that the files are copied once to the wwwroot folder so you can depend on them.

To do this, we can simply follow Bootstrap’s introduction and download the compiled files directly. As mentioned on the download site, this does not include jQuery, so we need to download that separately too; it does contain Popper.js though if we choose to use the bootstrap.bundle file later—which we will do. For jQuery, we can simply get a single “compressed, production” file from the download site (right-click the link and select "Save link as..." from the menu).

This leaves us with a few files which will simply extract and copy into the wwwroot folder. We can also make a lib folder to make it clearer that these are external dependencies:

wwwroot folder contains lib folder with our installed dependencies

That’s all we need, so now we just need to adjust our _Layout.cshtml file to include those dependencies. For that, we add the following block to the <head>:

<environment include="Development">
    <link rel="stylesheet" href="~/lib/css/bootstrap.css" />
</environment>
<environment exclude="Development">
    <link rel="stylesheet" href="~/lib/css/bootstrap.min.css" />
</environment>

And the following block at the very end of the <body>:

<environment include="Development">
    <script src="~/lib/js/jquery-3.3.1.js"></script>
    <script src="~/lib/js/bootstrap.bundle.js"></script>
</environment>
<environment exclude="Development">
    <script src="~/lib/js/jquery-3.3.1.min.js"></script>
    <script src="~/lib/js/bootstrap.bundle.min.js"></script>
</environment>

You can also just include the minified versions and skip the <environment> tag helpers here to make it a bit simpler. But that’s all you need to do to keep you starting.

Dependencies from NPM

The more modern way, also if you want to keep your dependencies updated, would be to get the dependencies from the NPM package repository. You can use either NPM or Yarn for this; in my example, I’ll use NPM.

To start off, we need to create a package.json file for our project, so we can specify our dependencies. To do this, we simply do that from the “Add New Item” dialog:

Add New Item: npm Configuration file

Once we have that, we need to edit it to include our dependencies. It should something look like this:

{
  "version": "1.0.0",
  "name": "asp.net",
  "private": true,
  "devDependencies": {
    "bootstrap": "4.0.0",
    "jquery": "3.3.1",
    "popper.js": "1.12.9"
  }
}

By saving, Visual Studio will already run NPM to install the dependencies for us. They will be installed into the node_modules folder. So what is left to do is to get the files from there into our wwwroot folder. There are a few options to do that:

bundleconfig.json for bundling and minification

We can use one of the various ways to consume a bundleconfig.json for bundling and minification, as explained in the documentation. A very easy way is to simply use the BuildBundlerMinifier NuGet package which automatically sets up a build task for this.

After installing that package, we need to create a bundleconfig.json at the root of the project with the following contents:

[
  {
    "outputFileName": "wwwroot/vendor.min.css",
    "inputFiles": [
      "node_modules/bootstrap/dist/css/bootstrap.min.css"
    ],
    "minify": { "enabled": false }
  },
  {
    "outputFileName": "wwwroot/vendor.min.js",
    "inputFiles": [
      "node_modules/jquery/dist/jquery.min.js",
      "node_modules/popper.js/dist/umd/popper.min.js",
      "node_modules/bootstrap/dist/js/bootstrap.min.js"
    ],
    "minify": { "enabled": false }
  }
]

This basically configures which files to combine into what. And when we build, we can see that the vendor.min.css and vendor.js.css are created correctly. So all we need to do is to adjust our _Layouts.html again to include those files:

<!-- inside <head> -->
<link rel="stylesheet" href="~/vendor.min.css" />

<!-- at the end of <body> -->
<script src="~/vendor.min.js"></script>

Using a task manager like Gulp

If we want to move a bit more into client-side development, we can also start to use tools that we would use there. For example Webpack which is a very commonly used build tool for really everything. But we can also start with a simpler task manager like Gulp and do the few necessary steps ourselves.

For that, we add a gulpfile.js into our project root, with the following contents:

const gulp = require('gulp');
const concat = require('gulp-concat');

const vendorStyles = [
    "node_modules/bootstrap/dist/css/bootstrap.min.css"
];
const vendorScripts = [
    "node_modules/jquery/dist/jquery.min.js",
    "node_modules/popper.js/dist/umd/popper.min.js",
    "node_modules/bootstrap/dist/js/bootstrap.min.js",
];

gulp.task('build-vendor-css', () => {
    return gulp.src(vendorStyles)
        .pipe(concat('vendor.min.css'))
        .pipe(gulp.dest('wwwroot'));
});

gulp.task('build-vendor-js', () => {
    return gulp.src(vendorScripts)
        .pipe(concat('vendor.min.js'))
        .pipe(gulp.dest('wwwroot'));
});

gulp.task('build-vendor', gulp.parallel('build-vendor-css', 'build-vendor-js'));

gulp.task('default', gulp.series('build-vendor'));

Now, we also need to adjust our package.json to have dependencies on gulp and gulp-concat:

{
  "version": "1.0.0",
  "name": "asp.net",
  "private": true,
  "devDependencies": {
    "bootstrap": "4.0.0",
    "gulp": "^4.0.2",
    "gulp-concat": "^2.6.1",
    "jquery": "3.3.1",
    "popper.js": "1.12.9"
  }
}

Finally, we edit our .csproj to add the following task which makes sure that our Gulp task runs when we build the project:

<Target Name="RunGulp" BeforeTargets="Build">
  <Exec Command="node_modules\.bin\gulp.cmd" />
</Target>

Now, when we build, the default Gulp task runs, which runs the build-vendor tasks, which then builds our vendor.min.css and vendor.min.js just like we did before. So after adjusting our _Layout.cshtml just like above, we can make use of jQuery and Bootstrap.

While the initial setup of Gulp is a bit more complicated than the bundleconfig.json one above, we have now have entered the Node-world and can start to make use of all the other cool tools there. So it might be worth to start with this.

Conclusion

While this suddenly got a lot more complicated than with just using Bower, we also do gain a lot of control with those new options. For example, we can now decide what files are actually included within the wwwroot folder and how those exactly look like. And we also can use this to make the first moves into the client-side development world with Node which at least should help a bit with the learning curve.

XPath with multiple conditions

Try:
//category[@name='Sport' and ./author/text()='James Small']

What are the differences between Mustache.js and Handlebars.js?

One subtle but significant difference is in the way the two libraries approach scope. Mustache will fall back to parent scope if it can't find a variable within the current context; Handlebars will return a blank string.

This is barely mentioned in the GitHub README, where there's one line for it:

Handlebars deviates from Mustache slightly in that it does not perform recursive lookup by default.

However, as noted there, there is a flag to make Handlebars behave in the same way as Mustache -- but it affects performance.

This has an effect on the way you can use # variables as conditionals.

For example in Mustache you can do this:

{{#variable}}<span class="text">{{variable}}</span>{{/variable}}

It basically means "if variable exists and is truthy, print a span with the variable in it". But in Handlebars, you would either have to:

  • use {{this}} instead
  • use a parent path, i.e., {{../variable}} to get back out to relevant scope
  • define a child variable value within the parent variable object

More details on this, if you want them, here.

How to do a subquery in LINQ?

This is how I've been doing subqueries in LINQ, I think this should get what you want. You can replace the explicit CompanyRoleId == 2... with another subquery for the different roles you want or join it as well.

from u in Users
join c in (
    from crt in CompanyRolesToUsers
    where CompanyRoleId == 2
    || CompanyRoleId == 3
    || CompanyRoleId == 4) on u.UserId equals c.UserId
where u.lastname.Contains("fra")
select u;

Adding to a vector of pair

Try using another temporary pair:

pair<string,double> temp;
vector<pair<string,double>> revenue;

// Inside the loop
temp.first = "string";
temp.second = map[i].second;
revenue.push_back(temp);

How can I clear or empty a StringBuilder?

I'll vote for sb.setLength(0); not only because it's one function call, but because it doesn't actually copy the array into another array like sb.delete(0, builder.length());. It just fill the remaining characters to be 0 and set the length variable to the new length.

You can take a look into their implementation to validate my point from here at setLength function and delete0 function.

How to apply `git diff` patch without Git installed?

git diff > patchfile

and

patch -p1 < patchfile

work but as many people noticed in comments and other answers patch does not understand adds, deletes and renames. There is no option but git apply patchfile if you need handle file adds, deletes and renames.


EDIT December 2015

Latest versions of patch command (2.7, released in September 2012) support most features of the "diff --git" format, including renames and copies, permission changes, and symlink diffs (but not yet binary diffs) (release announcement).

So provided one uses current/latest version of patch there is no need to use git to be able to apply its diff as a patch.

Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

This is what I needed:

public static byte[] encode(byte[] arr, String fromCharsetName) {
    return encode(arr, Charset.forName(fromCharsetName), Charset.forName("UTF-8"));
}

public static byte[] encode(byte[] arr, String fromCharsetName, String targetCharsetName) {
    return encode(arr, Charset.forName(fromCharsetName), Charset.forName(targetCharsetName));
}

public static byte[] encode(byte[] arr, Charset sourceCharset, Charset targetCharset) {

    ByteBuffer inputBuffer = ByteBuffer.wrap( arr );

    CharBuffer data = sourceCharset.decode(inputBuffer);

    ByteBuffer outputBuffer = targetCharset.encode(data);
    byte[] outputData = outputBuffer.array();

    return outputData;
}

jQuery .val() vs .attr("value")

PS: This is not an answer but just a supplement to the above answers.

Just for the future reference, I have included a good example that might help us to clear our doubt:

Try the following. In this example I shall create a file selector which can be used to select a file and then I shall try to retrieve the name of the file that I selected: The HTML code is below:

<html>
    <body>
        <form action="#" method="post">
            <input id ="myfile" type="file"/>
        </form>
        <script type="text/javascript" src="jquery.js"> </script>
        <script type="text/javascript" src="code.js"> </script>
    </body>
</html>

The code.js file contains the following jQuery code. Try to use both of the jQuery code snippets one by one and see the output.

jQuery code with attr('value'):

$('#myfile').change(function(){
    alert($(this).attr('value'));
    $('#mybutton').removeAttr('disabled');
});

jQuery code with val():

$('#myfile').change(function(){
    alert($(this).val());
    $('#mybutton').removeAttr('disabled');
});

Output:

The output of jQuery code with attr('value') will be 'undefined'. The output of jQuery code with val() will the file name that you selected.

Explanation: Now you may understand easily what the top answers wanted to convey. The output of jQuery code with attr('value') will be 'undefined' because initially there was no file selected so the value is undefined. It is better to use val() because it gets the current value.

In order to see why the undefined value is returned try this code in your HTML and you'll see that now the attr.('value') returns 'test' always, because the value is 'test' and previously it was undefined.

<input id ="myfile" type="file" value='test'/>

I hope it was useful to you.

Dynamically add child components in React

You need to pass your components as children, like this:

var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(
    <App>
        <SampleComponent name="SomeName"/> 
    <App>, 
    document.body
);

And then append them in the component's body:

var App = React.createClass({
    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                {
                    this.props.children
                }
            </div>
        );
    }
});

You don't need to manually manipulate HTML code, React will do that for you. If you want to add some child components, you just need to change props or state it depends. For example:

var App = React.createClass({

    getInitialState: function(){
        return [
            {id:1,name:"Some Name"}
        ]
    },

    addChild: function() {
        // State change will cause component re-render
        this.setState(this.state.concat([
            {id:2,name:"Another Name"}
        ]))
    }

    render: function() {
        return (
            <div>
                <h1>App main component! </h1>
                <button onClick={this.addChild}>Add component</button>
                {
                    this.state.map((item) => (
                        <SampleComponent key={item.id} name={item.name}/>
                    ))
                }
            </div>
        );
    }

});

How to print without newline or space?

How to print on the same line:

import sys
for i in xrange(0,10):
   sys.stdout.write(".")
   sys.stdout.flush()

Matplotlib discrete colorbar

I have been investigating these ideas and here is my five cents worth. It avoids calling BoundaryNorm as well as specifying norm as an argument to scatter and colorbar. However I have found no way of eliminating the rather long-winded call to matplotlib.colors.LinearSegmentedColormap.from_list.

Some background is that matplotlib provides so-called qualitative colormaps, intended to use with discrete data. Set1, e.g., has 9 easily distinguishable colors, and tab20 could be used for 20 colors. With these maps it could be natural to use their first n colors to color scatter plots with n categories, as the following example does. The example also produces a colorbar with n discrete colors approprately labelled.

import matplotlib, numpy as np, matplotlib.pyplot as plt
n = 5
from_list = matplotlib.colors.LinearSegmentedColormap.from_list
cm = from_list(None, plt.cm.Set1(range(0,n)), n)
x = np.arange(99)
y = x % 11
z = x % n
plt.scatter(x, y, c=z, cmap=cm)
plt.clim(-0.5, n-0.5)
cb = plt.colorbar(ticks=range(0,n), label='Group')
cb.ax.tick_params(length=0)

which produces the image below. The n in the call to Set1 specifies the first n colors of that colormap, and the last n in the call to from_list specifies to construct a map with n colors (the default being 256). In order to set cm as the default colormap with plt.set_cmap, I found it to be necessary to give it a name and register it, viz:

cm = from_list('Set15', plt.cm.Set1(range(0,n)), n)
plt.cm.register_cmap(None, cm)
plt.set_cmap(cm)
...
plt.scatter(x, y, c=z)

scatterplot with disrete colors

jQuery: Can I call delay() between addClass() and such?

jQuery's CSS manipulation isn't queued, but you can make it executed inside the 'fx' queue by doing:

$('#div').delay(1000).queue('fx', function() { $(this).removeClass('error'); });

Quite same thing as calling setTimeout but uses jQuery's queue mecanism instead.

MySQL Error 1153 - Got a packet bigger than 'max_allowed_packet' bytes

Set max_allowed_packet to the same (or more) than what it was when you dumped it with mysqldump. If you can't do that, make the dump again with a smaller value.

That is, assuming you dumped it with mysqldump. If you used some other tool, you're on your own.

Youtube autoplay not working on mobile devices with embedded HTML5 player

Preview The official statement "Due to this restriction, functions and parameters such as autoplay, playVideo(), loadVideoById() won't work in all mobile environments.

Reference: https://developers.google.com/youtube/iframe_api_reference

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

This is @Ben's answer updated for use with Ember...note you have to use Ember.get because context is passed in as a String.

Ember.Handlebars.registerHelper('eachProperty', function(context, options) {
  var ret = "";
  var newContext = Ember.get(this, context);
  for(var prop in newContext)
  {
    if (newContext.hasOwnProperty(prop)) {
      ret = ret + options.fn({property:prop,value:newContext[prop]});
    }
  }
  return ret;
});

Template:

{{#eachProperty object}}
  {{key}}: {{value}}<br/>
{{/eachProperty }}

How to change line-ending settings

For me what did the trick was running the command

git config auto.crlf false

inside the folder of the project, I wanted it specifically for one project.

That command changed the file in path {project_name}/.git/config (fyi .git is a hidden folder) by adding the lines

[auto]
    crlf = false

at the end of the file. I suppose changing the file does the same trick as well.

Docker: Copying files from Docker container to host

This can also be done in the SDK for example python. If you already have a container built you can lookup the name via console ( docker ps -a ) name seems to be some concatenation of a scientist and an adjective (i.e. "relaxed_pasteur").

Check out help(container.get_archive) :

Help on method get_archive in module docker.models.containers:

get_archive(path, chunk_size=2097152) method of docker.models.containers.Container instance
    Retrieve a file or folder from the container in the form of a tar
    archive.

    Args:
        path (str): Path to the file or folder to retrieve
        chunk_size (int): The number of bytes returned by each iteration
            of the generator. If ``None``, data will be streamed as it is
            received. Default: 2 MB

    Returns:
        (tuple): First element is a raw tar data stream. Second element is
        a dict containing ``stat`` information on the specified ``path``.

    Raises:
        :py:class:`docker.errors.APIError`
            If the server returns an error.

    Example:

        >>> f = open('./sh_bin.tar', 'wb')
        >>> bits, stat = container.get_archive('/bin/sh')
        >>> print(stat)
        {'name': 'sh', 'size': 1075464, 'mode': 493,
         'mtime': '2018-10-01T15:37:48-07:00', 'linkTarget': ''}
        >>> for chunk in bits:
        ...    f.write(chunk)
        >>> f.close()

So then something like this will pull out from the specified path ( /output) in the container to your host machine and unpack the tar.

import docker
import os
import tarfile

# Docker client
client = docker.from_env()
#container object
container = client.containers.get("relaxed_pasteur")
#setup tar to write bits to
f = open(os.path.join(os.getcwd(),"output.tar"),"wb")
#get the bits
bits, stat = container.get_archive('/output')
#write the bits
for chunk in bits:
    f.write(chunk)
f.close()
#unpack
tar = tarfile.open("output.tar")
tar.extractall()
tar.close()

How to get a string after a specific substring?

You want to use str.partition():

>>> my_string.partition("world")[2]
" , i'm a beginner "

because this option is faster than the alternatives.

Note that this produces an empty string if the delimiter is missing:

>>> my_string.partition("Monty")[2]  # delimiter missing
''

If you want to have the original string, then test if the second value returned from str.partition() is non-empty:

prefix, success, result = my_string.partition(delimiter)
if not success: result = prefix

You could also use str.split() with a limit of 1:

>>> my_string.split("world", 1)[-1]
" , i'm a beginner "
>>> my_string.split("Monty", 1)[-1]  # delimiter missing
"hello python world , i'm a beginner "

However, this option is slower. For a best-case scenario, str.partition() is easily about 15% faster compared to str.split():

                                missing        first         lower         upper          last
      str.partition(...)[2]:  [3.745 usec]  [0.434 usec]  [1.533 usec]  <3.543 usec>  [4.075 usec]
str.partition(...) and test:   3.793 usec    0.445 usec    1.597 usec    3.208 usec    4.170 usec
      str.split(..., 1)[-1]:  <3.817 usec>  <0.518 usec>  <1.632 usec>  [3.191 usec]  <4.173 usec>
            % best vs worst:         1.9%         16.2%          6.1%          9.9%          2.3%

This shows timings per execution with inputs here the delimiter is either missing (worst-case scenario), placed first (best case scenario), or in the lower half, upper half or last position. The fastest time is marked with [...] and <...> marks the worst.

The above table is produced by a comprehensive time trial for all three options, produced below. I ran the tests on Python 3.7.4 on a 2017 model 15" Macbook Pro with 2.9 GHz Intel Core i7 and 16 GB ram.

This script generates random sentences with and without the randomly selected delimiter present, and if present, at different positions in the generated sentence, runs the tests in random order with repeats (producing the fairest results accounting for random OS events taking place during testing), and then prints a table of the results:

import random
from itertools import product
from operator import itemgetter
from pathlib import Path
from timeit import Timer

setup = "from __main__ import sentence as s, delimiter as d"
tests = {
    "str.partition(...)[2]": "r = s.partition(d)[2]",
    "str.partition(...) and test": (
        "prefix, success, result = s.partition(d)\n"
        "if not success: result = prefix"
    ),
    "str.split(..., 1)[-1]": "r = s.split(d, 1)[-1]",
}

placement = "missing first lower upper last".split()
delimiter_count = 3

wordfile = Path("/usr/dict/words")  # Linux
if not wordfile.exists():
    # macos
    wordfile = Path("/usr/share/dict/words")
words = [w.strip() for w in wordfile.open()]

def gen_sentence(delimiter, where="missing", l=1000):
    """Generate a random sentence of length l

    The delimiter is incorporated according to the value of where:

    "missing": no delimiter
    "first":   delimiter is the first word
    "lower":   delimiter is present in the first half
    "upper":   delimiter is present in the second half
    "last":    delimiter is the last word

    """
    possible = [w for w in words if delimiter not in w]
    sentence = random.choices(possible, k=l)
    half = l // 2
    if where == "first":
        # best case, at the start
        sentence[0] = delimiter
    elif where == "lower":
        # lower half
        sentence[random.randrange(1, half)] = delimiter
    elif where == "upper":
        sentence[random.randrange(half, l)] = delimiter
    elif where == "last":
        sentence[-1] = delimiter
    # else: worst case, no delimiter

    return " ".join(sentence)

delimiters = random.choices(words, k=delimiter_count)
timings = {}
sentences = [
    # where, delimiter, sentence
    (w, d, gen_sentence(d, w)) for d, w in product(delimiters, placement)
]
test_mix = [
    # label, test, where, delimiter sentence
    (*t, *s) for t, s in product(tests.items(), sentences)
]
random.shuffle(test_mix)

for i, (label, test, where, delimiter, sentence) in enumerate(test_mix, 1):
    print(f"\rRunning timed tests, {i:2d}/{len(test_mix)}", end="")
    t = Timer(test, setup)
    number, _ = t.autorange()
    results = t.repeat(5, number)
    # best time for this specific random sentence and placement
    timings.setdefault(
        label, {}
    ).setdefault(
        where, []
    ).append(min(dt / number for dt in results))

print()

scales = [(1.0, 'sec'), (0.001, 'msec'), (1e-06, 'usec'), (1e-09, 'nsec')]
width = max(map(len, timings))
rows = []
bestrow = dict.fromkeys(placement, (float("inf"), None))
worstrow = dict.fromkeys(placement, (float("-inf"), None))

for row, label in enumerate(tests):
    columns = []
    worst = float("-inf")
    for p in placement:
        timing = min(timings[label][p])
        if timing < bestrow[p][0]:
            bestrow[p] = (timing, row)
        if timing > worstrow[p][0]:
            worstrow[p] = (timing, row)
        worst = max(timing, worst)
        columns.append(timing)

    scale, unit = next((s, u) for s, u in scales if worst >= s)
    rows.append(
        [f"{label:>{width}}:", *(f" {c / scale:.3f} {unit} " for c in columns)]
    )

colwidth = max(len(c) for r in rows for c in r[1:])
print(' ' * (width + 1), *(p.center(colwidth) for p in placement), sep="  ")
for r, row in enumerate(rows):
    for c, p in enumerate(placement, 1):
        if bestrow[p][1] == r:
            row[c] = f"[{row[c][1:-1]}]"
        elif worstrow[p][1] == r:
            row[c] = f"<{row[c][1:-1]}>"
    print(*row, sep="  ")

percentages = []
for p in placement:
    best, worst = bestrow[p][0], worstrow[p][0]
    ratio = ((worst - best) / worst)
    percentages.append(f"{ratio:{colwidth - 1}.1%} ")

print("% best vs worst:".rjust(width + 1), *percentages, sep="  ")

How do you format an unsigned long long int using printf?

Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU).

printf("%llu", 285212672);

Reload chart data via JSON with Highcharts

Correct answer is:

$.each(lines, function(lineNo, line) {
                    var items = line.split(',');
                    var data = {};
                    $.each(items, function(itemNo, item) {
                        if (itemNo === 0) {
                            data.name = item;
                        } else {
                            data.y = parseFloat(item);
                        }
                    });
                    options.series[0].data.push(data);
                    data = {};
                });

You need to flush the 'data' array.

data = {};

How can I get city name from a latitude and longitude point?

Same as @Sanchit Gupta.

in this part

if (results[0]) {
 var add= results[0].formatted_address ;
 var  value=add.split(",");
 count=value.length;
 country=value[count-1];
 state=value[count-2];
 city=value[count-3];
 x.innerHTML = "city name is: " + city;
}

just console the results array

if (results[0]) {
 console.log(results[0]);
 // choose from console whatever you need.
 var city = results[0].address_components[3].short_name;
 x.innerHTML = "city name is: " + city;
}

Do subclasses inherit private fields?

We can simply state that when a superclass is inherited, then the private members of superclass actually become private members of the subclass and cannot be further inherited or are inacessible to the objects of subclass.

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

I know this is an older question, but I felt the answer from t3chb0t led me to the best path and felt like sharing. You don't even need to go so far as implementing all the formatter's methods. I did the following for the content-type "application/vnd.api+json" being returned by an API I was using:

public class VndApiJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public VndApiJsonMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.api+json"));
    }
}

Which can be used simply like the following:

HttpClient httpClient = new HttpClient("http://api.someaddress.com/");
HttpResponseMessage response = await httpClient.GetAsync("person");

List<System.Net.Http.Formatting.MediaTypeFormatter> formatters = new List<System.Net.Http.Formatting.MediaTypeFormatter>();
formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
formatters.Add(new VndApiJsonMediaTypeFormatter());

var responseObject = await response.Content.ReadAsAsync<Person>(formatters);

Super simple and works exactly as I expected.

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

You can avoid compiler warning with workarounds like this one:

List<?> resultRaw = query.list();
List<MyObj> result = new ArrayList<MyObj>(resultRaw.size());
for (Object o : resultRaw) {
    result.add((MyObj) o);
}

But there are some issues with this code:

  • created superfluous ArrayList
  • unnecessary loop over all elements returned from the query
  • longer code.

And the difference is only cosmetic, so using such workarounds is - in my opinion - pointless.

You have to live with these warnings or suppress them.

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

RegEx - Match Numbers of Variable Length

Try this:

{[0-9]{1,3}:[0-9]{1,3}}

The {1,3} means "match between 1 and 3 of the preceding characters".

Sorting dictionary keys in python

my_list = sorted(dict.items(), key=lambda x: x[1])

HttpServletRequest - how to obtain the referring URL?

It's available in the HTTP referer header. You can get it in a servlet as follows:

String referrer = request.getHeader("referer"); // Yes, with the legendary misspelling.

You, however, need to realize that this is a client-controlled value and can thus be spoofed to something entirely different or even removed. Thus, whatever value it returns, you should not use it for any critical business processes in the backend, but only for presentation control (e.g. hiding/showing/changing certain pure layout parts) and/or statistics.

For the interested, background about the misspelling can be found in Wikipedia.

Multiple select statements in Single query

SELECT  (
    SELECT COUNT(*)
    FROM   user_table
) AS tot_user,
(
    SELECT COUNT(*)
    FROM   cat_table
) AS tot_cat,
(
    SELECT COUNT(*)
    FROM   course_table
) AS tot_course

How do you deploy Angular apps?

Hopefully this may help, and hopefully I'll get to try this during the week.

  1. Create Web app at Azure
  2. Create Angular 2 app in vs code.
  3. Webpack to bundle.js.
  4. Download Azure site published profile xml
  5. Configure Azure-deploy using https://www.npmjs.com/package/azure-deploy with site profile.
  6. Deploy.
  7. Taste the cream.

Export to xls using angularjs

I had this problem and I made a tool to export an HTML table to CSV file. The problem I had with FileSaver.js is that this tool grabs the table with html format, this is why some people can't open the file in excel or google. All you have to do is export the js file and then call the function. This is the github url https://github.com/snake404/tableToCSV if someone has the same problem.

Android SDK location

Just add a new empty directory that path is “/Users/username/Library/Android/sdk”. Then reopen it.

Python Tkinter clearing a frame

pack_forget and grid_forget will only remove widgets from view, it doesn't destroy them. If you don't plan on re-using the widgets, your only real choice is to destroy them with the destroy method.

To do that you have two choices: destroy each one individually, or destroy the frame which will cause all of its children to be destroyed. The latter is generally the easiest and most effective.

Since you claim you don't want to destroy the container frame, create a secondary frame. Have this secondary frame be the container for all the widgets you want to delete, and then put this one frame inside the parent you do not want to destroy. Then, it's just a matter of destroying this one frame and all of the interior widgets will be destroyed along with it.

How do I run a VBScript in 32-bit mode on a 64-bit machine?

We can force vbscript always run with 32 bit mode by changing "system32" to "sysWOW64" in default value of key "Computer\HKLM\SOFTWARE]\Classes\VBSFile\Shell\Open\Command"

How to update a plot in matplotlib?

You essentially have two options:

  1. Do exactly what you're currently doing, but call graph1.clear() and graph2.clear() before replotting the data. This is the slowest, but most simplest and most robust option.

  2. Instead of replotting, you can just update the data of the plot objects. You'll need to make some changes in your code, but this should be much, much faster than replotting things every time. However, the shape of the data that you're plotting can't change, and if the range of your data is changing, you'll need to manually reset the x and y axis limits.

To give an example of the second option:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 6*np.pi, 100)
y = np.sin(x)

# You probably won't need this if you're embedding things in a tkinter plot...
plt.ion()

fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma

for phase in np.linspace(0, 10*np.pi, 500):
    line1.set_ydata(np.sin(x + phase))
    fig.canvas.draw()
    fig.canvas.flush_events()

Uncaught TypeError: data.push is not a function

Your data variable contains an object, not an array, and objects do not have the push function as the error states. To do what you need you can do this:

data.country = 'IN';

Or

data['country'] = 'IN';

Android Fragment handle back button press

Use addToBackStack method when replacing one fragment by another:

getFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).addToBackStack("my_fragment").commit();

Then in your activity, use the following code to go back from a fragment to another (the previous one).

@Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() > 0) {
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
}

Have a fixed position div that needs to scroll if content overflows

Here are both fixes.

First, regarding the fixed sidebar, you need to give it a height for it to overflow:

HTML Code:

<div id="sidebar">Menu</div>
<div id="content">Text</div>

CSS Code:

body {font:76%/150% Arial, Helvetica, sans-serif; color:#666; width:100%; height:100%;}
#sidebar {position:fixed; top:0; left:0; width:20%; height:100%; background:#EEE; overflow:auto;}
#content {width:80%; padding-left:20%;}

@media screen and (max-height:200px){
    #sidebar {color:blue; font-size:50%;}
}

Live example: http://jsfiddle.net/RWxGX/3/

It's impossible NOT to get a scroll bar if your content overflows the height of the div. That's why I've added a media query for screen height. Maybe you can adjust your styles for short screen sizes so the scroll doesn't need to appear.

Cheers, Ignacio

How to search in array of object in mongodb

You can do this in two ways:

  1. ElementMatch - $elemMatch (as explained in above answers)

    db.users.find({ awards: { $elemMatch: {award:'Turing Award', year:1977} } })

  2. Use $and with find

    db.getCollection('users').find({"$and":[{"awards.award":"Turing Award"},{"awards.year":1977}]})

Python json.loads shows ValueError: Extra data

This may also happen if your JSON file is not just 1 JSON record. A JSON record looks like this:

[{"some data": value, "next key": "another value"}]

It opens and closes with a bracket [ ], within the brackets are the braces { }. There can be many pairs of braces, but it all ends with a close bracket ]. If your json file contains more than one of those:

[{"some data": value, "next key": "another value"}]
[{"2nd record data": value, "2nd record key": "another value"}]

then loads() will fail.

I verified this with my own file that was failing.

import json

guestFile = open("1_guests.json",'r')
guestData = guestFile.read()
guestFile.close()
gdfJson = json.loads(guestData)

This works because 1_guests.json has one record []. The original file I was using all_guests.json had 6 records separated by newline. I deleted 5 records, (which I already checked to be bookended by brackets) and saved the file under a new name. Then the loads statement worked.

Error was

   raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 2 column 1 - line 10 column 1 (char 261900 - 6964758)

PS. I use the word record, but that's not the official name. Also, if your file has newline characters like mine, you can loop through it to loads() one record at a time into a json variable.

Sending HTML mail using a shell script

In addition to the correct answer by mdma, you can also use the mail command as follows:

mail [email protected] -s"Subject Here" -a"Content-Type: text/html; charset=\"us-ascii\""

you will get what you're looking for. Don't forget to put <HTML> and </HTML> in the email. Here's a quick script I use to email a daily report in HTML:

#!/bin/sh
(cat /path/to/tomorrow.txt mysql -h mysqlserver -u user -pPassword Database -H -e "select statement;" echo "</HTML>") | mail [email protected] -s"Tomorrow's orders as of now" -a"Content-Type: text/html; charset=\"us-ascii\""

CSS Printing: Avoiding cut-in-half DIVs between pages?

I got this problem while using Bootstrap and I had multiple columns in each rows.

I was trying to give page-break-inside: avoid; or break-inside: avoid; to the col-md-6 div elements. That was not working.

I took a hint from the answers given above by DOK that floating elements do not work well with page-break-inside: avoid;.

Instead, I had to give page-break-inside: avoid; or break-inside: avoid; to the <div class="row"> element. And I had multiple rows in my print page.

That is, each row only had 2 columns in it. And they always fit horizontally and do not wrap on a new line.

In another example case, if you want 4 columns in each row, then use col-md-3.

Prevent Android activity dialog from closing on outside touch

builder.setCancelable(false);


public void Mensaje(View v){

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("¿Quieres ir a el Menú principal?");
    builder.setMessage("Al presionar SI iras a el menú y saldras de la materia.");
    builder.setPositiveButton("SI", null);
    builder.setNegativeButton("NO", null);
    builder.setCancelable(false);
    builder.show();
}

My httpd.conf is empty

It seems to me, that it is by design that this file is empty.

A similar question has been asked here: https://stackoverflow.com/questions/2567432/ubuntu-apache-httpd-conf-or-apache2-conf

So, you should have a look for /etc/apache2/apache2.conf

Squaring all elements in a list

Use a list comprehension (this is the way to go in pure Python):

>>> l = [1, 2, 3, 4]
>>> [i**2 for i in l]
[1, 4, 9, 16]

Or numpy (a well-established module):

>>> numpy.array([1, 2, 3, 4])**2
array([ 1,  4,  9, 16])

In numpy, math operations on arrays are, by default, executed element-wise. That's why you can **2 an entire array there.

Other possible solutions would be map-based, but in this case I'd really go for the list comprehension. It's Pythonic :) and a map-based solution that requires lambdas is slower than LC.

Angular2: Cannot read property 'name' of undefined

You just needed to read a little further and you would have been introduced to the *ngIf structural directive.

selectedHero.name doesn't exist yet because the user has yet to select a hero so it returns undefined.

<div *ngIf="selectedHero">
  <h2>{{selectedHero.name}} details!</h2>
  <div><label>id: </label>{{selectedHero.id}}</div>
  <div>
    <label>name: </label>
    <input [(ngModel)]="selectedHero.name" placeholder="name"/>
  </div>
</div>

The *ngIf directive keeps selectedHero off the DOM until it is selected and therefore becomes truthy.

This document helped me understand structural directives.

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Java Language Specification defines E1 op= E2 to be equivalent to E1 = (T) ((E1) op (E2)) where T is a type of E1 and E1 is evaluated once.

That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.

public class PlusEquals {
    public static void main(String[] args) {
        byte a = 1;
        byte b = 2;
        a = a + b;
        System.out.println(a);
    }
}

What does this program print?

Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.

But if a = a + b doesn't work, that would mean a += b would never work for bytes if it E1 += E2 was defined to be E1 = E1 + E2. As the previous example shows, that would be indeed the case. As a hack to make += operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.

How to test that a registered variable is not empty?

(ansible 2.9.6 ansible-lint 4.2.0)

See ansible-lint default rules. The condition below causes E602 Don’t compare to empty string

    when: test_myscript.stderr != ""

Correct syntax and also "Ansible Galaxy Warning-Free" option is

    when: test_myscript.stderr | length > 0

Quoting from source code

"Use when: var|length > 0 rather than when: var != "" (or ' 'conversely when: var|length == 0 rather than when: var == "")"


Notes

  1. Test empty bare variable e.g.
    - debug:
        msg: "Empty string '{{ var }}' evaluates to False"
      when: not var
      vars:
        var: ''

    - debug:
        msg: "Empty list {{ var }} evaluates to False"
      when: not var
      vars:
        var: []

give

    "msg": "Empty string '' evaluates to False"
    "msg": "Empty list [] evaluates to False"
  1. But, testing non-empty bare variable string depends on CONDITIONAL_BARE_VARS. Setting ANSIBLE_CONDITIONAL_BARE_VARS=false the condition works fine but setting ANSIBLE_CONDITIONAL_BARE_VARS=true the condition will fail
    - debug:
        msg: "String '{{ var }}' evaluates to True"
      when: var
      vars:
        var: 'abc'

gives

fatal: [localhost]: FAILED! => 
  msg: |-
    The conditional check 'var' failed. The error was: error while 
    evaluating conditional (var): 'abc' is undefined

Explicit cast to Boolean prevents the error but evaluates to False i.e. will be always skipped (unless var='True'). When the filter bool is used the options ANSIBLE_CONDITIONAL_BARE_VARS=true and ANSIBLE_CONDITIONAL_BARE_VARS=false have no effect

    - debug:
        msg: "String '{{ var }}' evaluates to True"
      when: var|bool
      vars:
        var: 'abc'

gives

skipping: [localhost]
  1. Quoting from Porting guide 2.8 Bare variables in conditionals
  - include_tasks: teardown.yml
    when: teardown

  - include_tasks: provision.yml
    when: not teardown

" based on a variable you define as a string (with quotation marks around it):"

  • In Ansible 2.7 and earlier, the two conditions above evaluated as True and False respectively if teardown: 'true'

  • In Ansible 2.7 and earlier, both conditions evaluated as False if teardown: 'false'

  • In Ansible 2.8 and later, you have the option of disabling conditional bare variables, so when: teardown always evaluates as True and when: not teardown always evaluates as False when teardown is a non-empty string (including 'true' or 'false')

  1. Quoting from CONDITIONAL_BARE_VARS

"Expect that this setting eventually will be deprecated after 2.12"

How to remove a build from itunes connect?

Wait! You can expire a build actually! :)

After 2017 Solution:

Still same at 2021

  1. From the homepage, click My Apps, select your app.

  2. Click the TestFlight tab.

  3. In the sidebar, below Builds, click the platform (iOS or tvOS).

  4. In the table on the right, in the Build column, click the app icon or build string for the build that is missing compliance information.

5.Click Expire Build.

how to Expire Build App store iTunes Connect

Ta-da! Build expired at the App Store Connect.

Means:

Required roles

See Role permissions.

For more information please visit.

substring of an entire column in pandas dataframe

case the column isn't string, use astype to convert:

df['col'] = df['col'].astype(str).str[:9]

How can I get a side-by-side diff when I do "git diff"?

If you'd like to see side-by-side diffs in a browser without involving GitHub, you might enjoy git webdiff, a drop-in replacement for git diff:

$ pip install webdiff
$ git webdiff

This offers a number of advantages over traditional GUI difftools like tkdiff in that it can give you syntax highlighting and show image diffs.

Read more about it here.

How do I enumerate the properties of a JavaScript object?

Use a for..in loop to enumerate an object's properties, but be careful. The enumeration will return properties not just of the object being enumerated, but also from the prototypes of any parent objects.

var myObject = {foo: 'bar'};

for (var name in myObject) {
  alert(name);
}

// results in a single alert of 'foo'

Object.prototype.baz = 'quux';

for (var name in myObject) {
  alert(name);
}

// results in two alerts, one for 'foo' and one for 'baz'

To avoid including inherited properties in your enumeration, check hasOwnProperty():

for (var name in myObject) {
  if (myObject.hasOwnProperty(name)) {
    alert(name);
  }
}

Edit: I disagree with JasonBunting's statement that we don't need to worry about enumerating inherited properties. There is danger in enumerating over inherited properties that you aren't expecting, because it can change the behavior of your code.

It doesn't matter whether this problem exists in other languages; the fact is it exists, and JavaScript is particularly vulnerable since modifications to an object's prototype affects child objects even if the modification takes place after instantiation.

This is why JavaScript provides hasOwnProperty(), and this is why you should use it in order to ensure that third party code (or any other code that might modify a prototype) doesn't break yours. Apart from adding a few extra bytes of code, there is no downside to using hasOwnProperty().

Effectively use async/await with ASP.NET Web API

You are not leveraging async / await effectively because the request thread will be blocked while executing the synchronous method ReturnAllCountries()

The thread that is assigned to handle a request will be idly waiting while ReturnAllCountries() does it's work.

If you can implement ReturnAllCountries() to be asynchronous, then you would see scalability benefits. This is because the thread could be released back to the .NET thread pool to handle another request, while ReturnAllCountries() is executing. This would allow your service to have higher throughput, by utilizing threads more efficiently.

How to increment a pointer address and pointer's value?

With regards to "How to increment a pointer address and pointer's value?" I think that ++(*p++); is actually well defined and does what you're asking for, e.g.:

#include <stdio.h>

int main() {
  int a = 100;
  int *p = &a;
  printf("%p\n",(void*)p);
  ++(*p++);
  printf("%p\n",(void*)p);
  printf("%d\n",a);
  return 0;
}

It's not modifying the same thing twice before a sequence point. I don't think it's good style though for most uses - it's a little too cryptic for my liking.

Finding the average of a list

On Python 3.4+ you can use statistics.mean()

l = [15, 18, 2, 36, 12, 78, 5, 6, 9]

import statistics
statistics.mean(l)  # 20.11111111111111

On older versions of Python you can do

sum(l) / len(l)

On Python 2 you need to convert len to a float to get float division

sum(l) / float(len(l))

There is no need to use reduce. It is much slower and was removed in Python 3.

Chrome - ERR_CACHE_MISS

This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.

How to display raw html code in PRE or something like it but without escaping it

Essentially the original question can be broken down in 2 parts:

  • Main objective/challenge: embedding(/transporting) a raw formatted code-snippet (any kind of code) in a web-page's markup (for simple copy/paste/edit due to no encoding/escaping)
  • correctly displaying/rendering that code-snippet (possibly edit it) in the browser

The short (but) ambiguous answer is: you can't, ...but you can (get very close).
(I know, that are 3 contradicting answers, so read on...)

(polyglot)(x)(ht)ml Markup-languages rely on wrapping (almost) everything between begin/opening and end/closing tags/character(sequences).
So, to embed any kind of raw code/snippet inside your markup-language, one will always have to escape/encode every instance (inside that snippet) that resembles the character(-sequence) that would close the wrapping 'container' element in the markup. (During this post I'll refer to this as rule no 1.)
Think of "some "data" here" or <i>..close italics with '</i>'-tag</i>, where it is obvious one should escape/encode (something in) </i and " (or change container's quote-character from " to ').

So, because of rule no 1, you can't 'just' embed 'any' unknown raw code-snippet inside markup.
Because, if one has to escape/encode even one character inside the raw snippet, then that snippet would no longer be the same original 'pure raw code' that anyone can copy/paste/edit in the document's markup without further thought. It would lead to malformed/illegal markup and Mojibake (mainly) because of entities.
Also, should that snippet contain such characters, you'd still need some javascript to 'translate' that character(sequence) from (and to) it's escaped/encoded representation to display the snippet correctly in the 'webpage' (for copy/paste/edit).

That brings us to (some of) the datatypes that markup-languages specify. These datatypes essentially define what are considered 'valid characters' and their meaning (per tag, property, etc.):

  • PCDATA (Parsed Character DATA): will expand entities and one must escape <, & (and > depending on markup language/version).
    Most tags like body, div, pre, etc, but also textarea (until HTML5) fall under this type.
    So not only do you need to encode all the container's closing character-sequences inside the snippet, you also have to encode all <, & (,>) characters (at minimum).
    Needless to say, encoding/escaping this many characters falls outside this objective's scope of embedding a raw snippet in the markup.
    '..But a textarea seems to work...', yes, either because of the browsers error-engine trying to make something out of it, or because HTML5:

  • RCDATA (Replaceable Character DATA): will not not treat tags inside the text as markup (but are still governed by rule 1), so one doesn't need to encode < (>). BUT entities are still expanded, so they and 'ambiguous ampersands' (&) need special care.
    The current HTML5 spec says the textarea is now a RCDATA field and (quote):

    The text in raw text and RCDATA elements must not contain any occurrences of the string "</" (U+003C LESS-THAN SIGN, U+002F SOLIDUS) followed by characters that case-insensitively match the tag name of the element followed by one of U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, U+003E GREATER-THAN SIGN (>), or U+002F SOLIDUS (/).

    Thus no matter what, textarea needs a hefty entity translation handler or it will eventually Mojibake on entities!

  • CDATA (Character Data) will not treat tags inside the text as markup and will not expand entities.
    So as long as the raw snippet code does not violate rule 1 (that one can't have the containers closing character(sequence) inside the snippet), this requires no other escaping/encoding.

Clearly this boils down to: how can we minimize the number of characters/character-sequences that still need to be encoded in the snippet's raw source and the number of times that character(sequence) might appear in an average snippet; something that is also of importance for the javascript that handles the translation of these characters (if they occur).

So what 'containers' have this CDATA context?

Most value properties of tags are CDATA, so one could (ab)use a hidden input's value property (proof of concept jsfiddle here).
However (conform rule 1) this creates an encoding/escape problem with nested quotes (" and ') in the raw snippet and one needs some javascript to get/translate and set the snippet in another (visible) element (or simply setting it as a text-area's value). Somehow this gave me problems with entities in FF (just like in a textarea). But it doesn't really matter, since the 'price' of having to escape/encode nested quotes is higher then a (HTML5) textarea (quotes are quite common in source code..).

What about trying to (ab)use <![CDATA[<tag>bla & bla</tag>]]>?
As Jukka points out in his extended answer, this would only work in (rare) 'real xhtml'.
I thought of using a script-tag (with or without such a CDATA wrapper inside the script-tag) together with a multi-line comment /* */ that wraps the raw snippet (script-tags can have an id and you can access them by count). But since this obviously introduces a escaping problem with */, ]]> and </script in the raw snippet, this doesn't seem like a solution either.

Please post other viable 'containers' in the comments to this answer.

By the way, encoding or counting the number of - characters and balancing them out inside a comment tag <!-- --> is just insane for this purpose (apart from rule 1).


That leaves us with Jukka K. Korpela's excellent answer: the <xmp> tag seems the best option!

The 'forgotten' <xmp> holds CDATA, is intended for this purpose AND is indeed still in the current HTML 5 spec (and has been at least since HTML3.2); exactly what we need! It's also widely supported, even in IE6 (that is.. until it suffers from the same regression as the scrolling table-body).
Note: as Jukka pointed out, this will not work in true xhtml or polyglot (that will treat it as a pre) and the xmp tag must still adhere to rule no 1. But that's the 'only' rule.

Consider the following markup:

<!-- ATTENTION: replace any occurrence of &lt;/xmp with </xmp -->
<xmp id="snippet-container">
<div>
    <div>this is an example div &amp; holds an xmp tag:<br />
        <xmp> 
<html><head>  <!-- indentation col 0!! -->
    <title>My Title</title>
</head><body>
    <p>hello world !!</p>
</body></html>
        &lt;/xmp>  <!-- note this encoded/escaped tag -->
    </div>
    This line is also part of the snippet
</div>
</xmp>

The above codeblok illustrates a raw piece of markup where <xmp id="snippet-container"> contains an (almost raw) code-snippet (containing div>div>xmp>html-document).
Notice the encoded closing tag in this markup? To comply with rule no 1, this was encoded/escaped).

So embedding/transporting the (sometimes almost) raw code is/seems solved.

What about displaying/rendering the snippet (and that encoded &lt;/xmp>)?

The browser will (or it should) render the snippet (the contents inside snippet-container) exactly the way you see it in the codeblock above (with some discrepancy amongst browsers whether or not the snippet starts with a blank line).
That includes the formatting/indentation, entities (like the string &amp;), full tags, comments AND the encoded closing tag &lt;/xmp> (just like it was encoded in the markup). And depending on browser(version) one could even try use the property contenteditable="true" to edit this snippet (all that without javascript enabled). Doing something like textarea.value=xmp.innerHTML is also a breeze.

So you can... if the snippet doesn't contain the containers closing character-sequence.

However, should a raw snippet contain the closing character-sequence </xmp (because it is an example of xmp itself or it contains some regex, etc), you must accept that you have to encode/escape that sequence in the raw snippet AND need a javascript handler to translate that encoding to display/render the encoded &lt;/xmp> like </xmp> inside a textarea (for editing/posting) or (for example) a pre just to correctly render the snippet's code (or so it seems).

A very rudimentary jsfiddle example of this here. Note that getting/embedding/displaying/retrieving-to-textarea worked perfect even in IE6. But setting the xmp's innerHTML revealed some interesting 'would-be-intelligent' behavior on IE's part. There is a more extensive note and workaround on that in the fiddle.

But now comes the important kicker (another reason why you only get very close): Just as an over-simplified example, imagine this rabbit-hole:

Intended raw code-snippet:

<!-- remember to translate between </xmp> and &lt;/xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>

Well, to comply with rule 1, we 'only' need to encode those </xmp[> \n\r\t\f\/] sequences, right?

So that gives us the following markup (using just a possible encoding):

<xmp id="container">
<!-- remember to translate between &lt;/xmp> and &lt;/xmp> -->
<xmp>
<p>a paragraph</p>
&lt;/xmp>
</xmp>

Hmm.. shalt I get my crystal ball or flip a coin? No, let the computer look at its system-clock and state that a derived number is 'random'. Yes, that should do it..

Using a regex like: xmp.innerHTML.replace(/&lt;(?=\/xmp[> \n\r\t\f\/])/gi, '<');, would translate 'back' to this:

<!-- remember to translate between </xmp> and </xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>

Hmm.. seems this random generator is broken... Houston..?
Should you have missed the joke/problem, read again starting at the 'intended raw code-snippet'.

Wait, I know, we (also) need to encode .... to ....
Ok, rewind to 'intended raw code-snippet' and read again.
Somehow this all begins to smell like the famous hilarious-but-true rexgex-answer on SO, a good read for people fluent in mojibake.

Maybe someone knows a clever algorithm or solution to fix this problem, but I assume that the embedded raw code will get more and more obscure to the point where you'd be better of properly escaping/encoding just your <, & (and >), just like the rest of the world.

Conclusion: (using the xmp tag)

  • it can be done with known snippets that do not contain the container's closing character-sequence,
  • we can get very close to the original objective with known snippets that only use 'basic first-level' escaping/encoding so we don't fall in the rabbithole,
  • but ultimately it seems that one can't do this reliably in a 'production-environment' where people can/should copy/paste/edit 'any unknown' raw snippets while not knowing/understanding the implications/rules/rabbithole (depending on your implementation of handling/translating for rule 1 and the rabbit-hole).

Hope this helps!

PS: Whilst I would appreciate an upvote if you find this explanation useful, I kind of think Jukka's answer should be the accepted answer (should no better option/answer come along), since he was the one who remembered the xmp tag (that I forgot about over the years and got 'distracted' by the commonly advocated PCDATA elements like pre, textarea, etc.).
This answer originated in explaining why you can't do it (with any unknown raw snippet) and explain some obvious pitfalls that some other (now deleted) answers overlooked when advising a textarea for embedding/transport. I've expanded my existing explanation to also support and further explain Jukka's answer (since all that entity and *CDATA stuff is almost harder than code-pages).

Delete specific values from column with where condition?

UPDATE myTable 
   SET myColumn = NULL 
 WHERE myCondition

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

When you use jackson to map from string to your concrete class, especially if you work with generic type. then this issue may happen because of different class loader. i met it one time with below scenarior:

Project B depend on Library A

in Library A:

public class DocSearchResponse<T> {
 private T data;
}

it has service to query data from external source, and use jackson to convert to concrete class

public class ServiceA<T>{
  @Autowired
  private ObjectMapper mapper;
  @Autowired
  private ClientDocSearch searchClient;

  public DocSearchResponse<T> query(Criteria criteria){
      String resultInString = searchClient.search(criteria);
      return convertJson(resultInString)
  }
}

public DocSearchResponse<T> convertJson(String result){
     return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {});
  }
}

in Project B:

public class Account{
 private String name;
 //come with other attributes
}

and i use ServiceA from library to make query and as well convert data

public class ServiceAImpl extends ServiceA<Account> {
    
}

and make use of that

public class MakingAccountService {
    @Autowired
    private ServiceA service;
    public void execute(Criteria criteria){
      
        DocSearchResponse<Account> result = service.query(criteria);
        Account acc = result.getData(); //  java.util.LinkedHashMap cannot be cast to com.testing.models.Account
    }
}

it happen because from classloader of LibraryA, jackson can not load Account class, then just override method convertJson in Project B to let jackson do its job

public class ServiceAImpl extends ServiceA<Account> {
        @Override
        public DocSearchResponse<T> convertJson(String result){
         return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {});
      }
    }
 }

using nth-child in tables tr td

Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td> that have $ inside. Example: using nth-child in tables tr td

html

<tr>
    <td>&nbsp;</td>
    <td data-rel='$'>$</td>
    <td>&nbsp;</td>
</tr>

css

table tr td[data-rel='$'] {
    background-color: #333;
    color: white;
}

Please try these example.

_x000D_
_x000D_
table tr td[data-content='$'] {_x000D_
    background-color: #333;_x000D_
    color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
    <tr>_x000D_
        <td>A</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>B</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>C</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>D</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

X-Frame-Options Allow-From multiple domains

Necromancing.
The provided answers are incomplete.

First, as already said, you cannot add multiple allow-from hosts, that's not supported.
Second, you need to dynamically extract that value from the HTTP referrer, which means that you can't add the value to Web.config, because it's not always the same value.

It will be necessary to do browser-detection to avoid adding allow-from when the browser is Chrome (it produces an error on the debug - console, which can quickly fill the console up, or make the application slow). That also means you need to modify the ASP.NET browser detection, as it wrongly identifies Edge as Chrome.

This can be done in ASP.NET by writing a HTTP-module which runs on every request, that appends a http-header for every response, depending on the request's referrer. For Chrome, it needs to add Content-Security-Policy.

// https://stackoverflow.com/questions/31870789/check-whether-browser-is-chrome-or-edge
public class BrowserInfo
{

    public System.Web.HttpBrowserCapabilities Browser { get; set; }
    public string Name { get; set; }
    public string Version { get; set; }
    public string Platform { get; set; }
    public bool IsMobileDevice { get; set; }
    public string MobileBrand { get; set; }
    public string MobileModel { get; set; }


    public BrowserInfo(System.Web.HttpRequest request)
    {
        if (request.Browser != null)
        {
            if (request.UserAgent.Contains("Edge")
                && request.Browser.Browser != "Edge")
            {
                this.Name = "Edge";
            }
            else
            {
                this.Name = request.Browser.Browser;
                this.Version = request.Browser.MajorVersion.ToString();
            }
            this.Browser = request.Browser;
            this.Platform = request.Browser.Platform;
            this.IsMobileDevice = request.Browser.IsMobileDevice;
            if (IsMobileDevice)
            {
                this.Name = request.Browser.Browser;
            }
        }
    }


}


void context_EndRequest(object sender, System.EventArgs e)
{
    if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)
    {
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;

        try
        {
            // response.Headers["P3P"] = "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"":
            // response.Headers.Set("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
            // response.AddHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
            response.AppendHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");

            // response.AppendHeader("X-Frame-Options", "DENY");
            // response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
            // response.AppendHeader("X-Frame-Options", "AllowAll");

            if (System.Web.HttpContext.Current.Request.UrlReferrer != null)
            {
                // "X-Frame-Options": "ALLOW-FROM " Not recognized in Chrome 
                string host = System.Web.HttpContext.Current.Request.UrlReferrer.Scheme + System.Uri.SchemeDelimiter
                            + System.Web.HttpContext.Current.Request.UrlReferrer.Authority
                ;

                string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
                string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;

                // SQL.Log(System.Web.HttpContext.Current.Request.RawUrl, System.Web.HttpContext.Current.Request.UrlReferrer.OriginalString, refAuth);

                if (IsHostAllowed(refAuth))
                {
                    BrowserInfo bi = new BrowserInfo(System.Web.HttpContext.Current.Request);

                    // bi.Name = Firefox
                    // bi.Name = InternetExplorer
                    // bi.Name = Chrome

                    // Chrome wants entire path... 
                    if (!System.StringComparer.OrdinalIgnoreCase.Equals(bi.Name, "Chrome"))
                        response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);    

                    // unsafe-eval: invalid JSON https://github.com/keen/keen-js/issues/394
                    // unsafe-inline: styles
                    // data: url(data:image/png:...)

                    // https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet
                    // https://www.ietf.org/rfc/rfc7034.txt
                    // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
                    // https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP

                    // https://stackoverflow.com/questions/10205192/x-frame-options-allow-from-multiple-domains
                    // https://content-security-policy.com/
                    // http://rehansaeed.com/content-security-policy-for-asp-net-mvc/

                    // This is for Chrome:
                    // response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);


                    System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
                    ls.Add("default-src");
                    ls.Add("'self'");
                    ls.Add("'unsafe-inline'");
                    ls.Add("'unsafe-eval'");
                    ls.Add("data:");

                    // http://az416426.vo.msecnd.net/scripts/a/ai.0.js

                    // ls.Add("*.msecnd.net");
                    // ls.Add("vortex.data.microsoft.com");

                    ls.Add(selfAuth);
                    ls.Add(refAuth);

                    string contentSecurityPolicy = string.Join(" ", ls.ToArray());
                    response.AppendHeader("Content-Security-Policy", contentSecurityPolicy);
                }
                else
                {
                    response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
                }

            }
            else
                response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
        }
        catch (System.Exception ex)
        {
            // WTF ? 
            System.Console.WriteLine(ex.Message); // Suppress warning
        }

    } // End if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)

} // End Using context_EndRequest


private static string[] s_allowedHosts = new string[] 
{
     "localhost:49533"
    ,"localhost:52257"
    ,"vmcompany1"
    ,"vmcompany2"
    ,"vmpostalservices"
    ,"example.com"
};


public static bool IsHostAllowed(string host)
{
    return Contains(s_allowedHosts, host);
} // End Function IsHostAllowed 


public static bool Contains(string[] allowed, string current)
{
    for (int i = 0; i < allowed.Length; ++i)
    {
        if (System.StringComparer.OrdinalIgnoreCase.Equals(allowed[i], current))
            return true;
    } // Next i 

    return false;
} // End Function Contains 

You need to register the context_EndRequest function in the HTTP-module Init function.

public class RequestLanguageChanger : System.Web.IHttpModule
{


    void System.Web.IHttpModule.Dispose()
    {
        // throw new NotImplementedException();
    }


    void System.Web.IHttpModule.Init(System.Web.HttpApplication context)
    {
        // https://stackoverflow.com/questions/441421/httpmodule-event-execution-order
        context.EndRequest += new System.EventHandler(context_EndRequest);
    }

    // context_EndRequest Code from above comes here


}

Next you need to add the module to your application. You can either do this programmatically in Global.asax by overriding the Init function of the HttpApplication, like this:

namespace ChangeRequestLanguage
{


    public class Global : System.Web.HttpApplication
    {

        System.Web.IHttpModule mod = new libRequestLanguageChanger.RequestLanguageChanger();

        public override void Init()
        {
            mod.Init(this);
            base.Init();
        }



        protected void Application_Start(object sender, System.EventArgs e)
        {

        }

        protected void Session_Start(object sender, System.EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, System.EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, System.EventArgs e)
        {

        }

        protected void Application_Error(object sender, System.EventArgs e)
        {

        }

        protected void Session_End(object sender, System.EventArgs e)
        {

        }

        protected void Application_End(object sender, System.EventArgs e)
        {

        }


    }


}

or you can add entries to Web.config if you don't own the application source-code:

      <httpModules>
        <add name="RequestLanguageChanger" type= "libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
      </httpModules>
    </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>

    <modules runAllManagedModulesForAllRequests="true">
      <add name="RequestLanguageChanger" type="libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
    </modules>
  </system.webServer>
</configuration>

The entry in system.webServer is for IIS7+, the other in system.web is for IIS 6.
Note that you need to set runAllManagedModulesForAllRequests to true, for that it works properly.

The string in type is in the format "Namespace.Class, Assembly". Note that if you write your assembly in VB.NET instead of C#, VB creates a default-Namespace for each project, so your string will look like

"[DefaultNameSpace.Namespace].Class, Assembly"

If you want to avoid this problem, write the DLL in C#.

What is the purpose of flush() in Java streams?

From the docs of the flush method:

Flushes the output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

The buffering is mainly done to improve the I/O performance. More on this can be read from this article: Tuning Java I/O Performance.

Search code inside a Github project

Google allows you to search in the project, but not the code :(

site:https://github.com/CreateJS/EaselJS test

Search and get a line in Python

you mentioned "entire line" , so i assumed mystring is the entire line.

if "token" in mystring:
    print(mystring)

however if you want to just get "token qwerty",

>>> mystring="""
...     qwertyuiop
...     asdfghjkl
...
...     zxcvbnm
...     token qwerty
...
...     asdfghjklñ
... """
>>> for item in mystring.split("\n"):
...  if "token" in item:
...     print (item.strip())
...
token qwerty

Getting execute permission to xp_cmdshell

Don't grant control to the user, it's totally unnecessay. Select permission on the database is enough. After you have created the login and the user on master (see above answers):

use YourDatabase
go
create user [YourDomain\YourUser] for login [YourDomain\YourUser] with default_schema=[dbo]
go
alter role [db_datareader] add member [YourDomain\YourUser]
go

Get all directories within directory nodejs

Fully async version with ES6, only native packages, fs.promises and async/await, does file operations in parallel:

const fs = require('fs');
const path = require('path');

async function listDirectories(rootPath) {
    const fileNames = await fs.promises.readdir(rootPath);
    const filePaths = fileNames.map(fileName => path.join(rootPath, fileName));
    const filePathsAndIsDirectoryFlagsPromises = filePaths.map(async filePath => ({path: filePath, isDirectory: (await fs.promises.stat(filePath)).isDirectory()}))
    const filePathsAndIsDirectoryFlags = await Promise.all(filePathsAndIsDirectoryFlagsPromises);
    return filePathsAndIsDirectoryFlags.filter(filePathAndIsDirectoryFlag => filePathAndIsDirectoryFlag.isDirectory)
        .map(filePathAndIsDirectoryFlag => filePathAndIsDirectoryFlag.path);
}

Tested, it works nicely.

how to delete the content of text file without deleting itself

Write an empty string to the file, flush, and close. Make sure that the file writer is not in append-mode. I think that should do the trick.

Update multiple tables in SQL Server using INNER JOIN

You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :

BEGIN TRANSACTION

update A
set A.ORG_NAME =  @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID

update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
    on B.ORG_ID = A.ORG_ID
    and A.ORG_ID = @ORG_ID

COMMIT

"Cross origin requests are only supported for HTTP." error when loading a local file

Not possible to load static local files(eg:svg) without server. If you have NPM /YARN installed in your machine, you can setup simple http server using "http-server"

npm install http-server -g
http-server [path] [options]

Or open terminal in that project folder and type "hs". It will automaticaly start HTTP live server.

OperationalError: database is locked

A very unusual scenario, which happened to me.

There was infinite recursion, which kept creating the objects.

More specifically, using DRF, I was overriding create method in a view, and I did

def create(self, request, *args, **kwargs):
    ....
    ....

    return self.create(request, *args, **kwargs)

How can I find which tables reference a given table in Oracle SQL Developer?

Replace [Your TABLE] with emp in the query below

select owner,constraint_name,constraint_type,table_name,r_owner,r_constraint_name
  from all_constraints 
 where constraint_type='R'
   and r_constraint_name in (select constraint_name 
                               from all_constraints 
                              where constraint_type in ('P','U') 
                                and table_name='[YOUR TABLE]');

How to resolve "Could not find schema information for the element/attribute <xxx>"?

I configured the app.config with the tool for EntLib configuration and set up my LoggingConfiguration block. Then I copied this into the DotNetConfig.xsd. Of course, it does not cover all attributes, only the ones I added but it does not display those annoying info messages anymore.

<xs:element name="loggingConfiguration">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="listeners">
        <xs:complexType>
          <xs:sequence>
            <xs:element maxOccurs="unbounded" name="add">
              <xs:complexType>
                <xs:attribute name="fileName" type="xs:string" use="required" />
                <xs:attribute name="footer" type="xs:string" use="required" />
                <xs:attribute name="formatter" type="xs:string" use="required" />
                <xs:attribute name="header" type="xs:string" use="required" />
                <xs:attribute name="rollFileExistsBehavior" type="xs:string" use="required" />
                <xs:attribute name="rollInterval" type="xs:string" use="required" />
                <xs:attribute name="rollSizeKB" type="xs:unsignedByte" use="required" />
                <xs:attribute name="timeStampPattern" type="xs:string" use="required" />
                <xs:attribute name="listenerDataType" type="xs:string" use="required" />
                <xs:attribute name="traceOutputOptions" type="xs:string" use="required" />
                <xs:attribute name="filter" type="xs:string" use="required" />
                <xs:attribute name="type" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="formatters">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="add">
              <xs:complexType>
                <xs:attribute name="template" type="xs:string" use="required" />
                <xs:attribute name="type" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="logFilters">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="add">
              <xs:complexType>
                <xs:attribute name="enabled" type="xs:boolean" use="required" />
                <xs:attribute name="type" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="categorySources">
        <xs:complexType>
          <xs:sequence>
            <xs:element maxOccurs="unbounded" name="add">
              <xs:complexType>
                <xs:sequence>
                  <xs:element name="listeners">
                    <xs:complexType>
                      <xs:sequence>
                        <xs:element name="add">
                          <xs:complexType>
                            <xs:attribute name="name" type="xs:string" use="required" />
                          </xs:complexType>
                        </xs:element>
                      </xs:sequence>
                    </xs:complexType>
                  </xs:element>
                </xs:sequence>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="specialSources">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="allEvents">
              <xs:complexType>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
            <xs:element name="notProcessed">
              <xs:complexType>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
            <xs:element name="errors">
              <xs:complexType>
                <xs:sequence>
                  <xs:element name="listeners">
                    <xs:complexType>
                      <xs:sequence>
                        <xs:element name="add">
                          <xs:complexType>
                            <xs:attribute name="name" type="xs:string" use="required" />
                          </xs:complexType>
                        </xs:element>
                      </xs:sequence>
                    </xs:complexType>
                  </xs:element>
                </xs:sequence>
                <xs:attribute name="switchValue" type="xs:string" use="required" />
                <xs:attribute name="name" type="xs:string" use="required" />
              </xs:complexType>
            </xs:element>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
    <xs:attribute name="name" type="xs:string" use="required" />
    <xs:attribute name="tracingEnabled" type="xs:boolean" use="required" />
    <xs:attribute name="defaultCategory" type="xs:string" use="required" />
    <xs:attribute name="logWarningsWhenNoCategoriesMatch" type="xs:boolean" use="required" />
  </xs:complexType>
</xs:element>

How to make the script wait/sleep in a simple way in unity

you can

        float Lasttime;
        public float Sec = 3f;
        public int Num;
        void Start(){
        ExampleStart();
        }
        public void ExampleStart(){
        Lasttime = Time.time;
        }
        void Update{

        if(Time.time - Lasttime > sec){
//           if(Num == step){
//             Yourcode
//You Can Change Sec with => sec = YOURTIME(Float)
//             Num++;
//            ExampleStart();
             }
             if(Num == 0){
             TextUI.text = "Welcome to Number Wizard!";
             Num++;
             ExampleStart();
             }
             if(Num == 1){
             TextUI.text = ("The highest number you can pick is " + max);
             Num++;
             ExampleStart();
             }
             if(Num == 2){
             TextUI.text = ("The lowest number you can pick is " + min);
             Num++;
             ExampleStart();
             }
        }

    }  

Khaled Developer
Easy For Gaming

How to append multiple items in one line in Python

Use this :

#Inputs
L1 = [1, 2]
L2 = [3,4,5]

#Code
L1+L2

#Output
[1, 2, 3, 4, 5]

By using the (+) operator you can skip the multiple append & extend operators in just one line of code and this is valid for more then two of lists by L1+L2+L3+L4.......etc.

Happy Learning...:)

Disable keyboard on EditText

To add to Alex Kucherenko solution: the issue with the cursor getting disappearing after calling setInputType(0) is due to a framework bug on ICS (and JB).

The bug is documented here: https://code.google.com/p/android/issues/detail?id=27609.

To workaround this, call setRawInputType(InputType.TYPE_CLASS_TEXT) right after the setInputType call.

To stop the keyboard from appearing, just override OnTouchListener of the EditText and return true (swallowing the touch event):

ed.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                return true;
            }
        });

The reasons for the cursor appearing on GB devices and not on ICS+ had me tearing my hair out for a couple of hours, so I hope this saves someone's time.

How to disable all <input > inside a form with jQuery?

Above example is technically incorrect. Per latest jQuery, use the prop() method should be used for things like disabled. See their API page.

To disable all form elements inside 'target', use the :input selector which matches all input, textarea, select and button elements.

$("#target :input").prop("disabled", true);

If you only want the elements, use this.

$("#target input").prop("disabled", true);

Drop shadow on a div container?

The most widely compatible way of doing this is likely going to be creating a second div under your auto-suggest box the same size as the box itself, nudged a few pixels down and to the right. You can use JS to create and position it, which shouldn't be terribly difficult if you're using a fairly modern framework.

Adding rows to dataset

To add rows to existing DataTable in Dataset:

DataRow drPartMtl = DSPartMtl.Tables[0].NewRow();
drPartMtl["Group"] = "Group";
drPartMtl["BOMPart"] = "BOMPart";
DSPartMtl.Tables[0].Rows.Add(drPartMtl);

Python string.join(list) on object array rather than string array

The built-in string constructor will automatically call obj.__str__:

''.join(map(str,list))

Is it possible to use argsort in descending order?

An elegant way could be as follows -

ids = np.flip(np.argsort(avgDists))

This will give you indices of elements sorted in descending order. Now you can use regular slicing...

top_n = ids[:n]

Returning multiple objects in an R function

Similarly in Java, you can create a S4 class in R that encapsulates your information:

setClass(Class="Person",
         representation(
            height="numeric",
            age="numeric"
          )
)

Then your function can return an instance of this class:

myFunction = function(age=28, height=176){
  return(new("Person",
          age=age,
          height=height))
}

and you can access your information:

aPerson = myFunction()

aPerson@age
aPerson@height

If/else else if in Jquery for a condition

Iam confused a lot from morning whether it should be less than or greater than`

this can accept value less than "99999"

I think you answered it yourself... But it's valid when it's less than. Thus the following is incorrect:

}elseif($("#seats").val() < 99999){
  alert("Not a valid Number");
}else{

You are saying if it's less than 99999, then it's not valid. You want to do the opposite:

}elseif($("#seats").val() >= 99999){
  alert("Not a valid Number");
}else{

Also, since you have $("#seats") twice, jQuery has to search the DOM twice. You should really be storing the value, or at least the DOM element in a variable. And some more of your code doesn't make much sense, so I'm going to make some assumptions and put it all together:

var seats = $("#seats").val();

var error = null;

if (seats == "") {
    error = "Number is required";
} else {
    var seatsNum = parseInt(seats);
    
    if (isNaN(seatsNum)) {
        error = "Not a valid number";
    } else if (seatsNum >= 99999) {
        error = "Number must be less than 99999";
    }
}

if (error != null) {
    alert(error);
} else {
    alert("Valid number");
}

// If you really need setflag:
var setflag = error != null;

Here's a working sample: http://jsfiddle.net/LUY8q/

How to pass multiple values to single parameter in stored procedure

I spent time finding a proper way. This may be useful for others.

Create a UDF and refer in the query -

http://www.geekzilla.co.uk/view5C09B52C-4600-4B66-9DD7-DCE840D64CBD.htm

Python: For each list element apply a function across the list

You can do this using list comprehensions and min() (Python 3.0 code):

>>> nums = [1,2,3,4,5]
>>> [(x,y) for x in nums for y in nums]
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]
>>> min(_, key=lambda pair: pair[0]/pair[1])
(1, 5)

Note that to run this on Python 2.5 you'll need to either make one of the arguments a float, or do from __future__ import division so that 1/5 correctly equals 0.2 instead of 0.

When does Java's Thread.sleep throw InterruptedException?

The InterruptedException is usually thrown when a sleep is interrupted.

How do you get current active/default Environment profile programmatically in Spring?

Seems there is some demand to be able to access this statically.

How can I get such thing in static methods in non-spring-managed classes? – Aetherus

It's a hack, but you can write your own class to expose it. You must be careful to ensure that nothing will call SpringContext.getEnvironment() before all beans have been created, since there is no guarantee when this component will be instantiated.

@Component
public class SpringContext
{
    private static Environment environment;

    public SpringContext(Environment environment) {
        SpringContext.environment = environment;
    }

    public static Environment getEnvironment() {
        if (environment == null) {
            throw new RuntimeException("Environment has not been set yet");
        }
        return environment;
    }
}

Concat a string to SELECT * MySql

If you want to concatenate the fields using / as a separator, you can use concat_ws:

select concat_ws('/', col1, col2, col3) from mytable

You cannot escape listing the columns in the query though. The *-syntax works only in "select * from". You can list the columns and construct the query dynamically though.

Automatically set appsettings.json for dev and release environments in asp.net core?

Update for .NET Core 3.0+

  1. You can use CreateDefaultBuilder which will automatically build and pass a configuration object to your startup class:

    WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
    
    public class Startup
    {
        public Startup(IConfiguration configuration) // automatically injected
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        /* ... */
    }
    
  2. CreateDefaultBuilder automatically includes the appropriate appsettings.Environment.json file so add a separate appsettings file for each environment:

    appsettings.env.json

  3. Then set the ASPNETCORE_ENVIRONMENT environment variable when running / debugging

How to set Environment Variables

Depending on your IDE, there are a couple places dotnet projects traditionally look for environment variables:

  • For Visual Studio go to Project > Properties > Debug > Environment Variables:

    Visual Studio - Environment Variables

  • For Visual Studio Code, edit .vscode/launch.json > env:

    Visual Studio Code > Launch Environment

  • Using Launch Settings, edit Properties/launchSettings.json > environmentVariables:

    Launch Settings

    Which can also be selected from the Toolbar in Visual Studio

    Launch Settings Dropdown

  • Using dotnet CLI, use the appropriate syntax for setting environment variables per your OS

    Note: When an app is launched with dotnet run, launchSettings.json is read if available, and environmentVariables settings in launchSettings.json override environment variables.

How does Host.CreateDefaultBuilder work?

.NET Core 3.0 added Host.CreateDefaultBuilder under platform extensions which will provide a default initialization of IConfiguration which provides default configuration for the app in the following order:

  1. appsettings.json using the JSON configuration provider.
  2. appsettings.Environment.json using the JSON configuration provider. For example:
    • appsettings.Production.json or
    • appsettings.Development.json
  3. App secrets when the app runs in the Development environment.
  4. Environment variables using the Environment Variables configuration provider.
  5. Command-line arguments using the Command-line configuration provider.

Further Reading - MS Docs

sending mail from Batch file

We use blat to do this all the time in our environment. I use it as well to connect to Gmail with Stunnel. Here's the params to send a file

blat -to [email protected] -server smtp.example.com -f [email protected] -subject "subject" -body "body" -attach c:\temp\file.txt

Or you can put that file in as the body

blat c:\temp\file.txt -to [email protected] -server smtp.example.com -f [email protected] -subject "subject"

What is the most efficient string concatenation method in python?

Python 3.6 changed the game for string concatenation of known components with Literal String Interpolation.

Given the test case from mkoistinen's answer, having strings

domain = 'some_really_long_example.com'
lang = 'en'
path = 'some/really/long/path/'

The contenders are

  • f'http://{domain}/{lang}/{path}' - 0.151 µs

  • 'http://%s/%s/%s' % (domain, lang, path) - 0.321 µs

  • 'http://' + domain + '/' + lang + '/' + path - 0.356 µs

  • ''.join(('http://', domain, '/', lang, '/', path)) - 0.249 µs (notice that building a constant-length tuple is slightly faster than building a constant-length list).

Thus currently the shortest and the most beautiful code possible is also fastest.

In alpha versions of Python 3.6 the implementation of f'' strings was the slowest possible - actually the generated byte code is pretty much equivalent to the ''.join() case with unnecessary calls to str.__format__ which without arguments would just return self unchanged. These inefficiencies were addressed before 3.6 final.

The speed can be contrasted with the fastest method for Python 2, which is + concatenation on my computer; and that takes 0.203 µs with 8-bit strings, and 0.259 µs if the strings are all Unicode.

Getting "cannot find Symbol" in Java project in Intellij

I had to right-click the project, and select "Reimport" under the "Run Maven" submenu.

How to set image to UIImage

Like vikingosgundo said, but keep in mind that if you use [UIImage imageNamed:image] then the image is cached and eats away memory. So unless you plan on using the same image in many places, you should load the image, with imageWithContentsOfFile: and imageWithData:

This will save you significant memory and speeds up your app.

Flutter- wrapping text

You Can Wrap your widget with Flexible Widget and than you can set property of Text using overflow property of Text Widget. you have to set TextOverflow.clip for example:-

Flexible
(child: new Text("This is Dummy Long Text",
 style: TextStyle(
 fontFamily: "Roboto",
 color: Colors.black,
 fontSize: 10.0,
 fontWeight: FontWeight.bold),
 overflow: TextOverflow.clip,),)

hope this help someone :)

Calculate time difference in Windows batch file

A re-hash of Aacini's code because most likely you are going to set the start time as a variable and want to save that data for output:

    @echo off

    rem ******************  MAIN CODE SECTION
    set STARTTIME=%TIME%

    rem Your code goes here (remove the ping line)
    ping -n 4 -w 1 127.0.0.1 >NUL

    set ENDTIME=%TIME%

    rem ******************  END MAIN CODE SECTION


    rem Change formatting for the start and end times
    for /F "tokens=1-4 delims=:.," %%a in ("%STARTTIME%") do (
       set /A "start=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
    )

    for /F "tokens=1-4 delims=:.," %%a in ("%ENDTIME%") do ( 
       IF %ENDTIME% GTR %STARTTIME% set /A "end=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100" 
       IF %ENDTIME% LSS %STARTTIME% set /A "end=((((%%a+24)*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100" 
    )

    rem Calculate the elapsed time by subtracting values
    set /A elapsed=end-start

    rem Format the results for output
    set /A hh=elapsed/(60*60*100), rest=elapsed%%(60*60*100), mm=rest/(60*100), rest%%=60*100, ss=rest/100, cc=rest%%100
    if %hh% lss 10 set hh=0%hh%
    if %mm% lss 10 set mm=0%mm%
    if %ss% lss 10 set ss=0%ss%
    if %cc% lss 10 set cc=0%cc%

    set DURATION=%hh%:%mm%:%ss%,%cc%

    echo Start    : %STARTTIME%
    echo Finish   : %ENDTIME%
    echo          ---------------
    echo Duration : %DURATION% 

Output:

    Start    : 11:02:45.92
    Finish   : 11:02:48.98
             ---------------
    Duration : 00:00:03,06

Postgresql Select rows where column = array

For dynamic SQL use:

'IN(' ||array_to_string(some_array, ',')||')'

Example

DO LANGUAGE PLPGSQL $$

DECLARE
    some_array bigint[];
    sql_statement text;

BEGIN

    SELECT array[1, 2] INTO some_array;
    RAISE NOTICE '%', some_array;

    sql_statement := 'SELECT * FROM my_table WHERE my_column IN(' ||array_to_string(some_array, ',')||')';
    RAISE NOTICE '%', sql_statement;

END;

$$;

Result: NOTICE: {1,2} NOTICE: SELECT * FROM my_table WHERE my_column IN(1,2)

pandas get column average/mean

Additionally if you want to get the round value after finding the mean.

#Create a DataFrame
df1 = {
    'Subject':['semester1','semester2','semester3','semester4','semester1',
               'semester2','semester3'],
   'Score':[62.73,47.76,55.61,74.67,31.55,77.31,85.47]}
df1 = pd.DataFrame(df1,columns=['Subject','Score'])

rounded_mean = round(df1['Score'].mean()) # specified nothing as decimal place
print(rounded_mean) # 62

rounded_mean_decimal_0 = round(df1['Score'].mean(), 0) # specified decimal place as 0
print(rounded_mean_decimal_0) # 62.0

rounded_mean_decimal_1 = round(df1['Score'].mean(), 1) # specified decimal place as 1
print(rounded_mean_decimal_1) # 62.2

Phonegap Cordova installation Windows

After hours of frustration... here's what i discovered.

  1. Ignore the installation documentation and all the command line, node.js stuff (seriously you will waste hours on this.
  2. Go to github and simply download the PhoneGap master .zip
  3. In that zip are project files for window phone, etc platform... just use those templates.

I don't know how such an easy process could have worse documentation. It as if it was written by lawyers.

Is there a way to take the first 1000 rows of a Spark Dataframe?

Limit is very simple, example limit first 50 rows

val df_subset = data.limit(50)

Auto generate function documentation in Visual Studio

You can use code snippets to insert any lines you want.

Also, if you type three single quotation marks (''') on the line above the function header, it will insert the XML header template that you can then fill out.

These XML comments can be interpreted by documentation software, and they are included in the build output as an assembly.xml file. If you keep that XML file with the DLL and reference that DLL in another project, those comments become available in intellisense.

How to create my json string by using C#?

No real need for the JSON.NET package. You could use JavaScriptSerializer. The Serialize method will turn a managed type instance into a JSON string.

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(instanceOfThing);

What is the difference between concurrency and parallelism?

I will try to explain with a interesting and easy to understand example. :)

Assume that a organization organizes a chess tournament where 10 players (with equal chess playing skills) will challenge a professional champion chess player. And since chess is 1:1 game thus organizers have to conduct 10 games in time efficient manner so that they can finish the whole event as quickly as possible.

Hopefully following scenarios will easily describe multiple ways of conducting these 10 games:

1) SERIAL - lets say that the professional plays with each person one by one i.e. starts and finishes the game with one person and then starts the next game with next person and so on. In other words, they decided to conduct the games sequentially. So if one game takes 10 mins to complete then 10 games will take 100 mins, also assume that transition from one game to other takes 6 secs then for 10 games it will be 54 secs (approx. 1 min).

so the whole event will approximately complete in 101 mins (WORST APPROACH)

2) CONCURRENT - lets say that professional plays his turn and moves on to next player so all 10 players are playing simultaneously but the professional player is not with two person at a time, he plays his turn and moves on to next person. Now assume professional player takes 6 sec to play his turn and also transition time of professional player b/w two players is 6 sec so total transition time to get back to first player will be 1min (10x6sec). Therefore, by the time he is back to first person with, whom event was started, 2mins have passed (10xtime_per_turn_by_champion + 10xtransition_time=2mins)

Assuming that all player take 45sec to complete their turn so based on 10mins per game from SERIAL event the no. of rounds before a game finishes should 600/(45+6) = 11 rounds (approx)

So the whole event will approximately complete in 11xtime_per_turn_by_player_&_champion + 11xtransition_time_across_10_players = 11x51 + 11x60sec= 561 + 660 = 1221sec = 20.35mins (approximately)

SEE THE IMPROVEMENT from 101 mins to 20.35 mins (BETTER APPROACH)

3) PARALLEL - lets say organizers get some extra funds and thus decided to invite two professional champion player (both equally capable) and divided the set of same 10 players (challengers) in two group of 5 each and assigned them to two champion i.e. one group each. Now the event is progressing in parallel in these two sets i.e. at least two players (one in each group) are playing against the two professional players in their respective group.

However within the group the professional player with take one player at a time (i.e. sequentially) so without any calculation you can easily deduce that whole event will approximately complete in 101/2=50.5mins to complete

SEE THE IMPROVEMENT from 101 mins to 50.5 mins (GOOD APPROACH)

4) CONCURRENT + PARALLEL - In above scenario, lets say that the two champion player will play concurrently (read 2nd point) with the 5 players in their respective groups so now games across groups are running in parallel but within group they are running concurrently.

So the games in one group will approximately complete in 11xtime_per_turn_by_player_&_champion + 11xtransition_time_across_5_players = 11x51 + 11x30 = 600 + 330 = 930sec = 15.5mins (approximately)

So the whole event (involving two such parallel running group) will approximately complete in 15.5mins

SEE THE IMPROVEMENT from 101 mins to 15.5 mins (BEST APPROACH)

NOTE: in above scenario if you replace 10 players with 10 similar jobs and two professional player with a two CPU cores then again the following ordering will remain true:

SERIAL > PARALLEL > CONCURRENT > CONCURRENT+PARALLEL

(NOTE: this order might change for other scenarios as this ordering highly depends on inter-dependency of jobs, communication needs b/w jobs and transition overhead b/w jobs)

How to get first element in a list of tuples?

you can unpack your tuples and get only the first element using a list comprehension:

l = [(1, u'abc'), (2, u'def')]
[f for f, *_ in l]

output:

[1, 2]

this will work no matter how many elements you have in a tuple:

l = [(1, u'abc'), (2, u'def', 2, 4, 5, 6, 7)]
[f for f, *_ in l]

output:

[1, 2]

msvcr110.dll is missing from computer error while installing PHP

You need to install the Visual C++ libraries: http://www.microsoft.com/en-us/download/details.aspx?id=30679

As mentioned by Stuart McLaughlin, make sure you get the x86 version even if you use a 64-bits OS because PHP needs some 32-bit libraries.

Are nested try/except blocks in Python a good programming practice?

According to the documentation, it is better to handle multiple exceptions through tuples or like this:

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as e:
    print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error: ", sys.exc_info()[0]
    raise

MVVM Passing EventArgs As Command Parameter

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

There are multiple ways of doing this:

1. Using WPF Tools. Easiest.

Add Namespaces:

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

XAML:

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

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

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

Code:

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

2. Using MVVMLight. Most difficult.

Install GalaSoft NuGet package.

enter image description here

Get the namespaces:

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

XAML:

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

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

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

Code Implementing Delegates: Source

You must get the Prism MVVM NuGet package for this.

enter image description here

using Microsoft.Practices.Prism.Commands;

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

public MainWindow()
{
    InitializeComponent();

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

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

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

Code Without DelegateCommand: Source

using GalaSoft.MvvmLight.CommandWpf

public MainWindow()
{
    InitializeComponent();

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

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

public RelayCommand CommandTwo { get; set; }

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

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

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

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

XAML:

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

Code:

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

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

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

Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

For me following worked:

in directive declare it like this:

.directive('myDirective', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            myFunction: '=',
        },
        templateUrl: 'myDirective.html'
    };
})  

In directive template use it in following way:

<select ng-change="myFunction(selectedAmount)">

And then when you use the directive, pass the function like this:

<data-my-directive
    data-my-function="setSelectedAmount">
</data-my-directive>

You pass the function by its declaration and it is called from directive and parameters are populated.

How to detect a remote side socket close?

The method Socket.Available will immediately throw a SocketException if the remote system has disconnected/closed the connection.

When to use Comparable and Comparator

Comparable should be used when you compare instances of the same class.

Comparator can be used to compare instances of different classes.

Comparable is implemented by the class which needs to define a natural ordering for its objects. For example, String implements Comparable.

In case a different sorting order is required, then, implement comparator and define its own way of comparing two instances.

Java: print contents of text file to screen

Before Java 7:

 BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
 String line;
 while ((line = br.readLine()) != null) {
   System.out.println(line);
 }
  • add exception handling
  • add closing the stream

Since Java 7, there is no need to close the stream, because it implements autocloseable

try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
   String line;
   while ((line = br.readLine()) != null) {
       System.out.println(line);
   }
}

Defining static const integer members in class definition

Here's another way to work around the problem:

std::min(9, int(test::N));

(I think Crazy Eddie's answer correctly describes why the problem exists.)

How to change row color in datagridview?

You can Change Backcolor row by row using your condition.and this function call after applying Datasource of DatagridView.

Here Is the function for that. Simply copy that and put it after Databind

private void ChangeRowColor()
{
    for (int i = 0; i < gvItem.Rows.Count; i++)
    {
        if (BindList[i].MainID == 0 && !BindList[i].SchemeID.HasValue)
            gvItem.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#C9CADD");
        else if (BindList[i].MainID > 0 && !BindList[i].SchemeID.HasValue)
            gvItem.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#DDC9C9");
        else if (BindList[i].MainID > 0)
            gvItem.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml("#D5E8D7");
        else
            gvItem.Rows[i].DefaultCellStyle.BackColor = Color.White;
    }
}

How to delete history of last 10 commands in shell?

I used a combination of solutions shared in this thread to erase the trace in commands history. First, I verified where is saved commands history with:

echo $HISTFILE

I edited the history with:

vi <pathToFile>

After that, I flush current session history buffer with:

history -r && exit

Next time you enter to this session, the last command that you will see on command history is the last that you left on pathToFile.

"The operation is not valid for the state of the transaction" error and transaction scope

After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:

public void MyAddUpdateMethod()
{
    using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
    {
        using(SQLServer Sql = new SQLServer(this.m_connstring))
        {
            //do my first add update statement            
        }

        //removed the method call from the first sql server using statement
        bool DoesRecordExist = this.SelectStatementCall(id)
    }
}

public bool SelectStatementCall(System.Guid id)
{
    using(SQLServer Sql = new SQLServer(this.m_connstring))
    {
        //create parameters
    }
}

Ellipsis for overflow text in dropdown boxes

NOTE: As of July 2020, text-overflow: ellipsis works for <select> on Chrome

HTML is limited in what it specifies for form controls. That leaves room for operating system and browser makers to do what they think is appropriate on that platform (like the iPhone’s modal select which, when open, looks totally different from the traditional pop-up menu).

If it bugs you, you can use a customizable replacement, like Chosen, which looks distinct from the native select.

Or, file a bug against a major operating system or browser. For all we know, the way text is cut off in selects might be the result of a years-old oversight that everyone copied, and it might be time for a change.

Print array to a file

just use file_put_contents('file',$myarray); file_put_contents() works with arrays too.

How to change max_allowed_packet size

For those running wamp mysql server

Wamp tray Icon -> MySql -> my.ini

[wampmysqld]
port        = 3306
socket      = /tmp/mysql.sock
key_buffer_size = 16M
max_allowed_packet = 16M        // --> changing this wont solve
sort_buffer_size = 512K

Scroll down to the end until u find

[mysqld]
port=3306
explicit_defaults_for_timestamp = TRUE

Add the line of packet_size in between

[mysqld]
port=3306
max_allowed_packet = 16M
explicit_defaults_for_timestamp = TRUE

Check whether it worked with this query

Select @@global.max_allowed_packet;

Using group by on two fields and count in SQL

SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup

How do you remove a specific revision in the git history?

So here is the scenario that I faced, and how I solved it.

[branch-a]

[Hundreds of commits] -> [R] -> [I]

here R is the commit that I needed to be removed, and I is a single commit that comes after R

I made a revert commit and squashed them together

git revert [commit id of R]
git rebase -i HEAD~3

During the interactive rebase squash the last 2 commits.

Segmentation Fault - C

Even better

#include <stdio.h>
int
main(void)
{
  char *line = NULL;
  size_t count;
  char *dup_line;

  getline(&line,&count, stdin);
  dup_line=strdup(line);

  puts(dup_line);

  free(dup_line);
  free(line);

  return 0;
}

Convert all strings in a list to int

You can do it simply in one line when taking input.

[int(i) for i in input().split("")]

Split it where you want.

If you want to convert a list not list simply put your list name in the place of input().split("").

Set transparent background using ImageMagick and commandline prompt

Solution

color=$( convert filename.png -format "%[pixel:p{0,0}]" info:- )
convert filename.png -alpha off -bordercolor $color -border 1 \
    \( +clone -fuzz 30% -fill none -floodfill +0+0 $color \
       -alpha extract -geometry 200% -blur 0x0.5 \
       -morphology erode square:1 -geometry 50% \) \
    -compose CopyOpacity -composite -shave 1 outputfilename.png

Explanation

This is rather a bit longer than the simple answers previously given, but it gives much better results: (1) The quality is superior due to antialiased alpha, and (2) only the background is removed as opposed to a single color. ("Background" is defined as approximately the same color as the top left pixel, using a floodfill from the picture edges.)

Additionally, the alpha channel is also eroded by half a pixel to avoid halos. Of course, ImageMagick's morphological operations don't (yet?) work at the subpixel level, so you can see I am blowing up the alpha channel to 200% before eroding.

Comparison of results

Here is a comparison of the simple approach ("-fuzz 2% -transparent white") versus my solution, when run on the ImageMagick logo. I've flattened both transparent images onto a saddle brown background to make the differences apparent (click for originals).

The simple replacement of white as transparent doesn't always work Antialiased alphachannel and floodfill looks much better

Notice how the Wizard's beard has disappeared in the simple approach. Compare the edges of the Wizard to see how antialiased alpha helps the figure blend smoothly into the background.

Of course, I completely admit there are times when you may wish to use the simpler solution. (For example: It's a heck of a lot easier to remember and if you're converting to GIF, you're limited to 1-bit alpha anyhow.)

mktrans shell script

Since it's unlikely you'll want to type this command repeatedly, I recommend wrapping it in a script. You can download a BASH shell script from github which performs my suggested solution. It can be run on multiple files in a directory and includes helpful comments in case you want to tweak things.

bg_removal script

By the way, ImageMagick actually comes with a script called "bg_removal" which uses floodfill in a similar manner as my solution. However, the results are not great because it still uses 1-bit alpha. Also, the bg_removal script runs slower and is a little bit trickier to use (it requires you to specify two different fuzz values). Here's an example of the output from bg_removal.

The bg_removal script: has beard, but lacks antialiasing

How to get a cross-origin resource sharing (CORS) post request working

For some reason, a question about GET requests was merged with this one, so I'll respond to it here.

This simple function will asynchronously get an HTTP status reply from a CORS-enabled page. If you run it, you'll see that only a page with the proper headers returns a 200 status if accessed via XMLHttpRequest -- whether GET or POST is used. Nothing can be done on the client side to get around this except possibly using JSONP if you just need a json object.

The following can be easily modified to get the data held in the xmlHttpRequestObject object:

_x000D_
_x000D_
function checkCorsSource(source) {_x000D_
  var xmlHttpRequestObject;_x000D_
  if (window.XMLHttpRequest) {_x000D_
    xmlHttpRequestObject = new XMLHttpRequest();_x000D_
    if (xmlHttpRequestObject != null) {_x000D_
      var sUrl = "";_x000D_
      if (source == "google") {_x000D_
        var sUrl = "https://www.google.com";_x000D_
      } else {_x000D_
        var sUrl = "https://httpbin.org/get";_x000D_
      }_x000D_
      document.getElementById("txt1").innerHTML = "Request Sent...";_x000D_
      xmlHttpRequestObject.open("GET", sUrl, true);_x000D_
      xmlHttpRequestObject.onreadystatechange = function() {_x000D_
        if (xmlHttpRequestObject.readyState == 4 && xmlHttpRequestObject.status == 200) {_x000D_
          document.getElementById("txt1").innerHTML = "200 Response received!";_x000D_
        } else {_x000D_
          document.getElementById("txt1").innerHTML = "200 Response failed!";_x000D_
        }_x000D_
      }_x000D_
      xmlHttpRequestObject.send();_x000D_
    } else {_x000D_
      window.alert("Error creating XmlHttpRequest object. Client is not CORS enabled");_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
  <title>Check if page is cors</title>_x000D_
</head>_x000D_
<body>_x000D_
  <p>A CORS-enabled source has one of the following HTTP headers:</p>_x000D_
  <ul>_x000D_
    <li>Access-Control-Allow-Headers: *</li>_x000D_
    <li>Access-Control-Allow-Headers: x-requested-with</li>_x000D_
  </ul>_x000D_
  <p>Click a button to see if the page allows CORS</p>_x000D_
  <form name="form1" action="" method="get">_x000D_
    <input type="button" name="btn1" value="Check Google Page" onClick="checkCorsSource('google')">_x000D_
    <input type="button" name="btn1" value="Check Cors Page" onClick="checkCorsSource('cors')">_x000D_
  </form>_x000D_
  <p id="txt1" />_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to get file creation & modification date/times in Python?

os.stat does include the creation time. There's just no definition of st_anything for the element of os.stat() that contains the time.

So try this:

os.stat('feedparser.py')[8]

Compare that with your create date on the file in ls -lah

They should be the same.

calculating number of days between 2 columns of dates in data frame

In Ronald's example, if the date formats are different (as displayed below) then modify the format parameter

survey <- data.frame(date=c("2012-07-26","2012-07-25"),tx_start=c("2012-01-01","2012-01-01"))

survey$date_diff <- as.Date(as.character(survey$date), format="%Y-%m-%d")-
              as.Date(as.character(survey$tx_start), format="%Y-%m-%d")

survey:

   date      tx_start     date_diff
1 2012-07-26     2012-01-01    207 days
2 2012-07-25     2012-01-01    206 days

Where is the itoa function in Linux?

I have used _itoa(...) on RedHat 6 and GCC compiler. It works.

Git fatal: protocol 'https' is not supported

I had the same problem, all I did was to restart the command line and then navigate to the document folder rather than the user folder using the command '' cd documents '' . That should be all thats needed. Also ensure that the link is correct.

Regex: match word that ends with "Id"

Gumbo gets my vote, however, the OP doesn't specify whether just "Id" is an allowable word, which means I'd make a minor modification:

\w+Id\b

1 or more word characters followed by "Id" and a breaking space. The [a-zA-Z] variants don't take into account non-English alphabetic characters. I might also use \s instead of \b as a space rather than a breaking space. It would depend if you need to wrap over multiple lines.

Android REST client, Sample?

There is plenty of libraries out there and I'm using this one: https://github.com/nerde/rest-resource. This was created by me, and, as you can see in the documentation, it's way cleaner and simpler than the other ones. It's not focused on Android, but I'm using in it and it's working pretty well.

It supports HTTP Basic Auth. It does the dirty job of serializing and deserializing JSON objects. You will like it, specially if your API is Rails like.