Programs & Examples On #Login automation

How do you cast a List of supertypes to a List of subtypes?

I think you are casting in the wrong direction though... if the method returns a list of TestA objects, then it really isn't safe to cast them to TestB.

Basically you are asking the compiler to let you perform TestB operations on a type TestA that does not support them.

SSL peer shut down incorrectly in Java

I had a similar issue that was resolved by unchecking the option in java advanced security for "Use SSL 2.0 compatible ClientHello format.

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

Short answer: classmaps are static while PSR autoloading is dynamic.

If you don't want to use classmaps, use PSR autoloading instead.

Image resizing client-side with JavaScript before upload to the server

If you were resizing before uploading I just found out this http://www.plupload.com/

It does all the magic for you in any imaginable method.

Unfortunately HTML5 resize only is supported with Mozilla browser, but you can redirect other browsers to Flash and Silverlight.

I just tried it and it worked with my android!

I was using http://swfupload.org/ in flash, it does the job very well, but the resize size is very small. (cannot remember the limit) and does not go back to html4 when flash is not available.

@Value annotation type casting to Integer from String

Since using the @Value("new Long("myconfig")") with cast could throw error on startup if the config is not found or if not in the same expected number format

We used the following approach and is working as expected with fail safe check.

@Configuration()
public class MyConfiguration {

   Long DEFAULT_MAX_IDLE_TIMEOUT = 5l;

   @Value("db.timeoutInString")
   private String timeout;

   public Long getTimout() {
        final Long timoutVal = StringUtil.parseLong(timeout);
        if (null == timoutVal) {
            return DEFAULT_MAX_IDLE_TIMEOUT;
        }
        return timoutVal;
    }
}
   

What is the correct way to start a mongod service on linux / OS X?

After installing mongodb through brew, run this to get it up and running:

mongod --dbpath /usr/local/var/mongodb

What is the use of DesiredCapabilities in Selenium WebDriver?

DesiredCapabilities are options that you can use to customize and configure a browser session.

You can read more about them here!

How to use Scanner to accept only valid int as input

What you could do is also to take the next token as a String, converts this string to a char array and test that each character in the array is a digit.

I think that's correct, if you don't want to deal with the exceptions.

checking if a number is divisible by 6 PHP

I see some of the other answers calling the modulo twice.

My preference is not to ask php to do the same thing more than once. For this reason, I cache the remainder.

Other devs may prefer to not generate the extra global variable or have other justifications for using modulo operator twice.

Code: (Demo)

$factor = 6;
for($x = 0; $x < 10; ++$x){  // battery of 10 tests
    $number = rand( 0 , 100 );
    echo "Number: $number Becomes: ";
    if( $remainder = $number % $factor ) {  // if not zero
        $number += $factor - $remainder;  // use cached $remainder instead of calculating again
    }
    echo "$number\n";
}

Possible Output:

Number: 80 Becomes: 84
Number: 57 Becomes: 60
Number: 94 Becomes: 96
Number: 48 Becomes: 48
Number: 80 Becomes: 84
Number: 36 Becomes: 36
Number: 17 Becomes: 18
Number: 41 Becomes: 42
Number: 3 Becomes: 6
Number: 64 Becomes: 66

PHP ternary operator vs null coalescing operator

If you use the shortcut ternary operator like this, it will cause a notice if $_GET['username'] is not set:

$val = $_GET['username'] ?: 'default';

So instead you have to do something like this:

$val = isset($_GET['username']) ? $_GET['username'] : 'default';

The null coalescing operator is equivalent to the above statement, and will return 'default' if $_GET['username'] is not set or is null:

$val = $_GET['username'] ?? 'default';

Note that it does not check truthiness. It checks only if it is set and not null.

You can also do this, and the first defined (set and not null) value will be returned:

$val = $input1 ?? $input2 ?? $input3 ?? 'default';

Now that is a proper coalescing operator.

Convert String to Integer in XSLT 1.0

Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.

Example

<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->

ElasticSearch: Unassigned Shards, how to fix?

I also encountered similar error. It happened to me because one of my data node was full and due to which shards allocation failed. If unassigned shards are there and your cluster is RED and few indices also RED, in that case I have followed below steps and these worked like a champ.
in kibana dev tool-

GET _cluster/allocation/explain

If any unassigned shards are there then you will get details else will throw ERROR.

simply running below command will solve everything-

POST _cluster/reroute?retry_failed

Thanks to -
https://github.com/elastic/elasticsearch/issues/23199#issuecomment-280272888

What is the correct syntax for 'else if'?

def function(a):
    if a == '1':
        print ('1a')
    elif a == '2':
        print ('2a')
    else:
        print ('3a')

Node.js Port 3000 already in use but it actually isn't?

In ubuntu first grab the process by using port number: sudo lsof -i:3000 then use kill command to kill the process, for example if the process PID is 4493 the use command: kill 4493 , for mac or windows find the related command

enter image description here

Sending simple message body + file attachment using Linux Mailx

Try this it works for me:

(echo "Hello XYX" ; uuencode /export/home/TOTAL_SI_COUNT_10042016.csv TOTAL_SI_COUNT_10042016.csv ) | mailx -s 'Script test' [email protected]

How to add Options Menu to Fragment in Android

If you want to add your menu custom

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_custom, menu);
}

Safely remove migration In Laravel

 php artisan migrate:fresh

Should do the job, if you are in development and the desired outcome is to start all over.

In production, that maybe not the desired thing, so you should be adverted. (The migrate:fresh command will drop all tables from the database and then execute the migrate command).

Split an NSString to access one particular piece

Its working fine

NSString *dateString = @"10/10/2010";//Date 
NSArray* dateArray = [dateString componentsSeparatedByString: @"/"];
NSString* dayString = [dateArray objectAtIndex: 0];

Check if instance is of a type

Also, somewhat in the same vein

Type.IsAssignableFrom(Type c)

"True if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c."

From here: http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx

Selecting the first "n" items with jQuery

.slice() isn't always better. In my case, with jQuery 1.7 in Chrome 36, .slice(0, 20) failed with error:

RangeError: Maximum call stack size exceeded

I found that :lt(20) worked without error in this case. I had probably tens of thousands of matching elements.

SSRS custom number format

am assuming that you want to know how to format numbers in SSRS

Just right click the TextBox on which you want to apply formatting, go to its expression.

suppose its expression is something like below

=Fields!myField.Value

then do this

=Format(Fields!myField.Value,"##.##") 

or

=Format(Fields!myFields.Value,"00.00")

difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00

this should give you an idea.

also: you might have to convert your field into a numerical one. i.e.

  =Format(CDbl(Fields!myFields.Value),"00.00")

so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present ie. 45.6567 would be 45.65 for both of them:

UPDATE :

if you want to apply variable formatting on the same column based on row values i.e. you want myField to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)

Go to the appropriate textbox and go to its expression and do this:

=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0, 
    Format(Fields!myField.Value, "##.##"),Fields!myField.Value)

so basically you are using IIF(condition, true,false) operator of SSRS, ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.

this should give you an idea, how to handle variable formatting.

Get LatLng from Zip Code - Google Maps API

Here is the most reliable way to get the lat/long from zip code (i.e. postal code):

https://maps.googleapis.com/maps/api/geocode/json?key=YOUR_API_KEY&components=postal_code:97403

How to pass parameter to a promise function

Even shorter

var foo = (user, pass) =>
  new Promise((resolve, reject) => {
    if (/* condition */) {
      resolve("Fine");
    } else {
      reject("Error message");
    }
  });

foo(user, pass).then(result => {
  /* process */
});

Closure in Java 7

Please see this wiki page for definition of closure.

And this page for closure in Java 8: http://mail.openjdk.java.net/pipermail/lambda-dev/2011-September/003936.html

Also look at this Q&A: Closures in Java 7

What does -> mean in C++?

x->y can mean 2 things. If x is a pointer, then it means member y of object pointed to by x. If x is an object with operator->() overloaded, then it means x.operator->().

filedialog, tkinter and opening files

I had to specify individual commands first and then use the * to bring all in command.

from tkinter import filedialog
from tkinter import *

Using only CSS, show div on hover over <a>

I would like to offer this general purpose template solution that expands on the correct solution provided by Yi Jiang's.

The additional benefits include:

  • support for hovering over any element type, or multiple elements;
  • the popup can be any element type or set of elements, including objects;
  • self-documenting code;
  • ensures the pop-up appears over the other elements;
  • a sound basis to follow if you are generating html code from a database.

In the html you place the following structure:

<div class="information_popup_container">
<div class="information">
<!-- The thing or things you want to hover over go here such as images, tables, 
     paragraphs, objects other divisions etc. --> 
</div>
<div class="popup_information">
<!-- The thing or things you want to popup go here such as images, tables, 
     paragraphs, objects other divisions etc. --> 
</div>
</div>

In the css you place the following structure:

div.information_popup_container {
position: absolute;
width:0px;
height:0px;
/* Position Information */
/* Appearance Information */
}
div.information_popup_container > div.information {
/* Position Information */
/* Appearance Information */
}
div.information_popup_container > div.popup_information {
position: fixed;
visibility: hidden;
/* Position Information */
/* Appearance Information */
}
div.information_popup_container > div.information:hover + div.popup_information {
visibility: visible;
z-index: 200;
}

A few points to note are:

  1. Because the position of the div.popup is set to fixed (would also work with absolute) the content is not inside the normal flow of the document which allows the visible attribute to work well.
  2. z-index is set to ensure that the div.popup appears above the other page elements.
  3. The information_popup_container is set to a small size and thus cannot be hovered over.
  4. This code only supports hovering over the div.information element. To support hovering over both the div.information and div.popup then see Hover Over The Popup below.
  5. It has been tested and works as expected in Opera 12.16 Internet Explorer 10.0.9200, Firefox 18.0 and Google Chrome 28.0.15.

Hover Over The Popup

As additional information. When the popup contains information that you might want to cut and paste or contains an object that you might want to interact with then first replace:

div.information_popup_container > div.information:hover + div.popup_information {
visibility: visible;
z-index: 200;
}

with

div.information_popup_container > div.information:hover + div.popup_information 
,div.information_popup_container > div.popup_information:hover {
visibility: visible;
z-index: 200;
}

And second, adjust the position of div.popup so that there is an overlap with div.information. A few pixels is sufficient to ensure that the div.popup is can receive the hover when moving the cusor off div.information.

This does not work as expected with Internet Explorer 10.0.9200 and does work as expected with Opera 12.16, Firefox 18.0 and Google Chrome 28.0.15.

See fiddle http://jsfiddle.net/F68Le/ for a complete example with a popup multilevel menu.

How to dismiss a Twitter Bootstrap popover by clicking outside?

This is late to the party... but I thought I'd share it. I love the popover but it has so little built-in functionality. I wrote a bootstrap extension .bubble() that is everything I'd like popover to be. Four ways to dismiss. Click outside, toggle on the link, click the X, and hit escape.

It positions automatically so it never goes off the page.

https://github.com/Itumac/bootstrap-bubble

This is not a gratuitous self promo...I've grabbed other people's code so many times in my life, I wanted to offer my own efforts. Give it a whirl and see if it works for you.

How to list all the files in android phone by using adb shell?

Open cmd type adb shell then press enter. Type ls to view files list.

Image comparison - fast algorithm

Below are three approaches to solving this problem (and there are many others).

  • The first is a standard approach in computer vision, keypoint matching. This may require some background knowledge to implement, and can be slow.

  • The second method uses only elementary image processing, and is potentially faster than the first approach, and is straightforward to implement. However, what it gains in understandability, it lacks in robustness -- matching fails on scaled, rotated, or discolored images.

  • The third method is both fast and robust, but is potentially the hardest to implement.

Keypoint Matching

Better than picking 100 random points is picking 100 important points. Certain parts of an image have more information than others (particularly at edges and corners), and these are the ones you'll want to use for smart image matching. Google "keypoint extraction" and "keypoint matching" and you'll find quite a few academic papers on the subject. These days, SIFT keypoints are arguably the most popular, since they can match images under different scales, rotations, and lighting. Some SIFT implementations can be found here.

One downside to keypoint matching is the running time of a naive implementation: O(n^2m), where n is the number of keypoints in each image, and m is the number of images in the database. Some clever algorithms might find the closest match faster, like quadtrees or binary space partitioning.


Alternative solution: Histogram method

Another less robust but potentially faster solution is to build feature histograms for each image, and choose the image with the histogram closest to the input image's histogram. I implemented this as an undergrad, and we used 3 color histograms (red, green, and blue), and two texture histograms, direction and scale. I'll give the details below, but I should note that this only worked well for matching images VERY similar to the database images. Re-scaled, rotated, or discolored images can fail with this method, but small changes like cropping won't break the algorithm

Computing the color histograms is straightforward -- just pick the range for your histogram buckets, and for each range, tally the number of pixels with a color in that range. For example, consider the "green" histogram, and suppose we choose 4 buckets for our histogram: 0-63, 64-127, 128-191, and 192-255. Then for each pixel, we look at the green value, and add a tally to the appropriate bucket. When we're done tallying, we divide each bucket total by the number of pixels in the entire image to get a normalized histogram for the green channel.

For the texture direction histogram, we started by performing edge detection on the image. Each edge point has a normal vector pointing in the direction perpendicular to the edge. We quantized the normal vector's angle into one of 6 buckets between 0 and PI (since edges have 180-degree symmetry, we converted angles between -PI and 0 to be between 0 and PI). After tallying up the number of edge points in each direction, we have an un-normalized histogram representing texture direction, which we normalized by dividing each bucket by the total number of edge points in the image.

To compute the texture scale histogram, for each edge point, we measured the distance to the next-closest edge point with the same direction. For example, if edge point A has a direction of 45 degrees, the algorithm walks in that direction until it finds another edge point with a direction of 45 degrees (or within a reasonable deviation). After computing this distance for each edge point, we dump those values into a histogram and normalize it by dividing by the total number of edge points.

Now you have 5 histograms for each image. To compare two images, you take the absolute value of the difference between each histogram bucket, and then sum these values. For example, to compare images A and B, we would compute

|A.green_histogram.bucket_1 - B.green_histogram.bucket_1| 

for each bucket in the green histogram, and repeat for the other histograms, and then sum up all the results. The smaller the result, the better the match. Repeat for all images in the database, and the match with the smallest result wins. You'd probably want to have a threshold, above which the algorithm concludes that no match was found.


Third Choice - Keypoints + Decision Trees

A third approach that is probably much faster than the other two is using semantic texton forests (PDF). This involves extracting simple keypoints and using a collection decision trees to classify the image. This is faster than simple SIFT keypoint matching, because it avoids the costly matching process, and keypoints are much simpler than SIFT, so keypoint extraction is much faster. However, it preserves the SIFT method's invariance to rotation, scale, and lighting, an important feature that the histogram method lacked.

Update:

My mistake -- the Semantic Texton Forests paper isn't specifically about image matching, but rather region labeling. The original paper that does matching is this one: Keypoint Recognition using Randomized Trees. Also, the papers below continue to develop the ideas and represent the state of the art (c. 2010):

Counting Line Numbers in Eclipse

Under linux, the simpler is:

  1. go to the root folder of your project
  2. use find to do a recursive search of *.java files
  3. use wc -l to count lines:

To resume, just do:

find . -name '*.java' | xargs wc -l    

how to display a div triggered by onclick event

function showstuff(boxid){
   document.getElementById(boxid).style.visibility="visible";
}
<button onclick="showstuff('id_to_show');" />

This will help you, I think.

Adding rows dynamically with jQuery

As an addition to answers above: you probably might need to change ids in names/ids of input elements (pls note, you should not have digits in fields name):

<input name="someStuff.entry[2].fieldOne" id="someStuff_fdf_fieldOne_2" ..>

I have done this having some global variable by default set to 0:

var globalNewIndex = 0;

and in the add function after you've cloned and resetted the values in the new row:

                var newIndex = globalNewIndex+1;
                var changeIds = function(i, val) {
                    return val.replace(globalNewIndex,newIndex);
                }
                $('#mytable tbody>tr:last input').attr('name', changeIds ).attr('id', changeIds );
                globalNewIndex++;

How to get post slug from post in WordPress?

I came across this method and I use it to make div IDs the slug name inside the loop:

<?php $slug = basename( get_permalink() ); echo $slug;?>

how much memory can be accessed by a 32 bit machine?

No your concepts are not right. And to set it right you need the answer to the question that you incorrectly answered:

What is meant by 32bit or 64 bit machine?

The answer to the question is "something significant in the CPU is 32bit or 64 bit". So the question is what is that something significant? Lot of people say the width of data bus that determine whether the machine is 32bit or 64 bit. But none of the latest 32 bit processors have 32 bit or 64 bit wide data buses. most 32 bit systems will have 36 bit at least to support more RAM. Most 64 bit processors have no more than 48bit wide data bus because that is hell lot of memory already.

So according to me a 32 bit or 64 bit machine is determined by the size of its general purpose registers used in computation or "the natural word size" used by the computer.

Note that a 32 bit OS is a different thing. You can have a 32 bit OS running on 64 bit computer. Additionally, you can have 32 bit application running on 64 bit OS. If you do not understand the difference, post another question.

So the maximum amount of RAM a processor can address is 2^(width of data bus in bits), given that the proper addressing mode is switched on in the processor.

Further note, there is nothing stopping someone to introduce a multiplex between data Bus and memory banks, that will select a bank and then address the RAM (in two steps). This way you can address even more RAM. But that is impractical, and highly inefficient.

Generic Interface

If I understand correctly, you want to have one class implement multiple of those interfaces with different input/output parameters? This will not work in Java, because the generics are implemented via erasure.

The problem with the Java generics is that the generics are in fact nothing but compiler magic. At runtime, the classes do not keep any information about the types used for generic stuff (class type parameters, method type parameters, interface type parameters). Therefore, even though you could have overloads of specific methods, you cannot bind those to multiple interface implementations which differ in their generic type parameters only.

In general, I can see why you think that this code has a smell. However, in order to provide you with a better solution, it would be necessary to know a little more about your requirements. Why do you want to use a generic interface in the first place?

spring PropertyPlaceholderConfigurer and context:property-placeholder

Following worked for me:
<context:property-placeholder location="file:src/resources/spring/AppController.properties"/>

Somehow "classpath:xxx" is not picking the file.

Installing PHP Zip Extension

The PHP5 version do not support in Ubuntu 18.04+ versions, so you have to do that configure manually from the source files. If you are using php-5.3.29,

# cd /usr/local/src/php-5.3.29
# ./configure --with-apxs2=/usr/local/apache/bin/apxs --with-mysql=MySQL_LOCATION/mysql --prefix=/usr/local/apache/php --with-config-file-path=/usr/local/apache/php --disable-cgi --with-zlib --with-gettext --with-gdbm --with-curl --enable-zip --with-xml --with-json --enable-shmop
# make
# make install

Restart the Apache server and check phpinfo function on the browser <?php echo phpinfo(); ?>

Note: Please change the MySQL_Location: --with-mysql=MySQL_LOCATION/mysql

How can I solve the error 'TS2532: Object is possibly 'undefined'?

Edit / Update:

If you are using Typescript 3.7 or newer you can now also do:

    const data = change?.after?.data();

    if(!data) {
      console.error('No data here!');
       return null
    }

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }

Original Response

Typescript is saying that change or data is possibly undefined (depending on what onUpdate returns).

So you should wrap it in a null/undefined check:

if(change && change.after && change.after.data){
    const data = change.after.data();

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }
}

If you are 100% sure that your object is always defined then you can put this:

const data = change.after!.data();

Accessing nested JavaScript objects and arrays by string path

While reduce is good, I am surprised no one used forEach:

function valueForKeyPath(obj, path){
        const keys = path.split('.');
        keys.forEach((key)=> obj = obj[key]);
        return obj;
    };

Test

Display Last Saved Date on worksheet

This might be an alternative solution. Paste the following code into the new module:

Public Function ModDate()
ModDate = 
Format(FileDateTime(ThisWorkbook.FullName), "m/d/yy h:n ampm") 
End Function

Before saving your module, make sure to save your Excel file as Excel Macro-Enabled Workbook.

Paste the following code into the cell where you want to display the last modification time:

=ModDate()

I'd also like to recommend an alternative to Excel allowing you to add creation and last modification time easily. Feel free to check on RowShare and this article I wrote: https://www.rowshare.com/blog/en/2018/01/10/Displaying-Last-Modification-Time-in-Excel

Fastest way to copy a file in Node.js

Same mechanism, but this adds error handling:

function copyFile(source, target, cb) {
  var cbCalled = false;

  var rd = fs.createReadStream(source);
  rd.on("error", function(err) {
    done(err);
  });
  var wr = fs.createWriteStream(target);
  wr.on("error", function(err) {
    done(err);
  });
  wr.on("close", function(ex) {
    done();
  });
  rd.pipe(wr);

  function done(err) {
    if (!cbCalled) {
      cb(err);
      cbCalled = true;
    }
  }
}

@class vs. #import

Another advantage: Quick compilation

If you include a header file, any change in it causes the current file also to compile but this is not the case if the class name is included as @class name. Of course you will need to include the header in source file

Proper way to declare custom exceptions in modern Python?

You should override __repr__ or __unicode__ methods instead of using message, the args you provide when you construct the exception will be in the args attribute of the exception object.

Is Ruby pass by reference or by value?

Try this:--

1.object_id
#=> 3

2.object_id
#=> 5

a = 1
#=> 1
a.object_id
#=> 3

b = 2
#=> 2
b.object_id
#=> 5

identifier a contains object_id 3 for value object 1 and identifier b contains object_id 5 for value object 2.

Now do this:--

a.object_id = 5
#=> error

a = b
#value(object_id) at b copies itself as value(object_id) at a. value object 2 has object_id 5
#=> 2

a.object_id 
#=> 5

Now, a and b both contain same object_id 5 which refers to value object 2. So, Ruby variable contains object_ids to refer to value objects.

Doing following also gives error:--

c
#=> error

but doing this won't give error:--

5.object_id
#=> 11

c = 5
#=> value object 5 provides return type for variable c and saves 5.object_id i.e. 11 at c
#=> 5
c.object_id
#=> 11 

a = c.object_id
#=> object_id of c as a value object changes value at a
#=> 11
11.object_id
#=> 23
a.object_id == 11.object_id
#=> true

a
#=> Value at a
#=> 11

Here identifier a returns value object 11 whose object id is 23 i.e. object_id 23 is at identifier a, Now we see an example by using method.

def foo(arg)
  p arg
  p arg.object_id
end
#=> nil
11.object_id
#=> 23
x = 11
#=> 11
x.object_id
#=> 23
foo(x)
#=> 11
#=> 23

arg in foo is assigned with return value of x. It clearly shows that argument is passed by value 11, and value 11 being itself an object has unique object id 23.

Now see this also:--

def foo(arg)
  p arg
  p arg.object_id
  arg = 12
  p arg
  p arg.object_id
end

#=> nil
11.object_id
#=> 23
x = 11
#=> 11
x.object_id
#=> 23
foo(x)
#=> 11
#=> 23
#=> 12
#=> 25
x
#=> 11
x.object_id
#=> 23

Here, identifier arg first contains object_id 23 to refer 11 and after internal assignment with value object 12, it contains object_id 25. But it does not change value referenced by identifier x used in calling method.

Hence, Ruby is pass by value and Ruby variables do not contain values but do contain reference to value object.

How much data can a List can hold at the maximum?

Numbering an items in the java array should start from zero. This was i think we can have access to Integer.MAX_VALUE+1 an items.

How to count certain elements in array?

        @{
            /**/

            var x = from z in Model.ListOfFaculty
                    select z;
        }



        @foreach (var c in x)
        {
            <div class="row">
                <div class="col-lg-3">
                    <label>FacultyName :@c.Name </label>
                </div>
                <div class="col-lg-3">
                    <label>
                        Count :@{
                            var b = from v in Model.ListOfDepartment
                                    where (v.Faculty_id == c.ID)
                                    select v;


                        }
                        @b.Count()
                    </label>
                </div>
            </div>



        }

    </div>

Electron: jQuery is not defined

Just came across this same problem

npm install jquery --save

<script>window.$ = window.jQuery = require('jquery');</script>

worked for me

PHP add elements to multidimensional array with array_push

I know the topic is old, but I just fell on it after a google search so... here is another solution:

$array_merged = array_merge($array_going_first, $array_going_second);

This one seems pretty clean to me, it works just fine!

How to enable ASP classic in IIS7.5

If you get the above problem on windows server 2008 you may need to enable ASP. To do so, follow these steps:

Add an 'Application Server' role:

  1. Click Start, point to Control Panel, click Programs, and then click Turn Windows features on or off.
  2. Right-click Server Manager, select Add Roles.
  3. On the Add Roles Wizard page, select Application Server, click Next three times, and then click Install. Windows Server installs the new role.

Then, add a 'Web Server' role:

  1. Web Server Role (IIS): in ServerManager, Roles, if the Web Server (IIS) role does not exist then add it.
  2. Under Web Server (IIS) role add role services for: ApplicationDevelopment:ASP, ApplicationDevelopment:ISAPI Exstensions, Security:Request Filtering.

More info: http://www.iis.net/learn/application-frameworks/running-classic-asp-applications-on-iis-7-and-iis-8/classic-asp-not-installed-by-default-on-iis

Default visibility for C# classes and members (fields, methods, etc.)?

From MSDN:

Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.


Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.

Default Nested Member Accessibility & Allowed Accessibility Modifiers

Source: Accessibility Levels (C# Reference) (December 6th, 2017)

Why are static variables considered evil?

I have just summarized some of the points made in the answers. If you find anything wrong please feel free to correct it.

Scaling: We have exactly one instance of a static variable per JVM. Suppose we are developing a library management system and we decided to put the name of book a static variable as there is only one per book. But if system grows and we are using multiple JVMs then we dont have a way to figure out which book we are dealing with?

Thread-Safety: Both instance variable and static variable need to be controlled when used in multi threaded environment. But in case of an instance variable it does not need protection unless it is explicitly shared between threads but in case of a static variable it is always shared by all the threads in the process.

Testing: Though testable design does not equal to good design but we will rarely observe a good design that is not testable. As static variables represent global state and it gets very difficult to test them.

Reasoning about state: If I create a new instance of a class then we can reason about the state of this instance but if it is having static variables then it could be in any state. Why? Because it is possible that the static variable has been modified by some different instance as static variable is shared across instances.

Serialization: Serialization also does not work well with them.

Creation and destruction: Creation and destruction of static variables can not be controlled. Usually they are created and destroyed at program loading and unloading time. It means they are bad for memory management and also add up the initialization time at start up.

But what if we really need them?

But sometimes we may have a genuine need of them. If we really feel the need of many static variables that are shared across the application then one option is to make use of Singleton Design pattern which will have all these variables. Or we can create some object which will have these static variable and can be passed around.

Also if the static variable is marked final it becomes a constant and value assigned to it once cannot be changed. It means it will save us from all the problems we face due to its mutability.

Get Memory Usage in Android

I use this function to calculate cpu usage. Hope it can help you.

private float readUsage() {
    try {
        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        String load = reader.readLine();

        String[] toks = load.split(" +");  // Split on one or more spaces

        long idle1 = Long.parseLong(toks[4]);
        long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
              + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        try {
            Thread.sleep(360);
        } catch (Exception e) {}

        reader.seek(0);
        load = reader.readLine();
        reader.close();

        toks = load.split(" +");

        long idle2 = Long.parseLong(toks[4]);
        long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5])
            + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

        return (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return 0;
} 

Manually Set Value for FormBuilder Control

If you are using form control then the simplest way to do this:

this.FormName.get('ControlName').setValue(value);

Convert array values from string to int?

Not sure if this is faster but flipping an array twice will cast numeric strings to integers:

$string = "1,2,3,bla";
$ids = array_flip(array_flip(explode(',', $string)));
var_dump($ids);

Important: Do not use this if you are dealing with duplicate values!

How to write a file or data to an S3 object using boto3

A cleaner and concise version which I use to upload files on the fly to a given S3 bucket and sub-folder-

import boto3

BUCKET_NAME = 'sample_bucket_name'
PREFIX = 'sub-folder/'

s3 = boto3.resource('s3')

# Creating an empty file called "_DONE" and putting it in the S3 bucket
s3.Object(BUCKET_NAME, PREFIX + '_DONE').put(Body="")

Note: You should ALWAYS put your AWS credentials (aws_access_key_id and aws_secret_access_key) in a separate file, for example- ~/.aws/credentials

Slide a layout up from bottom of screen

You were close. The key is to have the hidden layout inflate to match_parent in both height and weight. Simply start it off as View.GONE. This way, using the percentage in the animators works properly.

Layout (activity_main.xml):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_screen"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="@string/hello_world" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/hello_world" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:onClick="slideUpDown"
        android:text="Slide up / down" />

    <RelativeLayout
        android:id="@+id/hidden_panel"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        android:visibility="gone" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name"
            android:layout_centerInParent="true"
            android:onClick="slideUpDown" />
    </RelativeLayout>

</RelativeLayout>

Activity (MainActivity.java):

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

public class OffscreenActivity extends Activity {
    private View hiddenPanel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        hiddenPanel = findViewById(R.id.hidden_panel);
    }

    public void slideUpDown(final View view) {
        if (!isPanelShown()) {
            // Show the panel
            Animation bottomUp = AnimationUtils.loadAnimation(this,
                    R.anim.bottom_up);

            hiddenPanel.startAnimation(bottomUp);
            hiddenPanel.setVisibility(View.VISIBLE);
        }
        else {
            // Hide the Panel
            Animation bottomDown = AnimationUtils.loadAnimation(this,
                    R.anim.bottom_down);

            hiddenPanel.startAnimation(bottomDown);
            hiddenPanel.setVisibility(View.GONE);
        }
    }

    private boolean isPanelShown() {
        return hiddenPanel.getVisibility() == View.VISIBLE;
    }

}

Only other thing I changed was in bottom_up.xml. Instead of

android:fromYDelta="75%p"

I used:

android:fromYDelta="100%p"

But that's a matter of preference, I suppose.

in angularjs how to access the element that triggered the event?

you can get easily like this first write event on element

ng-focus="myfunction(this)"

and in your js file like below

$scope.myfunction= function (msg, $event) {
    var el = event.target
    console.log(el);
}

I have used it as well.

What is Dispatcher Servlet in Spring?

You can say Dispatcher Servlet acts as an entry and exit point for any request. Whenever a request comes it first goes to the Dispatcher Servlet(DS) where the DS then tries to identify its handler method ( the methods you define in the controller to handle the requests ), once the handler mapper (The DS asks the handler mapper) returns the controller the dispatcher servlet knows the controller which can handle this request and can now go to this controller to further complete the processing of the request. Now the controller can respond with an appropriate response and then the DS goes to the view resolver to identify where the view is located and once the view resolver tells the DS it then grabs that view and returns it back to you as the final response. I am adding an image which I took from YouTube from the channel Java Guides.

Dispatcher Servlet in Action

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

I got exactely the same error when I have stopped mysql service, and here how to solve it: by (re)starting mysql using these commands:

sudo systemctl start mysql

or

sudo systemctl restart mysql

Call a function after previous function is complete

Specify an anonymous callback, and make function1 accept it:

$('a.button').click(function(){
    if (condition == 'true'){
        function1(someVariable, function() {
          function2(someOtherVariable);
        });
    }
    else {
        doThis(someVariable);
    }
});


function function1(param, callback) {
  ...do stuff
  callback();
} 

mongodb group values by multiple fields

Using aggregate function like below :

[
{$group: {_id : {book : '$book',address:'$addr'}, total:{$sum :1}}},
{$project : {book : '$_id.book', address : '$_id.address', total : '$total', _id : 0}}
]

it will give you result like following :

        {
            "total" : 1,
            "book" : "book33",
            "address" : "address90"
        }, 
        {
            "total" : 1,
            "book" : "book5",
            "address" : "address1"
        }, 
        {
            "total" : 1,
            "book" : "book99",
            "address" : "address9"
        }, 
        {
            "total" : 1,
            "book" : "book1",
            "address" : "address5"
        }, 
        {
            "total" : 1,
            "book" : "book5",
            "address" : "address2"
        }, 
        {
            "total" : 1,
            "book" : "book3",
            "address" : "address4"
        }, 
        {
            "total" : 1,
            "book" : "book11",
            "address" : "address77"
        }, 
        {
            "total" : 1,
            "book" : "book9",
            "address" : "address3"
        }, 
        {
            "total" : 1,
            "book" : "book1",
            "address" : "address15"
        }, 
        {
            "total" : 2,
            "book" : "book1",
            "address" : "address2"
        }, 
        {
            "total" : 3,
            "book" : "book1",
            "address" : "address1"
        }

I didn't quite get your expected result format, so feel free to modify this to one you need.

JQuery - File attributes

To get the filenames, use:

var files = document.getElementById('inputElementID').files;

Using jQuery (since you already are) you can adapt this to the following:

$('input[type="file"][multiple]').change(
    function(e){
        var files = this.files;
        for (i=0;i<files.length;i++){
            console.log(files[i].fileName + ' (' + files[i].fileSize + ').');
        }
        return false;
    });

JS Fiddle demo.

How can I format date by locale in Java?

I agree with Laura and the SimpleDateFormat which is the best way to manage Dates in java. You can set the pattern and the locale. Plus you can have a look at this wikipedia article about Date in the world -there are not so many different ways to use it; typically USA / China / rest of the world -

How to access the local Django webserver from outside world

install ngrok in terminal

sudo apt-get install -y ngrok-client

after that run:

ngrok http 8000
or 
ngrok http example.com:9000 

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

I found that, if you are using a storyboard, you will want to put the code that is presenting the new view controller in viewDidAppear. It will also get rid of the "Presenting view controllers on detached view controllers is discouraged" warning.

MySQL error - #1062 - Duplicate entry ' ' for key 2

  1. Drop the primary key first: (The primary key is your responsibility)

    ALTER TABLE Persons DROP PRIMARY KEY ;
    
  2. Then make all insertions:

  3. Add new primary key just like before dropping:

    ALTER TABLE Persons ADD PRIMARY KEY (P_Id);
    

Linux find and grep command together

You are looking for -H option in gnu grep.

find . -name '*bills*' -exec grep -H "put" {} \;

Here is the explanation

    -H, --with-filename
      Print the filename for each match.

Adding an image to a project in Visual Studio

You need to turn on Show All Files option on solution pane toolbar and include this file manually.

adding css class to multiple elements

try this:

.button input, .button a {
//css here
}

That will apply the style to all a tags nested inside of <p class="button"></p>

How do I open a new fragment from another fragment?

first of all, give set an ID for your Fragment layout e.g:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
**android:id="@+id/cameraFragment"**
tools:context=".CameraFragment">

and use that ID to replace the view with another fragment.java file. e.g

 ivGallary.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          UploadDoc uploadDoc= new UploadDoc();
          (getActivity()).getSupportFragmentManager().beginTransaction()
                  .replace(**R.id.cameraFragment**, uploadDoc, "findThisFragment")
                  .addToBackStack(null)
                  .commit();
      }
  });

ASP.NET MVC Return Json Result?

It should be :

public async Task<ActionResult> GetSomeJsonData()
{
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
}

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

Passing base64 encoded strings in URL

There are additional base64 specs. (See the table here for specifics ). But essentially you need 65 chars to encode: 26 lowercase + 26 uppercase + 10 digits = 62.

You need two more ['+', '/'] and a padding char '='. But none of them are url friendly, so just use different chars for them and you're set. The standard ones from the chart above are ['-', '_'], but you could use other chars as long as you decoded them the same, and didn't need to share with others.

I'd recommend just writing your own helpers. Like these from the comments on the php manual page for base64_encode:

function base64_url_encode($input) {
 return strtr(base64_encode($input), '+/=', '._-');
}

function base64_url_decode($input) {
 return base64_decode(strtr($input, '._-', '+/='));
}

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

This error you are receiving :

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

is because the number of elements in $values & $matches is not the same or $matches contains more than 1 element.

If $matches contains more than 1 element, than the insert will fail, because there is only 1 column name referenced in the query(hash)

If $values & $matches do not contain the same number of elements then the insert will also fail, due to the query expecting x params but it is receiving y data $matches.

I believe you will also need to ensure the column hash has a unique index on it as well.

Try the code here:

<?php

/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'root';

/*** mysql password ***/
$password = '';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
    /*** echo a message saying we have connected ***/
    echo 'Connected to database';
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }


$matches = array('1');
$count = count($matches);
for($i = 0; $i < $count; ++$i) {
    $values[] = '?';
}

// INSERT INTO DATABASE
$sql = "INSERT INTO hashes (hash) VALUES (" . implode(', ', $values) . ") ON DUPLICATE KEY UPDATE hash='hash'";
$stmt = $dbh->prepare($sql);
$data = $stmt->execute($matches);

//Error reporting if something went wrong...
var_dump($dbh->errorInfo());

?>

You will need to adapt it a little.

Table structure I used is here:

CREATE TABLE IF NOT EXISTS `hashes` (
  `hashid` int(11) NOT NULL AUTO_INCREMENT,
  `hash` varchar(250) NOT NULL,
  PRIMARY KEY (`hashid`),
  UNIQUE KEY `hash1` (`hash`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Code was run on my XAMPP Server which is using PHP 5.3.8 with MySQL 5.5.16.

I hope this helps.

Showing the same file in both columns of a Sublime Text window

I would suggest you to use Origami. Its a great plugin for splitting the screen. For better information on keyboard short cuts install it and after restarting Sublime text open Preferences->Package Settings -> Origami -> Key Bindings - Default

For specific to your question I would suggest you to see the short cuts related to cloning of files in the above mentioned file.

Most efficient way to check for DBNull and then assign to a variable?

This is how I handle reading from DataRows

///<summary>
/// Handles operations for Enumerations
///</summary>
public static class DataRowUserExtensions
{
    /// <summary>
    /// Gets the specified data row.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="dataRow">The data row.</param>
    /// <param name="key">The key.</param>
    /// <returns></returns>
    public static T Get<T>(this DataRow dataRow, string key)
    {
        return (T) ChangeTypeTo<T>(dataRow[key]);
    }

    private static object ChangeTypeTo<T>(this object value)
    {
        Type underlyingType = typeof (T);
        if (underlyingType == null)
            throw new ArgumentNullException("value");

        if (underlyingType.IsGenericType && underlyingType.GetGenericTypeDefinition().Equals(typeof (Nullable<>)))
        {
            if (value == null)
                return null;
            var converter = new NullableConverter(underlyingType);
            underlyingType = converter.UnderlyingType;
        }

        // Try changing to Guid  
        if (underlyingType == typeof (Guid))
        {
            try
            {
                return new Guid(value.ToString());
            }
            catch

            {
                return null;
            }
        }
        return Convert.ChangeType(value, underlyingType);
    }
}

Usage example:

if (dbRow.Get<int>("Type") == 1)
{
    newNode = new TreeViewNode
                  {
                      ToolTip = dbRow.Get<string>("Name"),
                      Text = (dbRow.Get<string>("Name").Length > 25 ? dbRow.Get<string>("Name").Substring(0, 25) + "..." : dbRow.Get<string>("Name")),
                      ImageUrl = "file.gif",
                      ID = dbRow.Get<string>("ReportPath"),
                      Value = dbRow.Get<string>("ReportDescription").Replace("'", "\'"),
                      NavigateUrl = ("?ReportType=" + dbRow.Get<string>("ReportPath"))
                  };
}

Props to Monsters Got My .Net for ChageTypeTo code.

Dump Mongo Collection into JSON format

If you want to dump all collections, run this command:

mongodump -d {DB_NAME}   -o /tmp 

It will generate all collections data in json and bson extensions into /tmp/{DB_NAME} directory

Javascript Get Values from Multiple Select Option Box

Also, change this:

    SelBranchVal = SelBranchVal + "," + InvForm.SelBranch[x].value;

to

    SelBranchVal = SelBranchVal + InvForm.SelBranch[x].value+ "," ;

The reason is that for the first time the variable SelBranchVal will be empty

How to add (vertical) divider to a horizontal LinearLayout?

You have to create the any view for separater like textview or imageview then set the background for that if you have image else use the color as the background.

Hope this helps you.

How do I do a bulk insert in mySQL using node.js

If Ragnar's answer doesn't work for you. Here is probably why (based on my experience) -

  1. I wasn't using node-mysql package as shown my Ragnar. I was using mysql package. They're different (if you didn't notice - just like me). But I'm not sure if it has anything to do with the ? not working, since it seemed to work for many folks using the mysql package.

  2. Try using a variable instead of ?

The following worked for me -

var mysql = require('node-mysql');
var conn = mysql.createConnection({
    ...
});

var sql = "INSERT INTO Test (name, email, n) VALUES :params";
var values = [
    ['demian', '[email protected]', 1],
    ['john', '[email protected]', 2],
    ['mark', '[email protected]', 3],
    ['pete', '[email protected]', 4]
];
conn.query(sql, { params: values}, function(err) {
    if (err) throw err;
    conn.end();
});

Hope this helps someone.

Export to CSV via PHP

I personally use this function to create CSV content from any array.

function array2csv(array &$array)
{
   if (count($array) == 0) {
     return null;
   }
   ob_start();
   $df = fopen("php://output", 'w');
   fputcsv($df, array_keys(reset($array)));
   foreach ($array as $row) {
      fputcsv($df, $row);
   }
   fclose($df);
   return ob_get_clean();
}

Then you can make your user download that file using something like:

function download_send_headers($filename) {
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // force download  
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");

    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}

Usage example:

download_send_headers("data_export_" . date("Y-m-d") . ".csv");
echo array2csv($array);
die();

How to remove a package in sublime text 2

Simple steps for remove any package from Sublime as phpfmt, Xdebug etc..

1- Go to Sublime menu-> Preference or press Ctrl+Shift+P .
2- Choose -> Remove package option, after you choosing it will display all   packge installed in your sublime, select one of them.
3. After selection it will remove, or for better you can restart your system.

JS search in object values

search(searchText) {
  let arrayOfMatchedObjects = arrayOfAllObjects.filter(object => {
    return JSON.stringify(object)
      .toString()
      .toLowerCase()
      .includes(searchText);
  });
  return arrayOfMatchedObjects;
}

This could be very simple, easy, fast and understandable Search function for some of you just like me.

javascript - Create Simple Dynamic Array

If you are asking whether there is a built in Pythonic range-like function, there isn't. You have to do it the brute force way. Maybe rangy would be of interest to you.

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

Well, one way is to compile it as x64 with VS2008

This runs as you would expect:

int normalInt = 5; 
unsigned long long int num=285212672;
printf(
    "My number is %d bytes wide and its value is %ul. 
    A normal number is %d \n", 
    sizeof(num), 
    num, 
    normalInt);

For 32 bit code, we need to use the correct __int64 format specifier %I64u. So it becomes.

int normalInt = 5; 
unsigned __int64 num=285212672;
printf(
    "My number is %d bytes wide and its value is %I64u. 
    A normal number is %d", 
    sizeof(num),
    num, normalInt);

This code works for both 32 and 64 bit VS compiler.

Change Schema Name Of Table In SQL

In case, someone looking for lower version -

For SQL Server 2000:

sp_changeobjectowner @objname = 'dbo.Employess' , @newowner ='exe'

How do I set the selected item in a drop down box

You can try this after select tag:

<option value="yes" selected>yes</option>
<option value="no">no</option>

How/when to generate Gradle wrapper files?

  1. You generate it once, and again when you'd like to change the version of Gradle you use in the project. There's no need to generate is so often. Here are the docs. Just add wrapper task to build.gradle file and run this task to get the wrapper structure.

    Mind that you need to have Gradle installed to generate a wrapper. Great tool for managing g-ecosystem artifacts is SDKMAN!. To generate a gradle wrapper, add the following piece of code to build.gradle file:

    task wrapper(type: Wrapper) {
       gradleVersion = '2.0' //version required
    }
    

    and run:

    gradle wrapper
    

    task. Add the resulting files to SCM (e.g. git) and from now all developers will have the same version of Gradle when using Gradle Wrapper.

    With Gradle 2.4 (or higher) you can set up a wrapper without adding a dedicated task:

    gradle wrapper --gradle-version 2.3
    

    or

    gradle wrapper --gradle-distribution-url https://myEnterpriseRepository:7070/gradle/distributions/gradle-2.3-bin.zip
    

    All the details can be found here

From Gradle 3.1 --distribution-type option can be also used. The options are binary and all and bin. all additionally contains source code and documentation. all is also better when IDE is used, so the editor works better. Drawback is the build may last longer (need to download more data, pointless on CI server) and it will take more space.

  1. These are Gradle Wrapper files. You need to generate them once (for a particular version) and add to version control. If you need to change the version of Gradle Wrapper, change the version in build.gradle see (1.) and regenerate the files.

  2. Give a detailed example. Such file may have multiple purposes: multi-module project, responsibility separation, slightly modified script, etc.

  3. settings.gradle is responsible rather for structure of the project (modules, names, etc), while, gradle.properties is used for project's and Gradle's external details (version, command line arguments -XX, properties etc.)

How to get current PHP page name

You can use basename() and $_SERVER['PHP_SELF'] to get current page file name

echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */

How do I use a custom Serializer with Jackson?

You can put @JsonSerialize(using = CustomDateSerializer.class) over any date field of object to be serialized.

public class CustomDateSerializer extends SerializerBase<Date> {

    public CustomDateSerializer() {
        super(Date.class, true);
    }

    @Override
    public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
        SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)");
        String format = formatter.format(value);
        jgen.writeString(format);
    }

}

Regular expression for first and last name

For simplicities sake, you can use:

(.*)\s(.*)

The thing I like about this is that the last name is always after the first name, so if you're going to enter this matched groups into a database, and the name is John M. Smith, the 1st group will be John M., and the 2nd group will be Smith.

How to print bytes in hexadecimal using System.out.println?

for (int j=0; j<test.length; j++) {
   System.out.format("%02X ", test[j]);
}
System.out.println();

Getting the docstring from a function

On ipython or jupyter notebook, you can use all the above mentioned ways, but i go with

my_func?

or

?my_func

for quick summary of both method signature and docstring.

I avoid using

my_func??

(as commented by @rohan) for docstring and use it only to check the source code

Can we import XML file into another XML file?

The other answers cover the 2 most common approaches, Xinclude and XML external entities. Microsoft has a really great writeup on why one should prefer Xinclude, as well as several example implementations. I've quoted the comparison below:

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

Why XInclude?

The first question one may ask is "Why use XInclude instead of XML external entities?" The answer is that XML external entities have a number of well-known limitations and inconvenient implications, which effectively prevent them from being a general-purpose inclusion facility. Specifically:

  • An XML external entity cannot be a full-blown independent XML document—neither standalone XML declaration nor Doctype declaration is allowed. That effectively means an XML external entity itself cannot include other external entities.
  • An XML external entity must be well formed XML (not so bad at first glance, but imagine you want to include sample C# code into your XML document).
  • Failure to load an external entity is a fatal error; any recovery is strictly forbidden.
  • Only the whole external entity may be included, there is no way to include only a portion of a document. -External entities must be declared in a DTD or an internal subset. This opens a Pandora's Box full of implications, such as the fact that the document element must be named in Doctype declaration and that validating readers may require that the full content model of the document be defined in DTD among others.

The deficiencies of using XML external entities as an inclusion mechanism have been known for some time and in fact spawned the submission of the XML Inclusion Proposal to the W3C in 1999 by Microsoft and IBM. The proposal defined a processing model and syntax for a general-purpose XML inclusion facility.

Four years later, version 1.0 of the XML Inclusions, also known as Xinclude, is a Candidate Recommendation, which means that the W3C believes that it has been widely reviewed and satisfies the basic technical problems it set out to solve, but is not yet a full recommendation.

Another good site which provides a variety of example implementations is https://www.xml.com/pub/a/2002/07/31/xinclude.html. Below is a common use case example from their site:

<book xmlns:xi="http://www.w3.org/2001/XInclude">

  <title>The Wit and Wisdom of George W. Bush</title>

  <xi:include href="malapropisms.xml"/>

  <xi:include href="mispronunciations.xml"/>

  <xi:include href="madeupwords.xml"/>

</book>

XML Schema minOccurs / maxOccurs default values

example:

XML

<?xml version="1.0" encoding="UTF-8"?> 
<?xml-stylesheet type="text/xsl" href="country.xsl"?>
<country xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="country.xsd">
    <countryName>Australia</countryName>
    <capital>Canberra</capital>
    <nationalLanguage>English</nationalLanguage>
    <population>21000000</population>
    <currency>Australian Dollar</currency>
    <nationalIdentities>
        <nationalAnthem>Advance Australia Fair</nationalAnthem>
        <nationalDay>Australia Day (26 January)</nationalDay>
        <nationalColour>Green and Gold</nationalColour>
        <nationalGemstone>Opal</nationalGemstone>
        <nationalFlower>Wattle (Acacia pycnantha)</nationalFlower>
    </nationalIdentities>
    <publicHolidays>
        <newYearDay>1 January</newYearDay>
        <australiaDay>26 January</australiaDay>
        <anzacDay>25 April</anzacDay>
        <christmasDay>25 December</christmasDay>
        <boxingDay>26 December</boxingDay>
        <laborDay>Variable Date</laborDay>
        <easter>Variable Date</easter>
        <queenBirthDay>21 April (Variable Date)</queenBirthDay>
    </publicHolidays>
    <states>
        <stateName><Name>NSW -  New South Wales</Name></stateName>
        <stateName><Name>VIC -  Victoria</Name></stateName>
        <stateName><Name>QLD -  Queensland</Name></stateName>
        <stateName><Name>SA -  South Australia</Name></stateName>
        <stateName><Name>WA -  Western Australia</Name></stateName>
        <stateName><Name>TAS -  Tasmania</Name></stateName>
    </states>
    <territories>
        <territoryName>ACT -  Australian Capital Territory</territoryName>
        <territoryName>NT -  Northern Territory</territoryName>
    </territories>
</country>

XSD:

<?xml version="1.0" encoding="UTF-8"?> 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="country">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="countryName" type="xs:string"/>
                <xs:element name="capital" type="xs:string"/>
                <xs:element name="nationalLanguage" type="xs:string"/>
                <xs:element name="population" type="xs:double"/>
                <xs:element name="currency" type="xs:string"/>
                <xs:element name="nationalIdentities">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element name="nationalAnthem" type="xs:string"/>
                        <xs:element name="nationalDay" type="xs:string"/>
                        <xs:element name="nationalColour" type="xs:string"/>
                        <xs:element name="nationalGemstone" type="xs:string"/>
                        <xs:element name="nationalFlower" type="xs:string"/>
                    </xs:sequence>
                </xs:complexType>
                </xs:element>
                <xs:element name="publicHolidays">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="newYearDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="australiaDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="anzacDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="christmasDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="boxingDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="laborDay" maxOccurs="1" type="xs:string"/>
                            <xs:element name="easter" maxOccurs="1" type="xs:string"/>
                            <xs:element name="queenBirthDay" maxOccurs="1" type="xs:string"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="states">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="stateName" minOccurs="1" maxOccurs="unbounded">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element name="Name" type="xs:string"/>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
                <xs:element name="territories">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="territoryName" maxOccurs="unbounded"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

XSL:

<?xml version="1.0"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="html" indent="yes" version="4.0"/>
    <xsl:template match="/">
        <html>
            <body>          
                <xsl:for-each select="country">         
                    <xsl:value-of select="countryName"/><br/>
                    <xsl:value-of select="capital"/><br/>
                    <xsl:value-of select="nationalLanguage"/><br/>
                    <xsl:value-of select="population"/><br/>
                    <xsl:value-of select="currency"/><br/>              
                    <xsl:for-each select="nationalIdentities">
                        <xsl:value-of select="nationalAnthem"/><br/>
                        <xsl:value-of select="nationalDay"/><br/>
                        <xsl:value-of select="nationalColour"/><br/>
                        <xsl:value-of select="nationalGemstone"/><br/>
                        <xsl:value-of select="nationalFlower"/><br/>
                    </xsl:for-each>
                    <xsl:for-each select="publicHolidays">
                        <xsl:value-of select="newYearDay"/><br/>
                        <xsl:value-of select="australiaDay"/><br/>
                        <xsl:value-of select="anzacDay"/><br/>
                        <xsl:value-of select="christmasDay"/><br/>
                        <xsl:value-of select="boxingDay"/><br/>
                        <xsl:value-of select="laborDay"/><br/>
                        <xsl:value-of select="easter"/><br/>
                        <xsl:value-of select="queenBirthDay"/><br/>
                    </xsl:for-each>
                    <xsl:for-each select="states/stateName">
                        <xsl:value-of select="Name"/><br/>
                    </xsl:for-each>
                </xsl:for-each>
            </body>
        </html>
    </xsl:template>
</xsl:stylesheet>

Result:

Australia
Canberra
English
21000000
Australian Dollar
Advance Australia Fair
Australia Day (26 January)
Green and Gold
Opal
Wattle (Acacia pycnantha)
1 January
26 January
25 April
25 December
26 December
Variable Date
Variable Date
21 April (Variable Date)
NSW - New South Wales
VIC - Victoria
QLD - Queensland
SA - South Australia
WA - Western Australia
TAS - Tasmania

Using .text() to retrieve only text not nested in child tags

To be able to trim the result, use DotNetWala's like so:

$("#foo")
    .clone()    //clone the element
    .children() //select all the children
    .remove()   //remove all the children
    .end()  //again go back to selected element
    .text()
    .trim();

I found out that using the shorter version like document.getElementById("listItem").childNodes[0] won't work with jQuery's trim().

Set background color in PHP?

just insert the following line and use any color you like

    echo "<body style='background-color:pink'>";

Printing an int list in a single line python3

# Print In One Line Python

print('Enter Value')

n = int(input())

print(*range(1, n+1), sep="")

Create instance of generic type whose constructor requires a parameter?

As an addition to user1471935's suggestion:

To instantiate a generic class by using a constructor with one or more parameters, you can now use the Activator class.

T instance = Activator.CreateInstance(typeof(T), new object[] {...}) 

The list of objects are the parameters you want to supply. According to Microsoft:

CreateInstance [...] creates an instance of the specified type using the constructor that best matches the specified parameters.

There's also a generic version of CreateInstance (CreateInstance<T>()) but that one also does not allow you to supply constructor parameters.

Encrypt and decrypt a String in java

    public String encrypt(String str) {
        try {
            // Encode the string into bytes using utf-8
            byte[] utf8 = str.getBytes("UTF8");

            // Encrypt
            byte[] enc = ecipher.doFinal(utf8);

            // Encode bytes to base64 to get a string
            return new sun.misc.BASE64Encoder().encode(enc);
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }

    public String decrypt(String str) {
        try {
            // Decode base64 to get bytes
            byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

            // Decrypt
            byte[] utf8 = dcipher.doFinal(dec);

            // Decode using utf-8
            return new String(utf8, "UTF8");
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }
}

Here's an example that uses the class:

try {
    // Generate a temporary key. In practice, you would save this key.
    // See also Encrypting with DES Using a Pass Phrase.
    SecretKey key = KeyGenerator.getInstance("DES").generateKey();

    // Create encrypter/decrypter class
    DesEncrypter encrypter = new DesEncrypter(key);

    // Encrypt
    String encrypted = encrypter.encrypt("Don't tell anybody!");

    // Decrypt
    String decrypted = encrypter.decrypt(encrypted);
} catch (Exception e) {
}

How can an html element fill out 100% of the remaining screen height, using css only?

Please let me add my 5 cents here and offer a classical solution:

_x000D_
_x000D_
html {height:100%;}_x000D_
body {height:100%; margin:0;}_x000D_
#idOuter {position:relative; width:100%; height:100%;}_x000D_
#idHeader {position:absolute; left:0; right:0; border:solid 3px red;}_x000D_
#idContent {position:absolute; overflow-y:scroll; left:0; right:0; border:solid 3px green;}
_x000D_
<div id="idOuter">_x000D_
  <div id="idHeader" style="height:30px; top:0;">Header section</div>_x000D_
  <div id="idContent" style="top:36px; bottom:0;">Content section</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This will work in all browsers, no script, no flex. Open snippet in full page mode and resize browser: desired proportions are preserved even in fullscreen mode.

Note:

  • Elements with different background color can actually cover each other. Here I used solid border to ensure that elements are placed correctly.
  • idHeader.height and idContent.top are adjusted to include border, and should have the same value if border is not used. Otherwise elements will pull out of the viewport, since calculated width does not include border, margin and/or padding.
  • left:0; right:0; can be replaced by width:100% for the same reason, if no border used.
  • Testing in separate page (not as a snippet) does not require any html/body adjustment.
  • In IE6 and earlier versions we must add padding-top and/or padding-bottom attributes to #idOuter element.

To complete my answer, here is the footer layout:

_x000D_
_x000D_
html {height:100%;}_x000D_
body {height:100%; margin:0;}_x000D_
#idOuter {position:relative; width:100%; height:100%;}_x000D_
#idContent {position:absolute; overflow-y:scroll; left:0; right:0; border:solid 3px green;}_x000D_
#idFooter {position:absolute; left:0; right:0; border:solid 3px blue;}
_x000D_
<div id="idOuter">_x000D_
  <div id="idContent" style="bottom:36px; top:0;">Content section</div>_x000D_
  <div id="idFooter" style="height:30px; bottom:0;">Footer section</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

And here is the layout with both header and footer:

_x000D_
_x000D_
html {height:100%;}_x000D_
body {height:100%; margin:0;}_x000D_
#idOuter {position:relative; width:100%; height:100%;}_x000D_
#idHeader {position:absolute; left:0; right:0; border:solid 3px red;}_x000D_
#idContent {position:absolute; overflow-y:scroll; left:0; right:0; border:solid 3px green;}_x000D_
#idFooter {position:absolute; left:0; right:0; border:solid 3px blue;}
_x000D_
<div id="idOuter">_x000D_
  <div id="idHeader" style="height:30px; top:0;">Header section</div>_x000D_
  <div id="idContent" style="top:36px; bottom:36px;">Content section</div>_x000D_
  <div id="idFooter" style="height:30px; bottom:0;">Footer section</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to send POST request in JSON using HTTPClient in Android?

In this answer I am using an example posted by Justin Grammens.

About JSON

JSON stands for JavaScript Object Notation. In JavaScript properties can be referenced both like this object1.name and like this object['name'];. The example from the article uses this bit of JSON.

The Parts
A fan object with email as a key and [email protected] as a value

{
  fan:
    {
      email : '[email protected]'
    }
}

So the object equivalent would be fan.email; or fan['email'];. Both would have the same value of '[email protected]'.

About HttpClient Request

The following is what our author used to make a HttpClient Request. I do not claim to be an expert at all this so if anyone has a better way to word some of the terminology feel free.

public static HttpResponse makeRequest(String path, Map params) throws Exception 
{
    //instantiates httpclient to make request
    DefaultHttpClient httpclient = new DefaultHttpClient();

    //url with the post data
    HttpPost httpost = new HttpPost(path);

    //convert parameters into JSON object
    JSONObject holder = getJsonObjectFromMap(params);

    //passes the results to a string builder/entity
    StringEntity se = new StringEntity(holder.toString());

    //sets the post request as the resulting string
    httpost.setEntity(se);
    //sets a request header so the page receving the request
    //will know what to do with it
    httpost.setHeader("Accept", "application/json");
    httpost.setHeader("Content-type", "application/json");

    //Handles what is returned from the page 
    ResponseHandler responseHandler = new BasicResponseHandler();
    return httpclient.execute(httpost, responseHandler);
}

Map

If you are not familiar with the Map data structure please take a look at the Java Map reference. In short, a map is similar to a dictionary or a hash.

private static JSONObject getJsonObjectFromMap(Map params) throws JSONException {

    //all the passed parameters from the post request
    //iterator used to loop through all the parameters
    //passed in the post request
    Iterator iter = params.entrySet().iterator();

    //Stores JSON
    JSONObject holder = new JSONObject();

    //using the earlier example your first entry would get email
    //and the inner while would get the value which would be '[email protected]' 
    //{ fan: { email : '[email protected]' } }

    //While there is another entry
    while (iter.hasNext()) 
    {
        //gets an entry in the params
        Map.Entry pairs = (Map.Entry)iter.next();

        //creates a key for Map
        String key = (String)pairs.getKey();

        //Create a new map
        Map m = (Map)pairs.getValue();   

        //object for storing Json
        JSONObject data = new JSONObject();

        //gets the value
        Iterator iter2 = m.entrySet().iterator();
        while (iter2.hasNext()) 
        {
            Map.Entry pairs2 = (Map.Entry)iter2.next();
            data.put((String)pairs2.getKey(), (String)pairs2.getValue());
        }

        //puts email and '[email protected]'  together in map
        holder.put(key, data);
    }
    return holder;
}

Please feel free to comment on any questions that arise about this post or if I have not made something clear or if I have not touched on something that your still confused about... etc whatever pops in your head really.

(I will take down if Justin Grammens does not approve. But if not then thanks Justin for being cool about it.)

Update

I just happend to get a comment about how to use the code and realized that there was a mistake in the return type. The method signature was set to return a string but in this case it wasnt returning anything. I changed the signature to HttpResponse and will refer you to this link on Getting Response Body of HttpResponse the path variable is the url and I updated to fix a mistake in the code.

how to do file upload using jquery serialization

HTML

<form name="my_form" id="my_form" accept-charset="multipart/form-data" onsubmit="return false">
    <input id="name" name="name" placeholder="Enter Name" type="text" value="">
    <textarea id="detail" name="detail" placeholder="Enter Detail"></textarea>
    <select name="gender" id="gender">
        <option value="male" selected="selected">Male</option>
        <option value="female">Female</option>
    </select>
    <input type="file" id="my_images" name="my_images" multiple="" accept="image/x-png,image/gif,image/jpeg"/>
</form>

JavaScript

var data = new FormData();

//Form data
var form_data = $('#my_form').serializeArray();
$.each(form_data, function (key, input) {
    data.append(input.name, input.value);
});

//File data
var file_data = $('input[name="my_images"]')[0].files;
for (var i = 0; i < file_data.length; i++) {
    data.append("my_images[]", file_data[i]);
}

//Custom data
data.append('key', 'value');

$.ajax({
    url: "URL",
    method: "post",
    processData: false,
    contentType: false,
    data: data,
    success: function (data) {
        //success
    },
    error: function (e) {
        //error
    }
});

PHP

<?php
    echo '<pre>';
    print_r($_POST);
    print_r($_FILES);
    echo '</pre>';
    die();
?>

How to access POST form fields

Post Parameters can be retrieved as follows:

app.post('/api/v1/test',Testfunction);
http.createServer(app).listen(port, function(){
    console.log("Express server listening on port " + port)
});

function Testfunction(request,response,next) {
   console.log(request.param("val1"));
   response.send('HI');
}

MySQL's now() +1 day

You can use:

NOW() + INTERVAL 1 DAY

If you are only interested in the date, not the date and time then you can use CURDATE instead of NOW:

CURDATE() + INTERVAL 1 DAY

Why is using onClick() in HTML a bad practice?

If you are using jQuery then:

HTML:

 <a id="openMap" href="/map/">link</a>

JS:

$(document).ready(function() {
    $("#openMap").click(function(){
        popup('/map/', 300, 300, 'map');
        return false;
    });
});

This has the benefit of still working without JS, or if the user middle clicks the link.

It also means that I could handle generic popups by rewriting again to:

HTML:

 <a class="popup" href="/map/">link</a>

JS:

$(document).ready(function() {
    $(".popup").click(function(){
        popup($(this).attr("href"), 300, 300, 'map');
        return false;
    });
});

This would let you add a popup to any link by just giving it the popup class.

This idea could be extended even further like so:

HTML:

 <a class="popup" data-width="300" data-height="300" href="/map/">link</a>

JS:

$(document).ready(function() {
    $(".popup").click(function(){
        popup($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');
        return false;
    });
});

I can now use the same bit of code for lots of popups on my whole site without having to write loads of onclick stuff! Yay for reusability!

It also means that if later on I decide that popups are bad practice, (which they are!) and that I want to replace them with a lightbox style modal window, I can change:

popup($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');

to

myAmazingModalWindow($(this).attr("href"), $(this).data('width'), $(this).data('height'), 'map');

and all my popups on my whole site are now working totally differently. I could even do feature detection to decide what to do on a popup, or store a users preference to allow them or not. With the inline onclick, this requires a huge copy and pasting effort.

how to align text vertically center in android

just use like this to make anything to center

 android:layout_gravity="center"
 android:gravity="center"

updated :

android:layout_gravity="center|right"
android:gravity="center|right"

Updated : Just remove MarginBottom from your textview.. Do like this.. for your textView

<LinearLayout
        android:id="@+id/linearLayout5"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"  >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center" 
            android:gravity="center|right"
            android:text="hello" 
            android:textSize="20dp" />
    </LinearLayout>

Using android.support.v7.widget.CardView in my project (Eclipse)

https://github.com/yongjhih/CardView

A CardView v7 eclipse project. (from sdk/extras/android/m2repository/com/android/support/cardview-v7)

The project was built by steps:

cp {sdk}/extras/android/m2repository/com/android/support/cardview-v7/21.0.0-rc1/cardview-v7-21.0.0-rc1.aar cardview-v7-21.0.0-rc1.zip
unzip cardview-v7-21.0.0-rc1.zip
mkdir libs/
mv classes.jar libs/cardview-v7-21.0.0-rc1.jar

Moving from one activity to another Activity in Android

First You have to use this code in MainActivity.java class

@Override
public void onClick(View v)
{
    // TODO Auto-generated method stub
    Intent i = new Intent(getApplicationContext(),NextActivity.class);
    startActivity(i);

}

You can pass intent this way.

Second

add proper entry into manifest.xml file.

<activity android:name=".NextActivity" />

Now see what happens.

How do you clone a Git repository into a specific folder?

Clone:

git clone [email protected]:jittre/name.git

Clone the "specific branch":

git clone -b [branch-name] [email protected]:jittre/name.git

jQuery Popup Bubble/Tooltip

Autoresize simple Popup Bubble

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <link href="bubble.css" type="text/css" rel="stylesheet" />
  <script language="javascript" type="text/javascript" src="jquery.js"></script>
  <script language="javascript" type="text/javascript" src="bubble.js"></script>
</head>
<body>
  <br/><br/>
  <div class="bubbleInfo">
      <div class="bubble" title="Text 1">Set cursor</div>
  </div>
  <br/><br/><br/><br/>
  <div class="bubbleInfo">
      <div class="bubble" title="Text 2">Set cursor</div>
  </div>
</body>
</html>

bubble.js

$(function () {     
  var i = 0;
  var z=1;
  do{
    title = $('.bubble:eq('+i+')').attr('title');
    if(!title){
      z=0;
    } else {
       $('.bubble:eq('+i+')').after('<table style="opacity: 0; top: -50px; left: -33px; display: none;" id="dpop" class="popup"><tbody><tr><td id="topleft" class="corner"></td><td class="top"></td><td id="topright" class="corner"></td></tr><tr><td class="left"></td><td>'+title+'</td><td class="right"></td></tr><tr><td class="corner" id="bottomleft"></td><td class="bottom"><img src="bubble/bubble-tail.png" height="25px" width="30px" /></td><td id="bottomright" class="corner"></td></tr></tbody></table>');
       $('.bubble:eq('+i+')').removeAttr('title');
    }
    i++;
  }while(z>0)

  $('.bubbleInfo').each(function () {
    var distance = 10;
    var time = 250;
    var hideDelay = 500;        
    var hideDelayTimer = null;       
    var beingShown = false;
    var shown = false;
    var trigger = $('.bubble', this);
    var info = $('.popup', this).css('opacity', 0);        

    $([trigger.get(0), info.get(0)]).mouseover(function () {
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      if (beingShown || shown) {
        // don't trigger the animation again
        return;
      } else {
        // reset position of info box
        beingShown = true;

        info.css({
        top: -40,
        left: 10,
        display: 'block'
        }).animate({
        top: '-=' + distance + 'px',
        opacity: 1
        }, time, 'swing', function() {
          beingShown = false;
          shown = true;
        });
      }          
      return false;
    }).mouseout(function () {
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      hideDelayTimer = setTimeout(function () {
        hideDelayTimer = null;
        info.animate({
          top: '-=' + distance + 'px',
          opacity: 0
        }, time, 'swing', function () {
          shown = false;
          info.css('display', 'none');
        });
      }, hideDelay);
      return false;
    });
  }); 
});

bubble.css

/* Booble */
.bubbleInfo {
    position: relative;
    width: 500px;
}
.bubble {       
}
.popup {
    position: absolute;
    display: none;
    z-index: 50;
    border-collapse: collapse;
    font-size: .8em;
}
.popup td.corner {
    height: 13px;
    width: 15px;
}
.popup td#topleft { 
    background-image: url(bubble/bubble-1.png); 
} 
.popup td.top { 
    background-image: url(bubble/bubble-2.png); 
}
.popup td#topright { 
    background-image: url(bubble/bubble-3.png); 
}
.popup td.left { 
    background-image: url(bubble/bubble-4.png); 
}
.popup td.right { 
    background-image: url(bubble/bubble-5.png); 
}
.popup td#bottomleft { 
    background-image: url(bubble/bubble-6.png); 
}
.popup td.bottom { 
    background-image: url(bubble/bubble-7.png); 
    text-align: center;
}
.popup td.bottom img { 
    display: block; 
    margin: 0 auto; 
}
.popup td#bottomright { 
    background-image: url(bubble/bubble-8.png); 
}

Removing body margin in CSS

I would say that using:

* {
  margin: 0;
  padding: 0;
}

is a bad way of solving this.

The reason for the h1 margin popping out of the parent is that the parent does not have a padding.

If you add a padding to the parent element of the h1, the margin will be inside the parent.

Resetting all paddings and margins to 0 can cause a lot of side effects. Then it's better to remove margin-top for this specific headline.

How to force reloading php.ini file?

You also can use graceful restart the apache server with service apache2 reload or apachectl -k graceful. As the apache doc says:

The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.

Check if element at position [x] exists in the list

int? here = (list.ElementAtOrDefault(2) != 0 ? list[2]:(int?) null);

Add event handler for body.onload by javascript within <body> part

As @epascarello mentioned for W3C standard browsers, you should use:

body.addEventListener("load", init, false);

However, if you want it to work on IE<9 as well you can use:

var prefix = window.addEventListener ? "" : "on";
var eventName = window.addEventListener ? "addEventListener" : "attachEvent";
document.body[eventName](prefix + "load", init, false);

Or if you want it in a single line:

document.body[window.addEventListener ? 'addEventListener' : 'attachEvent'](
    window.addEventListener ? "load" : "onload", init, false);

Note: here I get a straight reference to the body element via the document, saving the need for the first line.

Also, if you're using jQuery, and you want to use the DOM ready event rather than when the body loads, the answer can be even shorter...

$(init);

How to output oracle sql result into a file in windows?

just to make the Answer 2 much easier, you can also define the folder where you can put your saved file

    spool /home/admin/myoutputfile.txt
    select * from table_name;
    spool off;

after that only with nano or vi myoutputfile.txt, you will see all the sql track.

hope is that help :)

Browser detection in JavaScript?

Here is how I do custom CSS for Internet Explorer:

In my JavaScript file:

function isIE () {
      var myNav = navigator.userAgent.toLowerCase();
      return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}

jQuery(document).ready(function(){
    if(var_isIE){
            if(var_isIE == 10){
                jQuery("html").addClass("ie10");
            }
            if(var_isIE == 8){
                jQuery("html").addClass("ie8");
                // you can also call here some function to disable things that 
                //are not supported in IE, or override browser default styles.
            }
        }
    });

And then in my CSS file, y define each different style:

.ie10 .some-class span{
    .......
}
.ie8 .some-class span{
    .......
}

How to have jQuery restrict file types on upload?

<form enctype="multipart/form-data">
   <input name="file" type="file" />
   <input type="submit" value="Upload" />
</form>
<script>
$('input[type=file]').change(function(){
    var file = this.files[0];
    name = file.name;
    size = file.size;
    type = file.type;
    //your validation
});
</script>

sudo in php exec()

I think you can bring specific access to user and command with visudo something like this:

nobody ALL = NOPASSWD: /path/to/osascript myscript.scpt

and with php:

@exec("sudo /path/to/osascript myscript.scpt ");

supposing nobody user is running apache.

How to break out of a loop from inside a switch?

A neatish way to do this would be to put this into a function:

int yourfunc() {

    while(true) {

        switch(msg->state) {
        case MSGTYPE: // ... 
            break;
        // ... more stuff ...
        case DONE:
            return; 
        }

    }
}

Optionally (but 'bad practices'): as already suggested you could use a goto, or throw an exception inside the switch.

A select query selecting a select statement

I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

Thanks for answering, it helped my train of thought.

UILabel Align Text to center

In xamarin ios suppose your label name is title then do the following

title.TextAlignment = UITextAlignment.Center;

"Rate This App"-link in Google Play store app on the phone

I use this approach to make user rate my apps:

public static void showRateDialog(final Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context)
            .setTitle("Rate application")
            .setMessage("Please, rate the app at PlayMarket")
            .setPositiveButton("RATE", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (context != null) {
                        String link = "market://details?id=";
                        try {
                            // play market available
                            context.getPackageManager()
                                    .getPackageInfo("com.android.vending", 0);
                        // not available
                        } catch (PackageManager.NameNotFoundException e) {
                            e.printStackTrace();
                            // should use browser
                            link = "https://play.google.com/store/apps/details?id=";
                        }
                        // starts external action
                        context.startActivity(new Intent(Intent.ACTION_VIEW, 
                                Uri.parse(link + context.getPackageName())));
                    }
                }
            })
            .setNegativeButton("CANCEL", null);
    builder.show();
}

What is the difference between null and undefined in JavaScript?

null and undefined are both are used to represent the absence of some value.

var a = null;

a is initialized and defined.

typeof(a)
//object

null is an object in JavaScript

Object.prototype.toString.call(a) // [object Object]

var b;

b is undefined and uninitialized

undefined object properties are also undefined. For example "x" is not defined on object c and if you try to access c.x, it will return undefined.

Generally we assign null to variables not undefined.

android:layout_height 50% of the screen size

This kind of worked for me. Though FAB doesn't float independently, but now it isn't getting pushed down.

Observe the weights given inside the LinearLayout

<LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:id="@+id/andsanddkasd">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/sharedResourcesRecyclerView"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="4"
                />

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_gravity="bottom|right"
                android:src="@android:drawable/ic_input_add"
                android:layout_weight="1"/>

        </LinearLayout>

Hope this helps :)

How do I iterate through table rows and cells in JavaScript?

If you want to go through each row(<tr>), knowing/identifying the row(<tr>), and iterate through each column(<td>) of each row(<tr>), then this is the way to go.

var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i]; i++) {
   //iterate through rows
   //rows would be accessed using the "row" variable assigned in the for loop
   for (var j = 0, col; col = row.cells[j]; j++) {
     //iterate through columns
     //columns would be accessed using the "col" variable assigned in the for loop
   }  
}

If you just want to go through the cells(<td>), ignoring which row you're on, then this is the way to go.

var table = document.getElementById("mytab1");
for (var i = 0, cell; cell = table.cells[i]; i++) {
     //iterate through cells
     //cells would be accessed using the "cell" variable assigned in the for loop
}

Uncaught TypeError: Cannot read property 'split' of undefined

ogdate is itself a string, why are you trying to access it's value property that it doesn't have ?

console.log(og_date.split('-'));

JSFiddle

How to auto adjust the div size for all mobile / tablet display formats?

You can use the viewport height, just set the height of your div to height:100vh;, this will set the height of your div to the height of the viewport of the device, furthermore, if you want it to be exactly as your device screen, set the margin and padding to 0.

Plus, It will be a good idea to set the viewport meta tag:

<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0" />

Please Note that this is relatively new and is not supported in IE8-, take a look at the support list before considering this approach (http://caniuse.com/#search=viewport).

Hope this helps.

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

For those who couldn't get choose007's answer up and running

If clickListener is not working properly at all times in chose007's solution, try to implement View.onTouchListener instead of clickListener. Handle touch event using any of the action ACTION_UP or ACTION_DOWN. For some reason, maps infoWindow causes some weird behaviour when dispatching to clickListeners.

infoWindow.findViewById(R.id.my_view).setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
          int action = MotionEventCompat.getActionMasked(event);
          switch (action){
                case MotionEvent.ACTION_UP:
                    Log.d(TAG,"a view in info window clicked" );
                    break;
                }
                return true;
          }

Edit : This is how I did it step by step

First inflate your own infowindow (global variable) somewhere in your activity/fragment. Mine is within fragment. Also insure that root view in your infowindow layout is linearlayout (for some reason relativelayout was taking full width of screen in infowindow)

infoWindow = (ViewGroup) getActivity().getLayoutInflater().inflate(R.layout.info_window, null);
/* Other global variables used in below code*/
private HashMap<Marker,YourData> mMarkerYourDataHashMap = new HashMap<>();
private GoogleMap mMap;
private MapWrapperLayout mapWrapperLayout;

Then in onMapReady callback of google maps android api (follow this if you donot know what onMapReady is Maps > Documentation - Getting Started )

   @Override
    public void onMapReady(GoogleMap googleMap) {
       /*mMap is global GoogleMap variable in activity/fragment*/
        mMap = googleMap;
       /*Some function to set map UI settings*/ 
        setYourMapSettings();

MapWrapperLayout initialization http://stackoverflow.com/questions/14123243/google-maps-android-api-v2- interactive-infowindow-like-in-original-android-go/15040761#15040761 39 - default marker height 20 - offset between the default InfoWindow bottom edge and it's content bottom edge */

        mapWrapperLayout.init(mMap, Utils.getPixelsFromDp(mContext, 39 + 20));

        /*handle marker clicks separately - not necessary*/
       mMap.setOnMarkerClickListener(this);

       mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
                @Override
                public View getInfoWindow(Marker marker) {
                    return null;
                }

            @Override
            public View getInfoContents(Marker marker) {
                YourData data = mMarkerYourDataHashMap.get(marker);
                setInfoWindow(marker,data);
                mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
                return infoWindow;
            }
        });
    }

SetInfoWindow method

private void setInfoWindow (final Marker marker, YourData data)
            throws NullPointerException{
        if (data.getVehicleNumber()!=null) {
            ((TextView) infoWindow.findViewById(R.id.VehicelNo))
                    .setText(data.getDeviceId().toString());
        }
        if (data.getSpeed()!=null) {
            ((TextView) infoWindow.findViewById(R.id.txtSpeed))
                    .setText(data.getSpeed());
        }

        //handle dispatched touch event for view click
        infoWindow.findViewById(R.id.any_view).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = MotionEventCompat.getActionMasked(event);
                switch (action) {
                    case MotionEvent.ACTION_UP:
                        Log.d(TAG,"any_view clicked" );
                        break;
                }
                return true;
            }
        });

Handle marker click separately

    @Override
    public boolean onMarkerClick(Marker marker) {
        Log.d(TAG,"on Marker Click called");
        marker.showInfoWindow();
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(marker.getPosition())      // Sets the center of the map to Mountain View
                .zoom(10)
                .build();
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),1000,null);
        return true;
    }

Pie chart with jQuery

There is a new player in the field, offering advanced Navigation Charts that are using Canvas for super-smooth animations and performance:

https://zoomcharts.com/

Example of charts:

interactive pie chart

Documentation: https://zoomcharts.com/en/javascript-charts-library/charts-packages/pie-chart/

What is cool about this lib:

  • Others slice can be expanded
  • Pie offers drill down for hierarchical structures (see example)
  • write your own data source controller easily, or provide simple json file
  • export high res images out of box
  • full touch support, works smoothly on iPad, iPhone, android, etc.

enter image description here

Charts are free for non-commercial use, commercial licenses and technical support available as well.

Also interactive Time charts and Net Charts are there for you to use. enter image description here

enter image description here

Charts come with extensive API and Settings, so you can control every aspect of the charts.

How to check if an user is logged in Symfony2 inside a controller?

Try this:

if( $this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') ){
    // authenticated (NON anonymous)
}

Further information:

"Anonymous users are technically authenticated, meaning that the isAuthenticated() method of an anonymous user object will return true. To check if your user is actually authenticated, check for the IS_AUTHENTICATED_FULLY role."

Source: http://symfony.com/doc/current/book/security.html

Input type number "only numeric value" validation

Sometimes it is just easier to try something simple like this.

validateNumber(control: FormControl): { [s: string]: boolean } {

  //revised to reflect null as an acceptable value 
  if (control.value === null) return null;

  // check to see if the control value is no a number
  if (isNaN(control.value)) {
    return { 'NaN': true };
  }

  return null; 
}

Hope this helps.

updated as per comment, You need to to call the validator like this

number: new FormControl('',[this.validateNumber.bind(this)])

The bind(this) is necessary if you are putting the validator in the component which is how I do it.

Javascript "Not a Constructor" Exception while creating objects

I just want to add that if the constructor is called from a different file, then something as simple as forgetting to export the constructor with

module.exports = NAME_OF_CONSTRUCTOR

will also cause the "Not a constructor" exception.

How can I see what I am about to push with git?

After git commit -m "{your commit message}", you will get a commit hash before the push. So you can see what you are about to push with git by running the following command:

git diff origin/{your_branch_name} commit hash

e.g: git diff origin/master c0e06d2

How do you round UP a number in Python?

To do it without any import:

>>> round_up = lambda num: int(num + 1) if int(num) != num else int(num)
>>> round_up(2.0)
2
>>> round_up(2.1)
3

How can I check if the array of objects have duplicate property values?

ECMA Script 6 Version

If you are in an environment which supports ECMA Script 6's Set, then you can use Array.prototype.some and a Set object, like this

let seen = new Set();
var hasDuplicates = values.some(function(currentObject) {
    return seen.size === seen.add(currentObject.name).size;
});

Here, we insert each and every object's name into the Set and we check if the size before and after adding are the same. This works because Set.size returns a number based on unique data (set only adds entries if the data is unique). If/when you have duplicate names, the size won't increase (because the data won't be unique) which means that we would have already seen the current name and it will return true.


ECMA Script 5 Version

If you don't have Set support, then you can use a normal JavaScript object itself, like this

var seen = {};
var hasDuplicates = values.some(function(currentObject) {

    if (seen.hasOwnProperty(currentObject.name)) {
        // Current name is already seen
        return true;
    }

    // Current name is being seen for the first time
    return (seen[currentObject.name] = false);
});

The same can be written succinctly, like this

var seen = {};
var hasDuplicates = values.some(function (currentObject) {
    return seen.hasOwnProperty(currentObject.name)
        || (seen[currentObject.name] = false);
});

Note: In both the cases, we use Array.prototype.some because it will short-circuit. The moment it gets a truthy value from the function, it will return true immediately, it will not process rest of the elements.

In PANDAS, how to get the index of a known value?

The other way around using numpy.where() :

import numpy as np
import pandas as pd

In [800]: df = pd.DataFrame(np.arange(10).reshape(5,2),columns=['c1','c2'])

In [801]: df
Out[801]: 
   c1  c2
0   0   1
1   2   3
2   4   5
3   6   7
4   8   9

In [802]: np.where(df["c1"]==6)
Out[802]: (array([3]),)

In [803]: indices = list(np.where(df["c1"]==6)[0])

In [804]: df.iloc[indices]
Out[804]: 
   c1  c2
3   6   7

In [805]: df.iloc[indices].index
Out[805]: Int64Index([3], dtype='int64')

In [806]: df.iloc[indices].index.tolist()
Out[806]: [3]

MomentJS getting JavaScript Date in UTC

Or simply:

Date.now

From MDN documentation:

The Date.now() method returns the number of milliseconds elapsed since January 1, 1970

Available since ECMAScript 5.1

It's the same as was mentioned above (new Date().getTime()), but more shortcutted version.

Play audio file from the assets directory

player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());

Your version would work if you had only one file in the assets directory. The asset directory contents are not actually 'real files' on disk. All of them are put together one after another. So, if you do not specify where to start and how many bytes to read, the player will read up to the end (that is, will keep playing all the files in assets directory)

How to get the number of characters in a string

Depends a lot on your definition of what a "character" is. If "rune equals a character " is OK for your task (generally it isn't) then the answer by VonC is perfect for you. Otherwise, it should be probably noted, that there are few situations where the number of runes in a Unicode string is an interesting value. And even in those situations it's better, if possible, to infer the count while "traversing" the string as the runes are processed to avoid doubling the UTF-8 decode effort.

get dictionary value by key

static String findFirstKeyByValue(Dictionary<string, string> Data_Array, String value)
{
    if (Data_Array.ContainsValue(value))
    {
        foreach (String key in Data_Array.Keys)
        {
            if (Data_Array[key].Equals(value))
                return key;
        }
    }
    return null;
}

How to make FileFilter in java?

Here is a little utility class that I created:

import java.io.File;
import java.io.FilenameFilter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * Convenience utility to create a FilenameFilter, based on a list of extensions
 */
public class FileExtensionFilter implements FilenameFilter {
    private Set<String> exts = new HashSet<String>();

    /**
     * @param extensions
     *            a list of allowed extensions, without the dot, e.g.
     *            <code>"xml","html","rss"</code>
     */
    public FileExtensionFilter(String... extensions) {
        for (String ext : extensions) {
            exts.add("." + ext.toLowerCase().trim());
        }
    }

    public boolean accept(File dir, String name) {
        final Iterator<String> extList = exts.iterator();
        while (extList.hasNext()) {
            if (name.toLowerCase().endsWith(extList.next())) {
                return true;
            }
        }
        return false;
    }
}

Usage:

       String[] files = new File("myfile").list(new FileExtensionFilter("pdf", "zip"));

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

  1. Go to Sql Server Management Studio >
  2. Object Explorer >
  3. Databases >
  4. Choose and expand your Database.
  5. Under your database right click on "Database Diagrams" and select "New Database Diagram".
  6. It will a open a new window. Choose tables to include in ER-Diagram (to select multiple tables press "ctrl" or "shift" button and select tables).
  7. Click add.
  8. Wait for it to complete. Done!

You can save generated diagram for future use.

screenshot

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

How to create a Jar file in Netbeans

Please do right click on the project and go to properties. Then go to Build and Packaging. You can see the JAR file location that is produced by defualt setting of netbean in the dist directory.

Creating .pem file for APNS?

->> Apple's own tutorial <<- is the only working set of instructions I've come across. It's straight forward and I can confirm it works brilliantly on both a linux php server and a windows php server.

You can find their 5-step pem creation process right at the bottom of the page.

How can I remove an entry in global configuration with git config?

You can check all the config settings using

git config --global --list

You can remove the setting for example username

git config --global --unset user.name

You can edit the configuration or remove the config setting manually by hand using:

git config --global --edit 

How to declare a variable in a template in Angular

I would suggest this: https://medium.com/@AustinMatherne/angular-let-directive-a168d4248138

This directive allow you to write something like:

<div *ngLet="'myVal' as myVar">
  <span> {{ myVar }} </span>
</div>

What are .dex files in Android?

.dex file

Compiled Android application code file.

Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.

React / JSX Dynamic Component Name

There should be a container that maps component names to all components that are supposed to be used dynamically. Component classes should be registered in a container because in modular environment there's otherwise no single place where they could be accessed. Component classes cannot be identified by their names without specifying them explicitly because function name is minified in production.

Component map

It can be plain object:

class Foo extends React.Component { ... }
...
const componentsMap = { Foo, Bar };
...
const componentName = 'Fo' + 'o';
const DynamicComponent = componentsMap[componentName];
<DynamicComponent/>;

Or Map instance:

const componentsMap = new Map([[Foo, Foo], [Bar, Bar]]);
...
const DynamicComponent = componentsMap.get(componentName);

Plain object is more suitable because it benefits from property shorthand.

Barrel module

A barrel module with named exports can act as such map:

// Foo.js
export class Foo extends React.Component { ... }

// dynamic-components.js
export * from './Foo';
export * from './Bar';

// some module that uses dynamic component
import * as componentsMap from './dynamic-components';

const componentName = 'Fo' + 'o';
const DynamicComponent = componentsMap[componentName];
<DynamicComponent/>;

This works well with one class per module code style.

Decorator

Decorators can be used with class components for syntactic sugar, this still requires to specify class names explicitly and register them in a map:

const componentsMap = {};

function dynamic(Component) {
  if (!Component.displayName)
    throw new Error('no name');

  componentsMap[Component.displayName] = Component;

  return Component;
}

...

@dynamic
class Foo extends React.Component {
  static displayName = 'Foo'
  ...
}

A decorator can be used as higher-order component with functional components:

const Bar = props => ...;
Bar.displayName = 'Bar';

export default dynamic(Bar);

The use of non-standard displayName instead of random property also benefits debugging.

PHP: trying to create a new line with "\n"

This works perfectly for me...

echo nl2br("\n");

Reference: http://www.w3schools.com/php/func_string_nl2br.asp

Hope it helps :)

Warning as error - How to get rid of these

In the Properties,

Go to Configuration Properties. In that go to C/C++ (or something like that). ,Then click General ,In that remove the check in the "Treat Warning As Errors" Check Box

Using LIMIT within GROUP BY to get N results per group?

SELECT year, id, rate
FROM (SELECT
  year, id, rate, row_number() over (partition by id order by rate DESC)
  FROM h
  WHERE year BETWEEN 2000 AND 2009
  AND id IN (SELECT rid FROM table2)
  GROUP BY id, year
  ORDER BY id, rate DESC) as subquery
WHERE row_number <= 5

The subquery is almost identical to your query. Only change is adding

row_number() over (partition by id order by rate DESC)

Programmatically obtain the phone number of the Android phone

A little contribution. In my case, the code launched an error exception. I have needed put an annotation that for the code be run and fix that problem. Here I let this code.

public static String getLineNumberPhone(Context scenario) {
    TelephonyManager tMgr = (TelephonyManager) scenario.getSystemService(Context.TELEPHONY_SERVICE);
    @SuppressLint("MissingPermission") String mPhoneNumber = tMgr.getLine1Number();
    return mPhoneNumber;
}

Statically rotate font-awesome icons

If you use Less you can directly use the following mixin:

.@{fa-css-prefix}-rotate-90  { .fa-icon-rotate(90deg, 1);  }

Should operator<< be implemented as a friend or as a member function?

The signature:

bool operator<<(const obj&, const obj&);

Seems rather suspect, this does not fit the stream convention nor the bitwise convention so it looks like a case of operator overloading abuse, operator < should return bool but operator << should probably return something else.

If you meant so say:

ostream& operator<<(ostream&, const obj&); 

Then since you can't add functions to ostream by necessity the function must be a free function, whether it a friend or not depends on what it has to access (if it doesn't need to access private or protected members there's no need to make it friend).

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

You cant access PHP session variables/values in JS, one is server side (PHP), the other client side (JS).

What you can do is pass or return the SESSION value to your JS, by say, an AJAX call. In your JS, make a call to a PHP script which simply outputs for return to your JS the SESSION variable's value, then use your JS to handle this returned information.

Alternatively store the value in a COOKIE, which can be accessed by either framework..though this may not be the best approach in your situation.

OR you can generate some JS in your PHP which returns/sets the variable, i.e.:

<? php
echo "<script type='text/javascript'>
    alert('".json_encode($_SESSION['msg'])."');
</script>";
?>

All ASP.NET Web API controllers return 404

I'm going to add my solution here because I personally hate the ones which edit the web.config without explaining what is going on.

For me it was how the default Handler Mappings are set in IIS. To check this...

  1. Open IIS Manager
  2. Click on the root node of your server (usually the name of the server)
  3. Open "Handler Mappings"
  4. Under Actions in the right pane, click "View ordered list"

This is the order of handlers that process a request. If yours are like mine, the "ExtensionlessUrlHandler-*" handlers are all below the StaticFile handler. Well that isn't going to work because the StaticFile handler has a wildcard of * and will return a 404 before even getting to an extensionless controller.

So rearranging this and moving the "ExtensionlessUrlHandler-*" above the wildcard handlers of TRACE, OPTIONS and StaticFile will then have the Extensionless handler activated first and should allow your controllers, in any website running in the system, to respond correctly.

Note: This is basically what happens when you remove and add the modules in the web.config but a single place to solve it for everything. And it doesn't require extra code!

C# testing to see if a string is an integer?

This function will tell you if your string contains ONLY the characters 0123456789.

private bool IsInt(string sVal)
{
    foreach (char c in sVal)
    {
         int iN = (int)c;
         if ((iN > 57) || (iN < 48))
            return false;
    }
    return true;
}

This is different from int.TryParse() which will tell you if your string COULD BE an integer.
eg. " 123\r\n" will return TRUE from int.TryParse() but FALSE from the above function.

...Just depends on the question you need to answer.

Why is an OPTIONS request sent and can I disable it?

Please refer this answer on the actual need for pre-flighted OPTIONS request: CORS - What is the motivation behind introducing preflight requests?

To disable the OPTIONS request, below conditions must be satisfied for ajax request:

  1. Request does not set custom HTTP headers like 'application/xml' or 'application/json' etc
  2. The request method has to be one of GET, HEAD or POST. If POST, content type should be one of application/x-www-form-urlencoded, multipart/form-data, or text/plain

Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Reverse Singly Linked List Java

The method for reversing a linked list is as below;

Reverse Method

public void reverseList() {
    Node<E> curr = head;
    Node<E> pre = null;
    Node<E> incoming = null;

    while(curr != null) {
        incoming = curr.next;   // store incoming item

        curr.next = pre;        // swap nodes
        pre = curr;             // increment also pre

        curr = incoming;        // increment current
    }

    head = pre; // pre is the latest item where
                // curr is null
}

Three references are needed to reverse a list: pre, curr, incoming

...      pre     curr    incoming
... --> (n-1) --> (n) --> (n+1) --> ...

To reverse a node, you have to store previous element, so that you can use the simple stament;

curr.next = pre;

To reverse the current element's direction. However, to iterate over the list, you have to store incoming element before the execution of the statement above because as reversing the current element's next reference, you don't know the incoming element anymore, that's why a third reference needed.

The demo code is as below;

LinkedList Sample Class

public class LinkedList<E> {

    protected Node<E> head;

    public LinkedList() {
        head = null;
    }

    public LinkedList(E[] list) {
        this();
        addAll(list);
    }

    public void addAll(E[] list) {
        for(int i = 0; i < list.length; i++)
            add(list[i]);
    }

    public void add(E e) {
        if(head == null)
            head = new Node<E>(e);
        else {
            Node<E> temp = head;

            while(temp.next != null)
                temp = temp.next;

            temp.next = new Node<E>(e);
        }
    }

    public void reverseList() {
        Node<E> curr = head;
        Node<E> pre = null;
        Node<E> incoming = null;

        while(curr != null) {
            incoming = curr.next;   // store incoming item

            curr.next = pre;        // swap nodes
            pre = curr;             // increment also pre

            curr = incoming;        // increment current
        }

        head = pre; // pre is the latest item where
                    // curr is null
    }

    public void printList() {
        Node<E> temp = head;

        System.out.print("List: ");
        while(temp != null) {
            System.out.print(temp + " ");
            temp = temp.next;
        }

        System.out.println();
    }

    public static class Node<E> {

        protected E e;
        protected Node<E> next;

        public Node(E e) {
            this.e = e;
            this.next = null;
        }

        @Override
        public String toString() {
            return e.toString();
        }

    }

}

Test Code

public class ReverseLinkedList {

    public static void main(String[] args) {
        Integer[] list = { 4, 3, 2, 1 };

        LinkedList<Integer> linkedList = new LinkedList<Integer>(list);

        linkedList.printList();
        linkedList.reverseList();
        linkedList.printList();
    }

}

Output

List: 4 3 2 1 
List: 1 2 3 4 

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

if anybody is experiencing is issue while updating to the latest react native, try updating your pod file with

  use_flipper!
  post_install do |installer|
    flipper_post_install(installer)
    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
        config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
      end
    end
   end

Passing array in GET for a REST call

As @Ravi_MCA mentioned, /users?ids[]=id1&ids[]=id2 worked for me, too.


When you want to send an array through PATCH or POST method, it's better to use JSON or XML. (I use JSON)
In HTTP Request body you should follow like this:

{"params":["arg1", "arg2", ...]}

You can even use JSON object instead of array.

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

That's the error you get when a function makes too many recursive calls to itself. It might be doing this because the base case is never met (and therefore it gets stuck in an infinite loop) or just by making an large number of calls to itself. You could replace the recursive calls with while loops.

How to check what version of jQuery is loaded?

if (jQuery){
   //jquery loaded
}

.....

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

Auto refresh page every 30 seconds

If you want refresh the page you could use like this, but refreshing the page is usually not the best method, it better to try just update the content that you need to be updated.

javascript:

<script language="javascript">
setTimeout(function(){
   window.location.reload(1);
}, 30000);
</script>

Load text file as strings using numpy.loadtxt()

There is also read_csv in Pandas, which is fast and supports non-comma column separators and automatic typing by column:

import pandas as pd
df = pd.read_csv('your_file',sep='\t')

It can be converted to a NumPy array if you prefer that type with:

import numpy as np
arr = np.array(df)

This is by far the easiest and most mature text import approach I've come across.

how do you filter pandas dataframes by multiple columns

In case somebody wonders what is the faster way to filter (the accepted answer or the one from @redreamality):

import pandas as pd
import numpy as np

length = 100_000
df = pd.DataFrame()
df['Year'] = np.random.randint(1950, 2019, size=length)
df['Gender'] = np.random.choice(['Male', 'Female'], length)

%timeit df.query('Gender=="Male" & Year=="2014" ')
%timeit df[(df['Gender']=='Male') & (df['Year']==2014)]

Results for 100,000 rows:

6.67 ms ± 557 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
5.54 ms ± 536 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Results for 10,000,000 rows:

326 ms ± 6.52 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
472 ms ± 25.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So results depend on the size and the data. On my laptop, query() gets faster after 500k rows. Further, the string search in Year=="2014" has an unnecessary overhead (Year==2014 is faster).

Python - How to sort a list of lists by the fourth element in each list?

Use sorted() with a key as follows -

>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

The lambda returns the fourth element of each of the inner lists and the sorted function uses that to sort those list. This assumes that int(elem) will not fail for the list.

Or use itemgetter (As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)

>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

How to drop column with constraint?

I have updated script a little bit to my SQL server version

DECLARE @sql nvarchar(max)

SELECT @sql = 'ALTER TABLE `table_name` DROP CONSTRAINT ' + df.NAME 
FROM sys.default_constraints df
  INNER JOIN sys.tables t ON df.parent_object_id = t.object_id
  INNER JOIN sys.columns c ON df.parent_object_id = c.object_id AND df.parent_column_id = c.column_id
where t.name = 'table_name' and c.name = 'column_name'

EXEC sp_executeSql @sql
GO

ALTER TABLE table_name
  DROP COLUMN column_name;

How can you integrate a custom file browser/uploader with CKEditor?

I just went through the learning process myself. I figured it out, but I agree the documentation is written in a way that was sorta intimidating to me. The big "aha" moment for me was understanding that for browsing, all CKeditor does is open a new window and provide a few parameters in the url. It allows you to add additional parameters but be advised you will need to use encodeURIComponent() on your values.

I call the browser and the uploader with

CKEDITOR.replace( 'body',  
{  
    filebrowserBrowseUrl: 'browse.php?type=Images&dir=' +  
        encodeURIComponent('content/images'),  
    filebrowserUploadUrl: 'upload.php?type=Files&dir=' +  
        encodeURIComponent('content/images')  
}

For the browser, in the open window (browse.php) you use php & js to supply a list of choices and then upon your supplied onclick handler, you call a CKeditor function with two arguments, the url/path to the selected image and CKEditorFuncNum supplied by CKeditor in the url:

function myOnclickHandler(){  
//..    
    window.opener.CKEDITOR.tools.callFunction(<?php echo $_GET['CKEditorFuncNum']; ?>, pathToImage);  
    window.close();
}       

Simarly, the uploader simply calls the url you supply, e.g., upload.php, and again supplies $_GET['CKEditorFuncNum']. The target is an iframe so, after you save the file from $_FILES you pass your feedback to CKeditor as thus:

$funcNum = $_GET['CKEditorFuncNum'];  
exit("<script>window.parent.CKEDITOR.tools.callFunction($funcNum, '$filePath', '$errorMessage');</script>");  

Below is a simple to understand custom browser script. While it does not allow users to navigate around in the server, it does allow you to indicate which directory to pull image files from when calling the browser.

It's all rather basic coding so it should work in all relatively modern browsers.

CKeditor merely opens a new window with the url provided

/*          
    in CKeditor **use encodeURIComponent()** to add dir param to the filebrowserBrowseUrl property

    Replace content/images with directory where your images are housed.
*/          
        CKEDITOR.replace( 'editor1', {  
            filebrowserBrowseUrl: '**browse.php**?type=Images&dir=' + encodeURIComponent('content/images'),  
            filebrowserUploadUrl: 'upload.php?type=Files&dir=' + encodeURIComponent('content/images') 
        });   

// ========= complete code below for browse.php

<?php  
header("Content-Type: text/html; charset=utf-8\n");  
header("Cache-Control: no-cache, must-revalidate\n");  
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");  

// e-z params  
$dim = 150;         /* image displays proportionally within this square dimension ) */  
$cols = 4;          /* thumbnails per row */
$thumIndicator = '_th'; /* e.g., *image123_th.jpg*) -> if not using thumbNails then use empty string */  
?>  
<!DOCTYPE html>  
<html>  
<head>  
    <title>browse file</title>  
    <meta charset="utf-8">  

    <style>  
        html,  
        body {padding:0; margin:0; background:black; }  
        table {width:100%; border-spacing:15px; }  
        td {text-align:center; padding:5px; background:#181818; }  
        img {border:5px solid #303030; padding:0; verticle-align: middle;}  
        img:hover { border-color:blue; cursor:pointer; }  
    </style>  

</head>  


<body>  

<table>  

<?php  

$dir = $_GET['dir'];    

$dir = rtrim($dir, '/'); // the script will add the ending slash when appropriate  

$files = scandir($dir);  

$images = array();  

foreach($files as $file){  
    // filter for thumbNail image files (use an empty string for $thumIndicator if not using thumbnails )
    if( !preg_match('/'. $thumIndicator .'\.(jpg|jpeg|png|gif)$/i', $file) )  
        continue;  

    $thumbSrc = $dir . '/' . $file;  
    $fileBaseName = str_replace('_th.','.',$file);  

    $image_info = getimagesize($thumbSrc);  
    $_w = $image_info[0];  
    $_h = $image_info[1]; 

    if( $_w > $_h ) {       // $a is the longer side and $b is the shorter side
        $a = $_w;  
        $b = $_h;  
    } else {  
        $a = $_h;  
        $b = $_w;  
    }     

    $pct = $b / $a;     // the shorter sides relationship to the longer side

    if( $a > $dim )   
        $a = $dim;      // limit the longer side to the dimension specified

    $b = (int)($a * $pct);  // calculate the shorter side

    $width =    $_w > $_h ? $a : $b;  
    $height =   $_w > $_h ? $b : $a;  

    // produce an image tag
    $str = sprintf('<img src="%s" width="%d" height="%d" title="%s" alt="">',   
        $thumbSrc,  
        $width,  
        $height,  
        $fileBaseName  
    );  

    // save image tags in an array
    $images[] = str_replace("'", "\\'", $str); // an unescaped apostrophe would break js  

}

$numRows = floor( count($images) / $cols );  

// if there are any images left over then add another row
if( count($images) % $cols != 0 )  
    $numRows++;  


// produce the correct number of table rows with empty cells
for($i=0; $i<$numRows; $i++)   
    echo "\t<tr>" . implode('', array_fill(0, $cols, '<td></td>')) . "</tr>\n\n";  

?>  
</table>  


<script>  

// make a js array from the php array
images = [  
<?php   

foreach( $images as $v)  
    echo sprintf("\t'%s',\n", $v);  

?>];  

tbl = document.getElementsByTagName('table')[0];  

td = tbl.getElementsByTagName('td');  

// fill the empty table cells with data
for(var i=0; i < images.length; i++)  
    td[i].innerHTML = images[i];  


// event handler to place clicked image into CKeditor
tbl.onclick =   

    function(e) {  

        var tgt = e.target || event.srcElement,  
            url;  

        if( tgt.nodeName != 'IMG' )  
            return;  

        url = '<?php echo $dir;?>' + '/' + tgt.title;  

        this.onclick = null;  

        window.opener.CKEDITOR.tools.callFunction(<?php echo $_GET['CKEditorFuncNum']; ?>, url);  

        window.close();  
    }  
</script>  
</body>  
</html>            

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3

Replace the line

"start": "ng serve -o --port 4300 --configuration=en" with

"start": "node --max_old_space_size=5096 node_modules/@angular/cli/bin/ng serve -o --port 4300 --configuration=en"

NOTE:

  1. port--4300 is not constant depends upon which port you selects.

  2. --max_old_space_size=5096 too not constant; any value 1024,2048,4096 etc

Error: Cannot find module 'webpack'

Just found out that using Atom IDE terminal did not install dependencies locally (probably a bug or just me). Installing git bash externally and running npm commands again worked for me

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

Incase you are running on a non-default port, you may try using --port=<port num> provided --skip-networking is not enabled.

Set System.Drawing.Color values

The Color structure is immutable (as all structures should really be), meaning that the values of its properties cannot be changed once that particular instance has been created.

Instead, you need to create a new instance of the structure with the property values that you want. Since you want to create a color using its component RGB values, you need to use the FromArgb method:

Color myColor = Color.FromArgb(100, 150, 75);

How do I concatenate const/literal strings in C?

You are trying to copy a string into an address that is statically allocated. You need to cat into a buffer.

Specifically:

...snip...

destination

Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.

...snip...

http://www.cplusplus.com/reference/clibrary/cstring/strcat.html

There's an example here as well.

SQL query for extracting year from a date

Edit: due to post-tag 'oracle', the first two queries become irrelevant, leaving 3rd query for oracle.

For MySQL:

SELECT YEAR(ASOFDATE) FROM PASOFDATE

Editted: In anycase if your date is a String, let's convert it into a proper date format. And select the year out of it.

SELECT YEAR(STR_TO_DATE(ASOFDATE, '%d-%b-%Y')) FROM PSASOFDATE

Since you are trying Toad, can you check the following code:

For Oracle:

SELECT EXTRACT (TO_DATE(YEAR, 'MM/DD/YY') FROM ASOFDATE) FROM PSASOFDATE;

Reference:

boto3 client NoRegionError: You must specify a region error only sometimes

For those using CloudFormation template. You can set AWS_DEFAULT_REGION environment variable using UserData and AWS::Region. For example,

MyInstance1:
    Type: AWS::EC2::Instance                
    Properties:                           
        ImageId: ami-04b9e92b5572fa0d1 #ubuntu
        InstanceType: t2.micro
        UserData: 
            Fn::Base64: !Sub |
                    #!/bin/bash -x

                    echo "export AWS_DEFAULT_REGION=${AWS::Region}" >> /etc/profile

How to monitor the memory usage of Node.js?

On Linux/Unix (note: Mac OS is a Unix) use top and press M (Shift+M) to sort processes by memory usage.

On Windows use the Task Manager.

How do I use sudo to redirect output to a location I don't have permission to write to?

A trick I figured out myself was

sudo ls -hal /root/ | sudo dd of=/root/test.out

"SyntaxError: Unexpected token < in JSON at position 0"

The possibilities for this error are overwhelming.

In my case, I found that the issue was adding the homepage filed in package.json caused the issue.

Worth checking: in package.json change:

homepage: "www.example.com"

to

hompage: ""   

What could cause java.lang.reflect.InvocationTargetException?

You've added an extra level of abstraction by calling the method with reflection. The reflection layer wraps any exception in an InvocationTargetException, which lets you tell the difference between an exception actually caused by a failure in the reflection call (maybe your argument list wasn't valid, for example) and a failure within the method called.

Just unwrap the cause within the InvocationTargetException and you'll get to the original one.

Polymorphism vs Overriding vs Overloading

Polymorphism means more than one form, same object performing different operations according to the requirement.

Polymorphism can be achieved by using two ways, those are

  1. Method overriding
  2. Method overloading

Method overloading means writing two or more methods in the same class by using same method name, but the passing parameters is different.

Method overriding means we use the method names in the different classes,that means parent class method is used in the child class.

In Java to achieve polymorphism a super class reference variable can hold the sub class object.

To achieve the polymorphism every developer must use the same method names in the project.

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

The above one with JQuery is the easiest and mostly used way. However you can use pure javascript but try to define this script in the head so that it is read at the beginning. What you are looking for is window.onload event.

Below is a simple script that I created to run a counter. The counter then stops after 10 iterations

window.onload=function()
{
    var counter = 0;
    var interval1 = setInterval(function()
    { 
        document.getElementById("div1").textContent=counter;
        counter++; 
        if(counter==10)
        {
            clearInterval(interval1);
        }
    },1000);

}

How to Convert JSON object to Custom C# object?

Rather than sending as just an object .

Create a public class of properties that is accessible and send the data to the Webmethod.

[WebMethod]
public static void SaveTeam(useSomeClassHere user)
{
}

use same parameters names in ajax call to send data.

What is the proper declaration of main in C++?

The two valid mains are int main() and int main(int, char*[]). Any thing else may or may not compile. If main doesn't explicitly return a value, 0 is implicitly returned.

Sleep function Visual Basic

This one is much easie.

Threading.Thread.Sleep(3000)

Use cases for the 'setdefault' dict method

I use setdefault() when I want a default value in an OrderedDict. There isn't a standard Python collection that does both, but there are ways to implement such a collection.

Add a user control to a wpf window

You need to add a reference inside the window tag. Something like:

xmlns:controls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"

(When you add xmlns:controls=" intellisense should kick in to make this bit easier)

Then you can add the control with:

<controls:CustomControlClassName ..... />

how to play video from url

It has something to do with your link and content. Try the following two links:

    String path="http://www.ted.com/talks/download/video/8584/talk/761";
    String path1="http://commonsware.com/misc/test2.3gp";

    Uri uri=Uri.parse(path1);

    VideoView video=(VideoView)findViewById(R.id.VideoView01);
    video.setVideoURI(uri);
    video.start();

Start with "path1", it is a small light weight video stream and then try the "path", it is a higher resolution than "path1", a perfect high resolution for the mobile phone.

How to replace multiple white spaces with one white space

Here is the Solution i work with. Without RegEx and String.Split.

public static string TrimWhiteSpace(this string Value)
{
    StringBuilder sbOut = new StringBuilder();
    if (!string.IsNullOrEmpty(Value))
    {
        bool IsWhiteSpace = false;
        for (int i = 0; i < Value.Length; i++)
        {
            if (char.IsWhiteSpace(Value[i])) //Comparion with WhiteSpace
            {
                if (!IsWhiteSpace) //Comparison with previous Char
                {
                    sbOut.Append(Value[i]);
                    IsWhiteSpace = true;
                }
            }
            else
            {
                IsWhiteSpace = false;
                sbOut.Append(Value[i]);
            }
        }
    }
    return sbOut.ToString();
}

so you can:

string cleanedString = dirtyString.TrimWhiteSpace();

App.Config Transformation for projects which are not Web Projects in Visual Studio?

If you use a TFS online(Cloud version) and you want to transform the App.Config in a project, you can do the following without installing any extra tools. From VS => Unload the project => Edit project file => Go to the bottom of the file and add the following:

<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="AfterBuild" Condition="Exists('App.$(Configuration).config')">
<TransformXml Source="App.config" Transform="App.$(Configuration).config" Destination="$(OutDir)\$(AssemblyName).dll.config" />

AssemblyFile and Destination works for local use and TFS online(Cloud) server.

How do I copy a hash in Ruby?

I am also a newbie to Ruby and I faced similar issues in duplicating a hash. Use the following. I've got no idea about the speed of this method.

copy_of_original_hash = Hash.new.merge(original_hash)

Convert string to date in Swift

Swift 3.0 - 4.2

import Foundation

extension String {

    func toDate(withFormat format: String = "yyyy-MM-dd HH:mm:ss")-> Date?{

        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
        dateFormatter.locale = Locale(identifier: "fa-IR")
        dateFormatter.calendar = Calendar(identifier: .gregorian)
        dateFormatter.dateFormat = format
        let date = dateFormatter.date(from: self)

        return date

    }
}

extension Date {

    func toString(withFormat format: String = "EEEE ? d MMMM yyyy") -> String {

        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "fa-IR")
        dateFormatter.timeZone = TimeZone(identifier: "Asia/Tehran")
        dateFormatter.calendar = Calendar(identifier: .persian)
        dateFormatter.dateFormat = format
        let str = dateFormatter.string(from: self)

        return str
    }
}

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

How to declare a static const char* in your header file?

To answer the why question, integral types are special in that they are not a reference to an allocated object but rather values that are duplicated and copied. It's just an implementation decision made when the language was defined, which was to handle values outside the object system and in as efficient and "inline" a fashion as possible.

This doesn't exactly explain why they are allowed as initializors in a type, but think of it as essentially a #define and then it will make sense as part of the type and not part of the object.

Run a PostgreSQL .sql file using command line arguments

You have four choices to supply a password:

  1. Set the PGPASSWORD environment variable. For details see the manual:
    http://www.postgresql.org/docs/current/static/libpq-envars.html
  2. Use a .pgpass file to store the password. For details see the manual:
    http://www.postgresql.org/docs/current/static/libpq-pgpass.html
  3. Use "trust authentication" for that specific user: http://www.postgresql.org/docs/current/static/auth-methods.html#AUTH-TRUST
  4. Since PostgreSQL 9.1 you can also use a connection string:
    https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING