Programs & Examples On #Variable types

How can I check if a var is a string in JavaScript?

My personal approach, which seems to work for all cases, is testing for the presence of members that will all only be present for strings.

function isString(x) {
    return (typeof x == 'string' || typeof x == 'object' && x.toUpperCase && x.substr && x.charAt && x.trim && x.replace ? true : false);
}

See: http://jsfiddle.net/x75uy0o6/

I'd like to know if this method has flaws, but it has served me well for years.

Should I use int or Int32

int is the same as System.Int32 and when compiled it will turn into the same thing in CIL.

We use int by convention in C# since C# wants to look like C and C++ (and Java) and that is what we use there...

BTW, I do end up using System.Int32 when declaring imports of various Windows API functions. I am not sure if this is a defined convention or not, but it reminds me that I am going to an external DLL...

Removing numbers from string

And, just to throw it in the mix, is the oft-forgotten str.translate which will work a lot faster than looping/regular expressions:

For Python 2:

from string import digits

s = 'abc123def456ghi789zero0'
res = s.translate(None, digits)
# 'abcdefghizero'

For Python 3:

from string import digits

s = 'abc123def456ghi789zero0'
remove_digits = str.maketrans('', '', digits)
res = s.translate(remove_digits)
# 'abcdefghizero'

Multiple "order by" in LINQ

If use generic repository

> lstModule = _ModuleRepository.GetAll().OrderBy(x => new { x.Level,
> x.Rank}).ToList();

else

> _db.Module.Where(x=> ......).OrderBy(x => new { x.Level, x.Rank}).ToList();

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

Add another option, maybe not the most lightweight.

_x000D_
_x000D_
dayjs.extend(dayjs_plugin_customParseFormat)
console.log(dayjs('2018-09-06 17:00:00').format( 'YYYY-MM-DDTHH:mm:ss.000ZZ'))
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/plugin/customParseFormat.js"></script>
_x000D_
_x000D_
_x000D_

The role of #ifdef and #ifndef

Text inside an ifdef/endif or ifndef/endif pair will be left in or removed by the pre-processor depending on the condition. ifdef means "if the following is defined" while ifndef means "if the following is not defined".

So:

#define one 0
#ifdef one
    printf("one is defined ");
#endif
#ifndef one
    printf("one is not defined ");
#endif

is equivalent to:

printf("one is defined ");

since one is defined so the ifdef is true and the ifndef is false. It doesn't matter what it's defined as. A similar (better in my opinion) piece of code to that would be:

#define one 0
#ifdef one
    printf("one is defined ");
#else
    printf("one is not defined ");
#endif

since that specifies the intent more clearly in this particular situation.

In your particular case, the text after the ifdef is not removed since one is defined. The text after the ifndef is removed for the same reason. There will need to be two closing endif lines at some point and the first will cause lines to start being included again, as follows:

     #define one 0
+--- #ifdef one
|    printf("one is defined ");     // Everything in here is included.
| +- #ifndef one
| |  printf("one is not defined "); // Everything in here is excluded.
| |  :
| +- #endif
|    :                              // Everything in here is included again.
+--- #endif

How to set null value to int in c#?

Use Null.NullInteger ex: private int _ReservationID = Null.NullInteger;

Get JSON data from external URL and display it in a div as plain text

You can use $.ajax call to get the value and then put it in the div you want to. One thing you must know is you cannot receive JSON Data. You have to use JSONP.

Code would be like this:

function CallURL()  {
    $.ajax({
        url: 'https://www.googleapis.com/freebase/v1/text/en/bob_dylan',
        type: "GET",
        dataType: "jsonp",
        async: false,
        success: function(msg)  {
            JsonpCallback(msg);
        },
        error: function()  {
            ErrorFunction();
        }
    });
}

function JsonpCallback(json)  {
    document.getElementById('summary').innerHTML = json.result;
}

Validation of file extension before uploading file

Do you use the input type="file" to choose the uploadfiles? if so, why not use the accept attribute?

<input type="file" name="myImage" accept="image/x-png,image/gif,image/jpeg" />

How to load data to hive from HDFS without removing the source file?

An alternative to 'LOAD DATA' is available in which the data will not be moved from your existing source location to hive data warehouse location.

You can use ALTER TABLE command with 'LOCATION' option. Here is below required command

ALTER TABLE table_name ADD PARTITION (date_col='2017-02-07') LOCATION 'hdfs/path/to/location/'

The only condition here is, the location should be a directory instead of file.

Hope this will solve the problem.

Regular expressions in C: examples?

While the answer above is good, I recommend using PCRE2. This means you can literally use all the regex examples out there now and not have to translate from some ancient regex.

I made an answer for this already, but I think it can help here too..

Regex In C To Search For Credit Card Numbers

// YOU MUST SPECIFY THE UNIT WIDTH BEFORE THE INCLUDE OF THE pcre.h

#define PCRE2_CODE_UNIT_WIDTH 8
#include <stdio.h>
#include <string.h>
#include <pcre2.h>
#include <stdbool.h>

int main(){

bool Debug = true;
bool Found = false;
pcre2_code *re;
PCRE2_SPTR pattern;
PCRE2_SPTR subject;
int errornumber;
int i;
int rc;
PCRE2_SIZE erroroffset;
PCRE2_SIZE *ovector;
size_t subject_length;
pcre2_match_data *match_data;


char * RegexStr = "(?:\\D|^)(5[1-5][0-9]{2}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4})(?:\\D|$)";
char * source = "5111 2222 3333 4444";

pattern = (PCRE2_SPTR)RegexStr;// <<<<< This is where you pass your REGEX 
subject = (PCRE2_SPTR)source;// <<<<< This is where you pass your bufer that will be checked. 
subject_length = strlen((char *)subject);




  re = pcre2_compile(
  pattern,               /* the pattern */
  PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */
  0,                     /* default options */
  &errornumber,          /* for error number */
  &erroroffset,          /* for error offset */
  NULL);                 /* use default compile context */

/* Compilation failed: print the error message and exit. */
if (re == NULL)
  {
  PCRE2_UCHAR buffer[256];
  pcre2_get_error_message(errornumber, buffer, sizeof(buffer));
  printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset,buffer);
  return 1;
  }


match_data = pcre2_match_data_create_from_pattern(re, NULL);

rc = pcre2_match(
  re,
  subject,              /* the subject string */
  subject_length,       /* the length of the subject */
  0,                    /* start at offset 0 in the subject */
  0,                    /* default options */
  match_data,           /* block for storing the result */
  NULL);

if (rc < 0)
  {
  switch(rc)
    {
    case PCRE2_ERROR_NOMATCH: //printf("No match\n"); //
    pcre2_match_data_free(match_data);
    pcre2_code_free(re);
    Found = 0;
    return Found;
    //  break;
    /*
    Handle other special cases if you like
    */
    default: printf("Matching error %d\n", rc); //break;
    }
  pcre2_match_data_free(match_data);   /* Release memory used for the match */
  pcre2_code_free(re);
  Found = 0;                /* data and the compiled pattern. */
  return Found;
  }


if (Debug){
ovector = pcre2_get_ovector_pointer(match_data);
printf("Match succeeded at offset %d\n", (int)ovector[0]);

if (rc == 0)
  printf("ovector was not big enough for all the captured substrings\n");


if (ovector[0] > ovector[1])
  {
  printf("\\K was used in an assertion to set the match start after its end.\n"
    "From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]),
      (char *)(subject + ovector[1]));
  printf("Run abandoned\n");
  pcre2_match_data_free(match_data);
  pcre2_code_free(re);
  return 0;
}

for (i = 0; i < rc; i++)
  {
  PCRE2_SPTR substring_start = subject + ovector[2*i];
  size_t substring_length = ovector[2*i+1] - ovector[2*i];
  printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
  }
}

else{
  if(rc > 0){
    Found = true;

    } 
} 
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return Found;

}

Install PCRE using:

wget https://ftp.pcre.org/pub/pcre/pcre2-10.31.zip
make 
sudo make install 
sudo ldconfig

Compile using :

gcc foo.c -lpcre2-8 -o foo

Check my answer for more details.

SQL MAX of multiple columns?

Either of the two samples below will work:

SELECT  MAX(date_columns) AS max_date
FROM    ( (SELECT   date1 AS date_columns
           FROM     data_table         )
          UNION
          ( SELECT  date2 AS date_columns
            FROM    data_table
          )
          UNION
          ( SELECT  date3 AS date_columns
            FROM    data_table
          )
        ) AS date_query

The second is an add-on to lassevk's answer.

SELECT  MAX(MostRecentDate)
FROM    ( SELECT    CASE WHEN date1 >= date2
                              AND date1 >= date3 THEN date1
                         WHEN date2 >= date1
                              AND date2 >= date3 THEN date2
                         WHEN date3 >= date1
                              AND date3 >= date2 THEN date3
                         ELSE date1
                    END AS MostRecentDate
          FROM      data_table
        ) AS date_query 

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

The sklearn.metrics.accuracy_score(y_true, y_pred) method defines y_pred as:

y_pred : 1d array-like, or label indicator array / sparse matrix. Predicted labels, as returned by a classifier.

Which means y_pred has to be an array of 1's or 0's (predicated labels). They should not be probabilities.

The predicated labels (1's and 0's) and/or predicted probabilites can be generated using the LinearRegression() model's methods predict() and predict_proba() respectively.

1. Generate predicted labels:

LR = linear_model.LinearRegression()
y_preds=LR.predict(X_test)
print(y_preds)

output:

[1 1 0 1]

y_preds can now be used for the accuracy_score() method: accuracy_score(y_true, y_pred)

2. Generate probabilities for labels:

Some metrics such as 'precision_recall_curve(y_true, probas_pred)' require probabilities, which can be generated as follows:

LR = linear_model.LinearRegression()
y_preds=LR.predict_proba(X_test)
print(y_preds)

output:

[0.87812372 0.77490434 0.30319547 0.84999743]

Sleep function in ORACLE

Seems the java procedure/function could work. But why don't you compile your function under a user like the application schema or a admin account that has this grant and just grant your developer account execute on it. That way the definer rights are used.

laravel 5.4 upload image

You can use it by easy way, through store method in your controller

like the below

First, we must create a form with file input to let us upload our file.

{{Form::open(['route' => 'user.store', 'files' => true])}}

{{Form::label('user_photo', 'User Photo',['class' => 'control-label'])}}
{{Form::file('user_photo')}}
{{Form::submit('Save', ['class' => 'btn btn-success'])}}

{{Form::close()}}

Here is how we can handle file in our controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{

  public function store(Request $request)
  {

  // get current time and append the upload file extension to it,
  // then put that name to $photoName variable.
  $photoName = time().'.'.$request->user_photo->getClientOriginalExtension();

  /*
  talk the select file and move it public directory and make avatars
  folder if doesn't exsit then give it that unique name.
  */
  $request->user_photo->move(public_path('avatars'), $photoName);

  }
}

That’s it. Now you can save the $photoName to the database as a user_photo field value. You can use asset(‘avatars’) function in your view and access the photos.

Add Favicon with React and Webpack

Use the file-loader for that:

{
    test: /\.(svg|png|gif|jpg|ico)$/,
    include: path.resolve(__dirname, path),
    use: {
        loader: 'file-loader',
        options: {
            context: 'src/assets',
            name: 'root[path][name].[ext]'
        }
    }
}

How to set only time part of a DateTime variable in C#

I'm not sure exactly what you're trying to do but you can set the date/time to exactly what you want in a number of ways...

You can specify 12/25/2010 4:58 PM by using

DateTime myDate = Convert.ToDateTime("2010-12-25 16:58:00");

OR if you have an existing datetime construct , say 12/25/2010 (and any random time) and you want to set it to 12/25/2010 4:58 PM, you could do so like this:

DateTime myDate = ExistingTime.Date.AddHours(16).AddMinutes(58);

The ExistingTime.Date will be 12/25 at midnight, and you just add hours and minutes to get it to the time you want.

Default SecurityProtocol in .NET 4.5

Some of the those leaving comments have noted that setting System.Net.ServicePointManager.SecurityProtocol to specific values means that your app won't be able to take advantage of future TLS versions that may become the default values in future updates to .NET. Instead of specifying a fixed list of protocols, you can instead turn on or off protocols you know and care about, leaving any others as they are.

To turn on TLS 1.1 and 1.2 without affecting other protocols:

System.Net.ServicePointManager.SecurityProtocol |= 
    SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

Notice the use of |= to turn on these flags without turning others off.

To turn off SSL3 without affecting other protocols:

System.Net.ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;

Parse Json string in C#

Instead of an arraylist or dictionary you can also use a dynamic. Most of the time I use EasyHttp for this, but sure there will by other projects that do the same. An example below:

var http = new HttpClient();
http.Request.Accept = HttpContentTypes.ApplicationJson;
var response = http.Get("url");
var body = response.DynamicBody;
Console.WriteLine("Name {0}", body.AppName.Description);
Console.WriteLine("Name {0}", body.AppName.Value);

On NuGet: EasyHttp

How to do while loops with multiple conditions

while not condition1 or not condition2 or val == -1:

But there was nothing wrong with your original of using an if inside of a while True.

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

From Twitter Bootstrap documentation:

  • small grid (= 768px) = .col-sm-*,
  • medium grid (= 992px) = .col-md-*,
  • large grid (= 1200px) = .col-lg-*.

to Read More...

How can I programmatically get the MAC address of an iphone

Starting from iOS 7, the system always returns the value 02:00:00:00:00:00 when you ask for the MAC address on any device.

In iOS 7 and later, if you ask for the MAC address of an iOS device, the system returns the value 02:00:00:00:00:00. If you need to identify the device, use the identifierForVendor property of UIDevice instead. (Apps that need an identifier for their own advertising purposes should consider using the advertisingIdentifier property of ASIdentifierManager instead.)"

Reference: releasenotes

Angular directives - when and how to use compile, controller, pre-link and post-link

Post-link function

When the post-link function is called, all previous steps have taken place - binding, transclusion, etc.

This is typically a place to further manipulate the rendered DOM.

Do:

  • Manipulate DOM (rendered, and thus instantiated) elements.
  • Attach event handlers.
  • Inspect child elements.
  • Set up observations on attributes.
  • Set up watches on the scope.

How to initialize var?

Well, I think you can assign it to a new object. Something like:

var v = new object();

How to increment datetime by custom months in python without using library

This implementation might have some value for someone who is working with billing.

If you are working with billing, you probably want to get "the same date next month (if possible)" as opposed to "add 1/12 of one year".

What is so confusing about this is you actually need take into account two values if you are doing this continuously. Otherwise for any dates past the 27th, you'll keep losing a few days until you end up at the 27th after leap year.

The values you need to account for:

  • The value you want to add a month to
  • The day you started with

This way if you get bumped from the 31st down to the 30th when you add one month, you'll get bumped back up to the 31st for the next month that has that day.

This is how I did it:

def closest_date_next_month(year, month, day):
    month = month + 1
    if month == 13:
        month = 1
        year  = year + 1


    condition = True
    while condition:
        try:
            return datetime.datetime(year, month, day)
        except ValueError:
            day = day-1
        condition = day > 26

    raise Exception('Problem getting date next month')

paid_until = closest_date_next_month(
                 last_paid_until.year, 
                 last_paid_until.month, 
                 original_purchase_date.day)  # The trick is here, I'm using the original date, that I started adding from, not the last one

Reading int values from SqlDataReader

Use the GetInt method.

reader.GetInt32(3);

How to sort strings in JavaScript

An updated answer (October 2014)

I was really annoyed about this string natural sorting order so I took quite some time to investigate this issue. I hope this helps.

Long story short

localeCompare() character support is badass, just use it. As pointed out by Shog9, the answer to your question is:

return item1.attr.localeCompare(item2.attr);

Bugs found in all the custom javascript "natural string sort order" implementations

There are quite a bunch of custom implementations out there, trying to do string comparison more precisely called "natural string sort order"

When "playing" with these implementations, I always noticed some strange "natural sorting order" choice, or rather mistakes (or omissions in the best cases).

Typically, special characters (space, dash, ampersand, brackets, and so on) are not processed correctly.

You will then find them appearing mixed up in different places, typically that could be:

  • some will be between the uppercase 'Z' and the lowercase 'a'
  • some will be between the '9' and the uppercase 'A'
  • some will be after lowercase 'z'

When one would have expected special characters to all be "grouped" together in one place, except for the space special character maybe (which would always be the first character). That is, either all before numbers, or all between numbers and letters (lowercase & uppercase being "together" one after another), or all after letters.

My conclusion is that they all fail to provide a consistent order when I start adding barely unusual characters (ie. characters with diacritics or charcters such as dash, exclamation mark and so on).

Research on the custom implementations:

Browsers' native "natural string sort order" implementations via localeCompare()

localeCompare() oldest implementation (without the locales and options arguments) is supported by IE6+, see http://msdn.microsoft.com/en-us/library/ie/s4esdbwz(v=vs.94).aspx (scroll down to localeCompare() method). The built-in localeCompare() method does a much better job at sorting, even international & special characters. The only problem using the localeCompare() method is that "the locale and sort order used are entirely implementation dependent". In other words, when using localeCompare such as stringOne.localeCompare(stringTwo): Firefox, Safari, Chrome & IE have a different sort order for Strings.

Research on the browser-native implementations:

Difficulty of "string natural sorting order"

Implementing a solid algorithm (meaning: consistent but also covering a wide range of characters) is a very tough task. UTF8 contains more than 2000 characters & covers more than 120 scripts (languages). Finally, there are some specification for this tasks, it is called the "Unicode Collation Algorithm", which can be found at http://www.unicode.org/reports/tr10/ . You can find more information about this on this question I posted https://softwareengineering.stackexchange.com/questions/257286/is-there-any-language-agnostic-specification-for-string-natural-sorting-order

Final conclusion

So considering the current level of support provided by the javascript custom implementations I came across, we will probably never see anything getting any close to supporting all this characters & scripts (languages). Hence I would rather use the browsers' native localeCompare() method. Yes, it does have the downside of beeing non-consistent across browsers but basic testing shows it covers a much wider range of characters, allowing solid & meaningful sort orders.

So as pointed out by Shog9, the answer to your question is:

return item1.attr.localeCompare(item2.attr);

Further reading:

Thanks to Shog9's nice answer, which put me in the "right" direction I believe

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

Laravel requires the Mcrypt PHP extension

Do you have MAMP installed?

Use which php in the terminal to see which version of PHP you are using.

If it's not the PHP version from MAMP, you should edit or add .bash_profile in the user's home directory, that is : cd ~

In .bash_profile, add following line:

export PATH=/Applications/MAMP/bin/php/php5.4.10/bin:$PATH

Edited: First you should use command cd /Applications/MAMP/bin/php to check which PHP version from MAMP you are using and then replace with the PHP version above.

Then restart the terminal to see which PHP you are using now.

And it should be working now.

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

TypeError: not all arguments converted during string formatting python

Most Easy way typecast string number to integer

number=89
number=int(89)

How to set a default value for an existing column

in case a restriction already exists with its default name:

-- Drop existing default constraint on Employee.CityBorn
DECLARE @default_name varchar(256);
SELECT @default_name = [name] FROM sys.default_constraints WHERE parent_object_id=OBJECT_ID('Employee') AND COL_NAME(parent_object_id, parent_column_id)='CityBorn';
EXEC('ALTER TABLE Employee DROP CONSTRAINT ' + @default_name);

-- Add default constraint on Employee.CityBorn
ALTER TABLE Employee ADD CONSTRAINT df_employee_1 DEFAULT 'SANDNES' FOR CityBorn;

String to LocalDate

As you use Joda Time, you should use DateTimeFormatter:

final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
final LocalDate dt = dtf.parseLocalDate(yourinput);

If using Java 8 or later, then refer to hertzi's answer

Getting attributes of Enum's value

Bryan Rowe and AdamCrawford thanks for your answers!

But if somebody need method for get Discription (not extension) you can use it:

string GetEnumDiscription(Enum EnumValue)
        {
            var type = EnumValue.GetType();
            var memInfo = type.GetMember(EnumValue.ToString());
            var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? ((DescriptionAttribute)attributes[0]).Description : null;
        }

Remove last specific character in a string c#

When you have spaces at the end. you can use beliow.

ProcessStr = ProcessStr.Replace(" ", "");
Emails     = ProcessStr.TrimEnd(';');

adding child nodes in treeview

void treeView(string [] LineString)
    {
        int line = LineString.Length;
        string AssmMark = "";
        string PartMark = "";
        TreeNode aNode;
        TreeNode pNode;
        for ( int i=0 ; i<line ; i++){
            string sLine = LineString[i];
            if ( sLine.StartsWith("ASSEMBLY:") ){
                sLine  = sLine.Replace("ASSEMBLY:","");
                string[] aData = sLine.Split(new char[] {','});
                AssmMark  = aData[0].Trim();
                //TreeNode aNode;
                //aNode = new TreeNode(AssmMark);
                treeView1.Nodes.Add(AssmMark,AssmMark);
            }
            if( sLine.Trim().StartsWith("PART:") ){
                sLine  = sLine.Replace("PART:","");
                string[] pData = sLine.Split(new char[] {','});
                PartMark = pData[0].Trim();
                pNode = new TreeNode(PartMark);
                treeView1.Nodes[AssmMark].Nodes.Add(pNode);
            }
        }

PostgreSQL ERROR: canceling statement due to conflict with recovery

There's no need to start idle transactions on the master. In postgresql-9.1 the most direct way to solve this problem is by setting

hot_standby_feedback = on

This will make the master aware of long-running queries. From the docs:

The first option is to set the parameter hot_standby_feedback, which prevents VACUUM from removing recently-dead rows and so cleanup conflicts do not occur.

Why isn't this the default? This parameter was added after the initial implementation and it's the only way that a standby can affect a master.

PowerShell array initialization

Here's two more ways, both very concise.

$arr1 = @(0) * 20
$arr2 = ,0 * 20

What does "select 1 from" do?

select 1 from table

will return a column of 1's for every row in the table. You could use it with a where statement to check whether you have an entry for a given key, as in:

if exists(select 1 from table where some_column = 'some_value')

What your friend was probably saying is instead of making bulk selects with select * from table, you should specify the columns that you need precisely, for two reasons:

1) performance & you might retrieve more data than you actually need.

2) the query's user may rely on the order of columns. If your table gets updated, the client will receive columns in a different order than expected.

require(vendor/autoload.php): failed to open stream

What you're missing is running composer install, which will import your packages and create the vendor folder, along with the autoload script.

Make sure your relative path is correct. For example the example scripts in PHPMailer are in examples/, below the project root, so the correct relative path to load the composer autoloader from there would be ../vendor/autoload.php.

The autoload.php you found in C:\Windows\SysWOW64\vendor\autoload.php is probably a global composer installation – where you'll usually put things like phpcs, phpunit, phpmd etc.

composer update is not the same thing, and probably not what you want to use. If your code is tested with your current package versions then running update may cause breakages which may require further work and testing, so don't run update unless you have a specific reason to and understand exactly what it means. To clarify further – you should probably only ever run composer update locally, never on your server as it is reasonably likely to break apps in production.

I often see complaints that people can't use composer because they can't run it on their server (e.g. because it's shared and they have no shell access). In that case, you can still use composer: run it locally (an environment that has no such restrictions), and upload the local vendor folder it generates along with all your other PHP scripts.

Running composer update also performs a composer install, and if you do not currently have a vendor folder (normal if you have a fresh checkout of a project), then it will create one, and also overwrite any composer.lock file you already have, updating package versions tagged in it, and this is what is potentially dangerous.

Similarly, if you do not currently have a composer.lock file (e.g. if it was not committed to the project), then composer install also effectively performs a composer update. It's thus vital to understand the difference between the two as they are definitely not interchangeable.

It is also possible to update a single package by naming it, for example:

composer update ramsey/uuid

This will re-resolve the version specified in your composer.json and install it in your vendor folder, and update your composer.lock file to match. This is far less likely to cause problems than a general composer update if you just need a specific update to one package.

It is normal for libraries to not include a composer.lock file of their own; it's up to apps to fix versions, not the libraries they use. As a result, library developers are expected to maintain compatibility with a wider range of host environments than app developers need to. For example, a library might be compatible with Laravel 5, 6, 7, and 8, but an app using it might require Laravel 8 for other reasons.

Composer 2.0 (out soon) should remove any remaining inconsistencies between install and update results.

How to check iOS version?

Basically the same idea as this one https://stackoverflow.com/a/19903595/1937908 but more robust:

#ifndef func_i_system_version_field
#define func_i_system_version_field

inline static int i_system_version_field(unsigned int fieldIndex) {
  NSString* const versionString = UIDevice.currentDevice.systemVersion;
  NSArray<NSString*>* const versionFields = [versionString componentsSeparatedByString:@"."];
  if (fieldIndex < versionFields.count) {
    NSString* const field = versionFields[fieldIndex];
    return field.intValue;
  }
  NSLog(@"[WARNING] i_system_version(%iu): field index not present in version string '%@'.", fieldIndex, versionString);
  return -1; // error indicator
}

#endif

Simply place the above code in a header file.

Usage:

int major = i_system_version_field(0);
int minor = i_system_version_field(1);
int patch = i_system_version_field(2);

How does GPS in a mobile phone work exactly?

GPS, the Global Positioning System run by the United States Military, is free for civilian use, though the reality is that we're paying for it with tax dollars.

However, GPS on cell phones is a bit more murky. In general, it won't cost you anything to turn on the GPS in your cell phone, but when you get a location it usually involves the cell phone company in order to get it quickly with little signal, as well as get a location when the satellites aren't visible (since the gov't requires a fix even if the satellites aren't visible for emergency 911 purposes). It uses up some cellular bandwidth. This also means that for phones without a regular GPS receiver, you cannot use the GPS at all if you don't have cell phone service.

For this reason most cell phone companies have the GPS in the phone turned off except for emergency calls and for services they sell you (such as directions).

This particular kind of GPS is called assisted GPS (AGPS), and there are several levels of assistance used.

GPS

A normal GPS receiver listens to a particular frequency for radio signals. Satellites send time coded messages at this frequency. Each satellite has an atomic clock, and sends the current exact time as well.

The GPS receiver figures out which satellites it can hear, and then starts gathering those messages. The messages include time, current satellite positions, and a few other bits of information. The message stream is slow - this is to save power, and also because all the satellites transmit on the same frequency and they're easier to pick out if they go slow. Because of this, and the amount of information needed to operate well, it can take 30-60 seconds to get a location on a regular GPS.

When it knows the position and time code of at least 3 satellites, a GPS receiver can assume it's on the earth's surface and get a good reading. 4 satellites are needed if you aren't on the ground and you want altitude as well.

AGPS

As you saw above, it can take a long time to get a position fix with a normal GPS. There are ways to speed this up, but unless you're carrying an atomic clock with you all the time, or leave the GPS on all the time, then there's always going to be a delay of between 5-60 seconds before you get a location.

In order to save cost, most cell phones share the GPS receiver components with the cellular components, and you can't get a fix and talk at the same time. People don't like that (especially when there's an emergency) so the lowest form of GPS does the following:

  1. Get some information from the cell phone company to feed to the GPS receiver - some of this is gross positioning information based on what cellular towers can 'hear' your phone, so by this time they already phone your location to within a city block or so.
  2. Switch from cellular to GPS receiver for 0.1 second (or some small, practically unoticable period of time) and collect the raw GPS data (no processing on the phone).
  3. Switch back to the phone mode, and send the raw data to the phone company
  4. The phone company processes that data (acts as an offline GPS receiver) and send the location back to your phone.

This saves a lot of money on the phone design, but it has a heavy load on cellular bandwidth, and with a lot of requests coming it requires a lot of fast servers. Still, overall it can be cheaper and faster to implement. They are reluctant, however, to release GPS based features on these phones due to this load - so you won't see turn by turn navigation here.

More recent designs include a full GPS chip. They still get data from the phone company - such as current location based on tower positioning, and current satellite locations - this provides sub 1 second fix times. This information is only needed once, and the GPS can keep track of everything after that with very little power. If the cellular network is unavailable, then they can still get a fix after awhile. If the GPS satellites aren't visible to the receiver, then they can still get a rough fix from the cellular towers.

But to completely answer your question - it's as free as the phone company lets it be, and so far they do not charge for it at all. I doubt that's going to change in the future. In the higher end phones with a full GPS receiver you may even be able to load your own software and access it, such as with mologogo on a motorola iDen phone - the J2ME development kit is free, and the phone is only $40 (prepaid phone with $5 credit). Unlimited internet is about $10 a month, so for $40 to start and $10 a month you can get an internet tracking system. (Prices circa August 2008)

It's only going to get cheaper and more full featured from here on out...

Re: Google maps and such

Yes, Google maps and all other cell phone mapping systems require a data connection of some sort at varying times during usage. When you move far enough in one direction, for instance, it'll request new tiles from its server. Your average phone doesn't have enough storage to hold a map of the US, nor the processor power to render it nicely. iPhone would be able to if you wanted to use the storage space up with maps, but given that most iPhones have a full time unlimited data plan most users would rather use that space for other things.

Concatenate text files with Windows command line, dropping leading lines

I use this, and it works well for me:

TYPE \\Server\Share\Folder\*.csv >> C:\Folder\ConcatenatedFile.csv

Of course, before every run, you have to DELETE C:\Folder\ConcatenatedFile.csv

The only issue is that if all files have headers, then it will be repeated in all files.

Convert HashBytes to VarChar

Use master.dbo.fn_varbintohexsubstring(0, HashBytes('SHA1', @input), 1, 0) instead of master.dbo.fn_varbintohexstr and then substringing the result.

In fact fn_varbintohexstr calls fn_varbintohexsubstring internally. The first argument of fn_varbintohexsubstring tells it to add 0xF as the prefix or not. fn_varbintohexstr calls fn_varbintohexsubstring with 1 as the first argument internaly.

Because you don't need 0xF, call fn_varbintohexsubstring directly.

Why does python use 'else' after for and while loops?

Because they didn't want to introduce a new keyword to the language. Each one steals an identifier and causes backwards compatibility problems, so it's usually a last resort.

Passing parameters to a JDBC PreparedStatement

You should use the setString() method to set the userID. This both ensures that the statement is formatted properly, and prevents SQL injection:

statement =con.prepareStatement("SELECT * from employee WHERE  userID = ?");
statement.setString(1, userID);

There is a nice tutorial on how to use PreparedStatements properly in the Java Tutorials.

Read Excel sheet in Powershell

Sorry I know this is an old one but still felt like helping out ^_^

Maybe it's the way I read this but assuming the excel sheet 1 is called "London" and has this information; B5="Marleybone" B6="Paddington" B7="Victoria" B8="Hammersmith". And the excel sheet 2 is called "Nottingham" and has this information; C5="Alverton" C6="Annesley" C7="Arnold" C8="Askham". Then I think this code below would work. ^_^

$xlCellTypeLastCell = 11 
$startRow = 5

$excel = new-object -com excel.application
$wb = $excel.workbooks.open("C:\users\administrator\my_test.xls")

for ($i = 1; $i -le $wb.sheets.count; $i++)
    {
        $sh = $wb.Sheets.Item($i)
        $endRow = $sh.UsedRange.SpecialCells($xlCellTypeLastCell).Row
        $col = $col + $i - 1
        $city = $wb.Sheets.Item($i).name
        $rangeAddress = $sh.Cells.Item($startRow, $col).Address() + ":" + $sh.Cells.Item($endRow, $col).Address()
        $sh.Range($rangeAddress).Value2 | foreach{
            New-Object PSObject -Property @{City = $city; Area=$_}
        }
    }

$excel.Workbooks.Close()

This should be the output (without the commas):

City, Area
---- ----
London, Marleybone
London, Paddington
London, Victoria
London, Hammersmith
Nottingham, Alverton
Nottingham, Annesley
Nottingham, Arnold
Nottingham, Askham

ImportError: No module named win32com.client

win32com.client is a part of pywin32

So, download pywin32 from here

C# - How to add an Excel Worksheet programmatically - Office XP / 2003

This is what i used to add addtional worksheet

Workbook workbook = null;
Worksheet worksheet = null;

workbook = app.Workbooks.Add(1);
workbook.Sheets.Add();

Worksheet additionalWorksheet = workbook.ActiveSheet;

Named capturing groups in JavaScript regex?

There is a node.js library called named-regexp that you could use in your node.js projects (on in the browser by packaging the library with browserify or other packaging scripts). However, the library cannot be used with regular expressions that contain non-named capturing groups.

If you count the opening capturing braces in your regular expression you can create a mapping between named capturing groups and the numbered capturing groups in your regex and can mix and match freely. You just have to remove the group names before using the regex. I've written three functions that demonstrate that. See this gist: https://gist.github.com/gbirke/2cc2370135b665eee3ef

Creating a blurring overlay view

I decided to post a written Objective-C version from the accepted answer just to provide more options in this question..

- (UIView *)applyBlurToView:(UIView *)view withEffectStyle:(UIBlurEffectStyle)style andConstraints:(BOOL)addConstraints
{
  //only apply the blur if the user hasn't disabled transparency effects
  if(!UIAccessibilityIsReduceTransparencyEnabled())
  {
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:style];
    UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    blurEffectView.frame = view.bounds;

    [view addSubview:blurEffectView];

    if(addConstraints)
    {
      //add auto layout constraints so that the blur fills the screen upon rotating device
      [blurEffectView setTranslatesAutoresizingMaskIntoConstraints:NO];

      [view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView
                                                       attribute:NSLayoutAttributeTop
                                                       relatedBy:NSLayoutRelationEqual
                                                          toItem:view
                                                       attribute:NSLayoutAttributeTop
                                                      multiplier:1
                                                        constant:0]];

      [view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView
                                                       attribute:NSLayoutAttributeBottom
                                                       relatedBy:NSLayoutRelationEqual
                                                          toItem:view
                                                       attribute:NSLayoutAttributeBottom
                                                      multiplier:1
                                                        constant:0]];

      [view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView
                                                       attribute:NSLayoutAttributeLeading
                                                       relatedBy:NSLayoutRelationEqual
                                                          toItem:view
                                                       attribute:NSLayoutAttributeLeading
                                                      multiplier:1
                                                        constant:0]];

      [view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView
                                                       attribute:NSLayoutAttributeTrailing
                                                       relatedBy:NSLayoutRelationEqual
                                                          toItem:view
                                                       attribute:NSLayoutAttributeTrailing
                                                      multiplier:1
                                                        constant:0]];
    }
  }
  else
  {
    view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
  }

  return view;
}

The constraints could be removed if you want incase if you only support portrait mode or I just add a flag to this function to use them or not..

Installing tkinter on ubuntu 14.04

Install the package python-tk like

sudo apt-get install python-tk

That is described (with apt-cache search python-tk as)

Tkinter - Writing Tk applications with Python

Why am I not getting a java.util.ConcurrentModificationException in this example?

This snippet will always throw a ConcurrentModificationException.

The rule is "You may not modify (add or remove elements from the list) while iterating over it using an Iterator (which happens when you use a for-each loop)".

JavaDocs:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

Hence if you want to modify the list (or any collection in general), use iterator, because then it is aware of the modifications and hence those will be handled properly.

Hope this helps.

How do I display a text file content in CMD?

If you want to display for example all .config (or .ini) file name and file content into one doc for user reference (and by this I mean user not knowing shell command i.e. 95% of them), you can try this :

FORFILES /M *myFile.ini /C "cmd /c echo File name : @file >> %temp%\stdout.txt && type @path >> %temp%\stdout.txt && echo. >> %temp%\stdout.txt" | type %temp%\stdout.txt

Explanation :

  • ForFiles : loop on a directory (and child, etc) each file meeting criteria
    • able to return the current file name being process (@file)
    • able to return the full path file being process (@path)
  • Type : Output the file content

Ps : The last pipe command is pointing the %temp% file and output the aggregate content. If you wish to copy/paste in some documentation, just open the stdout.txt file in textpad.

Port 443 in use by "Unable to open process" with PID 4

I had the same problem. Another way to solve this problem when running XAMPP on Windows:

  1. Open a CMD prompt and type in command: net stop was /y

  2. Run Dialog Box (press keys Win+R) .. then type: services.msc

I then scrolled down to: World Wide Web Publishing Service Double clicked on it and clicked STOP (if this service status is Started)

3.Start Apache again with XAMPP :)

Link Ref: http://www.sitepoint.com/unblock-port-80-on-windows-run-apache/

Selecting only first-level elements in jquery

Try this:

$("#myId > UL > LI")

How to use the curl command in PowerShell?

Use splatting.

$CurlArgument = '-u', '[email protected]:yyyy',
                '-X', 'POST',
                'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
                '--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument

How to convert CSV file to multiline JSON?

I see this is old but I needed the code from SingleNegationElimination however I had issue with the data containing non utf-8 characters. These appeared in fields I was not overly concerned with so I chose to ignore them. However that took some effort. I am new to python so with some trial and error I got it to work. The code is a copy of SingleNegationElimination with the extra handling of utf-8. I tried to do it with https://docs.python.org/2.7/library/csv.html but in the end gave up. The below code worked.

import csv, json

csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')

fieldnames = ("Scope","Comment","OOS Code","In RMF","Code","Status","Name","Sub Code","CAT","LOB","Description","Owner","Manager","Platform Owner")
reader = csv.DictReader(csvfile , fieldnames)

code = ''
for row in reader:
    try:
        print('+' + row['Code'])
        for key in row:
            row[key] = row[key].decode('utf-8', 'ignore').encode('utf-8')      
        json.dump(row, jsonfile)
        jsonfile.write('\n')
    except:
        print('-' + row['Code'])
        raise

HTML/CSS: how to put text both right and left aligned in a paragraph

enter image description here

If the texts has different sizes and they must be underlined this is the solution:

<table>
  <tr>
    <td class='left'>January</td>
    <td class='right'>2014</td>
  </tr>
</table>

css:

table{
    width: 100%;
    border-bottom: 2px solid black;
    /*this is the size of the small text's baseline over part  (˜25px*3/4)*/
    line-height: 19.5px; 
}
table td{
    vertical-align: baseline;
}
.left{
    font-family: Arial;
    font-size: 40px;
    text-align: left;

}
.right{
    font-size: 25px;
    text-align: right;
}

demo here

Best way to convert text files between character sets?

Simply change encoding of loaded file in IntelliJ IDEA IDE, on the right of status bar (bottom), where current charset is indicated. It prompts to Reload or Convert, use Convert. Make sure you backed up original file in advance.

How can I use tabs for indentation in IntelliJ IDEA?

Another useful option in IDEA to switch off or keep checked if you really need that:

Preferences -> Code Style -> Detect and use existing file indents for editing

if your team is going to switch to tab formatting with existing code written with spaces, uncheck that

How to use MySQLdb with Python and Django in OSX 10.6?

I encountered similar situations like yours that I am using python3.7 and django 2.1 in virtualenv on mac osx. Try to run command:

pip install mysql-python
pip install pymysql

And edit __init__.py file in your project folder and add following:

import pymysql

pymysql.install_as_MySQLdb()

Then run: python3 manage.py runserver or python manage.py runserver

Setting up Vim for Python

There is a bundled collection of Vim plugins for Python development: http://www.vim.org/scripts/script.php?script_id=3770

How to install gdb (debugger) in Mac OSX El Capitan?

On my Mac OS X El Capitan, I use homebrew to install gdb:

brew install gdb

Then I follow the instruction here: https://sourceware.org/gdb/wiki/BuildingOnDarwin, in the section 2.1. Method for Mac OS X 10.5 (Leopard) and later.

How to simulate a button click using code?

Android's callOnClick() (added in API 15) can sometimes be a better choice in my experience than performClick(). If a user has selection sounds enabled, then performClick() could cause the user to hear two continuous selection sounds that are somewhat layered on top of each other which can be jarring. (One selection sound for the user's first button click, and then another for the other button's OnClickListener that you're calling via code.)

How to set opacity to the background color of a div?

You can use CSS3 RGBA in this way:

rgba(255, 0, 0, 0.7);

0.7 means 70% opacity.

Meaning of tilde in Linux bash (not home directory)

It's a Bash feature called "tilde expansion". It's a function of the shell, not the OS. You'll get different behavior with csh, for example.

To answer your question about where the information comes from: your home directory comes from the variable $HOME (no matter what you store there), while other user's homes are retrieved real-time using getpwent(). This function is usually controlled by NSS; so by default values are pulled out of /etc/passwd, though it can be configured to retrieve the information using any source desired, such as NIS, LDAP or an SQL database.

Tilde expansion is more than home directory lookup. Here's a summary:

~              $HOME
~fred          (freds home dir)

~+             $PWD       (your current working directory)
~-             $OLDPWD    (your previous directory)
~1             `dirs +1`
~2             `dirs +2`
~-1            `dirs -1`

dirs and ~1, ~-1, etc., are used in conjunction with pushd and popd.

Declaring static constants in ES6 classes?

You can make the "constants" read-only (immutable) by freezing the class. e.g.

class Foo {
    static BAR = "bat"; //public static read-only
}

Object.freeze(Foo); 

/*
Uncaught TypeError: Cannot assign to read only property 'BAR' of function 'class Foo {
    static BAR = "bat"; //public static read-only
}'
*/
Foo.BAR = "wut";

Spring Security redirect to previous page after successful login

In order to redirect to a specific page no matter what the user role is, one can simply use defaultSucessUrl in the configuration file of Spring.

@Override
protected void configure(HttpSecurity http) throws Exception {
    
    
      http.authorizeRequests() 
      .antMatchers("/admin").hasRole("ADMIN") 
      .and()
      .formLogin() .loginPage("/login") 
                    .defaultSuccessUrl("/admin",true)
      .loginProcessingUrl("/authenticateTheUser")
      .permitAll();
     
    

Java Read Large Text File With 70million line of text

I tried the following three methods, my file size is 1M, and I got results:

enter image description here

I run the program several times it looks that BufferedReader is faster.

@Test
public void testLargeFileIO_Scanner() throws Exception {

    long start = new Date().getTime();

    String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
    InputStream inputStream = new FileInputStream(fileName);

    try (Scanner fileScanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
        while (fileScanner.hasNextLine()) {
            String line = fileScanner.nextLine();
            //System.out.println(line);
        }
    }
    long end = new Date().getTime();

    long time = end - start;
    System.out.println("Scanner Time Consumed => " + time);

}


@Test
 public void testLargeFileIO_BufferedReader() throws Exception {

    long start = new Date().getTime();

    String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
    try (BufferedReader fileBufferReader = new BufferedReader(new FileReader(fileName))) {
        String fileLineContent;
        while ((fileLineContent = fileBufferReader.readLine()) != null) {
            //System.out.println(fileLineContent);
        }
    }
    long end = new Date().getTime();

    long time = (long) (end - start);
    System.out.println("BufferedReader Time Consumed => " + time);

}


@Test
public void testLargeFileIO_Stream() throws Exception {

    long start = new Date().getTime();

    String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
    try (Stream inputStream = Files.lines(Paths.get(fileName), StandardCharsets.UTF_8)) {
        //inputStream.forEach(System.out::println);
    }
    long end = new Date().getTime();

    long time = end - start;
    System.out.println("Stream Time Consumed => " + time);

}

SSRS Conditional Formatting Switch or IIF

To dynamically change the color of a text box goto properties, goto font/Color and set the following expression

=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)

Same way for tolerance

=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")

Hiding and Showing TabPages in tabControl

You Can Use the Following

tabcontainer.tabs(1).visible=true

1 is tabindex

How to compare two columns in Excel and if match, then copy the cell next to it

It might be easier with vlookup. Try this:

=IFERROR(VLOOKUP(D2,G:H,2,0),"")

The IFERROR() is for no matches, so that it throws "" in such cases.

VLOOKUP's first parameter is the value to 'look for' in the reference table, which is column G and H.

VLOOKUP will thus look for D2 in column G and return the value in the column index 2 (column G has column index 1, H will have column index 2), meaning that the value from column H will be returned.

The last parameter is 0 (or equivalently FALSE) to mean an exact match. That's what you need as opposed to approximate match.

Remove icon/logo from action bar on android

If you do not want the icon in particular activity.

getActionBar().setIcon(
   new ColorDrawable(getResources().getColor(android.R.color.transparent)));    

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

With my centos 6.7 installation, not only did I have the problem starting httpd with root but also with xauth (getting /usr/bin/xauth: timeout in locking authority file /.Xauthority with underlying permission denied errors)

# setenforce 0

Fixed both issues.

Android - save/restore fragment state

I'm not quite sure if this question is still bothering you, since it has been several months. But I would like to share how I dealt with this. Here is the source code:

int FLAG = 0;
private View rootView;
private LinearLayout parentView;

/**
 * The fragment argument representing the section number for this fragment.
 */
private static final String ARG_SECTION_NUMBER = "section_number";

/**
 * Returns a new instance of this fragment for the given section number.
 */
public static Fragment2 newInstance(Bundle bundle) {
    Fragment2 fragment = new Fragment2();
    Bundle args = bundle;
    fragment.setArguments(args);
    return fragment;
}

public Fragment2() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    Log.e("onCreateView","onCreateView");
    if(FLAG!=12321){
        rootView = inflater.inflate(R.layout.fragment_create_new_album, container, false);
        changeFLAG(12321);
    }       
    parentView=new LinearLayout(getActivity());
    parentView.addView(rootView);

    return parentView;
}

/* (non-Javadoc)
 * @see android.support.v4.app.Fragment#onDestroy()
 */
@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    Log.e("onDestroy","onDestroy");
}

/* (non-Javadoc)
 * @see android.support.v4.app.Fragment#onStart()
 */
@Override
public void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
    Log.e("onstart","onstart");
}

/* (non-Javadoc)
 * @see android.support.v4.app.Fragment#onStop()
 */
@Override
public void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
    if(false){
        Bundle savedInstance=getArguments();
        LinearLayout viewParent;

        viewParent= (LinearLayout) rootView.getParent();
        viewParent.removeView(rootView);

    }
    parentView.removeView(rootView);

    Log.e("onStop","onstop");
}
@Override
public void onPause() {
    super.onPause();
    Log.e("onpause","onpause");
}

@Override
public void onResume() {
    super.onResume();
    Log.e("onResume","onResume");
}

And here is the MainActivity:

/**
 * Fragment managing the behaviors, interactions and presentation of the
 * navigation drawer.
 */
private NavigationDrawerFragment mNavigationDrawerFragment;

/**
 * Used to store the last screen title. For use in
 * {@link #restoreActionBar()}.
 */

public static boolean fragment2InstanceExists=false;
public static Fragment2 fragment2=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    setContentView(R.layout.activity_main);

    mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
            .findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));
}

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
    switch(position){
    case 0:
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(R.id.container, Fragment1.newInstance(position+1)).commit();
        break;
    case 1:

        Bundle bundle=new Bundle();
        bundle.putInt("source_of_create",CommonMethods.CREATE_FROM_ACTIVITY);

        if(!fragment2InstanceExists){
            fragment2=Fragment2.newInstance(bundle);
            fragment2InstanceExists=true;
        }
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(R.id.container, fragment2).commit();

        break;
    case 2:
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(R.id.container, FolderExplorerFragment.newInstance(position+1)).commit();
        break;
    default: 
        break;
    }
}

The parentView is the keypoint. Normally, when onCreateView, we just use return rootView. But now, I add rootView to parentView, and then return parentView. To prevent "The specified child already has a parent. You must call removeView() on the ..." error, we need to call parentView.removeView(rootView), or the method I supplied is useless. I also would like to share how I found it. Firstly, I set up a boolean to indicate if the instance exists. When the instance exists, the rootView will not be inflated again. But then, logcat gave the child already has a parent thing, so I decided to use another parent as a intermediate Parent View. That's how it works.

Hope it's helpful to you.

How to run php files on my computer

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

Show row number in row header of a DataGridView

You can also draw the string dynamically inside the RowPostPaint event:

private void dgGrid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    var grid = sender as DataGridView;
    var rowIdx = (e.RowIndex + 1).ToString();

    var centerFormat = new StringFormat() 
    { 
        // right alignment might actually make more sense for numbers
        Alignment = StringAlignment.Center, 
        LineAlignment = StringAlignment.Center
    };

    var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
    e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}

How to print multiple lines of text with Python

I wanted to answer to the following question which is a little bit different than this:

Best way to print messages on multiple lines

He wanted to show lines from repeated characters too. He wanted this output:

----------------------------------------
# Operator Micro-benchmarks
# Run_mode: short
# Num_repeats: 5
# Num_runs: 1000

----------------------------------------

You can create those lines inside f-strings with a multiplication, like this:

run_mode, num_repeats, num_runs = 'short', 5, 1000

s = f"""
{'-'*40}
# Operator Micro-benchmarks
# Run_mode: {run_mode}
# Num_repeats: {num_repeats}
# Num_runs: {num_runs}

{'-'*40}
"""

print(s)

Android list view inside a scroll view

You Create Custom ListView Which is non Scrollable

  public class NonScrollListView extends ListView {

            public NonScrollListView(Context context) {
                super(context);
            }
            public NonScrollListView(Context context, AttributeSet attrs) {
                super(context, attrs);
            }
            public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
                super(context, attrs, defStyle);
            }
            @Override
            public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                    int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
                            Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
                    super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
                    ViewGroup.LayoutParams params = getLayoutParams();
                    params.height = getMeasuredHeight();    
            }
        }

In Your Layout Resources File

     <?xml version="1.0" encoding="utf-8"?>
        <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fadingEdgeLength="0dp"
            android:fillViewport="true"
            android:overScrollMode="never"
            android:scrollbars="none" >

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

                <!-- com.Example Changed with your Package name -->

                <com.Example.NonScrollListView
                    android:id="@+id/lv_nonscroll_list"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" >
                </com.Example.NonScrollListView>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/lv_nonscroll_list" >

                    <!-- Your another layout in scroll view -->

                </RelativeLayout>
            </RelativeLayout>

        </ScrollView>

In Java File Create a object of your customListview instead of ListView like : NonScrollListView non_scroll_list = (NonScrollListView) findViewById(R.id.lv_nonscroll_list);

UPDATE with CASE and IN - Oracle

"The list are variables/paramaters that is pre-defined as comma separated lists". Do you mean that your query is actually

UPDATE tab1   SET budgpost_gr1=     
CASE  WHEN (budgpost in ('1001,1012,50055'))  THEN 'BP_GR_A'   
      WHEN (budgpost in ('5,10,98,0'))  THEN 'BP_GR_B'  
      WHEN (budgpost in ('11,876,7976,67465'))     
      ELSE 'Missing' END`

If so, you need a function to take a string and parse it into a list of numbers.

create type tab_num is table of number;

create or replace function f_str_to_nums (i_str in varchar2) return tab_num is
  v_tab_num tab_num := tab_num();
  v_start   number := 1;
  v_end     number;
  v_delim   VARCHAR2(1) := ',';
  v_cnt     number(1) := 1;
begin
  v_end := instr(i_str||v_delim,v_delim,1, v_start);
  WHILE v_end > 0 LOOP
    v_cnt := v_cnt + 1;
    v_tab_num.extend;
    v_tab_num(v_tab_num.count) := 
                  substr(i_str,v_start,v_end-v_start);
    v_start := v_end + 1;
    v_end := instr(i_str||v_delim,v_delim,v_start);
  END LOOP;
  RETURN v_tab_num;
end;
/

Then you can use the function like so:

select column_id, 
   case when column_id in 
     (select column_value from table(f_str_to_nums('1,2,3,4'))) then 'red' 
   else 'blue' end
from  user_tab_columns
where table_name = 'EMP'

C# int to enum conversion

if (Enum.IsDefined(typeof(foo), value))
{
   return (Foo)Enum.Parse(typeof(foo), value);
}

Hope this helps

Edit This answer got down voted as value in my example is a string, where as the question asked for an int. My applogies; the following should be a bit clearer :-)

Type fooType = typeof(foo);

if (Enum.IsDefined(fooType , value.ToString()))
{
   return (Foo)Enum.Parse(fooType , value.ToString());
}

How to Set focus to first text input in a bootstrap modal after shown

I found the best way to do this, without jQuery.

<input value="" autofocus>

works perfectly.

This is a html5 attribute. Supported by all major browsers.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input

How do I change the font size of a UILabel in Swift?

Programmatically

label.font = UIFont.systemFont(ofSize: 20.0)
label.font = UIFont.boldSystemFont(ofSize: 20.0)
label.font = UIFont.italicSystemFont(ofSize: 20.0)

label.font = UIFont(name:"Helvetica Neue", size: 20.0)//Set your font name here

Through Story board

To display multiple lines set 0(Zero), this will display more than one line in your label.

If you want to display only 2 lines set 2.

enter image description here

If you want to set minimum font size for label Click Autoshrink and Select Minimum Font Size option

See below screens

enter image description here

Here set minimum font size

EX: 9 (In this image)

If your label get more text at that time your label text will be shrink upto 9

enter image description here

iFrame onload JavaScript event

_x000D_
_x000D_
document.querySelector("iframe").addEventListener( "load", function(e) {_x000D_
_x000D_
    this.style.backgroundColor = "red";_x000D_
    alert(this.nodeName);_x000D_
_x000D_
    console.log(e.target);_x000D_
_x000D_
} );
_x000D_
<iframe src="example.com" ></iframe>
_x000D_
_x000D_
_x000D_

Can I restore a single table from a full mysql mysqldump file?

The chunks of SQL are blocked off with "Table structure for table my_table" and "Dumping data for table my_table."

You can use a Windows command line as follows to get the line numbers for the various sections. Adjust the searched string as needed.

find /n "for table `" sql.txt

The following will be returned:

---------- SQL.TXT

[4384]-- Table structure for table my_table

[4500]-- Dumping data for table my_table

[4514]-- Table structure for table some_other_table

... etc.

That gets you the line numbers you need... now, if I only knew how to use them... investigating.

How to update Ruby to 1.9.x on Mac?

As The Tin Man suggests (above) RVM (Ruby Version Manager) is the Standard for upgrading your Ruby installation on OSX: https://rvm.io

To get started, open a Terminal Window and issue the following command:

\curl -L https://get.rvm.io | bash -s stable --ruby

( you will need to trust the RVM Dev Team that the command is not malicious - if you're a paranoid penguin like me, you can always go read the source: https://github.com/wayneeseguin/rvm ) When it's complete you need to restart the terminal to get the rvm command working.

rvm list known

( shows you the latest available versions of Ruby )

rvm install ruby-2.3.1

For a specific version, followed by

rvm use ruby-2.3.1

or if you just want the latest (current) version:

rvm install current && rvm use current

( installs the current stable release - at time of writing ruby-2.3.1 - please update this wiki when new versions released )

Note on Compiling Ruby: In my case I also had to install Homebrew http://mxcl.github.com/homebrew/ to get the gems I needed (RSpec) which in turn forces you to install Xcode (if you haven't already) https://itunes.apple.com/us/app/xcode/id497799835 AND/OR install the GCC package from: https://github.com/kennethreitz/osx-gcc-installer to avoid errors running "make".

Edit: As of Mavericks you can choose to install only the Xcode command line tools instead of the whole Xcode package, which comes with gcc and lots of other things you might need for building packages. It can be installed by running xcode-select --install and following the on-screen prompt.

Note on erros: if you get the error "RVM is not a function" while trying this command, visit: How do I change my Ruby version using RVM? for the solution.

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

Use the backslash before db on the header and you can use it then typically as you wrote it before.

Here is the example:

Use \DB;

Then inside your controller class you can use as you did before, like that ie :

$item = DB::table('items')->get();

Why functional languages?

My view is that it will catch on now that Microsoft have pushed it much further into the mainstream. For me it's attractive because of what it can do for us, because it's a new challenge and because of the job opportunities it resents for the future.

Once mastered it will be another tool to further help make us more productive as programmers.

%i or %d to print integer in C using printf()?

As others said, they produce identical output on printf, but behave differently on scanf. I would prefer %d over %i for this reason. A number that is printed with %d can be read in with %d and you will get the same number. That is not always true with %i, if you ever choose to use zero padding. Because it is common to copy printf format strings into scanf format strings, I would avoid %i, since it could give you a surprising bug introduction:

I write fprintf("%i ...", ...);

You copy and write fscanf(%i ...", ...);

I decide I want to align columns more nicely and make alphabetization behave the same as sorting: fprintf("%03i ...", ...); (or %04d)

Now when you read my numbers, anything between 10 and 99 is interpreted in octal. Oops.

If you want decimal formatting, just say so.

Why can't non-default arguments follow default arguments?

SyntaxError: non-default argument follows default argument

If you were to allow this, the default arguments would be rendered useless because you would never be able to use their default values, since the non-default arguments come after.

In Python 3 however, you may do the following:

def fun1(a="who is you", b="True", *, x, y):
    pass

which makes x and y keyword only so you can do this:

fun1(x=2, y=2)

This works because there is no longer any ambiguity. Note you still can't do fun1(2, 2) (that would set the default arguments).

java.util.Date vs java.sql.Date

Congratulations, you've hit my favorite pet peeve with JDBC: Date class handling.

Basically databases usually support at least three forms of datetime fields which are date, time and timestamp. Each of these have a corresponding class in JDBC and each of them extend java.util.Date. Quick semantics of each of these three are the following:

  • java.sql.Date corresponds to SQL DATE which means it stores years, months and days while hour, minute, second and millisecond are ignored. Additionally sql.Date isn't tied to timezones.
  • java.sql.Time corresponds to SQL TIME and as should be obvious, only contains information about hour, minutes, seconds and milliseconds.
  • java.sql.Timestamp corresponds to SQL TIMESTAMP which is exact date to the nanosecond (note that util.Date only supports milliseconds!) with customizable precision.

One of the most common bugs when using JDBC drivers in relation to these three types is that the types are handled incorrectly. This means that sql.Date is timezone specific, sql.Time contains current year, month and day et cetera et cetera.

Finally: Which one to use?

Depends on the SQL type of the field, really. PreparedStatement has setters for all three values, #setDate() being the one for sql.Date, #setTime() for sql.Time and #setTimestamp() for sql.Timestamp.

Do note that if you use ps.setObject(fieldIndex, utilDateObject); you can actually give a normal util.Date to most JDBC drivers which will happily devour it as if it was of the correct type but when you request the data afterwards, you may notice that you're actually missing stuff.

I'm really saying that none of the Dates should be used at all.

What I am saying that save the milliseconds/nanoseconds as plain longs and convert them to whatever objects you are using (obligatory joda-time plug). One hacky way which can be done is to store the date component as one long and time component as another, for example right now would be 20100221 and 154536123. These magic numbers can be used in SQL queries and will be portable from database to another and will let you avoid this part of JDBC/Java Date API:s entirely.

IE6/IE7 css border on select element

It works!!! Use the following code:

<style>
div.select-container{
   border: 1px black;width:200px;
}
</style>


<div id="status" class="select-container">
    <select name="status">
        <option value="" >Please Select...</option>
        <option value="option1">Option 1</option>
        <option value="option2">Option 2</option>
    </select>
</div>

How can I use break or continue within for loop in Twig template?

This can be nearly done by setting a new variable as a flag to break iterating:

{% set break = false %}
{% for post in posts if not break %}
    <h2>{{ post.heading }}</h2>
    {% if post.id == 10 %}
        {% set break = true %}
    {% endif %}
{% endfor %}

An uglier, but working example for continue:

{% set continue = false %}
{% for post in posts %}
    {% if post.id == 10 %}
        {% set continue = true %}
    {% endif %}
    {% if not continue %}
        <h2>{{ post.heading }}</h2>
    {% endif %}
    {% if continue %}
        {% set continue = false %}
    {% endif %}
{% endfor %}

But there is no performance profit, only similar behaviour to the built-in break and continue statements like in flat PHP.

env: node: No such file or directory in mac

NOTE: Only mac users!

  1. uninstall node completely with the commands
curl -ksO https://gist.githubusercontent.com/nicerobot/2697848/raw/uninstall-node.sh
chmod +x ./uninstall-node.sh
./uninstall-node.sh
rm uninstall-node.sh

Or you could check out this website: How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

if this doesn't work, you need to remove node via control panel or any other method. As long as it gets removed.

  1. Install node via this website: https://nodejs.org/en/download/

If you use nvm, you can use:

nvm install node

You can already check if it works, then you don't need to take the following steps with: npm -v and then node -v

if you have nvm installed: command -v nvm

  1. Uninstall npm using the following command:

sudo npm uninstall npm -g

Or, if that fails, get the npm source code, and do:

sudo make uninstall

If you have nvm installed, then use: nvm uninstall npm

  1. Install npm using the following command: npm install -g grunt

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

It's the index column, pass pd.to_csv(..., index=False) to not write out an unnamed index column in the first place, see the to_csv() docs.

Example:

In [37]:
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
pd.read_csv(io.StringIO(df.to_csv()))

Out[37]:
   Unnamed: 0         a         b         c
0           0  0.109066 -1.112704 -0.545209
1           1  0.447114  1.525341  0.317252
2           2  0.507495  0.137863  0.886283
3           3  1.452867  1.888363  1.168101
4           4  0.901371 -0.704805  0.088335

compare with:

In [38]:
pd.read_csv(io.StringIO(df.to_csv(index=False)))

Out[38]:
          a         b         c
0  0.109066 -1.112704 -0.545209
1  0.447114  1.525341  0.317252
2  0.507495  0.137863  0.886283
3  1.452867  1.888363  1.168101
4  0.901371 -0.704805  0.088335

You could also optionally tell read_csv that the first column is the index column by passing index_col=0:

In [40]:
pd.read_csv(io.StringIO(df.to_csv()), index_col=0)

Out[40]:
          a         b         c
0  0.109066 -1.112704 -0.545209
1  0.447114  1.525341  0.317252
2  0.507495  0.137863  0.886283
3  1.452867  1.888363  1.168101
4  0.901371 -0.704805  0.088335

Draw path between two points using Google Maps Android API v2

Try below solution to draw path with animation and also get time and distance between two points.

DirectionHelper.java

public class DirectionHelper {

    public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

        List<List<HashMap<String, String>>> routes = new ArrayList<>();
        JSONArray jRoutes;
        JSONArray jLegs;
        JSONArray jSteps;
        JSONObject jDistance = null;
        JSONObject jDuration = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<>();

                /** Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {

                    /** Getting distance from the json data */
                    jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    HashMap<String, String> hmDistance = new HashMap<String, String>();
                    hmDistance.put("distance", jDistance.getString("text"));

                    /** Getting duration from the json data */
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    HashMap<String, String> hmDuration = new HashMap<String, String>();
                    hmDuration.put("duration", jDuration.getString("text"));

                    /** Adding distance object to the path */
                    path.add(hmDistance);

                    /** Adding duration object to the path */
                    path.add(hmDuration);

                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = "";
                        polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for (int l = 0; l < list.size(); l++) {
                            HashMap<String, String> hm = new HashMap<>();
                            hm.put("lat", Double.toString((list.get(l)).latitude));
                            hm.put("lng", Double.toString((list.get(l)).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

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


        return routes;
    }

    //Method to decode polyline points
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}

GetPathFromLocation.java

public class GetPathFromLocation extends AsyncTask<String, Void, List<List<HashMap<String, String>>>> {

    private Context context;
    private String TAG = "GetPathFromLocation";
    private LatLng source, destination;
    private ArrayList<LatLng> wayPoint;
    private GoogleMap mMap;
    private boolean animatePath, repeatDrawingPath;
    private DirectionPointListener resultCallback;
    private ProgressDialog progressDialog;

    //https://www.mytrendin.com/draw-route-two-locations-google-maps-android/
    //https://www.androidtutorialpoint.com/intermediate/google-maps-draw-path-two-points-using-google-directions-google-map-android-api-v2/

    public GetPathFromLocation(Context context, LatLng source, LatLng destination, ArrayList<LatLng> wayPoint, GoogleMap mMap, boolean animatePath, boolean repeatDrawingPath, DirectionPointListener resultCallback) {
        this.context = context;
        this.source = source;
        this.destination = destination;
        this.wayPoint = wayPoint;
        this.mMap = mMap;
        this.animatePath = animatePath;
        this.repeatDrawingPath = repeatDrawingPath;
        this.resultCallback = resultCallback;
    }

    synchronized public String getUrl(LatLng source, LatLng dest, ArrayList<LatLng> wayPoint) {

        String url = "https://maps.googleapis.com/maps/api/directions/json?sensor=false&mode=driving&origin="
                + source.latitude + "," + source.longitude + "&destination=" + dest.latitude + "," + dest.longitude;
        for (int centerPoint = 0; centerPoint < wayPoint.size(); centerPoint++) {
            if (centerPoint == 0) {
                url = url + "&waypoints=optimize:true|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            } else {
                url = url + "|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            }
        }
        url = url + "&key=" + context.getResources().getString(R.string.google_api_key);

        return url;
    }

    public int getRandomColor() {
        Random rnd = new Random();
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Please wait...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... url) {

        String data;

        try {
            InputStream inputStream = null;
            HttpURLConnection connection = null;
            try {
                URL directionUrl = new URL(getUrl(source, destination, wayPoint));
                connection = (HttpURLConnection) directionUrl.openConnection();
                connection.connect();
                inputStream = connection.getInputStream();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();

                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }

                data = stringBuffer.toString();
                bufferedReader.close();

            } catch (Exception e) {
                Log.e(TAG, "Exception : " + e.toString());
                return null;
            } finally {
                inputStream.close();
                connection.disconnect();
            }
            Log.e(TAG, "Background Task data : " + data);

            //Second AsyncTask

            JSONObject jsonObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jsonObject = new JSONObject(data);
                // Starts parsing data
                DirectionHelper helper = new DirectionHelper();
                routes = helper.parse(jsonObject);
                Log.e(TAG, "Executing Routes : "/*, routes.toString()*/);

                return routes;

            } catch (Exception e) {
                Log.e(TAG, "Exception in Executing Routes : " + e.toString());
                return null;
            }

        } catch (Exception e) {
            Log.e(TAG, "Background Task Exception : " + e.toString());
            return null;
        }
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        super.onPostExecute(result);

        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        ArrayList<LatLng> points;
        PolylineOptions lineOptions = null;
        String distance = "";
        String duration = "";

        // Traversing through all the routes
        for (int i = 0; i < result.size(); i++) {
            points = new ArrayList<>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);

                if (j == 0) {    // Get distance from the list
                    distance = (String) point.get("distance");
                    continue;
                } else if (j == 1) { // Get duration from the list
                    duration = (String) point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(8);
            lineOptions.color(Color.RED);
            //lineOptions.color(getRandomColor());

            if (animatePath) {
                final ArrayList<LatLng> finalPoints = points;
                ((AppCompatActivity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        PolylineOptions polylineOptions;
                        final Polyline greyPolyLine, blackPolyline;
                        final ValueAnimator polylineAnimator;

                        LatLngBounds.Builder builder = new LatLngBounds.Builder();
                        for (LatLng latLng : finalPoints) {
                            builder.include(latLng);
                        }
                        polylineOptions = new PolylineOptions();
                        polylineOptions.color(Color.RED);
                        polylineOptions.width(8);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.jointType(ROUND);
                        polylineOptions.addAll(finalPoints);
                        greyPolyLine = mMap.addPolyline(polylineOptions);

                        polylineOptions = new PolylineOptions();
                        polylineOptions.width(8);
                        polylineOptions.color(Color.WHITE);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.zIndex(5f);
                        polylineOptions.jointType(ROUND);

                        blackPolyline = mMap.addPolyline(polylineOptions);
                        polylineAnimator = ValueAnimator.ofInt(0, 100);
                        polylineAnimator.setDuration(5000);
                        polylineAnimator.setInterpolator(new LinearInterpolator());
                        polylineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                                List<LatLng> points = greyPolyLine.getPoints();
                                int percentValue = (int) valueAnimator.getAnimatedValue();
                                int size = points.size();
                                int newPoints = (int) (size * (percentValue / 100.0f));
                                List<LatLng> p = points.subList(0, newPoints);
                                blackPolyline.setPoints(p);
                            }
                        });

                        polylineAnimator.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                if (repeatDrawingPath) {
                                    List<LatLng> greyLatLng = greyPolyLine.getPoints();
                                    if (greyLatLng != null) {
                                        greyLatLng.clear();

                                    }
                                    polylineAnimator.start();
                                }
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {
                                polylineAnimator.cancel();
                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {
                            }
                        });
                        polylineAnimator.start();
                    }
                });
            }

            Log.e(TAG, "PolylineOptions Decoded");
        }

        // Drawing polyline in the Google Map for the i-th route
        if (resultCallback != null && lineOptions != null)
            resultCallback.onPath(lineOptions, distance, duration);
    }
}

DirectionPointListener

public interface DirectionPointListener {
    public void onPath(PolylineOptions polyLine,String distance,String duration);
}

Now draw path using below code in your Activity

private GoogleMap mMap;
private ArrayList<LatLng> wayPoint = new ArrayList<>();
private SupportMapFragment mapFragment;

mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                LatLngBounds.Builder builder = new LatLngBounds.Builder();

                /*Add Source Marker*/
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(source);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                mMap.addMarker(markerOptions);
                builder.include(source);

                /*Add Destination Marker*/
                markerOptions = new MarkerOptions();
                markerOptions.position(destination);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                mMap.addMarker(markerOptions);
                builder.include(destination);

                LatLngBounds bounds = builder.build();

                int width = mapFragment.getView().getMeasuredWidth();
                int height = mapFragment.getView().getMeasuredHeight();
                int padding = (int) (width * 0.15); // offset from edges of the map 10% of screen

                CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);

                mMap.animateCamera(cu);

                new GetPathFromLocation(context, source, destination, wayPoint, mMap, true, false, new DirectionPointListener() {
                    @Override
                    public void onPath(PolylineOptions polyLine, String distance, String duration) {
                        mMap.addPolyline(polyLine);
                        Log.e(TAG, "onPath :: Distance :: " + distance + " Duration :: " + duration);

                        binding.txtDistance.setText(String.format(" %s", distance));
                        binding.txtDuration.setText(String.format(" %s", duration));
                    }
                }).execute();
            }
        });
    }

OutPut

enter image description here

I hope this can help you!

Thank You.

How to understand nil vs. empty vs. blank in Ruby

nil? can be used on any object. It determines if the object has any value or not, including 'blank' values.

For example:

example = nil
example.nil?  # true

"".nil?  # false

Basically nil? will only ever return true if the object is in fact equal to 'nil'.

empty? is only called on objects that are considered a collection. This includes things like strings (a collection of characters), hashes (a collection of key/value pairs) and arrays (a collection of arbitrary objects). empty? returns true is there are no items in the collection.

For example:

"".empty? # true
"hi".empty?   # false
{}.empty?  # true
{"" => ""}.empty?   # false
[].empty?   # true
[nil].empty?  # false

nil.empty?  # NoMethodError: undefined method `empty?' for nil:NilClass

Notice that empty? can't be called on nil objects as nil objects are not a collection and it will raise an exception.

Also notice that even if the items in a collection are blank, it does not mean a collection is empty.

blank? is basically a combination of nil? and empty? It's useful for checking objects that you assume are collections, but could also be nil.

How to serialize an object to XML without getting xmlns="..."?

If you are unable to get rid of extra xmlns attributes for each element, when serializing to xml from generated classes (e.g.: when xsd.exe was used), so you have something like:

<manyElementWith xmlns="urn:names:specification:schema:xsd:one" />

then i would share with you what worked for me (a mix of previous answers and what i found here)

explicitly set all your different xmlns as follows:

Dim xmlns = New XmlSerializerNamespaces()
xmlns.Add("one", "urn:names:specification:schema:xsd:one")
xmlns.Add("two",  "urn:names:specification:schema:xsd:two")
xmlns.Add("three",  "urn:names:specification:schema:xsd:three")

then pass it to the serialize

serializer.Serialize(writer, object, xmlns);

you will have the three namespaces declared in the root element and no more needed to be generated in the other elements which will be prefixed accordingly

<root xmlns:one="urn:names:specification:schema:xsd:one" ... />
   <one:Element />
   <two:ElementFromAnotherNameSpace /> ...

What browsers support HTML5 WebSocket API?

Client side

  • Hixie-75:
    • Chrome 4.0 + 5.0
    • Safari 5.0.0
  • HyBi-00/Hixie-76:
  • HyBi-07+:
  • HyBi-10:
    • Chrome 14.0 + 15.0
    • Firefox 7.0 + 8.0 + 9.0 + 10.0 - prefixed: MozWebSocket
    • IE 10 (from Windows 8 developer preview)
  • HyBi-17/RFC 6455
    • Chrome 16
    • Firefox 11
    • Opera 12.10 / Opera Mobile 12.1

Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.

See caniuse for the current status of WebSockets support in desktop and mobile browsers.

See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.


Server side

It depends on which language you use.

In Java/Java EE:

Some other Java implementations:

In C#:

In PHP:

In Python:

In C:

In Node.js:

  • Socket.io : Socket.io also has serverside ports for Python, Java, Google GO, Rack
  • sockjs : sockjs also has serverside ports for Python, Java, Erlang and Lua
  • WebSocket-Node - Pure JavaScript Client & Server implementation of HyBi-10.

Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :

  • Support for Ruby(JRuby), Java, Groovy, Javascript(Rhino/Nashorn), Scala, ...
  • True threading. (unlike Node.js)
  • Understands multiple network protocols out of the box including: TCP, SSL, UDP, HTTP, HTTPS, Websockets, SockJS as fallback for WebSockets

Pusher.com is a Websocket cloud service accessible through a REST API.

DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.

Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.

For other language implementations, see the Wikipedia article for more information.

The RFC for Websockets : RFC6455

Angular redirect to login page

Following the awesome answers above I would also like to CanActivateChild: guarding child routes. It can be used to add guard to children routes helpful for cases like ACLs

It goes like this

src/app/auth-guard.service.ts (excerpt)

import { Injectable }       from '@angular/core';
import {
  CanActivate, Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  CanActivateChild
}                           from '@angular/router';
import { AuthService }      from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
  constructor(private authService: AuthService, private router:     Router) {}

  canActivate(route: ActivatedRouteSnapshot, state:    RouterStateSnapshot): boolean {
    let url: string = state.url;
    return this.checkLogin(url);
  }

  canActivateChild(route: ActivatedRouteSnapshot, state:  RouterStateSnapshot): boolean {
    return this.canActivate(route, state);
  }

/* . . . */
}

src/app/admin/admin-routing.module.ts (excerpt)

const adminRoutes: Routes = [
  {
    path: 'admin',
    component: AdminComponent,
    canActivate: [AuthGuard],
    children: [
      {
        path: '',
        canActivateChild: [AuthGuard],
        children: [
          { path: 'crises', component: ManageCrisesComponent },
          { path: 'heroes', component: ManageHeroesComponent },
          { path: '', component: AdminDashboardComponent }
        ]
      }
    ]
  }
];

@NgModule({
  imports: [
    RouterModule.forChild(adminRoutes)
  ],
  exports: [
    RouterModule
  ]
})
export class AdminRoutingModule {}

This is taken from https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard

error "Could not get BatchedBridge, make sure your bundle is packaged properly" on start of app

I ended up having to open up the port that I was using (8081 by default). On Linux, you can do the following

sudo iptables -A INPUT -p tcp --dport 8081 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -p tcp --sport 8081 -m conntrack --ctstate ESTABLISHED -j ACCEPT

You can test to see whether you actually need to do this. Just navigate to your dev server in Chrome on your Android device. If it doesn't respond, then this might be what you need. If it does respond, then this won't help you.

CASE IN statement with multiple values

The question is specific to SQL Server, but I would like to extend Martin Smith's answer.

SQL:2003 standard allows to define multiple values for simple case expression:

SELECT CASE c.Number
          WHEN '1121231','31242323' THEN 1
          WHEN '234523','2342423' THEN 2
       END AS Test
FROM tblClient c;

It is optional feature: Comma-separated predicates in simple CASE expression“ (F263).

Syntax:

CASE <common operand>
     WHEN <expression>[, <expression> ...] THEN <result>
    [WHEN <expression>[, <expression> ...] THEN <result>
     ...]
    [ELSE <result>]
END

As for know I am not aware of any RDBMS that actually supports that syntax.

How to get Tensorflow tensor dimensions (shape) as int values?

Another simple solution is to use map() as follows:

tensor_shape = map(int, my_tensor.shape)

This converts all the Dimension objects to int

How to properly create an SVN tag from trunk?

You are correct in that it's not "right" to add files to the tags folder.

You've correctly guessed that copy is the operation to use; it lets Subversion keep track of the history of these files, and also (I assume) store them much more efficiently.

In my experience, it's best to do copies ("snapshots") of entire projects, i.e. all files from the root check-out location. That way the snapshot can stand on its own, as a true representation of the entire project's state at a particular point in time.

This part of "the book" shows how the command is typically used.

jQuery - Detecting if a file has been selected in the file input

I'd suggest try the change event? test to see if it has a value if it does then you can continue with your code. jQuery has

.bind("change", function(){ ... });

Or

.change(function(){ ... }); 

which are equivalents.

http://api.jquery.com/change/

for a unique selector change your name attribute to id and then jQuery("#imafile") or a general jQuery('input[type="file"]') for all the file inputs

How to find the kth largest element in an unsorted array of length n in O(n)?

You can find the kth smallest element in O(n) time and constant space. If we consider the array is only for integers.

The approach is to do a binary search on the range of Array values. If we have a min_value and a max_value both in integer range, we can do a binary search on that range. We can write a comparator function which will tell us if any value is the kth-smallest or smaller than kth-smallest or bigger than kth-smallest. Do the binary search until you reach the kth-smallest number

Here is the code for that

class Solution:

def _iskthsmallest(self, A, val, k):
    less_count, equal_count = 0, 0
    for i in range(len(A)):
        if A[i] == val: equal_count += 1
        if A[i] < val: less_count += 1

    if less_count >= k: return 1
    if less_count + equal_count < k: return -1
    return 0

def kthsmallest_binary(self, A, min_val, max_val, k):
    if min_val == max_val:
        return min_val
    mid = (min_val + max_val)/2
    iskthsmallest = self._iskthsmallest(A, mid, k)
    if iskthsmallest == 0: return mid
    if iskthsmallest > 0: return self.kthsmallest_binary(A, min_val, mid, k)
    return self.kthsmallest_binary(A, mid+1, max_val, k)

# @param A : tuple of integers
# @param B : integer
# @return an integer
def kthsmallest(self, A, k):
    if not A: return 0
    if k > len(A): return 0
    min_val, max_val = min(A), max(A)
    return self.kthsmallest_binary(A, min_val, max_val, k)

How to count duplicate rows in pandas dataframe?

You can groupby on all the columns and call size the index indicates the duplicate values:

In [28]:
df.groupby(df.columns.tolist(),as_index=False).size()

Out[28]:
one    three  two  
False  False  True     1
True   False  False    2
       True   True     1
dtype: int64

What's the Kotlin equivalent of Java's String[]?

Some of the common ways to create a String array are

  1. var arr = Array(5){""}

This will create an array of 5 strings with initial values to be empty string.

  1. var arr = arrayOfNulls<String?>(5)

This will create an array of size 5 with initial values to be null. You can use String data to modify the array.

  1. var arr = arrayOf("zero", "one", "two", "three")

When you know the contents of array already then you can initialise the array directly.

  1. There is an easy way for creating an multi dimensional array of strings as well.

    var matrix = Array(5){Array(6) {""}}

    This is how you can create a matrix with 5 rows and 6 columns with initial values of empty string.

How to properly use jsPDF library

first, you have to create a handler.

var specialElementHandlers = {
    '#editor': function(element, renderer){
        return true;
    }
};

then write this code in click event:

doc.fromHTML($('body').get(0), 15, 15, {
    'width': 170, 
    'elementHandlers': specialElementHandlers
        });

var pdfOutput = doc.output();
            console.log(">>>"+pdfOutput );

assuming you've already declared doc variable. And Then you have save this pdf file using File-Plugin.

How to detect scroll position of page using jQuery

Check here DEMO http://jsfiddle.net/yeyene/Uhm2J/

function getData() {
    $.getJSON('Get/GetData?no=1', function (responseText) {
        //Load some data from the server
    })
};

$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
       alert("bottom!");
       // getData();
   }
});

Find column whose name contains a specific string

This answer uses the DataFrame.filter method to do this without list comprehension:

import pandas as pd

data = {'spike-2': [1,2,3], 'hey spke': [4,5,6]}
df = pd.DataFrame(data)

print(df.filter(like='spike').columns)

Will output just 'spike-2'. You can also use regex, as some people suggested in comments above:

print(df.filter(regex='spike|spke').columns)

Will output both columns: ['spike-2', 'hey spke']

Script Tag - async & defer

This image explains normal script tag, async and defer

enter image description here

  • Async scripts are executed as soon as the script is loaded, so it doesn't guarantee the order of execution (a script you included at the end may execute before the first script file )

  • Defer scripts guarantees the order of execution in which they appear in the page.

Ref this link : http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html

How to get the integer value of day of week

The correct answer, is indeed the correct answer to get the int value.

But, if you're just checking to make sure it's Sunday for example... Consider using the following code, instead of casting to an int. This provides much more readability.

if (yourDateTimeObject.DayOfWeek == DayOfWeek.Sunday)
{
    // You can easily see you're checking for sunday, and not just "0"
}

In MySQL, can I copy one row to insert into the same table?

This is an additional solution to the answer by "Grim..." There have been some comments on it having a primary key as null. Some comments about it not working. And some comments on solutions. None of the solutions worked for us. We have MariaDB with the InnoDB table.

We could not set the primary key to allow null. Using 0 instead of NULL led to duplicate value error for the primary key. SET SQL_SAFE_UPDATES = 0; Did not work either.

The solution from "Grim..." did work IF we changed our PRIMARY KEY to UNIQUE instead

Xcode: Could not locate device support files

I had a similar problem because the app store version was missing iOS 10.1 support in Xcode 8 and they haven't rolled an update yet. This caused the "Xcode: Could not locate device support files" problem. You can download the latest update https://developer.apple.com/download/ and it is more current and supports iOS 10.1 (14B72c).

Why is IoC / DI not common in Python?

pytest fixtures all based on DI (source)

Vue.js data-bind style backgroundImage not working

<div :style="{ backgroundImage: `url(${post.image})` }">

there are multiple ways but i found template string easy and simple

How to default to other directory instead of home directory

Here's a more Windows-ish solution: Right click on the Windows shortcut that you use to launch git bash, and click Properties. Change the value of "Start In" to your desired workspace path.

Edit: Also check that the Target value does not include the --cd-to-home option as noted in the comments below.

How to change value of ArrayList element in java

You're trying to change the value in the list, but all you're doing is changing the reference of x. Doing the following only changes x, not anything in the collection:

x = Integer.valueOf(9);

Additionally, Integer is immutable, meaning you can't change the value inside the Integer object (which would require a different method to do anyway). This means you need to replace the whole object. There is no way to do this with an Iterator (without adding your own layer of boxing). Do the following instead:

a.set(0, 9);

Convert Base64 string to an image file?

An easy way I'm using:

file_put_contents($output_file, file_get_contents($base64_string));

This works well because file_get_contents can read data from a URI, including a data:// URI.

TabLayout tab selection

This is probably not the ultimate solution, and it requires that you use the TabLayout together with a ViewPager, but this is how I solved it:

void selectPage(int pageIndex)
{
    viewPager.setCurrentItem(pageIndex);
    tabLayout.setupWithViewPager(viewPager);
}

I tested how big the performance impact of using this code is by first looking at the CPU- and memory monitors in Android Studio while running the method, then comparing it to the load that was put on the CPU and memory when I navigated between the pages myself (using swipe gestures), and the difference isn't significantly big, so at least it's not a horrible solution...

Hope this helps someone!

How do I change file permissions in Ubuntu

So that you don't mess up other permissions already on the file, use the flag +, such as via

sudo chmod -R o+rw /var/www

How to manually deploy artifacts in Nexus Repository Manager OSS 3

My team use Gradle and Nexus OSS 3.5.2,

I have found a solution: upload artyfacts from locakhost (I checked Nexus documentation and did not found anything about uploading artifacts from folders) => I have shared directory (use Apache httpd) and connected one to created new Nexus proxy repository. Now when I want to add my own artifacts I can upload ones into shared directory in my remote server.

Maybe someone find my solution useful: enter image description here

My question is here: Is it possible to deploy artifacts from local folder in Sonatype Nexus Repository Manager 3.x

ValueError: unconverted data remains: 02:05

The value of st at st = datetime.strptime(st, '%A %d %B') line something like 01 01 2013 02:05 and the strptime can't parse this. Indeed, you get an hour in addition of the date... You need to add %H:%M at your strptime.

How to save a new sheet in an existing excel file, using Pandas?

You can read existing sheets of your interests, for example, 'x1', 'x2', into memory and 'write' them back prior to adding more new sheets (keep in mind that sheets in a file and sheets in memory are two different things, if you don't read them, they will be lost). This approach uses 'xlsxwriter' only, no openpyxl involved.

import pandas as pd
import numpy as np

path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"

# begin <== read selected sheets and write them back
df1 = pd.read_excel(path, sheet_name='x1', index_col=0) # or sheet_name=0
df2 = pd.read_excel(path, sheet_name='x2', index_col=0) # or sheet_name=1
writer = pd.ExcelWriter(path, engine='xlsxwriter')
df1.to_excel(writer, sheet_name='x1')
df2.to_excel(writer, sheet_name='x2')
# end ==>

# now create more new sheets
x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)

x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)

df3.to_excel(writer, sheet_name='x3')
df4.to_excel(writer, sheet_name='x4')
writer.save()
writer.close()

If you want to preserve all existing sheets, you can replace above code between begin and end with:

# read all existing sheets and write them back
writer = pd.ExcelWriter(path, engine='xlsxwriter')
xlsx = pd.ExcelFile(path)
for sheet in xlsx.sheet_names:
    df = xlsx.parse(sheet_name=sheet, index_col=0)
    df.to_excel(writer, sheet_name=sheet)

Is JavaScript guaranteed to be single-threaded?

That's a good question. I'd love to say “yes”. I can't.

JavaScript is usually considered to have a single thread of execution visible to scripts(*), so that when your inline script, event listener or timeout is entered, you remain completely in control until you return from the end of your block or function.

(*: ignoring the question of whether browsers really implement their JS engines using one OS-thread, or whether other limited threads-of-execution are introduced by WebWorkers.)

However, in reality this isn't quite true, in sneaky nasty ways.

The most common case is immediate events. Browsers will fire these right away when your code does something to cause them:

_x000D_
_x000D_
var l= document.getElementById('log');_x000D_
var i= document.getElementById('inp');_x000D_
i.onblur= function() {_x000D_
    l.value+= 'blur\n';_x000D_
};_x000D_
setTimeout(function() {_x000D_
    l.value+= 'log in\n';_x000D_
    l.focus();_x000D_
    l.value+= 'log out\n';_x000D_
}, 100);_x000D_
i.focus();
_x000D_
<textarea id="log" rows="20" cols="40"></textarea>_x000D_
<input id="inp">
_x000D_
_x000D_
_x000D_

Results in log in, blur, log out on all except IE. These events don't just fire because you called focus() directly, they could happen because you called alert(), or opened a pop-up window, or anything else that moves the focus.

This can also result in other events. For example add an i.onchange listener and type something in the input before the focus() call unfocuses it, and the log order is log in, change, blur, log out, except in Opera where it's log in, blur, log out, change and IE where it's (even less explicably) log in, change, log out, blur.

Similarly calling click() on an element that provides it calls the onclick handler immediately in all browsers (at least this is consistent!).

(I'm using the direct on... event handler properties here, but the same happens with addEventListener and attachEvent.)

There's also a bunch of circumstances in which events can fire whilst your code is threaded in, despite you having done nothing to provoke it. An example:

_x000D_
_x000D_
var l= document.getElementById('log');_x000D_
document.getElementById('act').onclick= function() {_x000D_
    l.value+= 'alert in\n';_x000D_
    alert('alert!');_x000D_
    l.value+= 'alert out\n';_x000D_
};_x000D_
window.onresize= function() {_x000D_
    l.value+= 'resize\n';_x000D_
};
_x000D_
<textarea id="log" rows="20" cols="40"></textarea>_x000D_
<button id="act">alert</button>
_x000D_
_x000D_
_x000D_

Hit alert and you'll get a modal dialogue box. No more script executes until you dismiss that dialogue, yes? Nope. Resize the main window and you will get alert in, resize, alert out in the textarea.

You might think it's impossible to resize a window whilst a modal dialogue box is up, but not so: in Linux, you can resize the window as much as you like; on Windows it's not so easy, but you can do it by changing the screen resolution from a larger to a smaller one where the window doesn't fit, causing it to get resized.

You might think, well, it's only resize (and probably a few more like scroll) that can fire when the user doesn't have active interaction with the browser because script is threaded. And for single windows you might be right. But that all goes to pot as soon as you're doing cross-window scripting. For all browsers other than Safari, which blocks all windows/tabs/frames when any one of them is busy, you can interact with a document from the code of another document, running in a separate thread of execution and causing any related event handlers to fire.

Places where events that you can cause to be generated can be raised whilst script is still threaded:

  • when the modal popups (alert, confirm, prompt) are open, in all browsers but Opera;

  • during showModalDialog on browsers that support it;

  • the “A script on this page may be busy...” dialogue box, even if you choose to let the script continue to run, allows events like resize and blur to fire and be handled even whilst the script is in the middle of a busy-loop, except in Opera.

  • a while ago for me, in IE with the Sun Java Plugin, calling any method on an applet could allow events to fire and script to be re-entered. This was always a timing-sensitive bug, and it's possible Sun have fixed it since (I certainly hope so).

  • probably more. It's been a while since I tested this and browsers have gained complexity since.

In summary, JavaScript appears to most users, most of the time, to have a strict event-driven single thread of execution. In reality, it has no such thing. It is not clear how much of this is simply a bug and how much deliberate design, but if you're writing complex applications, especially cross-window/frame-scripting ones, there is every chance it could bite you — and in intermittent, hard-to-debug ways.

If the worst comes to the worst, you can solve concurrency problems by indirecting all event responses. When an event comes in, drop it in a queue and deal with the queue in order later, in a setInterval function. If you are writing a framework that you intend to be used by complex applications, doing this could be a good move. postMessage will also hopefully soothe the pain of cross-document scripting in the future.

Get HTML source of WebElement in Selenium WebDriver using Python

Sure we can get all HTML source code with this script below in Selenium Python:

elem = driver.find_element_by_xpath("//*")
source_code = elem.get_attribute("outerHTML")

If you you want to save it to file:

with open('c:/html_source_code.html', 'w') as f:
    f.write(source_code.encode('utf-8'))

I suggest saving to a file because source code is very very long.

Select 50 items from list at random to write to file

If the list is in random order, you can just take the first 50.

Otherwise, use

import random
random.sample(the_list, 50)

random.sample help text:

sample(self, population, k) method of random.Random instance
    Chooses k unique random elements from a population sequence.

    Returns a new list containing elements from the population while
    leaving the original population unchanged.  The resulting list is
    in selection order so that all sub-slices will also be valid random
    samples.  This allows raffle winners (the sample) to be partitioned
    into grand prize and second place winners (the subslices).

    Members of the population need not be hashable or unique.  If the
    population contains repeats, then each occurrence is a possible
    selection in the sample.

    To choose a sample in a range of integers, use xrange as an argument.
    This is especially fast and space efficient for sampling from a
    large population:   sample(xrange(10000000), 60)

C# using streams

I would start by reading up on streams on MSDN: http://msdn.microsoft.com/en-us/library/system.io.stream.aspx

Memorystream and FileStream are streams used to work with raw memory and Files respectively...

How to export private key from a keystore of self-signed certificate

Use Keystore Explorer gui - http://keystore-explorer.sourceforge.net/ - allows you to extract the private key from a .jks in various formats.

How can I combine two HashMap objects containing the same types?

You can use putAll function for Map as explained in the code below

HashMap<String, Integer> map1 = new HashMap<String, Integer>();
map1.put("a", 1);
map1.put("b", 2);
map1.put("c", 3);
HashMap<String, Integer> map2 = new HashMap<String, Integer>();
map1.put("aa", 11);
map1.put("bb", 12);
HashMap<String, Integer> map3 = new HashMap<String, Integer>();
map3.putAll(map1);
map3.putAll(map2);
map3.keySet().stream().forEach(System.out::println);
map3.values().stream().forEach(System.out::println);

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

Calculating the area under a curve given a set of coordinates, without knowing the function

If you have sklearn isntalled, a simple alternative is to use sklearn.metrics.auc

This computes the area under the curve using the trapezoidal rule given arbitrary x, and y array

import numpy as np
from sklearn.metrics import auc

dx = 5
xx = np.arange(1,100,dx)
yy = np.arange(1,100,dx)

print('computed AUC using sklearn.metrics.auc: {}'.format(auc(xx,yy)))
print('computed AUC using np.trapz: {}'.format(np.trapz(yy, dx = dx)))

both output the same area: 4607.5

the advantage of sklearn.metrics.auc is that it can accept arbitrarily-spaced 'x' array, just make sure it is ascending otherwise the results will be incorrect

Search for an item in a Lua list

Use the following representation instead:

local items = { apple=true, orange=true, pear=true, banana=true }
if items.apple then
    ...
end

Virtualenv Command Not Found

I had the same issue. I used the following steps to make it work

sudo pip uninstall virtualenv

sudo -H pip install virtualenv

That is it. It started working.

Usage of sudo -H----> sudo -H: set HOME variable to target user's home dir.

How to convert BigDecimal to Double in Java?

Use doubleValue method present in BigDecimal class :

double doubleValue()

Converts this BigDecimal to a double.

Android: Unable to add window. Permission denied for this window type

For Android API level of 8.0.0, you should use

WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY

instead of

LayoutParams.TYPE_TOAST or TYPE_APPLICATION_PANEL

or SYSTEM_ALERT.

How to change UINavigationBar background color from the AppDelegate

You can set UINavigation Background color by using this code in any view controller

self.navigationController.navigationBar.backgroundColor = [UIColor colorWithRed:10.0f/255.0f green:30.0f/255.0f blue:200.0f/255.0f alpha:1.0f];

How to set selectedIndex of select element using display text?

You can use the HTMLOptionsCollection.namedItem() That means that you have to define your select options to have a name attribute and have the value of the displayed text. e.g California

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

I think you have not installed these features. see below in picture.

enter image description here

I also suffered from this problem some days ago. After installing this feature then I solved it. If you have not installed this feature then installed it.

Install Process:

  1. go to android studio
  2. Tools
  3. Android
  4. SDK Manager
  5. Appearance & Behavior
  6. Android SDK

How to sort a list of strings numerically?

scores = ['91','89','87','86','85']
scores.sort()
print (scores)

This worked for me using python version 3, though it didn't in version 2.

Create a OpenSSL certificate on Windows

To create a self signed certificate on Windows 7 with IIS 6...

  1. Open IIS

  2. Select your server (top level item or your computer's name)

  3. Under the IIS section, open "Server Certificates"

  4. Click "Create Self-Signed Certificate"

  5. Name it "localhost" (or something like that that is not specific)

  6. Click "OK"

You can then bind that certificate to your website...

  1. Right click on your website and choose "Edit bindings..."

  2. Click "Add"

    • Type: https
    • IP address: "All Unassigned"
    • Port: 443
    • SSL certificate: "localhost"
  3. Click "OK"

  4. Click "Close"

getting the difference between date in days in java

Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.set(2010, 7, 23);
end.set(2010, 8, 26);
Date startDate = start.getTime();
Date endDate = end.getTime();
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
DateFormat dateFormat = DateFormat.getDateInstance();
System.out.println("The difference between "+
  dateFormat.format(startDate)+" and "+
  dateFormat.format(endDate)+" is "+
  diffDays+" days.");

This will not work when crossing daylight savings time (or leap seconds) as orange80 pointed out and might as well not give the expected results when using different times of day. Using JodaTime might be easier for correct results, as the only correct way with plain Java before 8 I know is to use Calendar's add and before/after methods to check and adjust the calculation:

start.add(Calendar.DAY_OF_MONTH, (int)diffDays);
while (start.before(end)) {
    start.add(Calendar.DAY_OF_MONTH, 1);
    diffDays++;
}
while (start.after(end)) {
    start.add(Calendar.DAY_OF_MONTH, -1);
    diffDays--;
}

How to add 'libs' folder in Android Studio?

also, to get the right arrow, right click and "Add as Library".enter image description here

Passing variables through handlebars partial

Not sure if this is helpful but here's an example of Handlebars template with dynamic parameters passed to an inline RadioButtons partial and the client(browser) rendering the radio buttons in the container.

For my use it's rendered with Handlebars on the server and lets the client finish it up. With it a forms tool can provide inline data within Handlebars without helpers.

Note : This example requires jQuery

{{#*inline "RadioButtons"}}
{{name}} Buttons<hr>
<div id="key-{{{name}}}"></div>
<script>
  {{{buttons}}}.map((o)=>{
    $("#key-{{name}}").append($(''
      +'<button class="checkbox">'
      +'<input name="{{{name}}}" type="radio" value="'+o.value+'" />'+o.text
      +'</button>'
    ));
  });
  // A little test script
  $("#key-{{{name}}} .checkbox").on("click",function(){
      alert($("input",this).val());
  });
</script>
{{/inline}}
{{>RadioButtons name="Radio" buttons='[
 {value:1,text:"One"},
 {value:2,text:"Two"}, 
 {value:3,text:"Three"}]' 
}}

How can I sort a std::map first by value, then by key?

std::map already sorts the values using a predicate you define or std::less if you don't provide one. std::set will also store items in order of the of a define comparator. However neither set nor map allow you to have multiple keys. I would suggest defining a std::map<int,std::set<string> if you want to accomplish this using your data structure alone. You should also realize that std::less for string will sort lexicographically not alphabetically.

How to show android checkbox at right side?

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/location_permissions"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:textColor="@android:color/black" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <CheckBox
                android:id="@+id/location_permission_checkbox"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_marginRight="8dp"
                android:onClick="onLocationPermissionClicked" />

        </RelativeLayout>
    </LinearLayout>

Convert pyQt UI to python

For Ubuntu it works for following commands; If you want individual files to contain main method to run the files individually, may be for testing purpose,

pyuic5 filename.ui -o filename.py -x

No main method in file, cannot run individually... try

pyuic5 filename.ui -o filename.py

Consider, I'm using PyQT5.

Sample database for exercise

You could try the classic MySQL world database.

The world.sql file is available for download here:

http://dev.mysql.com/doc/index-other.html

Just scroll down to Example Databases and you will find it.

How to get image width and height in OpenCV?

You can use rows and cols:

cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;

or size():

cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;

How should I copy Strings in Java?

Since strings are immutable, both versions are safe. The latter, however, is less efficient (it creates an extra object and in some cases copies the character data).

With this in mind, the first version should be preferred.

Rotate a div using javascript

Can be pretty easily done assuming you're using jQuery and css3:

http://jsfiddle.net/S7JDU/8/

HTML:

<div id="clicker">Click Here</div>
<div id="rotating"></div>

CSS:

#clicker { 
    width: 100px; 
    height: 100px; 
    background-color: Green; 
}

#rotating { 
    width: 100px; 
    height: 100px; 
    background-color: Red; 
    margin-top: 50px; 
    -webkit-transition: all 0.3s ease-in-out;
    -moz-transition: all 0.3s ease-in-out;
    -o-transition: all 0.3s ease-in-out;
    transition: all 0.3s ease-in-out;
}

.rotated { 
    transform:rotate(25deg); 
    -webkit-transform:rotate(25deg); 
    -moz-transform:rotate(25deg); 
    -o-transform:rotate(25deg); 
}

JS:

$(document).ready(function() {
    $('#clicker').click(function() {
        $('#rotating').toggleClass('rotated');
    });
});

How to write html code inside <?php ?>, I want write html code within the PHP script so that it can be echoed from Backend

You can drop in and out of the PHP context using the <?php and ?> tags. For example...

<?php
$array = array(1, 2, 3, 4);
?>

<table>
<thead><tr><th>Number</th></tr></thead>
<tbody>
<?php foreach ($array as $num) : ?>
<tr><td><?= htmlspecialchars($num) ?></td></tr>
<?php endforeach ?>
</tbody>
</table>

Also see Alternative syntax for control structures

SQL Server Express CREATE DATABASE permission denied in database 'master'

For SQL server 2012,

  1. First, log in to the SQL server as an administrator and go to Security tab

  2. Then move into Server Roles and double click on sysadmin role

  3. Now add user which you want to give permission to create Database by clicking Add button

  4. Click OK button and now run the query

Hope this will help for someone

Is it possible to use the SELECT INTO clause with UNION [ALL]?

This works in SQL Server:

SELECT * INTO tmpFerdeen FROM (
  SELECT top 100 * 
  FROM Customers
  UNION All
  SELECT top 100 * 
  FROM CustomerEurope
  UNION All
  SELECT top 100 * 
  FROM CustomerAsia
  UNION All
  SELECT top 100 * 
  FROM CustomerAmericas
) as tmp

Android BroadcastReceiver within Activity

You forget to write .show() at the end, which is used to show the toast message.

Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();

It is a common mistake that programmer does, but i am sure after this you won't repeat the mistake again... :D

Passing a variable from node.js to html

If using Express it's not necessary to use a View Engine at all, use something like this:

<h1>{{ name }} </h1>

This works if you previously set your application to use HTML instead of any View Engine

How to refer environment variable in POM.xml?

It might be safer to directly pass environment variables to maven system properties. For example, say on Linux you want to access environment variable MY_VARIABLE. You can use a system property in your pom file.

<properties>
    ...
    <!-- Default value for my.variable can be defined here -->
    <my.variable>foo</my.variable>
    ...
</properties>
...
<!-- Use my.variable -->
... ${my.variable} ...

Set the property value on the maven command line:

mvn clean package -Dmy.variable=$MY_VARIABLE

Exit a Script On Error

If you want to be able to handle an error instead of blindly exiting, instead of using set -e, use a trap on the ERR pseudo signal.

#!/bin/bash
f () {
    errorCode=$? # save the exit code as the first thing done in the trap function
    echo "error $errorCode"
    echo "the command executing at the time of the error was"
    echo "$BASH_COMMAND"
    echo "on line ${BASH_LINENO[0]}"
    # do some error handling, cleanup, logging, notification
    # $BASH_COMMAND contains the command that was being executed at the time of the trap
    # ${BASH_LINENO[0]} contains the line number in the script of that command
    # exit the script or return to try again, etc.
    exit $errorCode  # or use some other value or do return instead
}
trap f ERR
# do some stuff
false # returns 1 so it triggers the trap
# maybe do some other stuff

Other traps can be set to handle other signals, including the usual Unix signals plus the other Bash pseudo signals RETURN and DEBUG.

How to create image slideshow in html?

  1. Set var step=1 as global variable by putting it above the function call
  2. put semicolons

It will look like this

<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "images/pentagg.jpg"
var image2 = new Image()
image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
        var step=1;
        function slideit()
        {
            document.images.slide.src = eval("image"+step+".src");
            if(step<2)
                step++;
            else
                step=1;
            setTimeout("slideit()",2500);
        }
        slideit();
</script>
</body>

Remove tracking branches no longer on remote

Based on info above, this worked for me:

git br -d `git br -vv | grep ': gone] ' | awk '{print $1}' | xargs`

It removes all local branches with are ': gone] ' on remote.

How can I make content appear beneath a fixed DIV element?

I just had this problem, and this was my solution:

#floatingMenu + * {
    margin-top: 35px;
}

Adjust for the height of your floatingMenu. If you don't know for sure that it's a div following then you can use * rather than div. This is all valid CSS2.

Toggle input disabled attribute using jQuery

I guess to get full browser comparability disabled should set by the value disabled or get removed!
Here is a small plugin that I've just made:

(function($) {
    $.fn.toggleDisabled = function() {
        return this.each(function() {
            var $this = $(this);
            if ($this.attr('disabled')) $this.removeAttr('disabled');
            else $this.attr('disabled', 'disabled');
        });
    };
})(jQuery);

Example link.

EDIT: updated the example link/code to maintaining chainability!
EDIT 2:
Based on @lonesomeday comment, here's an enhanced version:

(function($) {
    $.fn.toggleDisabled = function(){
        return this.each(function(){
            this.disabled = !this.disabled;
        });
    };
})(jQuery);

Integer to IP Address - C

From string to int and back

const char * s_ip = "192.168.0.5";
unsigned int ip;
unsigned char * c_ip = (unsigned char *)&ip;
sscanf(s_ip, "%hhu.%hhu.%hhu.%hhu", &c_ip[3], &c_ip[2], &c_ip[1], &c_ip[0]);
printf("%u.%u.%u.%u", ((ip & 0xff000000) >> 24), ((ip & 0x00ff0000) >> 16), ((ip & 0x0000ff00) >> 8), (ip & 0x000000ff));

%hhu instructs sscanf to read into unsigned char pointer; (Reading small int with scanf)


inet_ntoa from glibc

char *
inet_ntoa (struct in_addr in)
{
unsigned char *bytes = (unsigned char *) &in;
__snprintf (buffer, sizeof (buffer), "%d.%d.%d.%d",
bytes[0], bytes[1], bytes[2], bytes[3]);
return buffer;
}

Component is part of the declaration of 2 modules

Had same problem. Just make sure to remove every occurrence of module in "declarations" but AppModule.

Worked for me.

checking if a number is divisible by 6 PHP

if ($variable % 6 == 0) {
    echo 'This number is divisible by 6.';
}:

Make divisible by 6:

$variable += (6 - ($variable % 6)) % 6; // faster than while for large divisors

How to add one column into existing SQL Table

alter table table_name add field_name (size);

alter table arnicsc add place number(10);

Handler vs AsyncTask vs Thread

As the Tutorial on Android background processing with Handlers, AsyncTask and Loaders on the Vogella site puts it:

The Handler class can be used to register to a thread and provides a simple channel to send data to this thread.

The AsyncTask class encapsulates the creation of a background process and the synchronization with the main thread. It also supports reporting progress of the running tasks.

And a Thread is basically the core element of multithreading which a developer can use with the following disadvantage:

If you use Java threads you have to handle the following requirements in your own code:

  • Synchronization with the main thread if you post back results to the user interface
  • No default for canceling the thread
  • No default thread pooling
  • No default for handling configuration changes in Android

And regarding the AsyncTask, as the Android Developer's Reference puts it:

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

Update May 2015: I found an excellent series of lectures covering this topic.

This is the Google Search: Douglas Schmidt lecture android concurrency and synchronisation

This is the video of the first lecture on YouTube

All this is part of the CS 282 (2013): Systems Programming for Android from the Vanderbilt University. Here's the YouTube Playlist

Douglas Schmidt seems to be an excellent lecturer

Important: If you are at a point where you are considering to use AsyncTask to solve your threading issues, you should first check out ReactiveX/RxAndroid for a possibly more appropriate programming pattern. A very good resource for getting an overview is Learning RxJava 2 for Android by example.

Negative regex for Perl string pattern match

What's wrong with using two regexs (or three)? This makes your intentions more clear and may even improve your performance:

if ($string =~ /^(Clinton|Reagan)/i && $string !~ /Bush/i) { ... }

if (($string =~ /^Clinton/i || $string =~ /^Reagan/i)
        && $string !~ /Bush/i) {
    print "$string\n"
}

Regex doesn't work in String.matches()

[a-z] matches a single char between a and z. So, if your string was just "d", for example, then it would have matched and been printed out.

You need to change your regex to [a-z]+ to match one or more chars.

What is the difference between "mvn deploy" to a local repo and "mvn install"?

From the Maven docs, sounds like it's just a difference in which repository you install the package into:

  • install - install the package into the local repository, for use as a dependency in other projects locally
  • deploy - done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

Maybe there is some confusion in that "install" to the CI server installs it to it's local repository, which then you as a user are sharing?

How do I make a Windows batch script completely silent?

Just add a >NUL at the end of the lines producing the messages.

For example,

COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat >NUL

How to take character input in java

using java you can do this:

Using the Scanner:

Scanner reader = new Scanner(System.in);
String line = reader.nextLine();
// now you can use some converter to change the String value to the value you need.
// for example Long.parseLong(line) or Integer.parseInt(line) or other type cast

Using the BufferedReader:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
// now you can use some converter to change the String value to the value you need.
// for example Long.parseLong(line) or Integer.parseInt(line) or other type cast

In the two cases you need to pass you Default input, in my case System.in

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

change the date format in laravel view page

In Laravel you can add a function inside app/Helper/helper.php like

function formatDate($date = '', $format = 'Y-m-d'){
    if($date == '' || $date == null)
        return;

    return date($format,strtotime($date));
}

And call this function on any controller like this

$start_date = formatDate($start_date,'Y-m-d');

Hope it helps!

php - push array into array - key issue

Don't use array_values on your $row

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
   {
       array_push($res_arr_values, $row);
   }

Also, the preferred way to add a value to an array is writing $array[] = $value;, not using array_push

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
   {
       $res_arr_values[] = $row;
   }

And a further optimization is not to call mysql_fetch_array($result, MYSQL_ASSOC) but to use mysql_fetch_assoc($result) directly.

$res_arr_values = array();
while ($row = mysql_fetch_assoc($result))
   {
       $res_arr_values[] = $row;
   }

How can I uninstall npm modules in Node.js?

In npm v6+ npm uninstall <package_name> removes it both in folder node_modules and file package.json.

How to install toolbox for MATLAB

Use ver it will list all the installed toolboxes and versions of the toolbox.

Generate Java classes from .XSD files...?

the easiest way is using command line. Just type in directory of your .xsd file:

xjc myFile.xsd.

So, the java will generate all Pojos.

Extracting numbers from vectors of strings

How about

# pattern is by finding a set of numbers in the start and capturing them
as.numeric(gsub("([0-9]+).*$", "\\1", years))

or

# pattern is to just remove _years_old
as.numeric(gsub(" years old", "", years))

or

# split by space, get the element in first index
as.numeric(sapply(strsplit(years, " "), "[[", 1))

Difference between hamiltonian path and euler path

They are related but are neither dependent nor mutually exclusive. If a graph has an Eurler cycle, it may or may not also have a Hamiltonian cyle and vice versa.


Euler cycles visit every edge in the graph exactly once. If there are vertices in the graph with more than two edges, then by definition, the cycle will pass through those vertices more than once. As a result, vertices can be repeated but edges cannot.

Hamiltonian cycles visit every vertex in the graph exactly once (similar to the travelling salesman problem). As a result, neither edges nor vertices can be repeated.

Laravel 5.2 - pluck() method returns array

The current alternative for pluck() is value().

Java collections maintaining insertion order

Why is it necessary to maintain the order of insertion? If you use HashMap, you can get the entry by key. It does not mean it does not provide classes that do what you want.

Change the value in app.config file dynamically

It works, just look at the bin/Debug folder, you are probably looking at app.config file inside project.

Cannot connect to repo with TortoiseSVN

Try clearing the settings under "Saved Data" - refer to:

http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-settings.html

This worked for me with Windows 7.

Eric

How to add parameters to HttpURLConnection using POST using NameValuePair

One solution is to make your own params string.

This is the actual method I've been using for my latest project. You need to change args from hashtable to namevaluepair's:

private static String getPostParamString(Hashtable<String, String> params) {
    if(params.size() == 0)
        return "";

    StringBuffer buf = new StringBuffer();
    Enumeration<String> keys = params.keys();
    while(keys.hasMoreElements()) {
        buf.append(buf.length() == 0 ? "" : "&");
        String key = keys.nextElement();
        buf.append(key).append("=").append(params.get(key));
    }
    return buf.toString();
}

POSTing the params:

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(getPostParamString(req.getPostParams()));

Concatenate in jQuery Selector

There is nothing wrong with syntax of

$('#part' + number).html(text);

jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.

In your case you should pass a String to $() that is

$(<a string>)

Make sure you have access to the variables number and text.

To test do:

function(){
    alert(number + ":" + text);//or use console.log(number + ":" + text)
    $('#part' + number).html(text);
}); 

If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.

How do I specify the platform for MSBuild?

In Visual Studio 2019, version 16.8.4, you can just add

<Prefer32Bit>false</Prefer32Bit>

What could cause java.lang.reflect.InvocationTargetException?

The error vanished after I did Clean->Run xDoclet->Run xPackaging.

In my workspace, in ecllipse.

Android: failed to convert @drawable/picture into a drawable

Restart Eclipse (unfortunately) and the problem will go away.

Android: Pass data(extras) to a fragment

Two things. First I don't think you are adding the data that you want to pass to the fragment correctly. What you need to pass to the fragment is a bundle, not an intent. For example if I wanted send an int value to a fragment I would create a bundle, put the int into that bundle, and then set that bundle as an argument to be used when the fragment was created.

Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

Second to retrieve that information you need to get the arguments sent to the fragment. You then extract the value based on the key you identified it with. For example in your fragment:

Bundle bundle = this.getArguments();
if (bundle != null) {
    int i = bundle.getInt(key, defaulValue);
}

What you are getting changes depending on what you put. Also the default value is usually null but does not need to be. It depends on if you set a default value for that argument.

Lastly I do not think you can do this in onCreateView. I think you must retrieve this data within your fragment's onActivityCreated method. My reasoning is as follows. onActivityCreated runs after the underlying activity has finished its own onCreate method. If you are placing the information you wish to retrieve within the bundle durring your activity's onCreate method, it will not exist during your fragment's onCreateView. Try using this in onActivityCreated and just update your ListView contents later.

Parsing a JSON array using Json.Net

You can get at the data values like this:

string json = @"
[ 
    { ""General"" : ""At this time we do not have any frequent support requests."" },
    { ""Support"" : ""For support inquires, please see our support page."" }
]";

JArray a = JArray.Parse(json);

foreach (JObject o in a.Children<JObject>())
{
    foreach (JProperty p in o.Properties())
    {
        string name = p.Name;
        string value = (string)p.Value;
        Console.WriteLine(name + " -- " + value);
    }
}

Fiddle: https://dotnetfiddle.net/uox4Vt

How to select a single field for all documents in a MongoDB collection?

From the MongoDB docs:

A projection can explicitly include several fields. In the following operation, find() method returns all documents that match the query. In the result set, only the item and qty fields and, by default, the _id field return in the matching documents.

db.inventory.find( { type: 'food' }, { item: 1, qty: 1 } )

In this example from the folks at Mongo, the returned documents will contain only the fields of item, qty, and _id.


Thus, you should be able to issue a statement such as:

db.students.find({}, {roll:1, _id:0})

The above statement will select all documents in the students collection, and the returned document will return only the roll field (and exclude the _id).

If we don't mention _id:0 the fields returned will be roll and _id. The '_id' field is always displayed by default. So we need to explicitly mention _id:0 along with roll.

How to hide soft keyboard on android after clicking outside EditText?

I got this working with a slight variant on Fernando Camarago's solution. In my onCreate method I attach a single onTouchListener to the root view but send the view rather than activity as an argument.

        findViewById(android.R.id.content).setOnTouchListener(new OnTouchListener() {           
        public boolean onTouch(View v, MotionEvent event) {
            Utils.hideSoftKeyboard(v);
            return false;
        }
    });

In a separate Utils class is...

    public static void hideSoftKeyboard(View v) {
    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 
    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}

Hiding the address bar of a browser (popup)

This is how I do it for popups, though it is only working with IE11, not Chrome- haven't tested in Firefox.

window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no');

How to trim a string in SQL Server before 2017?

SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer

Where is database .bak file saved from SQL Server Management Studio?

Use the script below, and switch the DatabaseName with then name of the database that you've backed up. On the column physical_device_name, you'll have the full path of your backed-up database:

select a.backup_set_id, a.server_name, a.database_name, a.name, a.user_name, a.position, a.software_major_version, a.backup_start_date, backup_finish_date, a.backup_size, a.recovery_model, b.physical_device_name
from msdb.dbo.backupset a join msdb.dbo.backupmediafamily b
  on a.media_set_id = b.media_set_id
where a.database_name = 'DatabaseName'
order by a.backup_finish_date desc