Programs & Examples On #Coolite

Attempt to set a non-property-list object as an NSUserDefaults

First off, rmaddy's answer (above) is right: implementing NSCoding doesn't help. However, you need to implement NSCoding to use NSKeyedArchiver and all that, so it's just one more step... converting via NSData.

Example methods

- (NSUserDefaults *) defaults {
    return [NSUserDefaults standardUserDefaults];
}

- (void) persistObj:(id)value forKey:(NSString *)key {
    [self.defaults setObject:value  forKey:key];
    [self.defaults synchronize];
}

- (void) persistObjAsData:(id)encodableObject forKey:(NSString *)key {
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:encodableObject];
    [self persistObj:data forKey:key];
}    

- (id) objectFromDataWithKey:(NSString*)key {
    NSData *data = [self.defaults objectForKey:key];
    return [NSKeyedUnarchiver unarchiveObjectWithData:data];
}

So you can wrap your NSCoding objects in an NSArray or NSDictionary or whatever...

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

I had a similar issue (using Jackson, lombok, gradle) and a POJO without no args constructor - the solution was to add

lombok.anyConstructor.addConstructorProperties=true

to the lombok.config file

Error "package android.support.v7.app does not exist"

It is 2020 December. The same problem came to me in a different way. When I was going to Deploy in google play store, it said I have to create the bundle higher than android v28 and I updated my projects Compile using Android Version 30 (in Xamarin Android project properties). It was not possible to do it with the same error (Android support library has no support for V7). I tried everything mentioned above and was not working and here is what worked for me. I was using this in splashactivity.cs

using Android.Support.V7.App;

And it is the one giving the trouble and i changed it into V4

using Android.Support.V4.App;

then AppCompatActivity was underlined red and I had to get androidx appcompat app as follows

using AndroidX.AppCompat.App;

Now it is working and it may help someone else too.

C# How can I check if a URL exists/is valid?

If I understand your question correctly, you could use a small method like this to give you the results of your URL test:

WebRequest webRequest = WebRequest.Create(url);  
WebResponse webResponse;
try 
{
  webResponse = webRequest.GetResponse();
}
catch //If exception thrown then couldn't get response from address
{
  return 0;
} 
return 1;

You could wrap the above code in a method and use it to perform validation. I hope this answers the question you were asking.

How to terminate a python subprocess launched with shell=True

I could do it using

from subprocess import Popen

process = Popen(command, shell=True)
Popen("TASKKILL /F /PID {pid} /T".format(pid=process.pid))

it killed the cmd.exe and the program that i gave the command for.

(On Windows)

Should Jquery code go in header or footer?

For me jQuery is a little bit special. Maybe an exception to the norm. There are so many other scripts that rely on it, so its quite important that it loads early so the other scripts that come later will work as intended. As someone else pointed out even this page loads jQuery in the head section.

Generate full SQL script from EF 5 Code First Migrations

The API appears to have changed (or at least, it doesn't work for me).

Running the following in the Package Manager Console works as expected:

Update-Database -Script -SourceMigration:0

join on multiple columns

tableB.col1 = tableA.col1 
OR tableB.col2 = tableA.col1  
OR tableB.col1 = tableA.col2  
OR tableB.col1 = tableA.col2

How do I create a branch?

Normally you'd copy it to svn+ssh://host.example.com/repos/project/branches/mybranch so that you can keep several branches in the repository, but your syntax is valid.

Here's some advice on how to set up your repository layout.

How to save all files from source code of a web site?

Try Winhttrack

...offline browser utility.

It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online. HTTrack can also update an existing mirrored site, and resume interrupted downloads. HTTrack is fully configurable, and has an integrated help system.

WinHTTrack is the Windows 2000/XP/Vista/Seven release of HTTrack, and WebHTTrack the Linux/Unix/BSD release...

What is the purpose of a self executing function in javascript?

Here's a solid example of how a self invoking anonymous function could be useful.

for( var i = 0; i < 10; i++ ) {
  setTimeout(function(){
    console.log(i)
  })
}

Output: 10, 10, 10, 10, 10...

for( var i = 0; i < 10; i++ ) {
  (function(num){
    setTimeout(function(){
      console.log(num)
    })
  })(i)
}

Output: 0, 1, 2, 3, 4...

"Invalid signature file" when attempting to run a .jar

If you are looking for a Fat JAR solution without unpacking or tampering with the original libraries but with a special JAR classloader, take a look at my project here.

Disclaimer: I did not write the code, just package it and publish it on Maven Central and describe in my read-me how to use it.

I personally use it for creating runnable uber JARs containing BouncyCastle dependencies. Maybe it is useful for you, too.

<hr> tag in Twitter Bootstrap not functioning correctly?

the css property of <hr> are :

hr {
  -moz-border-bottom-colors: none;
  -moz-border-image: none;
  -moz-border-left-colors: none;
  -moz-border-right-colors: none;
  -moz-border-top-colors: none;
  border-color: #EEEEEE -moz-use-text-color #FFFFFF;
  border-style: solid none;
  border-width: 1px 0;
  margin: 18px 0;
}

It correspond to a 1px horizontal line with a very light grey and vertical margin of 18px.

and because <hr> is inside a <div> without class the width depends on the content of the <div>

if you would like the <hr> to be full width, replace <div> with <div class='row'><div class='span12'> (with according closing tags).

If you expect something different, describe what you expect by adding a comment.

Cannot open Windows.h in Microsoft Visual Studio

If you are targeting Windows XP (v140_xp), try installing Windows XP Support for C++.

Starting with Visual Studio 2012, the default toolset (v110) dropped support for Windows XP. As a result, a Windows.h error can occur if your project is targeting Windows XP with the default C++ packages.

Check which Windows SDK version is specified in your project's Platform Toolset. (Project ? Properties ? Configuration Properties ? General). If your Toolset ends in _xp, you'll need to install XP support.

Visual Studio: Project toolset

Open the Visual Studio Installer and click Modify for your version of Visual Studio. Open the Individual Components tab and scroll down to Compilers, build tools, and runtimes. Near the bottom, check Windows XP support for C++ and click Modify to begin installing.

Visual Studio Installer: XP Support for C++

See Also:

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)

For SDK 29 :

String str1 = "";
folder1 = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)));
if (folder1.exists()) {str1 = folder1.toString() + File.separator;}

public static void createTextFile(String sBody, String FileName, String Where) {
    try {
        File gpxfile = new File(Where, FileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Then you can save your file like this :

createTextFile("This is Content","file.txt",str1);

How do I filter date range in DataTables?

Follow the link below and configure it to what you need. Daterangepicker does it for you, very easily. :)

http://www.daterangepicker.com/#ex1

Set initially selected item in Select list in Angular2

I hope it will help someone ! (works on Angular 6)

I had to add lots of select/options dynamically and following worked for me:

<div *ngFor="let option of model.q_options; let ind=index;">

        <select 
          [(ngModel)]="model.q_options[ind].type" 
          [ngModelOptions]="{standalone: true}"
        > 
          <option 
            *ngFor="let object of objects" 
            [ngValue]="object.type" 
            [selected]="object.type === model.q_options[ind].type"
          >{{object.name}}
          </option>
        </select> 

        <div [ngSwitch]="model.q_options[ind].type">
          ( here <div *ngSwitchCase="'text' or 'imagelocal' or etc."> is used to add specific input forms )
        </div>
</div>

and in *.ts

// initial state of the model
// q_options in html = NewOption and its second argument is option type
model = new NewQuestion(1, null, 2, 
  [
    new NewOption(0, 'text', '', 1), 
    new NewOption(1, 'imagelocal', '', 1)
  ]);

// dropdown options
objects = [
    {type: 'text', name: 'text'},
    {type: 'imagelocal', name: 'image - local file'},
    {type: 'imageurl', name: 'image URL'}
   ( and etc.)
];

When user adds one more 'input option' (pls do not confuse 'input option' with select/options - select/options are static here) specific select/option, selected by the user earlier, is preserved on each/all dynamically added 'input option's select/options.

XAMPP Start automatically on Windows 7 startup

I am using XAMPP on Win 7 and 8.1 too...it start normally.

Did you try to check the services on Start > RUN > services.msc

Find the service: Apache 2.x. (right click) choose Properties. At form "Startup type" choose "Automatically" and Start the service on.

you should reset the PC and check out again.

Do the same with mySQL.

If you can not solve the problem, use XAMPP Panel to start it manually.

Java : Convert formatted xml file to one line string

Using this answer which provides the code to use Dom4j to do pretty-printing, change the line that sets the output format from: createPrettyPrint() to: createCompactFormat()

public String unPrettyPrint(final String xml){  

    if (StringUtils.isBlank(xml)) {
        throw new RuntimeException("xml was null or blank in unPrettyPrint()");
    }

    final StringWriter sw;

    try {
        final OutputFormat format = OutputFormat.createCompactFormat();
        final org.dom4j.Document document = DocumentHelper.parseText(xml);
        sw = new StringWriter();
        final XMLWriter writer = new XMLWriter(sw, format);
        writer.write(document);
    }
    catch (Exception e) {
        throw new RuntimeException("Error un-pretty printing xml:\n" + xml, e);
    }
    return sw.toString();
}

how to convert integer to string?

NSArray *myArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3]];

Update for new Objective-C syntax:

NSArray *myArray = @[@1, @2, @3];

Those two declarations are identical from the compiler's perspective.

if you're just wanting to use an integer in a string for putting into a textbox or something:

int myInteger = 5;
NSString* myNewString = [NSString stringWithFormat:@"%i", myInteger];

boundingRectWithSize for NSAttributedString returning wrong size

One thing I was noticing is that the rect that would come back from (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context would have a larger width than what I passed in. When this happened my string would be truncated. I resolved it like this:

NSString *aLongString = ...
NSInteger width = //some width;            
UIFont *font = //your font;
CGRect rect = [aLongString boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                        options:(NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin)
                                     attributes:@{ NSFontAttributeName : font,
                                                   NSForegroundColorAttributeName : [UIColor whiteColor]}
                                        context:nil];

if(rect.size.width > width)
{
    return rect.size.height + font.lineHeight;
}
return rect.size.height;

For some more context; I had multi line text and I was trying to find the right height to display it in. boundRectWithSize was sometimes returning a width larger than what I would specify, thus when I used my past in width and the calculated height to display my text, it would truncate. From testing when boundingRectWithSize used the wrong width the amount it would make the height short by was 1 line. So I would check if the width was greater and if so add the font's lineHeight to provide enough space to avoid truncation.

Python Web Crawlers and "getting" html source code

Use Python 2.7, is has more 3rd party libs at the moment. (Edit: see below).

I recommend you using the stdlib module urllib2, it will allow you to comfortably get web resources. Example:

import urllib2

response = urllib2.urlopen("http://google.de")
page_source = response.read()

For parsing the code, have a look at BeautifulSoup.

BTW: what exactly do you want to do:

Just for background, I need to download a page and replace any img with ones I have

Edit: It's 2014 now, most of the important libraries have been ported, and you should definitely use Python 3 if you can. python-requests is a very nice high-level library which is easier to use than urllib2.

How do I compare two DateTime objects in PHP 5.2.8?

$elapsed = '2592000';
// Time in the past
$time_past = '2014-07-16 11:35:33';
$time_past = strtotime($time_past);

// Add a month to that time
$time_past = $time_past + $elapsed;

// Time NOW
$time_now = time();

// Check if its been a month since time past
if($time_past > $time_now){
    echo 'Hasnt been a month';    
}else{
    echo 'Been longer than a month';
}

Double precision - decimal places

Decimal representation of floating point numbers is kind of strange. If you have a number with 15 decimal places and convert that to a double, then print it out with exactly 15 decimal places, you should get the same number. On the other hand, if you print out an arbitrary double with 15 decimal places and the convert it back to a double, you won't necessarily get the same value back—you need 17 decimal places for that. And neither 15 nor 17 decimal places are enough to accurately display the exact decimal equivalent of an arbitrary double. In general, you need over 100 decimal places to do that precisely.

See the Wikipedia page for double-precision and this article on floating-point precision.

How to tell when UITableView has completed ReloadData?

Actually this one solved my problem:

-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

NSSet *visibleSections = [NSSet setWithArray:[[tableView indexPathsForVisibleRows] valueForKey:@"section"]];
if (visibleSections) {
    // hide the activityIndicator/Loader
}}

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

Using @property versus getters and setters

Prefer properties. It's what they're there for.

The reason is that all attributes are public in Python. Starting names with an underscore or two is just a warning that the given attribute is an implementation detail that may not stay the same in future versions of the code. It doesn't prevent you from actually getting or setting that attribute. Therefore, standard attribute access is the normal, Pythonic way of, well, accessing attributes.

The advantage of properties is that they are syntactically identical to attribute access, so you can change from one to another without any changes to client code. You could even have one version of a class that uses properties (say, for code-by-contract or debugging) and one that doesn't for production, without changing the code that uses it. At the same time, you don't have to write getters and setters for everything just in case you might need to better control access later.

Adding files to a GitHub repository

You can use Git GUI on Windows, see instructions:

  1. Open the Git Gui (After installing the Git on your computer).

enter image description here

  1. Clone your repository to your local hard drive:

enter image description here

  1. After cloning, GUI opens, choose: "Rescan" for changes that you made:

enter image description here

  1. You will notice the scanned files:

enter image description here

  1. Click on "Stage Changed":

enter image description here

  1. Approve and click "Commit":

enter image description here

  1. Click on "Push":

enter image description here

  1. Click on "Push":

enter image description here

  1. Wait for the files to upload to git:

enter image description here

enter image description here

Android Transparent TextView?

If you are looking for something like the text view on the image on the pulse app do this

 android:background="#88000000"
android:textColor="#ffffff"

Increasing (or decreasing) the memory available to R processes

Use memory.limit(). You can increase the default using this command, memory.limit(size=2500), where the size is in MB. You need to be using 64-bit in order to take real advantage of this.

One other suggestion is to use memory efficient objects wherever possible: for instance, use a matrix instead of a data.frame.

TypeError: 'str' object is not callable (Python)

It is important to note (in case you came here by Google) that "TypeError: 'str' object is not callable" means only that a variable that was declared as String-type earlier is attempted to be used as a function (e.g. by adding parantheses in the end.)

You can get the exact same error message also, if you use any other built-in method as variable name.

Android WebView not loading URL

First, check if you have internet permission in Manifest file.

<uses-permission android:name="android.permission.INTERNET" />

You can then add following code in onCreate() or initialize() method-

final WebView webview = (WebView) rootView.findViewById(R.id.webview);
        webview.setWebViewClient(new MyWebViewClient());
        webview.getSettings().setBuiltInZoomControls(false);
        webview.getSettings().setSupportZoom(false);
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webview.getSettings().setAllowFileAccess(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.loadUrl(URL);

And write a class to handle callbacks of webview -

public class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                           //your handling...
                return super.shouldOverrideUrlLoading(view, url);
        }
    }

in same class, you can also use other important callbacks such as -

- onPageStarted()
- onPageFinished()
- onReceivedSslError()

Also, you can add "SwipeRefreshLayout" to enable swipe refresh and refresh the webview.

<android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <WebView
            android:id="@+id/webview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.v4.widget.SwipeRefreshLayout>

And refresh the webview when user swipes screen:

SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
            mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mSwipeRefreshLayout.setRefreshing(false);
                            webview.reload();
                        }
                    }, 3000);
                }
            });

read string from .resx file in C#

This example is from the MSDN page on ResourceManager.GetString():

// Create a resource manager to retrieve resources.
ResourceManager rm = new ResourceManager("items", Assembly.GetExecutingAssembly());

// Retrieve the value of the string resource named "welcome".
// The resource manager will retrieve the value of the  
// localized resource using the caller's current culture setting.
String str = rm.GetString("welcome");

Select query to get data from SQL Server

According to MSDN

http://msdn.microsoft.com/ru-ru/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx

result is the number of lines affected, and since your query is select no lines are affected (i.e. inserted, deleted or updated) anyhow.

If you want to return a single row of the query, use ExecuteScalar() instead of ExecuteNonQuery():

  int result = (int) (command.ExecuteScalar());

However, if you expect many rows to be returned, ExecuteReader() is the only option:

  using (SqlDataReader reader = command.ExecuteReader()) {
    while (reader.Read()) {
      int result = reader.GetInt32(0);

      ...
    }
  }

CSS: Position text in the middle of the page

Try this CSS:

h1 {
    left: 0;
    line-height: 200px;
    margin-top: -100px;
    position: absolute;
    text-align: center;
    top: 50%;
    width: 100%;
}

jsFiddle: http://jsfiddle.net/wprw3/

CronJob not running

I want to add 2 points that I learned:

  1. Cron config files put in /etc/cron.d/ should not contain a dot (.). Otherwise, it won't be read by cron.
  2. If the user running your command is not in /etc/shadow. It won't be allowed to schedule cron.

Refs:

  1. http://manpages.ubuntu.com/manpages/xenial/en/man8/cron.8.html
  2. https://help.ubuntu.com/community/CronHowto

How to count lines of Java code using IntelliJ IDEA?

You can to use Count Lines of Code (CLOC)

On Settings -> External Tools add a new tool

  • Name: Count Lines of Code
  • Group: Statistics
  • Program: path/to/cloc
  • Parameters: $ProjectFileDir$ or $FileParentDir$

Setting a windows batch file variable to the day of the week

@ECHO OFF
REM GET DAY OF WEEK VIA DATE TO JULIAN DAY NUMBER CONVERSION
REM ANTONIO PEREZ AYALA
REM GET MONTH, DAY, YEAR VALUES AND ELIMINATE LEFT ZEROS
FOR /F "TOKENS=1-3 DELIMS=/" %%A IN ("%DATE%") DO SET /A MM=10%%A %% 100, DD=10%%B %% 100, YY=%%C
REM CALCULATE JULIAN DAY NUMBER, THEN DAY OF WEEK
IF %MM% LSS 3 SET /A MM+=12, YY-=1
SET /A A=YY/100, B=A/4, C=2-A+B, E=36525*(YY+4716)/100, F=306*(MM+1)/10, JDN=C+DD+E+F-1524
SET /A DOW=(JDN+1)%%7

DOW is 0 for Sunday, 1 for Monday, etc.

Get table column names in MySQL?

I have write a simple php script to fetch table columns through PHP: Show_table_columns.php

<?php
$db = 'Database'; //Database name
$host = 'Database_host'; //Hostname or Server ip
$user = 'USER'; //Database user
$pass = 'Password'; //Database user password
$con = mysql_connect($host, $user, $pass);
if ($con) {
    $link = mysql_select_db($db) or die("no database") . mysql_error();
    $count = 0;
    if ($link) {
        $sql = "
            SELECT column_name
            FROM   information_schema.columns
            WHERE  table_schema = '$db'
                   AND table_name = 'table_name'"; // Change the table_name your own table name
        $result = mysql_query($sql, $con);
        if (mysql_query($sql, $con)) {
            echo $sql . "<br> <br>";
            while ($row = mysql_fetch_row($result)) {
                echo "COLUMN " . ++$count . ": {$row[0]}<br>";
                $table_name = $row[0];
            }
            echo "<br>Total No. of COLUMNS: " . $count;
        } else {
            echo "Error in query.";
        }
    } else {
        echo "Database not found.";
    }
} else {
    echo "Connection Failed.";
}
?>

Enjoy!

MySQL join with where clause

You need to put it in the join clause, not the where:

SELECT *
FROM categories
LEFT JOIN user_category_subscriptions ON 
    user_category_subscriptions.category_id = categories.category_id
    and user_category_subscriptions.user_id =1

See, with an inner join, putting a clause in the join or the where is equivalent. However, with an outer join, they are vastly different.

As a join condition, you specify the rowset that you will be joining to the table. This means that it evaluates user_id = 1 first, and takes the subset of user_category_subscriptions with a user_id of 1 to join to all of the rows in categories. This will give you all of the rows in categories, while only the categories that this particular user has subscribed to will have any information in the user_category_subscriptions columns. Of course, all other categories will be populated with null in the user_category_subscriptions columns.

Conversely, a where clause does the join, and then reduces the rowset. So, this does all of the joins and then eliminates all rows where user_id doesn't equal 1. You're left with an inefficient way to get an inner join.

Hopefully this helps!

Detect WebBrowser complete page loading

I had the same issue of multiple DocumentCompleted fired events and tried out all the suggestions above. Finally, seems that in my case neither IsBusy property works right nor Url property, but the ReadyState seems to be what I needed, because it has the status 'Interactive' while loading the multiple frames and it gets the status 'Complete' only after loading the last one. Thus, I know when the page is fully loaded with all its components.

I hope this may help others too :)

Make the current commit the only (initial) commit in a Git repository?

Deleting the .git folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:

  1. Checkout

    git checkout --orphan latest_branch

  2. Add all the files

    git add -A

  3. Commit the changes

    git commit -am "commit message"

  4. Delete the branch

    git branch -D master

  5. Rename the current branch to master

    git branch -m master

  6. Finally, force update your repository

    git push -f origin master

PS: this will not keep your old commit history around

Gradle DSL method not found: 'runProguard'

runProguard has been renamed to minifyEnabled in version 0.14.0 (2014/10/31) or more in Gradle.

To fix this, you need to change runProguard to minifyEnabled in the build.gradle file of your project.

enter image description here

List distinct values in a vector in R

Try using the duplicated function in combination with the negation operator "!".

Example:

wdups <- rep(1:5,5)
wodups <- wdups[which(!duplicated(wdups))]

Hope that helps.

How to display image from database using php

put you $image in img tag of html

try this

echo '<img src="your_path_to_image/'.$image.'" />';

instead of

print $image;

your_path_to_image would be absolute path of your image folder like eg: /home/son/public_html/images/ or as your folder structure on server.

Update 2 :

if your image is resides in the same folder where this page file is exists
you can user this

echo '<img src="'.$image.'" />';

Changing date format in R

After reading your data in via a textConnection, the following seems to work:

dat <- read.table(textConnection(txt), header = TRUE)
dat$date <- strptime(dat$date, format= "%d/%m/%Y")
format(dat$date, format="%Y-%m-%d")

> format(dat$date, format="%Y-%m-%d")
 [1] "2011-08-31" "2011-07-31" "2011-06-30" "2011-05-31" "2011-04-30" "2011-03-31"
 [7] "2011-02-28" "2011-01-31" "2010-12-31" "2010-11-30" "2010-10-31" "2010-09-30"
[13] "2010-08-31" "2010-07-31" "2010-06-30" "2010-05-31" "2010-04-30" "2010-03-31"
[19] "2010-02-28" "2010-01-31" "2009-12-31" "2009-11-30" "2009-10-31"

> str(dat)
'data.frame':   23 obs. of  2 variables:
 $ date    : POSIXlt, format: "2011-08-31" "2011-07-31" "2011-06-30" ...
 $ midpoint: num  0.838 0.846 0.815 0.797 0.788 ...

How to parse a JSON Input stream

All the current answers assume that it is okay to pull the entire JSON into memory where the advantage of an InputStream is that you can read the input little by little. If you would like to avoid reading the entire Json file at once then I would suggest using the Jackson library (which is my personal favorite but I'm sure others like Gson have similar functions).

With Jackson you can use a JsonParser to read one section at a time. Below is an example of code I wrote that wraps the reading of an Array of JsonObjects in an Iterator. If you just want to see an example of Jackson, look at the initJsonParser, initFirstElement, and initNextObject methods.

public class JsonObjectIterator implements Iterator<Map<String, Object>>, Closeable {
    private static final Logger LOG = LoggerFactory.getLogger(JsonObjectIterator.class);

    private final InputStream inputStream;
    private JsonParser jsonParser;
    private boolean isInitialized;

    private Map<String, Object> nextObject;

    public JsonObjectIterator(final InputStream inputStream) {
        this.inputStream = inputStream;
        this.isInitialized = false;
        this.nextObject = null;
    }

    private void init() {
        this.initJsonParser();
        this.initFirstElement();
        this.isInitialized = true;
    }

    private void initJsonParser() {
        final ObjectMapper objectMapper = new ObjectMapper();
        final JsonFactory jsonFactory = objectMapper.getFactory();

        try {
            this.jsonParser = jsonFactory.createParser(inputStream);
        } catch (final IOException e) {
            LOG.error("There was a problem setting up the JsonParser: " + e.getMessage(), e);
            throw new RuntimeException("There was a problem setting up the JsonParser: " + e.getMessage(), e);
        }
    }

    private void initFirstElement() {
        try {
            // Check that the first element is the start of an array
            final JsonToken arrayStartToken = this.jsonParser.nextToken();
            if (arrayStartToken != JsonToken.START_ARRAY) {
                throw new IllegalStateException("The first element of the Json structure was expected to be a start array token, but it was: " + arrayStartToken);
            }

            // Initialize the first object
            this.initNextObject();
        } catch (final Exception e) {
            LOG.error("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e);
            throw new RuntimeException("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e);
        }

    }

    private void initNextObject() {
        try {
            final JsonToken nextToken = this.jsonParser.nextToken();

            // Check for the end of the array which will mean we're done
            if (nextToken == JsonToken.END_ARRAY) {
                this.nextObject = null;
                return;
            }

            // Make sure the next token is the start of an object
            if (nextToken != JsonToken.START_OBJECT) {
                throw new IllegalStateException("The next token of Json structure was expected to be a start object token, but it was: " + nextToken);
            }

            // Get the next product and make sure it's not null
            this.nextObject = this.jsonParser.readValueAs(new TypeReference<Map<String, Object>>() { });
            if (this.nextObject == null) {
                throw new IllegalStateException("The next parsed object of the Json structure was null");
            }
        } catch (final Exception e) {
            LOG.error("There was a problem initializing the next Object: " + e.getMessage(), e);
            throw new RuntimeException("There was a problem initializing the next Object: " + e.getMessage(), e);
        }
    }

    @Override
    public boolean hasNext() {
        if (!this.isInitialized) {
            this.init();
        }

        return this.nextObject != null;
    }

    @Override
    public Map<String, Object> next() {
        // This method will return the current object and initialize the next object so hasNext will always have knowledge of the current state

        // Makes sure we're initialized first
        if (!this.isInitialized) {
            this.init();
        }

        // Store the current next object for return
        final Map<String, Object> currentNextObject = this.nextObject;

        // Initialize the next object
        this.initNextObject();

        return currentNextObject;
    }

    @Override
    public void close() throws IOException {
        IOUtils.closeQuietly(this.jsonParser);
        IOUtils.closeQuietly(this.inputStream);
    }

}

If you don't care about memory usage, then it would certainly be easier to read the entire file and parse it as one big Json as mentioned in other answers.

HTTP requests and JSON parsing in Python

Try this:

import requests
import json

# Goole Maps API.
link = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'

# Request data from link as 'str'
data = requests.get(link).text

# convert 'str' to Json
data = json.loads(data)

# Now you can access Json 
for i in data['routes'][0]['legs'][0]['steps']:
    lattitude = i['start_location']['lat']
    longitude = i['start_location']['lng']
    print('{}, {}'.format(lattitude, longitude))

Group by multiple field names in java 8

I needed to make report for a catering firm which serves lunches for various clients. In other words, catering may have on or more firms which take orders from catering, and it must know how many lunches it must produce every single day for all it's clients !

Just to notice, I didn't use sorting, in order not to over complicate this example.

This is my code :

@Test
public void test_2() throws Exception {
    Firm catering = DS.firm().get(1);
    LocalDateTime ldtFrom = LocalDateTime.of(2017, Month.JANUARY, 1, 0, 0);
    LocalDateTime ldtTo = LocalDateTime.of(2017, Month.MAY, 2, 0, 0);
    Date dFrom = Date.from(ldtFrom.atZone(ZoneId.systemDefault()).toInstant());
    Date dTo = Date.from(ldtTo.atZone(ZoneId.systemDefault()).toInstant());

    List<PersonOrders> LON = DS.firm().getAllOrders(catering, dFrom, dTo, false);
    Map<Object, Long> M = LON.stream().collect(
            Collectors.groupingBy(p
                    -> Arrays.asList(p.getDatum(), p.getPerson().getIdfirm(), p.getIdProduct()),
                    Collectors.counting()));

    for (Map.Entry<Object, Long> e : M.entrySet()) {
        Object key = e.getKey();
        Long value = e.getValue();
        System.err.println(String.format("Client firm :%s, total: %d", key, value));
    }
}

SQL Server procedure declare a list

Alternative to @Peter Monks.

If the number in the 'in' statement is small and fixed.

DECLARE @var1 varchar(30), @var2 varchar(30), @var3  varchar(30);

SET @var1 = 'james';
SET @var2 = 'same';
SET @var3 = 'dogcat';

Select * FROM Database Where x in (@var1,@var2,@var3);

Make footer stick to bottom of page correctly

Why not using: { position: fixed; bottom: 0 } ?

How to read a single character from the user?

The answers here were informative, however I also wanted a way to get key presses asynchronously and fire off key presses in separate events, all in a thread-safe, cross-platform way. PyGame was also too bloated for me. So I made the following (in Python 2.7 but I suspect it's easily portable), which I figured I'd share here in case it was useful for anyone else. I stored this in a file named keyPress.py.

class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen. From http://code.activestate.com/recipes/134892/"""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            try:
                self.impl = _GetchMacCarbon()
            except(AttributeError, ImportError):
                self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys, termios # import termios now or else you'll get the Unix version on the Mac

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()

class _GetchMacCarbon:
    """
    A function which returns the current ASCII key that is down;
    if no ASCII key is down, the null string is returned.  The
    page http://www.mactech.com/macintosh-c/chap02-1.html was
    very helpful in figuring out how to do this.
    """
    def __init__(self):
        import Carbon
        Carbon.Evt #see if it has this (in Unix, it doesn't)

    def __call__(self):
        import Carbon
        if Carbon.Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask
            return ''
        else:
            #
            # The event contains the following info:
            # (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
            #
            # The message (msg) contains the ASCII char which is
            # extracted with the 0x000000FF charCodeMask; this
            # number is converted to an ASCII character with chr() and
            # returned
            #
            (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1]
            return chr(msg & 0x000000FF)

import threading
            
            
# From  https://stackoverflow.com/a/2022629/2924421
class Event(list):
    def __call__(self, *args, **kwargs):
        for f in self:
            f(*args, **kwargs)

    def __repr__(self):
        return "Event(%s)" % list.__repr__(self)            


def getKey():
    inkey = _Getch()
    import sys
    for i in xrange(sys.maxint):
        k=inkey()
        if k<>'':break
    return k

class KeyCallbackFunction():
    callbackParam = None
    actualFunction = None
    
    def __init__(self, actualFunction, callbackParam):
        self.actualFunction = actualFunction
        self.callbackParam = callbackParam

    def doCallback(self, inputKey):
        if not self.actualFunction is None:
            if self.callbackParam is None:
                callbackFunctionThread = threading.Thread(target=self.actualFunction, args=(inputKey,))
            else:
                callbackFunctionThread = threading.Thread(target=self.actualFunction, args=(inputKey,self.callbackParam))
            
            callbackFunctionThread.daemon = True
            callbackFunctionThread.start()
        
        

class KeyCapture():


    gotKeyLock = threading.Lock()
    gotKeys = []
    gotKeyEvent = threading.Event()

    keyBlockingSetKeyLock = threading.Lock()

    addingEventsLock = threading.Lock()
    keyReceiveEvents = Event()


    keysGotLock = threading.Lock()
    keysGot = []

    keyBlockingKeyLockLossy = threading.Lock()
    keyBlockingKeyLossy = None
    keyBlockingEventLossy = threading.Event()
    
    keysBlockingGotLock = threading.Lock()
    keysBlockingGot = []
    keyBlockingGotEvent = threading.Event()
    

    
    wantToStopLock = threading.Lock()
    wantToStop = False
    
    stoppedLock = threading.Lock()
    stopped = True
    
    isRunningEvent = False
    
    getKeyThread = None
    
    keyFunction = None
    keyArgs = None
    
    # Begin capturing keys. A seperate thread is launched that
    # captures key presses, and then these can be received via get,
    # getAsync, and adding an event via addEvent. Note that this
    # will prevent the system to accept keys as normal (say, if
    # you are in a python shell) because it overrides that key
    # capturing behavior.
    
    # If you start capture when it's already been started, a
    # InterruptedError("Keys are still being captured")
    # will be thrown
    
    # Note that get(), getAsync() and events are independent, so if a key is pressed:
    #
    # 1: Any calls to get() that are waiting, with lossy on, will return
    #    that key
    # 2: It will be stored in the queue of get keys, so that get() with lossy
    #    off will return the oldest key pressed not returned by get() yet.
    # 3: All events will be fired with that key as their input
    # 4: It will be stored in the list of getAsync() keys, where that list
    #    will be returned and set to empty list on the next call to getAsync().
    # get() call with it, aand add it to the getAsync() list.
    def startCapture(self, keyFunction=None, args=None):
        # Make sure we aren't already capturing keys
        self.stoppedLock.acquire()
        if not self.stopped:
            self.stoppedLock.release()
            raise InterruptedError("Keys are still being captured")
            return
        self.stopped = False
        self.stoppedLock.release()
        
        # If we have captured before, we need to allow the get() calls to actually
        # wait for key presses now by clearing the event
        if self.keyBlockingEventLossy.is_set():
            self.keyBlockingEventLossy.clear()
            
        # Have one function that we call every time a key is captured, intended for stopping capture
        # as desired
        self.keyFunction = keyFunction
        self.keyArgs = args
        
        # Begin capturing keys (in a seperate thread)
        self.getKeyThread = threading.Thread(target=self._threadProcessKeyPresses)
        self.getKeyThread.daemon = True
        self.getKeyThread.start()
        
        # Process key captures (in a seperate thread)
        self.getKeyThread = threading.Thread(target=self._threadStoreKeyPresses)
        self.getKeyThread.daemon = True
        self.getKeyThread.start()
    
    
    def capturing(self):
        self.stoppedLock.acquire()
        isCapturing = not self.stopped
        self.stoppedLock.release()
        return isCapturing
    # Stops the thread that is capturing keys on the first opporunity
    # has to do so. It usually can't stop immediately because getting a key
    # is a blocking process, so this will probably stop capturing after the
    # next key is pressed.
    #
    # However, Sometimes if you call stopCapture it will stop before starting capturing the
    # next key, due to multithreading race conditions. So if you want to stop capturing
    # reliably, call stopCapture in a function added via addEvent. Then you are
    # guaranteed that capturing will stop immediately after the rest of the callback
    # functions are called (before starting to capture the next key).
    def stopCapture(self):
        self.wantToStopLock.acquire()
        self.wantToStop = True 
        self.wantToStopLock.release()

    # Takes in a function that will be called every time a key is pressed (with that
    # key passed in as the first paramater in that function)
    def addEvent(self, keyPressEventFunction, args=None):   
        self.addingEventsLock.acquire()
        callbackHolder = KeyCallbackFunction(keyPressEventFunction, args)
        self.keyReceiveEvents.append(callbackHolder.doCallback)
        self.addingEventsLock.release()
    def clearEvents(self):
        self.addingEventsLock.acquire()
        self.keyReceiveEvents = Event()
        self.addingEventsLock.release()
    # Gets a key captured by this KeyCapture, blocking until a key is pressed.
    # There is an optional lossy paramater:
    # If True all keys before this call are ignored, and the next pressed key
    #   will be returned.
    # If False this will return the oldest key captured that hasn't
    #   been returned by get yet. False is the default.
    def get(self, lossy=False):
        if lossy:
            # Wait for the next key to be pressed
            self.keyBlockingEventLossy.wait()
            self.keyBlockingKeyLockLossy.acquire()
            keyReceived = self.keyBlockingKeyLossy
            self.keyBlockingKeyLockLossy.release()
            return keyReceived
        else:
            while True:
                # Wait until a key is pressed
                self.keyBlockingGotEvent.wait()
                
                # Get the key pressed
                readKey = None
                self.keysBlockingGotLock.acquire()
                # Get a key if it exists
                if len(self.keysBlockingGot) != 0:
                    readKey = self.keysBlockingGot.pop(0)
                # If we got the last one, tell us to wait
                if len(self.keysBlockingGot) == 0:
                    self.keyBlockingGotEvent.clear()
                self.keysBlockingGotLock.release()
                
                # Process the key (if it actually exists)
                if not readKey is None:
                    return readKey
                
                # Exit if we are stopping
                self.wantToStopLock.acquire()
                if self.wantToStop:
                    self.wantToStopLock.release()
                    return None
                self.wantToStopLock.release()
            
            
            
    
    def clearGetList(self):
        self.keysBlockingGotLock.acquire()
        self.keysBlockingGot = []
        self.keysBlockingGotLock.release()
    
    # Gets a list of all keys pressed since the last call to getAsync, in order
    # from first pressed, second pressed, .., most recent pressed
    def getAsync(self):
        self.keysGotLock.acquire();
        keysPressedList = list(self.keysGot)
        self.keysGot = []
        self.keysGotLock.release()
        return keysPressedList
    
    def clearAsyncList(self):
        self.keysGotLock.acquire();
        self.keysGot = []
        self.keysGotLock.release();

    def _processKey(self, readKey):
        # Append to list for GetKeyAsync
        self.keysGotLock.acquire()
        self.keysGot.append(readKey)
        self.keysGotLock.release()
        
        # Call lossy blocking key events
        self.keyBlockingKeyLockLossy.acquire()
        self.keyBlockingKeyLossy = readKey
        self.keyBlockingEventLossy.set()
        self.keyBlockingEventLossy.clear()
        self.keyBlockingKeyLockLossy.release()
        
        # Call non-lossy blocking key events
        self.keysBlockingGotLock.acquire()
        self.keysBlockingGot.append(readKey)
        if len(self.keysBlockingGot) == 1:
            self.keyBlockingGotEvent.set()
        self.keysBlockingGotLock.release()
        
        # Call events added by AddEvent
        self.addingEventsLock.acquire()
        self.keyReceiveEvents(readKey)
        self.addingEventsLock.release()

    def _threadProcessKeyPresses(self):
        while True:
            # Wait until a key is pressed
            self.gotKeyEvent.wait()
            
            # Get the key pressed
            readKey = None
            self.gotKeyLock.acquire()
            # Get a key if it exists
            if len(self.gotKeys) != 0:
                readKey = self.gotKeys.pop(0)
            # If we got the last one, tell us to wait
            if len(self.gotKeys) == 0:
                self.gotKeyEvent.clear()
            self.gotKeyLock.release()
            
            # Process the key (if it actually exists)
            if not readKey is None:
                self._processKey(readKey)
            
            # Exit if we are stopping
            self.wantToStopLock.acquire()
            if self.wantToStop:
                self.wantToStopLock.release()
                break
            self.wantToStopLock.release()
            
    def _threadStoreKeyPresses(self):
        while True:
            # Get a key
            readKey = getKey()
            
            # Run the potential shut down function
            if not self.keyFunction is None:
                self.keyFunction(readKey, self.keyArgs)
        
            # Add the key to the list of pressed keys
            self.gotKeyLock.acquire()
            self.gotKeys.append(readKey)
            if len(self.gotKeys) == 1:
                self.gotKeyEvent.set()
            self.gotKeyLock.release()
            
            # Exit if we are stopping
            self.wantToStopLock.acquire()
            if self.wantToStop:
                self.wantToStopLock.release()
                self.gotKeyEvent.set()
                break
            self.wantToStopLock.release()
    
        
        # If we have reached here we stopped capturing
        
        # All we need to do to clean up is ensure that
        # all the calls to .get() now return None.
        # To ensure no calls are stuck never returning,
        # we will leave the event set so any tasks waiting
        # for it immediately exit. This will be unset upon
        # starting key capturing again.
        
        self.stoppedLock.acquire()
        
        # We also need to set this to True so we can start up
        # capturing again.
        self.stopped = True
        self.stopped = True
        
        self.keyBlockingKeyLockLossy.acquire()
        self.keyBlockingKeyLossy = None
        self.keyBlockingEventLossy.set()
        self.keyBlockingKeyLockLossy.release()
        
        self.keysBlockingGotLock.acquire()
        self.keyBlockingGotEvent.set()
        self.keysBlockingGotLock.release()
        
        self.stoppedLock.release()

The idea is that you can either simply call keyPress.getKey(), which will read a key from the keyboard, then return it.

If you want something more than that, I made a KeyCapture object. You can create one via something like keys = keyPress.KeyCapture().

Then there are three things you can do:

addEvent(functionName) takes in any function that takes in one parameter. Then every time a key is pressed, this function will be called with that key's string as it's input. These are ran in a separate thread, so you can block all you want in them and it won't mess up the functionality of the KeyCapturer nor delay the other events.

get() returns a key in the same blocking way as before. It is now needed here because the keys are being captured via the KeyCapture object now, so keyPress.getKey() would conflict with that behavior and both of them would miss some keys since only one key can be captured at a time. Also, say the user presses 'a', then 'b', you call get(), the user presses 'c'. That get() call will immediately return 'a', then if you call it again it will return 'b', then 'c'. If you call it again it will block until another key is pressed. This ensures that you don't miss any keys, in a blocking way if desired. So in this way it's a little different than keyPress.getKey() from before

If you want the behavior of getKey() back, get(lossy=True) is like get(), except that it only returns keys pressed after the call to get(). So in the above example, get() would block until the user presses 'c', and then if you call it again it will block until another key is pressed.

getAsync() is a little different. It's designed for something that does a lot of processing, then occasionally comes back and checks which keys were pressed. Thus getAsync() returns a list of all the keys pressed since the last call to getAsync(), in order from oldest key pressed to most recent key pressed. It also doesn't block, meaning that if no keys have been pressed since the last call to getAsync(), an empty [] will be returned.

To actually start capturing keys, you need to call keys.startCapture() with your keys object made above. startCapture is non-blocking, and simply starts one thread that just records the key presses, and another thread to process those key presses. There are two threads to ensure that the thread that records key presses doesn't miss any keys.

If you want to stop capturing keys, you can call keys.stopCapture() and it will stop capturing keys. However, since capturing a key is a blocking operation, the thread capturing keys might capture one more key after calling stopCapture().

To prevent this, you can pass in an optional parameter(s) into startCapture(functionName, args) of a function that just does something like checks if a key equals 'c' and then exits. It's important that this function does very little before, for example, a sleep here will cause us to miss keys.

However, if stopCapture() is called in this function, key captures will be stopped immediately, without trying to capture any more, and that all get() calls will be returned immediately, with None if no keys have been pressed yet.

Also, since get() and getAsync() store all the previous keys pressed (until you retrieve them), you can call clearGetList() and clearAsyncList() to forget the keys previously pressed.

Note that get(), getAsync() and events are independent, so if a key is pressed:

  1. One call to get() that is waiting, with lossy on, will return that key. The other waiting calls (if any) will continue waiting.
  2. That key will be stored in the queue of get keys, so that get() with lossy off will return the oldest key pressed not returned by get() yet.
  3. All events will be fired with that key as their input
  4. That key will be stored in the list of getAsync() keys, where that lis twill be returned and set to empty list on the next call to getAsync()

If all this is too much, here is an example use case:

import keyPress
import time
import threading

def KeyPressed(k, printLock):
    printLock.acquire()
    print "Event: " + k
    printLock.release()
    time.sleep(4)
    printLock.acquire()
    print "Event after delay: " + k
    printLock.release()

def GetKeyBlocking(keys, printLock):    
    while keys.capturing():
        keyReceived = keys.get()
        time.sleep(1)
        printLock.acquire()
        if not keyReceived is None:
            print "Block " + keyReceived
        else:
            print "Block None"
        printLock.release()

def GetKeyBlockingLossy(keys, printLock):   
    while keys.capturing():
        keyReceived = keys.get(lossy=True)
        time.sleep(1)
        printLock.acquire()
        if not keyReceived is None:
            print "Lossy: " + keyReceived
        else:
            print "Lossy: None"
        printLock.release()

def CheckToClose(k, (keys, printLock)):
    printLock.acquire()
    print "Close: " + k
    printLock.release()
    if k == "c":
        keys.stopCapture()
        
printLock = threading.Lock()

print "Press a key:"
print "You pressed: " + keyPress.getKey()
print ""

keys = keyPress.KeyCapture()

keys.addEvent(KeyPressed, printLock)



print "Starting capture"
            
keys.startCapture(CheckToClose, (keys, printLock))
            
getKeyBlockingThread = threading.Thread(target=GetKeyBlocking, args=(keys, printLock))
getKeyBlockingThread.daemon = True
getKeyBlockingThread.start()

            
getKeyBlockingThreadLossy = threading.Thread(target=GetKeyBlockingLossy, args=(keys, printLock))
getKeyBlockingThreadLossy.daemon = True
getKeyBlockingThreadLossy.start()

while keys.capturing():
    keysPressed = keys.getAsync()
    printLock.acquire()
    if keysPressed != []:
        print "Async: " + str(keysPressed)
    printLock.release()
    time.sleep(1)

print "done capturing"

It is working well for me from the simple test I made, but I will happily take others feedback as well if there is something I missed.

I posted this here as well.

string decode utf-8

A string needs no encoding. It is simply a sequence of Unicode characters.

You need to encode when you want to turn a String into a sequence of bytes. The charset the you choose (UTF-8, cp1255, etc.) determines the Character->Byte mapping. Note that a character is not necessarily translated into a single byte. In most charsets, most Unicode characters are translated to at least two bytes.

Encoding of a String is carried out by:

String s1 = "some text";
byte[] bytes = s1.getBytes("UTF-8"); // Charset to encode into

You need to decode when you have ? sequence of bytes and you want to turn them into a String. When y?u d? that you need to specify, again, the charset with which the byt?s were originally encoded (otherwise you'll end up with garbl?d t?xt).

Decoding:

String s2 = new String(bytes, "UTF-8"); // Charset with which bytes were encoded 

If you want to understand this better, a great text is "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)"

How to add an extra column to a NumPy array

Add an extra column to a numpy array:

Numpy's np.append method takes three parameters, the first two are 2D numpy arrays and the 3rd is an axis parameter instructing along which axis to append:

import numpy as np  
x = np.array([[1,2,3], [4,5,6]]) 
print("Original x:") 
print(x) 

y = np.array([[1], [1]]) 
print("Original y:") 
print(y) 

print("x appended to y on axis of 1:") 
print(np.append(x, y, axis=1)) 

Prints:

Original x:
[[1 2 3]
 [4 5 6]]
Original y:
[[1]
 [1]]
x appended to y on axis of 1:
[[1 2 3 1]
 [4 5 6 1]]

How to set Sqlite3 to be case insensitive when string comparing?

If the column is of type char then you need to append the value you are querying with spaces, please refer to this question here . This in addition to using COLLATE NOCASE or one of the other solutions (upper(), etc).

Install an apk file from command prompt?

For people who wants to load apk from Linux system with React native application running on it. I have given the path in which the android application resides as well. So that those who need to find the apk file can go to view it.

adb -s 434eeads install android/app/build/outputs/apk/debug/app-debug.apk

For reinstalling the android app on phone

adb -s 434eeads install -r android/app/build/outputs/apk/debug/app-debug.apk

-s -> source/serialNumber

r -> Re-install path + file name : android/app/build/outputs/apk/debug/app-debug.apk

It is for react native applications.

Is there a way to pass optional parameters to a function?

The Python 2 documentation, 7.6. Function definitions gives you a couple of ways to detect whether a caller supplied an optional parameter.

First, you can use special formal parameter syntax *. If the function definition has a formal parameter preceded by a single *, then Python populates that parameter with any positional parameters that aren't matched by preceding formal parameters (as a tuple). If the function definition has a formal parameter preceded by **, then Python populates that parameter with any keyword parameters that aren't matched by preceding formal parameters (as a dict). The function's implementation can check the contents of these parameters for any "optional parameters" of the sort you want.

For instance, here's a function opt_fun which takes two positional parameters x1 and x2, and looks for another keyword parameter named "optional".

>>> def opt_fun(x1, x2, *positional_parameters, **keyword_parameters):
...     if ('optional' in keyword_parameters):
...         print 'optional parameter found, it is ', keyword_parameters['optional']
...     else:
...         print 'no optional parameter, sorry'
... 
>>> opt_fun(1, 2)
no optional parameter, sorry
>>> opt_fun(1,2, optional="yes")
optional parameter found, it is  yes
>>> opt_fun(1,2, another="yes")
no optional parameter, sorry

Second, you can supply a default parameter value of some value like None which a caller would never use. If the parameter has this default value, you know the caller did not specify the parameter. If the parameter has a non-default value, you know it came from the caller.

Setting Remote Webdriver to run tests in a remote computer using Java

  • First you need to create HubNode(Server) and start the HubNode(Server) from command Line/prompt using Java: -jar selenium-server-standalone-2.44.0.jar -role hub
  • Then bind the node/Client to this Hub using Hub machines IPAddress or Name with any port number >1024. For Node Machine for example: Java -jar selenium-server-standalone-2.44.0.jar -role webdriver -hub http://HubmachineIPAddress:4444/grid/register -port 5566

One more thing is that whenever we use Internet Explore or Google Chrome we need to set: System.setProperty("webdriver.ie.driver",path);

How to run a script as root on Mac OS X?

Or you can access root terminal by typing sudo -s

gson throws MalformedJsonException

I suspect that result1 has some characters at the end of it that you can't see in the debugger that follow the closing } character. What's the length of result1 versus result2? I'll note that result2 as you've quoted it has 169 characters.

GSON throws that particular error when there's extra characters after the end of the object that aren't whitespace, and it defines whitespace very narrowly (as the JSON spec does) - only \t, \n, \r, and space count as whitespace. In particular, note that trailing NUL (\0) characters do not count as whitespace and will cause this error.

If you can't easily figure out what's causing the extra characters at the end and eliminate them, another option is to tell GSON to parse in lenient mode:

Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(result1));
reader.setLenient(true);
Userinfo userinfo1 = gson.fromJson(reader, Userinfo.class);

How to delete a file from SD card?

This works for me: (Delete image from Gallery)

File file = new File(photoPath);
file.delete();

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(photoPath))));

How do you convert a byte array to a hexadecimal string, and vice versa?

I guess its speed is worth 16 extra bytes.

    static char[] hexes = new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    public static string ToHexadecimal (this byte[] Bytes)
    {
        char[] Result = new char[Bytes.Length << 1];
        int Offset = 0;
        for (int i = 0; i != Bytes.Length; i++) {
            Result[Offset++] = hexes[Bytes[i] >> 4];
            Result[Offset++] = hexes[Bytes[i] & 0x0F];
        }
        return new string(Result);
    }

Is it possible to change a UIButtons background color?

Swift 3:

        static func imageFromColor(color: UIColor, width: CGFloat, height: CGFloat) -> UIImage {
            let rect = CGRect(x: 0, y: 0, width: width, height: height)
            UIGraphicsBeginImageContext(rect.size)
            let context = UIGraphicsGetCurrentContext()!
            context.setFillColor(color.cgColor)
            context.fill(rect)
            let img = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
            return img
        }

        let button = UIButton(type: .system)
        let image = imageFromColor(color: .red, width: 
        button.frame.size.width, height: button.frame.size.height)
        button.setBackgroundImage(image, for: .normal)

How do I pass an object from one activity to another on Android?

Maybe it's an unpopular answer, but in the past I've simply used a class that has a static reference to the object I want to persist through activities. So,

public class PersonHelper
{
    public static Person person;
}

I tried going down the Parcelable interface path, but ran into a number of issues with it and the overhead in your code was unappealing to me.

Could not autowire field:RestTemplate in Spring boot application

If a TestRestTemplate is a valid option in your unit test, this documentation might be relevant

http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-rest-templates-test-utility

Short answer: if using

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)

then @Autowired will work. If using

@SpringBootTest(webEnvironment=WebEnvironment.MOCK)

then create a TestRestTemplate like this

private TestRestTemplate template = new TestRestTemplate();

Why am I getting "undefined reference to sqrt" error even though I include math.h header?

Because you didn't tell the linker about location of math library. Compile with gcc test.c -o test -lm

Loading basic HTML in Node.js

I know this is an old question, but as no one has mentioned it I thought it was worth adding:

If you literally want to serve static content (say an 'about' page, image, css, etc) you can use one of the static content serving modules, for example node-static. (There's others that may be better/worse - try search.npmjs.org.) With a little bit of pre-processing you can then filter dynamic pages from static and send them to the right request handler.

bootstrap initially collapsed element

I just added class hide to the div before "card-body" and it hidden by default.

<div id="collapseOne" class="collapse hide" aria-labelledby="headingOne" data-parent="#accordion">

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.

What is the difference between concurrency and parallelism?

Great, let me take an scenario to show what I understand. suppose there're 3 kids named: A, B, C. A and B talk, C listen. For A and B, they are parallel: A: I am A. B: I am B.

But for C, his brain must take the concurrent process to listen A and B, it maybe: I am I A am B.

Find kth smallest element in a binary search tree in Optimum way

public TreeNode findKthElement(TreeNode root, int k){
    if((k==numberElement(root.left)+1)){
        return root;
    }
    else if(k>numberElement(root.left)+1){
        findKthElement(root.right,k-numberElement(root.left)-1);
    }
    else{
        findKthElement(root.left, k);
    }
}

public int numberElement(TreeNode node){
    if(node==null){
        return 0;
    }
    else{
        return numberElement(node.left) + numberElement(node.right) + 1;
    }
}

What does 'wb' mean in this code, using Python?

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.

References:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open

How can I combine multiple rows into a comma-delimited list in Oracle?

The fastest way it is to use the Oracle collect function.

You can also do this:

select *
  2    from (
  3  select deptno,
  4         case when row_number() over (partition by deptno order by ename)=1
  5             then stragg(ename) over
  6                  (partition by deptno
  7                       order by ename
  8                         rows between unbounded preceding
  9                                  and unbounded following)
 10         end enames
 11    from emp
 12         )
 13   where enames is not null

Visit the site ask tom and search on 'stragg' or 'string concatenation' . Lots of examples. There is also a not-documented oracle function to achieve your needs.

How to write inline if statement for print?

Inline if-else EXPRESSION must always contain else clause, e.g:

a = 1 if b else 0

If you want to leave your 'a' variable value unchanged - assing old 'a' value (else is still required by syntax demands):

a = 1 if b else a

This piece of code leaves a unchanged when b turns to be False.

Detect URLs in text with JavaScript

First you need a good regex that matches urls. This is hard to do. See here, here and here:

...almost anything is a valid URL. There are some punctuation rules for splitting it up. Absent any punctuation, you still have a valid URL.

Check the RFC carefully and see if you can construct an "invalid" URL. The rules are very flexible.

For example ::::: is a valid URL. The path is ":::::". A pretty stupid filename, but a valid filename.

Also, ///// is a valid URL. The netloc ("hostname") is "". The path is "///". Again, stupid. Also valid. This URL normalizes to "///" which is the equivalent.

Something like "bad://///worse/////" is perfectly valid. Dumb but valid.

Anyway, this answer is not meant to give you the best regex but rather a proof of how to do the string wrapping inside the text, with JavaScript.

OK so lets just use this one: /(https?:\/\/[^\s]+)/g

Again, this is a bad regex. It will have many false positives. However it's good enough for this example.

_x000D_
_x000D_
function urlify(text) {_x000D_
  var urlRegex = /(https?:\/\/[^\s]+)/g;_x000D_
  return text.replace(urlRegex, function(url) {_x000D_
    return '<a href="' + url + '">' + url + '</a>';_x000D_
  })_x000D_
  // or alternatively_x000D_
  // return text.replace(urlRegex, '<a href="$1">$1</a>')_x000D_
}_x000D_
_x000D_
var text = 'Find me at http://www.example.com and also at http://stackoverflow.com';_x000D_
var html = urlify(text);_x000D_
_x000D_
console.log(html)
_x000D_
_x000D_
_x000D_

// html now looks like:
// "Find me at <a href="http://www.example.com">http://www.example.com</a> and also at <a href="http://stackoverflow.com">http://stackoverflow.com</a>"

So in sum try:

$$('#pad dl dd').each(function(element) {
    element.innerHTML = urlify(element.innerHTML);
});

How to transform numpy.matrix or array to scipy sparse matrix

In Python, the Scipy library can be used to convert the 2-D NumPy matrix into a Sparse matrix. SciPy 2-D sparse matrix package for numeric data is scipy.sparse

The scipy.sparse package provides different Classes to create the following types of Sparse matrices from the 2-dimensional matrix:

  1. Block Sparse Row matrix
  2. A sparse matrix in COOrdinate format.
  3. Compressed Sparse Column matrix
  4. Compressed Sparse Row matrix
  5. Sparse matrix with DIAgonal storage
  6. Dictionary Of Keys based sparse matrix.
  7. Row-based list of lists sparse matrix
  8. This class provides a base class for all sparse matrices.

CSR (Compressed Sparse Row) or CSC (Compressed Sparse Column) formats support efficient access and matrix operations.

Example code to Convert Numpy matrix into Compressed Sparse Column(CSC) matrix & Compressed Sparse Row (CSR) matrix using Scipy classes:

import sys                 # Return the size of an object in bytes
import numpy as np         # To create 2 dimentional matrix
from scipy.sparse import csr_matrix, csc_matrix 
# csr_matrix: used to create compressed sparse row matrix from Matrix
# csc_matrix: used to create compressed sparse column matrix from Matrix

create a 2-D Numpy matrix

A = np.array([[1, 0, 0, 0, 0, 0],\
              [0, 0, 2, 0, 0, 1],\
              [0, 0, 0, 2, 0, 0]])
print("Dense matrix representation: \n", A)
print("Memory utilised (bytes): ", sys.getsizeof(A))
print("Type of the object", type(A))

Print the matrix & other details:

Dense matrix representation: 
 [[1 0 0 0 0 0]
 [0 0 2 0 0 1]
 [0 0 0 2 0 0]]
Memory utilised (bytes):  184
Type of the object <class 'numpy.ndarray'>

Converting Matrix A to the Compressed sparse row matrix representation using csr_matrix Class:

S = csr_matrix(A)
print("Sparse 'row' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))

The output of print statements:

Sparse 'row' matrix:
(0, 0) 1
(1, 2) 2
(1, 5) 1
(2, 3) 2
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csr.csc_matrix'>

Converting Matrix A to Compressed Sparse Column matrix representation using csc_matrix Class:

S = csc_matrix(A)
print("Sparse 'column' matrix: \n",S)
print("Memory utilised (bytes): ", sys.getsizeof(S))
print("Type of the object", type(S))

The output of print statements:

Sparse 'column' matrix:
(0, 0) 1
(1, 2) 2
(2, 3) 2
(1, 5) 1
Memory utilised (bytes): 56
Type of the object: <class 'scipy.sparse.csc.csc_matrix'>

As it can be seen the size of the compressed matrices is 56 bytes and the original matrix size is 184 bytes.

For a more detailed explanation and code examples please refer to this article: https://limitlessdatascience.wordpress.com/2020/11/26/sparse-matrix-in-machine-learning/

How to unzip gz file using Python

from sh import gunzip

gunzip('/tmp/file1.gz')

Common elements in two lists

Some of the answers above are similar but not the same so posting it as a new answer.

Solution:
1. Use HashSet to hold elements which need to be removed
2. Add all elements of list1 to HashSet
3. iterate list2 and remove elements from a HashSet which are present in list2 ==> which are present in both list1 and list2
4. Now iterate over HashSet and remove elements from list1(since we have added all elements of list1 to set), finally, list1 has all common elements
Note: We can add all elements of list2 and in a 3rd iteration, we should remove elements from list2.

Time complexity: O(n)
Space Complexity: O(n)

Code:

import com.sun.tools.javac.util.Assert;
import org.apache.commons.collections4.CollectionUtils;

    List<Integer> list1 = new ArrayList<>();
    list1.add(1);
    list1.add(2);
    list1.add(3);
    list1.add(4);
    list1.add(5);

    List<Integer> list2 = new ArrayList<>();
    list2.add(1);
    list2.add(3);
    list2.add(5);
    list2.add(7);
    Set<Integer> toBeRemoveFromList1 = new HashSet<>(list1);
    System.out.println("list1:" + list1);
    System.out.println("list2:" + list2);
    for (Integer n : list2) {
        if (toBeRemoveFromList1.contains(n)) {
            toBeRemoveFromList1.remove(n);
        }
    }
    System.out.println("toBeRemoveFromList1:" + toBeRemoveFromList1);
    for (Integer n : toBeRemoveFromList1) {
        list1.remove(n);
    }
    System.out.println("list1:" + list1);
    System.out.println("collectionUtils:" + CollectionUtils.intersection(list1, list2));
    Assert.check(CollectionUtils.intersection(list1, list2).containsAll(list1));

output:

list1:[1, 2, 3, 4, 5]
list2:[1, 3, 5, 7]
toBeRemoveFromList1:[2, 4]
list1:[1, 3, 5]
collectionUtils:[1, 3, 5]

How to create an alert message in jsp page after submit process is complete

in your servlet

 request.setAttribute("submitDone","done");
 return mapping.findForward("success");

In your jsp

<c:if test="${not empty submitDone}">
  <script>alert("Form submitted");
</script></c:if>

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

You may have found the answer for it already, but here is what I do.

I usually place this line at the beginning of my installation scripts:

if(!$PSScriptRoot){ $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent } #In case if $PSScriptRoot is empty (version of powershell V.2).  

Then I can use $PSScriptRoot variable as a location of the current script(path), like in the example bellow:

if(!$PSScriptRoot){ $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent } #In case if $PSScriptRoot is empty (version of powershell V.2).  

Try {
If (Test-Path 'C:\Program Files (x86)') {
    $ChromeInstallArgs= "/i", "$PSScriptRoot\googlechromestandaloneenterprise64_v.57.0.2987.110.msi", "/q", "/norestart", "/L*v `"C:\Windows\Logs\Google_Chrome_57.0.2987.110_Install_x64.log`""
    Start-Process -FilePath msiexec -ArgumentList $ChromeInstallArgs -Wait -ErrorAction Stop
    $Result= [System.Environment]::ExitCode
} Else {
    $ChromeInstallArgs= "/i", "$PSScriptRoot\googlechromestandaloneenterprise_v.57.0.2987.110.msi", "/q", "/norestart", "/L*v `"C:\Windows\Logs\Google_Chrome_57.0.2987.110_Install_x86.log`""
    Start-Process -FilePath msiexec -ArgumentList $ChromeInstallArgs -Wait -ErrorAction Stop
    $Result= [System.Environment]::ExitCode
    }

} ### End Try block


Catch  {
    $Result = [System.Environment]::Exitcode
    [System.Environment]::Exit($Result)
   }
[System.Environment]::Exit($Result)

In your case, you can replace

Start-process... line with

Invoke-Expression $PSScriptRoot\ScriptName.ps1

You can read more about $MYINVOCATION and $PSScriptRoot automatic variables on the Microsoft site: https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/about/about_automatic_variables

How to get just numeric part of CSS property with jQuery?

Id go for:

Math.abs(parseFloat($(this).css("property")));

HttpWebRequest using Basic authentication

If you can use the WebClient class, using basic authentication becomes simple:

var client = new WebClient {Credentials = new NetworkCredential("user_name", "password")};
var response = client.DownloadString("https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2");

Online SQL syntax checker conforming to multiple databases

I am willing to bet some of my reputation that there is no such thing.

Partially because if you are worried about cross-platform SQL compatibility, your best bet in turn is to abstract your database code with some API or ORM tool that handles these things for you, and is well supported, so will deal with newer database versions as they come out.

Exact kind of API available to you will be dependent on your programming language/platform. For example, PHP has Pear:DB and others, I personally have found quite nice Python's ORM features implemented in Django framework. I presume there should be some of these things available on other platforms as well.

Are parameters in strings.xml possible?

Yes, just format your strings in the standard String.format() way.

See the method Context.getString(int, Object...) and the Android or Java Formatter documentation.

In your case, the string definition would be:

<string name="timeFormat">%1$d minutes ago</string>

ElasticSearch: Unassigned Shards, how to fix?

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

GET _cluster/allocation/explain

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

simply running below command will solve everything-

POST _cluster/reroute?retry_failed

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

Normalizing a list of numbers in Python

If working with data, many times pandas is the simple key

This particular code will put the raw into one column, then normalize by column per row. (But we can put it into a row and do it by row per column, too! Just have to change the axis values where 0 is for row and 1 is for column.)

import pandas as pd


raw = [0.07, 0.14, 0.07]  

raw_df = pd.DataFrame(raw)
normed_df = raw_df.div(raw_df.sum(axis=0), axis=1)
normed_df

where normed_df will display like:

    0
0   0.25
1   0.50
2   0.25

and then can keep playing with the data, too!

Call and receive output from Python script in Java?

I've looked for different libraries like Jepp or Jython, but most seem to be very out of date.

Jython is not "a library"; it's an implementation of the Python language on top of the Java Virtual Machine. It is definitely not out of date; the most recent release was Feb. 24 of this year. It implements Python 2.5, which means you will be missing a couple of more recent features, but it is honestly not much different from 2.7.

Note: the actual communication between Java and Python is not a requirement of the aforementioned assignment, so this isn't doing my homework for me. This is, however, the only way I can think of to easily perform what needs to be done.

This seems extremely unlikely for a school assignment. Please tell us more about what you're really trying to do. Usually, school assignments specify exactly what languages you'll be using for what, and I've never heard of one that involved more than one language at all. If it did, they'd tell you if you needed to set up this kind of communication, and how they intended you to do it.

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

You should extend your Application class with MultiDexApplication instead of Application.

Does SVG support embedding of bitmap images?

You could use a Data URI to supply the image data, for example:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

<image width="20" height="20" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="/>

</svg>

The image will go through all normal svg transformations.

But this technique has disadvantages, for example the image will not be cached by the browser

Can there exist two main methods in a Java program?

The below code in file "Locomotive.java" will compile and run successfully, with the execution results showing

2<SPACE>

As mentioned in above post, the overload rules still work for the main method. However, the entry point is the famous psvm (public static void main(String[] args))

public class Locomotive {
    Locomotive() { main("hi");}

    public static void main(String[] args) {
        System.out.print("2 ");
    }

    public static void main(String args) {
        System.out.print("3 " + args);
    }
}

maximum value of int

O.K. I neither have rep to comment on previous answer (of Philippe De Muyter) nor raise it's score, hence a new example using his define for SIGNED_MAX trivially extended for unsigned types:

// We can use it to define limits based on actual compiler built-in types also: 
#define INT_MAX   SIGNED_MAX(int)
// based on the above, we can extend it for unsigned types also:
#define UNSIGNED_MAX(x) (  (SIGNED_MAX(x)<<1) | 1 ) // We reuse SIGNED_MAX
#define UINT_MAX  UNSIGNED_MAX(unsigned int) // on ARM: 4294967295
// then we can have:
unsigned int width = UINT_MAX;

Unlike using this or that header, here we use the real type from the compiler.

Is there a format code shortcut for Visual Studio?

To align the text in the proper format -

  • Ctrl + K + D for front end pages like .aspx or .cshtml

  • Ctrl + K + F for a .cs page

But observe to press all buttons in sequence...

Adding an assets folder in Android Studio

According to new Gradle based build system. We have to put assets under main folder.

Or simply right click on your project and create it like

File > New > folder > assets Folder

How to read data from a file in Lua

There's a I/O library available, but if it's available depends on your scripting host (assuming you've embedded lua somewhere). It's available, if you're using the command line version. The complete I/O model is most likely what you're looking for.

How might I force a floating DIV to match the height of another floating DIV?

Wrap them in a containing div with the background color applied to it, and have a clearing div after the 'columns'.

<div style="background-color: yellow;">
  <div style="float: left;width: 65%;">column a</div>
  <div style="float: right;width: 35%;">column b</div>
  <div style="clear: both;"></div>
</div>

Updated to address some comments and my own thoughts:

This method works because its essentially a simplification of your problem, in this somewhat 'oldskool' method I put two columns in followed by an empty clearing element, the job of the clearing element is to tell the parent (with the background) this is where floating behaviour ends, this allows the parent to essentially render 0 pixels of height at the position of the clear, which will be whatever the highest priorly floating element is.

The reason for this is to ensure the parent element is as tall as the tallest column, the background is then set on the parent to give the appearance that both columns have the same height.

It should be noted that this technique is 'oldskool' because the better choice is to trigger this height calculation behaviour with something like clearfix or by simply having overflow: hidden on the parent element.

Whilst this works in this limited scenario, if you wish for each column to look visually different, or have a gap between them, then setting a background on the parent element won't work, there is however a trick to get this effect.

The trick is to add bottom padding to all columns, to the max amount of size you expect that could be the difference between the shortest and tallest column, if you can't work this out then pick a large figure, you then need to add a negative bottom margin of the same number.

You'll need overflow hidden on the parent object, but the result will be that each column will request to render this additional height suggested by the margin, but not actually request layout of that size (because the negative margin counters the calculation).

This will render the parent at the size of the tallest column, whilst allowing all the columns to render at their height + the size of bottom padding used, if this height is larger than the parent then the rest will simply clip off.

<div style="overflow: hidden;">
  <div style="background: blue;float: left;width: 65%;padding-bottom: 500px;margin-bottom: -500px;">column a<br />column a</div>
  <div style="background: red;float: right;width: 35%;padding-bottom: 500px;margin-bottom: -500px;">column b</div>
</div>

You can see an example of this technique on the bowers and wilkins website (see the four horizontal spotlight images the bottom of the page).

How does Content Security Policy (CSP) work?

Apache 2 mod_headers

You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:

# First enable headers module for Apache 2,
# and then restart the Apache2 service
a2enmod headers
apache2 -k graceful

On Ubuntu/Debian you can configure headers in the file /etc/apache2/conf-enabled/security.conf

#
# Setting this header will prevent MSIE from interpreting files as something
# else than declared by the content type in the HTTP headers.
# Requires mod_headers to be enabled.
#
#Header set X-Content-Type-Options: "nosniff"

#
# Setting this header will prevent other sites from embedding pages from this
# site as frames. This defends against clickjacking attacks.
# Requires mod_headers to be enabled.
#
Header always set X-Frame-Options: "sameorigin"
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Permitted-Cross-Domain-Policies "master-only"
Header always set Cache-Control "no-cache, no-store, must-revalidate"
Header always set Pragma "no-cache"
Header always set Expires "-1"
Header always set Content-Security-Policy: "default-src 'none';"
Header always set Content-Security-Policy: "script-src 'self' www.google-analytics.com adserver.example.com www.example.com;"
Header always set Content-Security-Policy: "style-src 'self' www.example.com;"

Note: This is the bottom part of the file. Only the last three entries are CSP settings.

The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, www.example.com and example.com configured in Apache 2 you should add them to the white-list as well.

Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.

While you're at it you could take a look at the other header settings and install mod_security

Further reading:

https://developers.google.com/web/fundamentals/security/csp/

https://www.w3.org/TR/CSP/

How to trim a list in Python

>>> [1,2,3,4,5,6,7,8,9][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]

Is Task.Result the same as .GetAwaiter.GetResult()?

If a task faults, the exception is re-thrown when the continuation code calls awaiter.GetResult(). Rather than calling GetResult, we could simply access the Result property of the task. The benefit of calling GetResult is that if the task faults, the exception is thrown directly without being wrapped in AggregateException, allowing for simpler and cleaner catch blocks.

For nongeneric tasks, GetResult() has a void return value. Its useful function is then solely to rethrow exceptions.

source : c# 7.0 in a Nutshell

What is a Subclass

A subclass is a class that extends another class.

public class BaseClass{
    public String getFoo(){
        return "foo";
    }
}

public class SubClass extends BaseClass{
}

Then...

System.out.println(new SubClass().getFoo());

Will print:

foo

This works because a subclass inherits the functionality of the class it extends.

Normalize numpy array columns in python

You can use sklearn.preprocessing:

from sklearn.preprocessing import normalize
data = np.array([
    [1000, 10, 0.5],
    [765, 5, 0.35],
    [800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1.     1.     1.   ]
[ 0.765  0.5    0.7  ]
[ 0.8    0.7    0.18 ]]

Uploading a file in Rails

Okay. If you do not want to store the file in database and store in the application, like assets (custom folder), you can define non-db instance variable defined by attr_accessor: document and use form_for - f.file_field to get the file,

In controller,

 @person = Person.new(person_params)

Here person_params return whitelisted params[:person] (define yourself)

Save file as,

dir = "#{Rails.root}/app/assets/custom_path"
FileUtils.mkdir(dir) unless File.directory? dir
document = @person.document.document_file_name # check document uploaded params
File.copy_stream(@font.document, "#{dir}/#{document}")

Note, Add this path in .gitignore & if you want to use this file again add this path asset_pathan of application by application.rb

Whenever form read file field, it get store in tmp folder, later you can store at your place, I gave example to store at assets

note: Storing files like this will increase the size of the application, better to store in the database using paperclip.

Display the current time and date in an Android application

If you want to get the date and time in a specific pattern you can use

Date d = new Date();
CharSequence s = DateFormat.format("yyyy-MM-dd hh:mm:ss", d.getTime());

Omit rows containing specific column of NA

Just try this:

DF %>% t %>% na.omit %>% t

It transposes the data frame and omits null rows which were 'columns' before transposition and then you transpose it back.

Where is body in a nodejs http.get response?

If you want to use .get you can do it like this

http.get(url, function(res){
    res.setEncoding('utf8');
    res.on('data', function(chunk){
        console.log(chunk);
    });

});

"No rule to make target 'install'"... But Makefile exists

I was receiving the same error message, and my issue was that I was not in the correct directory when running the command make install. When I changed to the directory that had my makefile it worked.

So possibly you aren't in the right directory.

What does "atomic" mean in programming?

In Java reading and writing fields of all types except long and double occurs atomically, and if the field is declared with the volatile modifier, even long and double are atomically read and written. That is, we get 100% either what was there, or what happened there, nor can there be any intermediate result in the variables.

PySpark: multiple conditions in when clause

It should be:

$when(((tdata.Age == "" ) & (tdata.Survived == "0")), mean_age_0)

How to make a radio button unchecked by clicking it?

Old question but people keep coming from Google here and OP asked preferably without jQuery, so here is my shot.

Should works even on IE 9

_x000D_
_x000D_
// iterate using Array method for compatibility_x000D_
Array.prototype.forEach.call(document.querySelectorAll('[type=radio]'), function(radio) {_x000D_
 radio.addEventListener('click', function(){_x000D_
  var self = this;_x000D_
  // get all elements with same name but itself and mark them unchecked_x000D_
  Array.prototype.filter.call(document.getElementsByName(this.name), function(filterEl) {_x000D_
   return self !== filterEl;_x000D_
  }).forEach(function(otherEl) {_x000D_
   delete otherEl.dataset.check_x000D_
  })_x000D_
_x000D_
  // set state based on previous one_x000D_
  if (this.dataset.hasOwnProperty('check')) {_x000D_
   this.checked = false_x000D_
   delete this.dataset.check_x000D_
  } else {_x000D_
   this.dataset.check = ''_x000D_
  }_x000D_
 }, false)_x000D_
})
_x000D_
<label><input type="radio" name="foo" value="1"/>foo = 1</label><br/>_x000D_
<label><input type="radio" name="foo" value="2"/>foo = 2</label><br/>_x000D_
<label><input type="radio" name="foo" value="3"/>foo = 3</label><br/>_x000D_
<br/>_x000D_
<label><input type="radio" name="bar" value="1"/>bar = 1</label><br/>_x000D_
<label><input type="radio" name="bar" value="2"/>bar = 2</label><br/>_x000D_
<label><input type="radio" name="bar" value="3"/>bar = 3</label><br/>
_x000D_
_x000D_
_x000D_

How to show validation message below each textbox using jquery?

This is the simple solution may work for you.

Check this solution

$('form').on('submit', function (e) {
e.preventDefault();
var emailBox=$("#email");
var passBox=$("#password");
if (!emailBox.val() || !passBox.val()) {
    $(".validationText").text("Please Enter Value").show();
}
else if(!IsEmail(emailBox.val()))
{
    emailBox.prev().text("Invalid E-mail").show();
}
$("input#email, input#password").focus(function(){
    $(this).prev(".validationText").hide();
});});

When should I use nil and NULL in Objective-C?

To expand on a comment from @cobbal:

MacTypes.h contains:

#ifndef nil
   #define nil NULL
#endif

How to break out of nested loops?

A different approach is to refactor the code from two for loops into a for loop and one manual loop. That way the break in the manual loop applies to the outer loop. I used this once in a Gauss-Jordan Elimination which required three nested loops to process.

for (int i = 0; i < 1000; i++)
{
    int j = 0;

MANUAL_LOOP:;

    if (j < 1000)
    {
       if (condition)
       {
           break;
       }

       j++;
       goto MANUAL_LOOP;
    }
}

Nodejs convert string into UTF-8

I had the same problem, when i loaded a text file via fs.readFile(), I tried to set the encodeing to UTF8, it keeped the same. my solution now is this:

myString = JSON.parse( JSON.stringify( myString ) )

after this an Ö is realy interpreted as an Ö.

"Keep Me Logged In" - the best approach

I asked one angle of this question here, and the answers will lead you to all the token-based timing-out cookie links you need.

Basically, you do not store the userId in the cookie. You store a one-time token (huge string) which the user uses to pick-up their old login session. Then to make it really secure, you ask for a password for heavy operations (like changing the password itself).

How do I get the absolute directory of a file in bash?

This will work for both file and folder:

absPath(){
    if [[ -d "$1" ]]; then
        cd "$1"
        echo "$(pwd -P)"
    else 
        cd "$(dirname "$1")"
        echo "$(pwd -P)/$(basename "$1")"
    fi
}

How can I make a countdown with NSTimer?

import UIKit

class ViewController: UIViewController {

    let eggTimes = ["Soft": 300, "Medium": 420, "Hard": 720]
    
    var secondsRemaining = 60

    @IBAction func hardnessSelected(_ sender: UIButton) {
        let hardness = sender.currentTitle!

        secondsRemaining = eggTimes[hardness]!

        Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:
            #selector(UIMenuController.update), userInfo: nil, repeats: true)
    }
    @objc func countDown() {
         if secondsRemaining > 0 {
             print("\(secondsRemaining) seconds.")
            secondsRemaining -= 1
        
         }
    }
}

How do I compile a .cpp file on Linux?

Just type the code and save it in .cpp format. then try "gcc filename.cpp" . This will create the object file. then try "./a.out" (This is the default object file name). If you want to know about gcc you can always try "man gcc"

The program can't start because cygwin1.dll is missing... in Eclipse CDT

You can compile with either Cygwin's g++ or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll (and others) PATH to the system Windows PATH, before any cygwin style paths.

Thus add: ;C:\cygwin64\bin to the end of your Windows system PATH variable.

Also, to compile for use in CMD or PowerShell, you may need to use:

x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe

(This invokes the cross-compiler, if installed.)

Can't bind to 'formGroup' since it isn't a known property of 'form'

The error says that FormGroup is not recognized in this module. So You have to import these(below) modules in every module that uses FormGroup

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

Then add FormsModule and ReactiveFormsModule into your Module's imports array.

imports: [
  FormsModule,
  ReactiveFormsModule
],

You may be thinking that I have already added it in AppModule and it should inherit from it? But it is not. because these modules are exporting required directives that are available only in importing modules. Read more here... https://angular.io/guide/sharing-ngmodules.

Other factors for these errors may be spell error like below...

[FormGroup]="form" Capital F instead of small f

[formsGroup]="form" Extra s after form

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

Based on answers of neeraj t and Everton Fernandes Rosario I wrote in Kotlin, where password is an id of an EditText in your layout.

// Show passwords' symbols.
private fun showPassword() {
    password.run {
        val cursorPosition = selectionStart
        transformationMethod = HideReturnsTransformationMethod.getInstance()
        setSelection(cursorPosition)
    }
}

// Show asterisks.
private fun hidePassword() {
    password.run {
        val cursorPosition = selectionStart
        transformationMethod = PasswordTransformationMethod.getInstance()
        setSelection(cursorPosition)
    }
}

Get size of folder or file

After lot of researching and looking into different solutions proposed here at StackOverflow. I finally decided to write my own solution. My purpose is to have no-throw mechanism because I don't want to crash if the API is unable to fetch the folder size. This method is not suitable for mult-threaded scenario.

First of all I want to check for valid directories while traversing down the file system tree.

private static boolean isValidDir(File dir){
    if (dir != null && dir.exists() && dir.isDirectory()){
        return true;
    }else{
        return false;
    }
}

Second I do not want my recursive call to go into symlinks (softlinks) and include the size in total aggregate.

public static boolean isSymlink(File file) throws IOException {
    File canon;
    if (file.getParent() == null) {
        canon = file;
    } else {
        canon = new File(file.getParentFile().getCanonicalFile(),
                file.getName());
    }
    return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
}

Finally my recursion based implementation to fetch the size of the specified directory. Notice the null check for dir.listFiles(). According to javadoc there is a possibility that this method can return null.

public static long getDirSize(File dir){
    if (!isValidDir(dir))
        return 0L;
    File[] files = dir.listFiles();
    //Guard for null pointer exception on files
    if (files == null){
        return 0L;
    }else{
        long size = 0L;
        for(File file : files){
            if (file.isFile()){
                size += file.length();
            }else{
                try{
                    if (!isSymlink(file)) size += getDirSize(file);
                }catch (IOException ioe){
                    //digest exception
                }
            }
        }
        return size;
    }
}

Some cream on the cake, the API to get the size of the list Files (might be all of files and folder under root).

public static long getDirSize(List<File> files){
    long size = 0L;
    for(File file : files){
        if (file.isDirectory()){
            size += getDirSize(file);
        } else {
            size += file.length();
        }
    }
    return size;
}

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

  1. Create multiple appSettings.$(Configuration).json files like:

    • appSettings.staging.json
    • appSettings.production.json
  2. Create a pre-build event on the project which copies the respective file to appSettings.json:

    copy appSettings.$(Configuration).json appSettings.json
    
  3. Use only appSettings.json in your Config Builder:

    var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables();
    
    Configuration = builder.Build();
    

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

You map your dispatcher on *.do:

<servlet-mapping>
   <servlet-name>Dispatcher</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>

but your controller is mapped on an url without .do:

@RequestMapping("/editPresPage")

Try changing this to:

@RequestMapping("/editPresPage.do")

How to add many functions in ONE ng-click?

You have 2 options :

  1. Create a third method that wrap both methods. Advantage here is that you put less logic in your template.

  2. Otherwise if you want to add 2 calls in ng-click you can add ';' after edit($index) like this

    ng-click="edit($index); open()"

See here : http://jsfiddle.net/laguiz/ehTy6/

How to include Authorization header in cURL POST HTTP Request in PHP?

You have most of the code…

CURLOPT_HTTPHEADER for curl_setopt() takes an array with each header as an element. You have one element with multiple headers.

You also need to add the Authorization header to your $header array.

$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString';

Uncaught ReferenceError: jQuery is not defined

In my case, the error occurred because I was using the wrong version of jquery.

<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

I changed it to:

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

Vuex - Computed property "name" was assigned to but it has no setter

If you're going to v-model a computed, it needs a setter. Whatever you want it to do with the updated value (probably write it to the $store, considering that's what your getter pulls it from) you do in the setter.

If writing it back to the store happens via form submission, you don't want to v-model, you just want to set :value.

If you want to have an intermediate state, where it's saved somewhere but doesn't overwrite the source in the $store until form submission, you'll need to create such a data item.

svn list of files that are modified in local copy

I'm not familiar with tortoise, but with subversion to linux i would type

svn status

Some googling tells me that tortoise also supports commandline commandos, try svn status in the folder that contains the svn repository.

Should I URL-encode POST data?

@DougW has clearly answered this question, but I still like to add some codes here to explain Doug's points. (And correct errors in the code above)

Solution 1: URL-encode the POST data with a content-type header :application/x-www-form-urlencoded .

Note: you do not need to urlencode $_POST[] fields one by one, http_build_query() function can do the urlencoding job nicely.

$fields = array(
    'mediaupload'=>$file_field,
    'username'=>$_POST["username"],
    'password'=>$_POST["password"],
    'latitude'=>$_POST["latitude"],
    'longitude'=>$_POST["longitude"],
    'datetime'=>$_POST["datetime"],
    'category'=>$_POST["category"],
    'metacategory'=>$_POST["metacategory"],
    'caption'=>$_POST["description"]
);

$fields_string = http_build_query($fields);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);

Solution 2: Pass the array directly as the post data without URL-encoding, while the Content-Type header will be set to multipart/form-data.

$fields = array(
        'mediaupload'=>$file_field,
        'username'=>$_POST["username"],
        'password'=>$_POST["password"],
        'latitude'=>$_POST["latitude"],
        'longitude'=>$_POST["longitude"],
        'datetime'=>$_POST["datetime"],
        'category'=>$_POST["category"],
        'metacategory'=>$_POST["metacategory"],
        'caption'=>$_POST["description"]
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);

Both code snippets work, but using different HTTP headers and bodies.

Running SSH Agent when starting Git Bash on Windows

In a git bash session, you can add a script to ~/.profile or ~/.bashrc (with ~ being usually set to %USERPROFILE%), in order for said session to launch automatically the ssh-agent. If the file doesn't exist, just create it.

This is what GitHub describes in "Working with SSH key passphrases".

The "Auto-launching ssh-agent on Git for Windows" section of that article has a robust script that checks if the agent is running or not. Below is just a snippet, see the GitHub article for the full solution.

# This is just a snippet. See the article above.
if ! agent_is_running; then
    agent_start
    ssh-add
elif ! agent_has_keys; then
    ssh-add
fi

Other Resources:

"Getting ssh-agent to work with git run from windows command shell" has a similar script, but I'd refer to the GitHub article above primarily, which is more robust and up to date.

Exit a while loop in VBS/VBA

Use Do...Loop with Until keyword

num=0
Do Until //certain_condition_to_break_loop
 num=num+1
Loop

This loop will continue to execute, Until the condition becomes true

While...Wend is the old syntax and does not provide feature to break loop! Prefer do while loops

Error creating bean with name

I think it comes from this line in your XML file:

<context:component-scan base-package="org.assessme.com.controller." />

Replace it by:

<context:component-scan base-package="org.assessme.com." />

It is because your Autowired service is not scanned by Spring since it is not in the right package.

How do I find all the files that were created today in Unix/Linux?

After going through may posts i found the best one that really works

find $file_path -type f -name "*.txt" -mtime -1 -printf "%f\n"

This prints only the file name like abc.txt not the /path/tofolder/abc.txt

Also also play around or customize with -mtime -1

Unable to compile simple Java 10 / Java 11 project with Maven

It might not exactly be the same error, but I had a similar one.

Check Maven Java Version

Since Maven is also runnig with Java, check first with which version your Maven is running on:

mvn --version | grep -i java 

It returns:

Java version 1.8.0_151, vendor: Oracle Corporation, runtime: C:\tools\jdk\openjdk1.8

Incompatible version

Here above my maven is running with Java Version 1.8.0_151. So even if I specify maven to compile with Java 11:

<properties>
    <java.version>11</java.version>
    <maven.compiler.source>${java.version}</maven.compiler.source>
    <maven.compiler.target>${java.version}</maven.compiler.target>
</properties>

It will logically print out this error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile (default-compile) on project efa-example-commons-task: Fatal error compiling: invalid target release: 11 -> [Help 1]

How to set specific java version to Maven

The logical thing to do is to set a higher Java Version to Maven (e.g. Java version 11 instead 1.8).

Maven make use of the environment variable JAVA_HOME to find the Java Version to run. So change this variable to the JDK you want to compile against (e.g. OpenJDK 11).

Sanity check

Then run again mvn --version to make sure the configuration has been taken care of:

mvn --version | grep -i java

yields

Java version: 11.0.2, vendor: Oracle Corporation, runtime: C:\tools\jdk\openjdk11

Which is much better and correct to compile code written with the Java 11 specifications.

Sort array by value alphabetically php

Note that sort() operates on the array in place, so you only need to call

sort($a);
doSomething($a);

This will not work;

$a = sort($a);
doSomething($a);

Add and remove a class on click using jQuery?

Here is an article with live working demo Class Animation In JQuery

You can try this,

$(function () {
   $("#btnSubmit").click(function () {
   $("#btnClass").removeClass("btnDiv").addClass("btn");
   });
});

you can also use switchClass() method - it allows you to animate the transition of adding and removing classes at the same time.

$(function () {
        $("#btnSubmit").click(function () {
            $("#btnClass").switchClass("btn", "btnReset", 1000, "easeInOutQuad");
        });
    });

How can I remove a button or make it invisible in Android?

First make the button invisible in xml file.Then set button visible in java code if needed.

Button resetButton=(Button)findViewById(R.id.my_button_del);
resetButton.setVisibility(View.VISIBLE); //To set visible

Xml:

<Button
android:text="Delete"
android:id="@+id/my_button_del"
android:layout_width="72dp" 
android:layout_height="40dp"
android:visibility="invisible"/>

Online PHP syntax checker / validator

To expand on my comment.

You can validate on the command line using php -l [filename], which does a syntax check only (lint). This will depend on your php.ini error settings, so you can edit you php.ini or set the error_reporting in the script.

Here's an example of the output when run on a file containing:

<?php
echo no quotes or semicolon

Results in:

PHP Parse error:  syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2

Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2

Errors parsing badfile.php

I suggested you build your own validator.

A simple page that allows you to upload a php file. It takes the uploaded file runs it through php -l and echos the output.

Note: this is not a security risk it does not execute the file, just checks for syntax errors.

Here's a really basic example of creating your own:

<?php
if (isset($_FILES['file'])) {
    echo '<pre>';
    passthru('php -l '.$_FILES['file']['tmp_name']);
    echo '</pre>';
}
?>
<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit"/>
</form>

Dynamically creating keys in a JavaScript associative array

var myArray = new Array();
myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;

// Show the values stored
for (var i in myArray) {
    alert('key is: ' + i + ', value is: ' + myArray[i]);
}

This is ok, but it iterates through every property of the array object.

If you want to only iterate through the properties myArray.one, myArray.two... you try like this:

myArray['one'] = 1;
myArray['two'] = 2;
myArray['three'] = 3;
myArray.push("one");
myArray.push("two");
myArray.push("three");
for(var i=0;i<maArray.length;i++){
    console.log(myArray[myArray[i]])
}

Now you can access both by myArray["one"] and iterate only through these properties.

Apache2: 'AH01630: client denied by server configuration'

For me, all proposed solutions won't worked. This can help, if you use cgi, fastcig or fpm as proxy you have to add a location in your vhost to avoid this problem. This allows 404 to be passthrough proxy.

<Location />
require all granted
</Location>

Questions every good PHP Developer should be able to answer

I'd ask something like:

a) what about caching?

b) how can cache be organised?

c) are you sure, you do not do extra DB queries? (In my first stuff I've made on PHP it was a mysql_query inside foreach to get names of users who've made comments... terrible :) )

d) why register_globals is evil?

e) why and how you should split view from code?

f) what is the main aim of "implement"?

Here are questions that were not clear at all for me after I've read some basic books. I've found out all about injections and csx, strpos in a few days\weeks through thousands of FAQs in the web. But until I found answers to these questions my code was really terrible :)

Create stacked barplot where each stack is scaled to sum to 100%

Chris Beeley is rigth, you only need the proportions by column. Using your data is:

 your_matrix<-( 
               rbind(
                       c(23,234,324), 
                       c(34,534,12), 
                       c(56,324,124), 
                       c(34,234,124),
                       c(123,534,654)
                    )
                )

 barplot(prop.table(your_matrix, 2) )

Gives:

enter image description here

Internet Explorer cache location

If it's been moved you can also (in IE 11, and I'm pretty sure this translates back to at least 10):

  • Tools - Internet Options
  • Under Browsing history click Settings
  • Under Current location it shows the directory name

Note: The View files button will open a Windows Explorer window there.

For example, mine shows C:\BrowserCache\IE\Temporary Internet Files

How to check if a line is blank using regex

Well...I tinkered around (using notepadd++) and this is the solution I found

\n\s

\n for end of line (where you start matching) -- the caret would not be of help in my case as the beginning of the row is a string \s takes any space till the next string

hope it helps

Node.js: Gzip compression?

1- Install compression

npm install compression

2- Use it

var express     = require('express')
var compression = require('compression')

var app = express()
app.use(compression())

compression on Github

How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

There is also a solution:
http://www.welefen.com/php-unicode-to-utf8.html

function entity2utf8onechar($unicode_c){
    $unicode_c_val = intval($unicode_c);
    $f=0x80; // 10000000
    $str = "";
    // U-00000000 - U-0000007F:   0xxxxxxx
    if($unicode_c_val <= 0x7F){         $str = chr($unicode_c_val);     }     //U-00000080 - U-000007FF:  110xxxxx 10xxxxxx
    else if($unicode_c_val >= 0x80 && $unicode_c_val <= 0x7FF){         $h=0xC0; // 11000000
        $c1 = $unicode_c_val >> 6 | $h;
        $c2 = ($unicode_c_val & 0x3F) | $f;
        $str = chr($c1).chr($c2);
    } else if($unicode_c_val >= 0x800 && $unicode_c_val <= 0xFFFF){         $h=0xE0; // 11100000
        $c1 = $unicode_c_val >> 12 | $h;
        $c2 = (($unicode_c_val & 0xFC0) >> 6) | $f;
        $c3 = ($unicode_c_val & 0x3F) | $f;
        $str=chr($c1).chr($c2).chr($c3);
    }
    //U-00010000 - U-001FFFFF:  11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
    else if($unicode_c_val >= 0x10000 && $unicode_c_val <= 0x1FFFFF){         $h=0xF0; // 11110000
        $c1 = $unicode_c_val >> 18 | $h;
        $c2 = (($unicode_c_val & 0x3F000) >>12) | $f;
        $c3 = (($unicode_c_val & 0xFC0) >>6) | $f;
        $c4 = ($unicode_c_val & 0x3F) | $f;
        $str = chr($c1).chr($c2).chr($c3).chr($c4);
    }
    //U-00200000 - U-03FFFFFF:  111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
    else if($unicode_c_val >= 0x200000 && $unicode_c_val <= 0x3FFFFFF){         $h=0xF8; // 11111000
        $c1 = $unicode_c_val >> 24 | $h;
        $c2 = (($unicode_c_val & 0xFC0000)>>18) | $f;
        $c3 = (($unicode_c_val & 0x3F000) >>12) | $f;
        $c4 = (($unicode_c_val & 0xFC0) >>6) | $f;
        $c5 = ($unicode_c_val & 0x3F) | $f;
        $str = chr($c1).chr($c2).chr($c3).chr($c4).chr($c5);
    }
    //U-04000000 - U-7FFFFFFF:  1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
    else if($unicode_c_val >= 0x4000000 && $unicode_c_val <= 0x7FFFFFFF){         $h=0xFC; // 11111100
        $c1 = $unicode_c_val >> 30 | $h;
        $c2 = (($unicode_c_val & 0x3F000000)>>24) | $f;
        $c3 = (($unicode_c_val & 0xFC0000)>>18) | $f;
        $c4 = (($unicode_c_val & 0x3F000) >>12) | $f;
        $c5 = (($unicode_c_val & 0xFC0) >>6) | $f;
        $c6 = ($unicode_c_val & 0x3F) | $f;
        $str = chr($c1).chr($c2).chr($c3).chr($c4).chr($c5).chr($c6);
    }
    return $str;
}
function entities2utf8($unicode_c){
    $unicode_c = preg_replace("/\&\#([\da-f]{5})\;/es", "entity2utf8onechar('\\1')", $unicode_c);
    return $unicode_c;
}

Hash string in c#

I think what you're looking for is not hashing but encryption. With hashing, you will not be able to retrieve the original filename from the "hash" variable. With encryption you can, and it is secure.

See AES in ASP.NET with VB.NET for more information about encryption in .NET.

How to hide image broken Icon using only CSS/HTML?

The same idea as described by others works in React as follow:

<img src='YOUR-URL' onError={(e) => e.target.style.display='none' }/>

Powershell: A positional parameter cannot be found that accepts argument "xxx"

Cmdlets in powershell accept a bunch of arguments. When these arguments are defined you can define a position for each of them.

This allows you to call a cmdlet without specifying the parameter name. So for the following cmdlet the path attribute is define with a position of 0 allowing you to skip typing -Path when invoking it and as such both the following will work.

Get-Item -Path C:\temp\thing.txt
Get-Item C:\temp\thing.txt

However if you specify more arguments than there are positional parameters defined then you will get the error.

Get-Item C:\temp\thing.txt "*"

As this cmdlet does not know how to accept the second positional parameter you get the error. You can fix this by telling it what the parameter is meant to be.

Get-Item C:\temp\thing.txt -Filter "*"

I assume you are getting the error on the following line of code as it seems to be the only place you are not specifying the parameter names correctly, and maybe it is treating the = as a parameter and $username as another parameter.

Set-ADUser $user -userPrincipalName = $newname

Try specifying the parameter name for $user and removing the =

Cannot push to Git repository on Bitbucket

If you are using SourceTree (I'm using 2.4.1), I found a simpler way to generate an SSH key and add it to my Bitbucket settings. This solved the problem for me.

  1. In SourceTree, go to Preferences.
  2. Go to the Accounts tab and select your account.
  3. There should be an option to generate and copy an SSH key to clipboard.
  4. Once you have copied that, go to Bitbucket in your browser. Go to [avatar] -> Bitbucket settings.
  5. Go to SSH keys.
  6. Click Add key
  7. Paste in the key you copied.

I received a confirmation email from Bitbucket that an SSH key had been added to my account.

For reference, on macOS, using Terminal, you can use the following command to see the keys generated for your device. This is where the key you generated is stored.

ls -la ~/.ssh

As others have stated, this documentation helped me: Use the SSH protocol with Bitbucket Cloud

Google maps Marker Label with multiple characters

As of API version 3.26.10, you can set the marker label with more than one characters. The restriction is lifted.

Try it, it works!

Moreover, using a MarkerLabel object instead of just a string, you can set a number of properties for the appearance, and if using a custom Icon you can set the labelOrigin property to reposition the label.

Source: https://code.google.com/p/gmaps-api-issues/issues/detail?id=8578#c30 (also, you can report any issues regarding this at the above linked thread)

best practice to generate random token for forgot password

The earlier version of the accepted answer (md5(uniqid(mt_rand(), true))) is insecure and only offers about 2^60 possible outputs -- well within the range of a brute force search in about a week's time for a low-budget attacker:

Since a 56-bit DES key can be brute-forced in about 24 hours, and an average case would have about 59 bits of entropy, we can calculate 2^59 / 2^56 = about 8 days. Depending on how this token verification is implemented, it might be possible to practically leak timing information and infer the first N bytes of a valid reset token.

Since the question is about "best practices" and opens with...

I want to generate identifier for forgot password

...we can infer that this token has implicit security requirements. And when you add security requirements to a random number generator, the best practice is to always use a cryptographically secure pseudorandom number generator (abbreviated CSPRNG).


Using a CSPRNG

In PHP 7, you can use bin2hex(random_bytes($n)) (where $n is an integer larger than 15).

In PHP 5, you can use random_compat to expose the same API.

Alternatively, bin2hex(mcrypt_create_iv($n, MCRYPT_DEV_URANDOM)) if you have ext/mcrypt installed. Another good one-liner is bin2hex(openssl_random_pseudo_bytes($n)).

Separating the Lookup from the Validator

Pulling from my previous work on secure "remember me" cookies in PHP, the only effective way to mitigate the aforementioned timing leak (typically introduced by the database query) is to separate the lookup from the validation.

If your table looks like this (MySQL)...

CREATE TABLE account_recovery (
    id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT 
    userid INTEGER(11) UNSIGNED NOT NULL,
    token CHAR(64),
    expires DATETIME,
    PRIMARY KEY(id)
);

... you need to add one more column, selector, like so:

CREATE TABLE account_recovery (
    id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT 
    userid INTEGER(11) UNSIGNED NOT NULL,
    selector CHAR(16),
    token CHAR(64),
    expires DATETIME,
    PRIMARY KEY(id),
    KEY(selector)
);

Use a CSPRNG When a password reset token is issued, send both values to the user, store the selector and a SHA-256 hash of the random token in the database. Use the selector to grab the hash and User ID, calculate the SHA-256 hash of the token the user provides with the one stored in the database using hash_equals().

Example Code

Generating a reset token in PHP 7 (or 5.6 with random_compat) with PDO:

$selector = bin2hex(random_bytes(8));
$token = random_bytes(32);

$urlToEmail = 'http://example.com/reset.php?'.http_build_query([
    'selector' => $selector,
    'validator' => bin2hex($token)
]);

$expires = new DateTime('NOW');
$expires->add(new DateInterval('PT01H')); // 1 hour

$stmt = $pdo->prepare("INSERT INTO account_recovery (userid, selector, token, expires) VALUES (:userid, :selector, :token, :expires);");
$stmt->execute([
    'userid' => $userId, // define this elsewhere!
    'selector' => $selector,
    'token' => hash('sha256', $token),
    'expires' => $expires->format('Y-m-d\TH:i:s')
]);

Verifying the user-provided reset token:

$stmt = $pdo->prepare("SELECT * FROM account_recovery WHERE selector = ? AND expires >= NOW()");
$stmt->execute([$selector]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!empty($results)) {
    $calc = hash('sha256', hex2bin($validator));
    if (hash_equals($calc, $results[0]['token'])) {
        // The reset token is valid. Authenticate the user.
    }
    // Remove the token from the DB regardless of success or failure.
}

These code snippets are not complete solutions (I eschewed the input validation and framework integrations), but they should serve as an example of what to do.

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

STEP 1: Include the following in OnConfiguring()

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json")
            .Build();
        optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
    }

STEP 2: Create appsettings.json:

  {
    "ConnectionStrings": {       
      "DefaultConnection": "Server=YOURSERVERNAME; Database=YOURDATABASENAME; Trusted_Connection=True; MultipleActiveResultSets=true"        
    } 
  }

STEP 3: Hard copy appsettings.json to the correct directory

  Hard copy appsettings.json.config to the directory specified in the AppDomain.CurrentDomain.BaseDirectory directory. 
  Use your debugger to find out which directory that is.        

Assumption: you have already included package Microsoft.Extensions.Configuration.Json (get it from Nuget) in your project.

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

One thing to note when using uuid1, if you use the default call (without giving clock_seq parameter) you have a chance of running into collisions: you have only 14 bit of randomness (generating 18 entries within 100ns gives you roughly 1% chance of a collision see birthday paradox/attack). The problem will never occur in most use cases, but on a virtual machine with poor clock resolution it will bite you.

How to customize message box

You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:

FormBorderStyle    FixedToolWindow
ShowInTaskBar      False
StartPosition      CenterScreen

To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:

MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
    // etc
}

It would be advisable to add your own Show method that takes the text and other options you require:

public DialogResult Show(string text, Color foreColour)
{
     lblText.Text = text;
     lblText.ForeColor = foreColour;
     return this.ShowDialog();
}

Laravel Eloquent get results grouped by days

I believe I have found a solution to this, the key is the DATE() function in mysql, which converts a DateTime into just Date:

DB::table('page_views')
      ->select(DB::raw('DATE(created_at) as date'), DB::raw('count(*) as views'))
      ->groupBy('date')
      ->get();

However, this is not really an Laravel Eloquent solution, since this is a raw query.The following is what I came up with in Eloquent-ish syntax. The first where clause uses carbon dates to compare.

$visitorTraffic = PageView::where('created_at', '>=', \Carbon\Carbon::now->subMonth())
                            ->groupBy('date')
                            ->orderBy('date', 'DESC')
                            ->get(array(
                                DB::raw('Date(created_at) as date'),
                                DB::raw('COUNT(*) as "views"')
                            ));

How to properly ignore exceptions

I usually just do:

try:
    doSomething()
except:
    _ = ""

Add new line in text file with Windows batch file

You can use:

type text1.txt >> combine.txt
echo >> combine.txt
type text2.txt >> combine.txt

or something like this:

echo blah >> combine.txt
echo blah2 >> combine.txt
echo >> combine.txt
echo other >> combine.txt

Default value in Go's method

NO,but there are some other options to implement default value. There are some good blog posts on the subject, but here are some specific examples.


**Option 1:** The caller chooses to use default values
// Both parameters are optional, use empty string for default value
func Concat1(a string, b int) string {
  if a == "" {
    a = "default-a"
  }
  if b == 0 {
    b = 5
  }

  return fmt.Sprintf("%s%d", a, b)
}

**Option 2:** A single optional parameter at the end
// a is required, b is optional.
// Only the first value in b_optional will be used.
func Concat2(a string, b_optional ...int) string {
  b := 5
  if len(b_optional) > 0 {
    b = b_optional[0]
  }

  return fmt.Sprintf("%s%d", a, b)
}

**Option 3:** A config struct
// A declarative default value syntax
// Empty values will be replaced with defaults
type Parameters struct {
  A string `default:"default-a"` // this only works with strings
  B string // default is 5
}

func Concat3(prm Parameters) string {
  typ := reflect.TypeOf(prm)

  if prm.A == "" {
    f, _ := typ.FieldByName("A")
    prm.A = f.Tag.Get("default")
  }

  if prm.B == 0 {
    prm.B = 5
  }

  return fmt.Sprintf("%s%d", prm.A, prm.B)
}

**Option 4:** Full variadic argument parsing (javascript style)
func Concat4(args ...interface{}) string {
  a := "default-a"
  b := 5

  for _, arg := range args {
    switch t := arg.(type) {
      case string:
        a = t
      case int:
        b = t
      default:
        panic("Unknown argument")
    }
  }

  return fmt.Sprintf("%s%d", a, b)
}

Bitbucket fails to authenticate on git pull

If you've changed the password on Windows 10, go to credential manager and update the password:

go to credential manager and update the password

Advantage of switch over if-else statement

I know its old but

public class SwitchTest {
static final int max = 100000;

public static void main(String[] args) {

int counter1 = 0;
long start1 = 0l;
long total1 = 0l;

int counter2 = 0;
long start2 = 0l;
long total2 = 0l;
boolean loop = true;

start1 = System.currentTimeMillis();
while (true) {
  if (counter1 == max) {
    break;
  } else {
    counter1++;
  }
}
total1 = System.currentTimeMillis() - start1;

start2 = System.currentTimeMillis();
while (loop) {
  switch (counter2) {
    case max:
      loop = false;
      break;
    default:
      counter2++;
  }
}
total2 = System.currentTimeMillis() - start2;

System.out.println("While if/else: " + total1 + "ms");
System.out.println("Switch: " + total2 + "ms");
System.out.println("Max Loops: " + max);

System.exit(0);
}
}

Varying the loop count changes a lot:

While if/else: 5ms Switch: 1ms Max Loops: 100000

While if/else: 5ms Switch: 3ms Max Loops: 1000000

While if/else: 5ms Switch: 14ms Max Loops: 10000000

While if/else: 5ms Switch: 149ms Max Loops: 100000000

(add more statements if you want)

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

In my case, the error occurred because I had not initialized the select list in the controller like this:

viewModel.MySelectList = new List<System.Web.Mvc.SelectListItem>();

As none of the existing answers made this clear to me, I post this. Perhaps it helps anybody.

Does JavaScript have a method like "range()" to generate a range within the supplied bounds?

For numbers you can use ES6 Array.from(), which works in everything these days except IE:

Shorter version:

Array.from({length: 20}, (x, i) => i);

Longer version:

Array.from(new Array(20), (x, i) => i);??????

which creates an array from 0 to 19 inclusive. This can be further shortened to one of these forms:

Array.from(Array(20).keys());
// or
[...Array(20).keys()];

Lower and upper bounds can be specified too, for example:

Array.from(new Array(20), (x, i) => i + *lowerBound*);

An article describing this in more detail: http://www.2ality.com/2014/05/es6-array-methods.html

How to check if all inputs are not empty with jQuery

I just wanted to point out my answer since I know for loop is faster then $.each loop here it is:

just add class="required" to inputs you want to be required and then in jquery do:

$('#signup_form').submit(function(){
    var fields = $('input.required');
    for(var i=0;i<fields.length;i++){
        if($(fields[i]).val() != ''){
            //whatever
        }
    }
});

Use multiple css stylesheets in the same html page

The one you include last will be the one that is used. Note however that if any rules has !important in the first stylesheet they will take priority.

Xcode Error: "The app ID cannot be registered to your development team."

I encountered the same problem when I was trying to compile a sample project provided by Apple. In the end I figured out that apparently they pre-compiled the sample code before shipping them to developers, so the binary had their signature.

The way to solve it is simple, just delete all the built binaries and re-compile using your own bundle identifier and you should be fine.

Just go to the menu bar, click on [Product] -> [Clean Build Folder] to delete all compiled binaries

Clean Build Folder

Resetting a setTimeout

You will have to remember the timeout "Timer", cancel it, then restart it:

g_timer = null;

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

function startTimer() {
    g_timer = window.setTimeout(function() {
        window.location.href = 'file.php';
    }, 115000);
}

function onClick() {
    clearTimeout(g_timer);
    startTimer();
}

Getting around the Max String size in a vba function?

Couldn't you just have another sub that acts as a caller using module level variable(s) for the arguments you want to pass. For example...

Option Explicit
Public strMsg As String

Sub Scheduler()

    strMsg = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    Application.OnTime Now + TimeValue("00:00:01"), "'Caller'"

End Sub

Sub Caller()

    Call aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa("It Works! " & strMsg)

End Sub

Sub aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(strMessage As String)

    MsgBox strMessage

End Sub

How to properly set the 100% DIV height to match document/window height?

Use #element{ height:100vh}

This will set the height of the #element to 100% of viewport. Hope this helps.

ImportError: No module named 'django.core.urlresolvers'

For django version greater than 2.0 use:

from django.urls import reverse

in your models.py file.

Write / add data in JSON file using Node.js

I agree with above answers, Here is a complete read and write sample for anyone who needs it.

     router.post('/', function(req, res, next) {

        console.log(req.body);
        var id = Math.floor((Math.random()*100)+1);

        var tital = req.body.title;
        var description = req.body.description;
        var mynotes = {"Id": id, "Title":tital, "Description": description};
        
        fs.readFile('db.json','utf8', function(err,data){
            var obj = JSON.parse(data);
            obj.push(mynotes);
            var strNotes = JSON.stringify(obj);
            fs.writeFile('db.json',strNotes, function(err){
                if(err) return console.log(err);
                console.log('Note added');
            });

        })
        
        
    });


  

Runtime vs. Compile time

For example: In a strongly typed language, a type could be checked at compile time or at runtime. At compile time it means, that the compiler complains if the types are not compatible. At runtime means, that you can compile your program just fine but at runtime, it throws an exception.

How to force 'cp' to overwrite directory instead of creating another one inside?

The operation you defined is a "merge" and you cannot do that with cp. However, if you are not looking for merging and ok to lose the folder bar then you can simply rm -rf bar to delete the folder and then mv foo bar to rename it. This will not take any time as both operations are done by file pointers, not file contents.

Removing double quotes from variables in batch file creates problems with CMD environment

You have an extra double quote at the end, which is adding it back to the end of the string (after removing both quotes from the string).

Input:

set widget="a very useful item"
set widget
set widget=%widget:"=%
set widget

Output:

widget="a very useful item"
widget=a very useful item

Note: To replace Double Quotes " with Single Quotes ' do the following:

set widget=%widget:"='%

Note: To replace the word "World" (not case sensitive) with BobB do the following:

set widget="Hello World!"
set widget=%widget:world=BobB%
set widget

Output:

widget="Hello BobB!"

As far as your initial question goes (save the following code to a batch file .cmd or .bat and run):

@ECHO OFF
ECHO %0
SET BathFileAndPath=%~0
ECHO %BathFileAndPath%
ECHO "%BathFileAndPath%"
ECHO %~0
ECHO %0
PAUSE

Output:

"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd
"C:\Users\Test\Documents\Batch Files\Remove Quotes.cmd"
Press any key to continue . . .

%0 is the Script Name and Path.
%1 is the first command line argument, and so on.

Select top 1 result using JPA

The easiest way is by using @Query with NativeQuery option like below:

@Query(value="SELECT 1 * FROM table ORDER BY anyField DESC LIMIT 1", nativeQuery = true)

Complexities of binary tree traversals

In-order, Pre-order, and Post-order traversals are Depth-First traversals.

For a Graph, the complexity of a Depth First Traversal is O(n + m), where n is the number of nodes, and m is the number of edges.

Since a Binary Tree is also a Graph, the same applies here. The complexity of each of these Depth-first traversals is O(n+m).

Since the number of edges that can originate from a node is limited to 2 in the case of a Binary Tree, the maximum number of total edges in a Binary Tree is n-1, where n is the total number of nodes.

The complexity then becomes O(n + n-1), which is O(n).

Difference between onStart() and onResume()

onStart() called when the activity is becoming visible to the user. onResume() called when the activity will start interacting with the user. You may want to do different things in this cases.

See this link for reference.

Eclipse CDT project built but "Launch Failed. Binary Not Found"

This happened to me and I found a solution, see if this works for you:

Once you have built your project with the hammer icon:

  1. select "Run".
  2. Run Configurations.
  3. Choose "C++ Application".
  4. Click on the "New Launch Configuration" icon on the top left of the open window.
  5. Select "Browse" under the C/C++ Application.
  6. Browse to the folder where you made your project initially.
  7. Enter the Debug folder.
  8. Click on the binary file with the same name as the project.
  9. Select "OK".
  10. Click "Apply" to confirm the link you just set.
  11. Close that window.

Afterwards you should be able to run the project as much as you'd like.

Hopefully this works for you.

Change the name of a key in dictionary

In python 2.7 and higher, you can use dictionary comprehension: This is an example I encountered while reading a CSV using a DictReader. The user had suffixed all the column names with ':'

ori_dict = {'key1:' : 1, 'key2:' : 2, 'key3:' : 3}

to get rid of the trailing ':' in the keys:

corrected_dict = { k.replace(':', ''): v for k, v in ori_dict.items() }

Windows batch command(s) to read first line from text file

Another way

setlocal enabledelayedexpansion
@echo off
for /f "delims=" %%i in (filename.txt) do (
if 1==1 (
set first_line=%%i
echo !first_line!
goto :eof
))

How can I let a user download multiple files when a button is clicked?

Found the easiest way to do this. Works even with div!

<div onclick="downloadFiles()">
  <!--do not put any text in <a>, it should be invisible-->
  <a href="path/file1" id="a1" download></a>
  <a href="path/file2" id="a2" download></a>
  <a href="path/file3" id="a3" download></a>
  <script>
    function downloadFiles() {
      document.getElementById("a1").click();
      document.getElementById("a2").click();
      document.getElementById("a3").click();
    }
  </script>
  Download
</div>

That's all, hope it helps.

How to get my project path?

Your program has no knowledge of where your VS project is, so see get path for my .exe and go ../.. to get your project's path.

Creating a new empty branch for a new project

Let's say you have a master branch with files/directories:

> git branch  
master
> ls -la # (files and dirs which you may keep in master)
.git
directory1
directory2
file_1
..
file_n

Step by step how to make an empty branch:

  1. git checkout —orphan new_branch_name
  2. Make sure you are in the right directory before executing the following command:
    ls -la |awk '{print $9}' |grep -v git |xargs -I _ rm -rf ./_
  3. git rm -rf .
  4. touch new_file
  5. git add new_file
  6. git commit -m 'added first file in the new branch'
  7. git push origin new_branch_name

In step 2, we simply remove all the files locally to avoid confusion with the files on your new branch and those ones you keep in master branch. Then, we unlink all those files in step 3. Finally, step 4 and after are working with our new empty branch.

Once you're done, you can easily switch between your branches:

git checkout master 
git checkout new_branch

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

I had a similar problem when I had installed the 12c database as per Oracle's tutorial . The instruction instructs reader to create a PLUGGABLE DATABASE (pdb).

The problem

sqlplus hr/hr@pdborcl would result in ORACLE initialization or shutdown in progress.

The solution

    1. Login as SYSDBA to the dabase :

      sqlplus SYS/Oracle_1@pdborcl AS SYSDBA
      
    1. Alter database:

      alter pluggable database pdborcl open read write;
      
    1. Login again:

      sqlplus hr/hr@pdborcl
      

That worked for me

Some documentation here

Generating CSV file for Excel, how to have a newline inside a value

You could use keyboard shortcut ALT+Enter.

  1. Select the cell you wish to edit
  2. enter edit mode either by double clicking it or pressing F2 3.Press Alt+enter. This will create a new line in cell

Looking for simple Java in-memory cache

Ehcache is a pretty good solution for this and has a way to peek (getQuiet() is the method) such that it doesn't update the idle timestamp. Internally, Ehcache is implemented with a set of maps, kind of like ConcurrentHashMap, so it has similar kinds of concurrency benefits.

Cannot open new Jupyter Notebook [Permission Denied]

change the ownership of the ~/.local/share/jupyter directory from root to user.

sudo chown -R user:user ~/.local/share/jupyter 

see here: https://github.com/ipython/ipython/issues/8997

The first user before the colon is your username, the second user after the colon is your group. If you get chown: [user]: illegal group name, find your group with groups, or specify no group with sudo chown user: ~/.local/share/jupyter.

EDIT: Added -R option in comments to the answer. You have to change ownership of all files inside this directory (or inside ~/.jupyter/, wherever it gives you PermissionError) to your user to make it work.

How to simulate browsing from various locations?

The only thing that springs to mind for this is to use a proxy server based in Europe. Either have your colleague set one up [if possible] or find a free proxy. A quick Google search came up with http://www.anonymousinet.com/ as the top result.

Xcode stuck on Indexing

I had the same issue in swift 2.2

It had to do with a generic function overloaded function

func warnLog() {
    print("Warning line: \(#line) file: \(#file) ")
}

func warnLog<T>(input:T? = nil) -> T? {
    print("Warning line: \(#line) file: \(#file) ")
    return input
}

func warnLog<T>(input:T) -> T {
    print("Warning line: \(#line) file: \(#file) ")
    return input
}

all I needed to do is remove one of the non used overloads

func warnLog<T>(input:T? = nil) -> T? {
    print("Warning line: \(#line) file: \(#file) ")
    return input
}

What is the apply function in Scala?

It comes from the idea that you often want to apply something to an object. The more accurate example is the one of factories. When you have a factory, you want to apply parameter to it to create an object.

Scala guys thought that, as it occurs in many situation, it could be nice to have a shortcut to call apply. Thus when you give parameters directly to an object, it's desugared as if you pass these parameters to the apply function of that object:

class MyAdder(x: Int) {
  def apply(y: Int) = x + y
}

val adder = new MyAdder(2)
val result = adder(4) // equivalent to x.apply(4)

It's often use in companion object, to provide a nice factory method for a class or a trait, here is an example:

trait A {
  val x: Int
  def myComplexStrategy: Int
}

object A {
  def apply(x: Int): A = new MyA(x)

  private class MyA(val x: Int) extends A {
    val myComplexStrategy = 42
  }
}

From the scala standard library, you might look at how scala.collection.Seq is implemented: Seq is a trait, thus new Seq(1, 2) won't compile but thanks to companion object and apply, you can call Seq(1, 2) and the implementation is chosen by the companion object.

Bootstrap 4, how to make a col have a height of 100%?

I solved this like this:

    <section className="container-fluid">
            <div className="row justify-content-center">

                <article className="d-flex flex-column justify-content-center align-items-center vh-100">
                        <!-- content -->
                </article>

            </div>
    </section>

How to count certain elements in array?

I believe what you are looking for is functional approach

    const arr = ['a', 'a', 'b', 'g', 'a', 'e'];
    const count = arr.filter(elem => elem === 'a').length;
    console.log(count); // Prints 3

elem === 'a' is the condition, replace it with your own.

How can I get a resource "Folder" from inside my jar File?

As the other answers point out, once the resources are inside a jar file, things get really ugly. In our case, this solution:

https://stackoverflow.com/a/13227570/516188

works very well in the tests (since when the tests are run the code is not packed in a jar file), but doesn't work when the app actually runs normally. So what I've done is... I hardcode the list of the files in the app, but I have a test which reads the actual list from disk (can do it since that works in tests) and fails if the actual list doesn't match with the list the app returns.

That way I have simple code in my app (no tricks), and I'm sure I didn't forget to add a new entry in the list thanks to the test.

Why does git revert complain about a missing -m option?

Say the other guy created bar on top of foo, but you created baz in the meantime and then merged, giving a history of

$ git lola
*   2582152 (HEAD, master) Merge branch 'otherguy'
|\  
| * c7256de (otherguy) bar
* | b7e7176 baz
|/  
* 9968f79 foo

Note: git lola is a non-standard but useful alias.

No dice with git revert:

$ git revert HEAD
fatal: Commit 2582152... is a merge but no -m option was given.

Charles Bailey gave an excellent answer as usual. Using git revert as in

$ git revert --no-edit -m 1 HEAD
[master e900aad] Revert "Merge branch 'otherguy'"
 0 files changed, 0 insertions(+), 0 deletions(-)
 delete mode 100644 bar

effectively deletes bar and produces a history of

$ git lola
* e900aad (HEAD, master) Revert "Merge branch 'otherguy'"
*   2582152 Merge branch 'otherguy'
|\  
| * c7256de (otherguy) bar
* | b7e7176 baz
|/  
* 9968f79 foo

But I suspect you want to throw away the merge commit:

$ git reset --hard HEAD^
HEAD is now at b7e7176 baz

$ git lola
* b7e7176 (HEAD, master) baz
| * c7256de (otherguy) bar
|/  
* 9968f79 foo

As documented in the git rev-parse manual

<rev>^, e.g. HEAD^, v1.5.1^0
A suffix ^ to a revision parameter means the first parent of that commit object. ^<n> means the n-th parent (i.e. <rev>^ is equivalent to <rev>^1). As a special rule, <rev>^0 means the commit itself and is used when <rev> is the object name of a tag object that refers to a commit object.

so before invoking git reset, HEAD^ (or HEAD^1) was b7e7176 and HEAD^2 was c7256de, i.e., respectively the first and second parents of the merge commit.

Be careful with git reset --hard because it can destroy work.

How to say no to all "do you want to overwrite" prompts in a batch file copy?

I know you all think /D: date is going to use date stuff, but just /D without the: does exactly what we want so...

xcopy {Source} {Destination} /E /D 

Will copy without overwriting to pickup those files that are new or maybe failed before for some reason.

Just try it, it works.