Programs & Examples On #Implicits

Fetching distinct values on a column using Spark DataFrame

This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates which is more suitable than distinct for certain queries.

Suppose you have this DataFrame:

+-------+-------------+
|country|    continent|
+-------+-------------+
|  china|         asia|
| brazil|south america|
| france|       europe|
|  china|         asia|
+-------+-------------+

Here's how to take all the distinct countries and run a transformation:

df
  .select("country")
  .distinct
  .withColumn("country", concat(col("country"), lit(" is fun!")))
  .show()
+--------------+
|       country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+

You can use dropDuplicates instead of distinct if you don't want to lose the continent information:

df
  .dropDuplicates("country")
  .withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
  .show(false)
+-------+-------------+------------------------------------+
|country|continent    |description                         |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe       |france is a country in europe       |
|china  |asia         |china is a country in asia          |
+-------+-------------+------------------------------------+

See here for more information about filtering DataFrames and here for more information on dropping duplicates.

Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.

sort files by date in PHP

I use your exact proposed code with only some few additional lines. The idea is more or less the same of the one proposed by @elias, but in this solution there cannot be conflicts on the keys since each file in the directory has a different filename and so adding it to the key solves the conflicts. The first part of the key is the datetime string formatted in a manner such that I can lexicographically compare two of them.

if ($handle = opendir('.')) {
    $result = array();
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $lastModified = date('F d Y, H:i:s',filemtime($file));
            if(strlen($file)-strpos($file,".swf")== 4){
                $result [date('Y-m-d H:i:s',filemtime($file)).$file] =
                    "<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
            }
        }
    }
    closedir($handle);
    krsort($result);
    echo implode('', $result);
}

SQLRecoverableException: I/O Exception: Connection reset

add java security in your run command

java -jar -Djava.security.egd="file:///dev/urandom" yourjarfilename.jar

Codeigniter : calling a method of one controller from other

Controller to be extended

require_once(PHYSICAL_BASE_URL . 'system/application/controllers/abc.php');

        $report= new onlineAssessmentReport();
        echo ($report->detailView());

Convert an integer to a byte array

I agree with Brainstorm's approach: assuming that you're passing a machine-friendly binary representation, use the encoding/binary library. The OP suggests that binary.Write() might have some overhead. Looking at the source for the implementation of Write(), I see that it does some runtime decisions for maximum flexibility.

func Write(w io.Writer, order ByteOrder, data interface{}) error {
    // Fast path for basic types.
    var b [8]byte
    var bs []byte
    switch v := data.(type) {
    case *int8:
        bs = b[:1]
        b[0] = byte(*v)
    case int8:
        bs = b[:1]
        b[0] = byte(v)
    case *uint8:
        bs = b[:1]
        b[0] = *v
    ...

Right? Write() takes in a very generic data third argument, and that's imposing some overhead as the Go runtime then is forced into encoding type information. Since Write() is doing some runtime decisions here that you simply don't need in your situation, maybe you can just directly call the encoding functions and see if it performs better.

Something like this:

package main

import (
    "encoding/binary"
    "fmt"
)

func main() {
    bs := make([]byte, 4)
    binary.LittleEndian.PutUint32(bs, 31415926)
    fmt.Println(bs)
}

Let us know how this performs.

Otherwise, if you're just trying to get an ASCII representation of the integer, you can get the string representation (probably with strconv.Itoa) and cast that string to the []byte type.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    bs := []byte(strconv.Itoa(31415926))
    fmt.Println(bs)
}

AJAX Mailchimp signup form integration

For anyone looking for a solution on a modern stack:

import jsonp from 'jsonp';
import queryString from 'query-string';

// formData being an object with your form data like:
// { EMAIL: '[email protected]' }

jsonp(`//YOURMAILCHIMP.us10.list-manage.com/subscribe/post-json?u=YOURMAILCHIMPU&${queryString.stringify(formData)}`, { param: 'c' }, (err, data) => {
  console.log(err);
  console.log(data);
});

Why is this HTTP request not working on AWS Lambda?

enter image description here

Add above code in API gateway under GET-Integration Request> mapping section.

Invalid syntax when using "print"?

They changed print in Python 3. In 2 it was a statement, now it is a function and requires parenthesis.

Here's the docs from Python 3.0.

HTTP POST using JSON in Java

I recomend http-request built on apache http api.

HttpRequest<String> httpRequest = HttpRequestBuilder.createPost(yourUri, String.class)
    .responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();

public void send(){
   ResponseHandler<String> responseHandler = httpRequest.execute("details", yourJsonData);

   int statusCode = responseHandler.getStatusCode();
   String responseContent = responseHandler.orElse(null); // returns Content from response. If content isn't present returns null. 
}

If you want send JSON as request body you can:

  ResponseHandler<String> responseHandler = httpRequest.executeWithBody(yourJsonData);

I higly recomend read documentation before use.

C++ deprecated conversion from string constant to 'char*'

In fact a string constant literal is neither a const char * nor a char* but a char[]. Its quite strange but written down in the c++ specifications; If you modify it the behavior is undefined because the compiler may store it in the code segment.

What does the colon (:) operator do?

In your specific case,

String cardString = "";
for (PlayingCard c : this.list)  // <--
{
    cardString = cardString + c + "\n";
}

this.list is a collection (list, set, or array), and that code assigns c to each element of the collection.

So, if this.list were a collection {"2S", "3H", "4S"} then the cardString on the end would be this string:

2S
3H
4S

percentage of two int?

Two options:

Do the division after the multiplication:

int n = 25;
int v = 100;
int percent = n * 100 / v;

Convert an int to a float before dividing

int n = 25;
int v = 100;
float percent = n * 100f / v;
//Or:
//  float percent = (float) n * 100 / v;
//  float percent = n * 100 / (float) v;

How can VBA connect to MySQL database in Excel?

Updating this topic with a more recent answer, solution that worked for me with version 8.0 of MySQL Connector/ODBC (downloaded at https://downloads.mysql.com/archives/c-odbc/):

Public oConn As ADODB.Connection
Sub MySqlInit()
    If oConn Is Nothing Then
        Dim str As String
        str = "Driver={MySQL ODBC 8.0 Unicode Driver};SERVER=xxxxx;DATABASE=xxxxx;PORT=3306;UID=xxxxx;PWD=xxxxx;"
        Set oConn = New ADODB.Connection
        oConn.Open str
    End If
End Sub

The most important thing on this matter is to check the proper name and version of the installed driver at: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers\

What is the final version of the ADT Bundle?

You can also get an updated version of the Eclipse's ADT plugin (based on an unreleased 24.2.0 version) that I managed to patch and compile at https://github.com/khaledev/ADT.

How to place two forms on the same page?

You could make two forms with 2 different actions

<form action="login.php" method="post">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="submit" value="Login">
</form>

<br />

<form action="register.php" method="post">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="submit" value="Register">
</form>

Or do this

<form action="doStuff.php" method="post">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="hidden" name="action" value="login">
    <input type="submit" value="Login">
</form>

<br />

<form action="doStuff.php" method="post">
    <input type="text" name="user">
    <input type="password" name="password">
    <input type="hidden" name="action" value="register">
    <input type="submit" value="Register">
</form>

Then you PHP file would work as a switch($_POST['action']) ... furthermore, they can't click on both links at the same time or make a simultaneous request, each submit is a separate request.

Your PHP would then go on with the switch logic or have different php files doing a login procedure then a registration procedure

Changing the size of a column referenced by a schema-bound view in SQL Server

here is what works with the version of the program that I'm using: may work for you too.

I will just place the instruction and command that does it. class is the name of the table. you change it in the table its self with this method. not just the return on the search process.


view the table class

select * from class

change the length of the columns FacID (seen as "faci") and classnumber (seen as "classnu") to fit the whole labels.

alter table class modify facid varchar (5);

alter table class modify classnumber varchar(11);

view table again to see the difference

select * from class;

(run the command again to see the difference)


This changes the the actual table for good, but for better.

P.S. I made these instructions up as a note for the commands. This is not a test, but can help on one :)

Finding a substring within a list in Python

I'd just use a simple regex, you can do something like this

import re
old_list = ['abc123', 'def456', 'ghi789']
new_list = [x for x in old_list if re.search('abc', x)]
for item in new_list:
    print item

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

Validating URL in Java

Use the android.webkit.URLUtil on android:

URLUtil.isValidUrl(URL_STRING);

Note: It is just checking the initial scheme of URL, not that the entire URL is valid.

SVN Repository Search

A lot of SVN repos are "simply" HTTP sites, so you might consider looking at some off the shelf "web crawling" search app that you can point at the SVN root and it will give you basic functionality. Updating it will probably be a bit of a trick, perhaps some SVN check in hackery can tickle the index to discard or reindex changes as you go.

Just thinking out loud.

Missing Maven dependencies in Eclipse project

So I'm about 4 or 5 years late to this party, but I had this issue after pulling from our repo, and none of the other solutions from this thread worked out in my case to get rid of these warnings/errors.

This worked for me:

From Eclipse go to to Window -> Preferences -> Maven (expand) -> Errors/Warnings. The last option reads "Plugin execution not covered by lifecycle configuration" - use the drop-down menu for this option and toggle "Ignore", then Apply, then OK. (At "Requires updating Maven Projects" prompt say OK).

Further Info:

This may not necessarily "fix" the underlying issue(s), and may not qualify as "best practice" by some, however it should remove/supress these warnings from appearing in Eclipse and let you move forward at least. Specifically - I was working with Eclipse Luna Service Release 1 (4.4.1) w/ Spring Dashboard & Spring IDE Core (3.6.3), and m2e (1.5) installed, running on Arch Linux and OpenJDK 1.7. I imported my project as an existing maven project and selected OK when warned about existing warnings/errors (to deal with them later).

Suppress/Remove "Plugin Execution not covered..." warnings Eclipse-Maven

(Sorry, I'm not a designer, but added picture for clarity.)

How to capture a JFrame's close button click event?

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

also works. First create a JFrame called frame, then add this code underneath.

What is the hamburger menu icon called and the three vertical dots icon called?

According to Reddit, more options icon and kabob menu are popular names. I prefer the latter as it goes well with hamburger menu.

Oracle - How to generate script from sql developer

In Oracle the location that contains information about all database objects including tables and stored procedures is called the Data Dictionary. It is a collection of views that provides you with access to the metadata that defines the database. You can query the Data Dictionary views for a list of desired database objects and then use the functions available in dbms_metadata package to get the DDL for each object. Alternative is to investigate the support in dbms_metadata to export DDLs for a collection of objects.

For a few pointers, for example to get a list of tables you can use the following Data Dictionary views

  • user_tables contains all tables owned by the user
  • all_tables contains all tables that are accessible by the user
  • and so on...

HttpUtility does not exist in the current context

It worked for by following process:

Add Reference:

system.net
system.web

also, include the namespace

using system.net
using system.web

How to send email from MySQL 5.1

I agree with Jim Blizard. The database is not the part of your technology stack that should send emails. For example, what if you send an email but then roll back the change that triggered that email? You can't take the email back.

It's better to send the email in your application code layer, after your app has confirmed that the SQL change was made successfully and committed.

How to set app icon for Electron / Atom Shell App

Setting the icon property when creating the BrowserWindow only has an effect on Windows and Linux.

To set the icon on OS X, you can use electron-packager and set the icon using the --icon switch.

It will need to be in .icns format for OS X. There is an online icon converter which can create this file from your .png.

PHP Warning: mysqli_connect(): (HY000/2002): Connection refused

You have to change the mamp Mysql Database port into 8889.

Usage of @see in JavaDoc?

@see is useful for information about related methods/classes in an API. It will produce a link to the referenced method/code on the documentation. Use it when there is related code that might help the user understand how to use the API.

How to open warning/information/error dialog in Swing?

JOptionPane.showOptionDialog
JOptionPane.showMessageDialog
....

Have a look on this tutorial on how to make dialogs.

What does git rev-parse do?

git rev-parse is an ancillary plumbing command primarily used for manipulation.

One common usage of git rev-parse is to print the SHA1 hashes given a revision specifier. In addition, it has various options to format this output such as --short for printing a shorter unique SHA1.

There are other use cases as well (in scripts and other tools built on top of git) that I've used for:

  • --verify to verify that the specified object is a valid git object.
  • --git-dir for displaying the abs/relative path of the the .git directory.
  • Checking if you're currently within a repository using --is-inside-git-dir or within a work-tree using --is-inside-work-tree
  • Checking if the repo is a bare using --is-bare-repository
  • Printing SHA1 hashes of branches (--branches), tags (--tags) and the refs can also be filtered based on the remote (using --remote)
  • --parse-opt to normalize arguments in a script (kind of similar to getopt) and print an output string that can be used with eval

Massage just implies that it is possible to convert the info from one form into another i.e. a transformation command. These are some quick examples I can think of:

  • a branch or tag name into the commit's SHA1 it is pointing to so that it can be passed to a plumbing command which only accepts SHA1 values for the commit.
  • a revision range A..B for git log or git diff into the equivalent arguments for the underlying plumbing command as B ^A

How do I get sed to read from standard input?

use "-e" to specify the sed-expression

cat input.txt | sed -e 's/foo/bar/g'

Best way to create enum of strings?

Use its name() method:

public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Strings.ONE.name());
    }
}

enum Strings {
    ONE, TWO, THREE
}

yields ONE.

Turn a number into star rating display using jQuery and CSS

Why not just have five separate images of a star (empty, quarter-full, half-full, three-quarter-full and full) then just inject the images into your DOM depending on the truncated or rouded value of rating multiplied by 4 (to get a whole numner for the quarters)?

For example, 4.8618164 multiplied by 4 and rounded is 19 which would be four and three quarter stars.

Alternatively (if you're lazy like me), just have one image selected from 21 (0 stars through 5 stars in one-quarter increments) and select the single image based on the aforementioned value. Then it's just one calculation followed by an image change in the DOM (rather than trying to change five different images).

How to escape double quotes in a title attribute

It may work with any character from the HTML Escape character list, but I had the same problem with a Java project. I used StringEscapeUtils.escapeHTML("Testing \" <br> <p>") and the title was <a href=".." title="Test&quot; &lt;br&gt; &lt;p&gt;">Testing</a>.

It only worked for me when I changed the StringEscapeUtils to StringEscapeUtils.escapeJavascript("Testing \" <br> <p>") and it worked in every browser.

jQuery, get html of a whole element

Differences might not be meaningful in a typical use case, but using the standard DOM functionality

$("#el")[0].outerHTML

is about twice as fast as

$("<div />").append($("#el").clone()).html();

so I would go with:

/* 
 * Return outerHTML for the first element in a jQuery object,
 * or an empty string if the jQuery object is empty;  
 */
jQuery.fn.outerHTML = function() {
   return (this[0]) ? this[0].outerHTML : '';  
};

How can I get the application's path in a .NET console application?

Probably a bit late but this is worth a mention:

Environment.GetCommandLineArgs()[0];

Or more correctly to get just the directory path:

System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);

Edit:

Quite a few people have pointed out that GetCommandLineArgs is not guaranteed to return the program name. See The first word on the command line is the program name only by convention. The article does state that "Although extremely few Windows programs use this quirk (I am not aware of any myself)". So it is possible to 'spoof' GetCommandLineArgs, but we are talking about a console application. Console apps are usually quick and dirty. So this fits in with my KISS philosophy.

Convert seconds into days, hours, minutes and seconds

Laravel example

700+ locales support by Carbon

\Carbon\CarbonInterval::seconds(1640467)->cascade()->forHumans(); //2 weeks 4 days 23 hours 41 minutes 7 seconds

Edit a text file on the console using Powershell

Kinesics Text Editor.

It's super fast and handles large text files, though minimal in features. There's a GUI version and console version (k.exe) included. Should work the same on linux.

Example: In my test it took 7 seconds to open a 500mb disk image.

screenshot

How to store images in mysql database using php

<!-- 
//THIS PROGRAM WILL UPLOAD IMAGE AND WILL RETRIVE FROM DATABASE. UNSING BLOB
(IF YOU HAVE ANY QUERY CONTACT:[email protected])


CREATE TABLE  `images` (
  `id` int(100) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `image` longblob NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB ;

-->
<!-- this form is user to store images-->
<form action="index.php" method="post"  enctype="multipart/form-data">
Enter the Image Name:<input type="text" name="image_name" id="" /><br />

<input name="image" id="image" accept="image/JPEG" type="file"><br /><br />
<input type="submit" value="submit" name="submit" />
</form>
<br /><br />
<!-- this form is user to display all the images-->
<form action="index.php" method="post"  enctype="multipart/form-data">
Retrive all the images:
<input type="submit" value="submit" name="retrive" />
</form>



<?php
//THIS IS INDEX.PHP PAGE
//connect to database.db name is images
        mysql_connect("", "", "") OR DIE (mysql_error());
        mysql_select_db ("") OR DIE ("Unable to select db".mysql_error());
//to retrive send the page to another page
if(isset($_POST['retrive']))
{
    header("location:search.php");

}

//to upload
if(isset($_POST['submit']))
{
if(isset($_FILES['image'])) {
        $name=$_POST['image_name'];
        $email=$_POST['mail'];
        $fp=addslashes(file_get_contents($_FILES['image']['tmp_name'])); //will store the image to fp
        }
                // our sql query
                $sql = "INSERT INTO images VALUES('null', '{$name}','{$fp}');";
                            mysql_query($sql) or die("Error in Query insert: " . mysql_error());
} 
?>



<?php
//SEARCH.PHP PAGE
    //connect to database.db name = images
         mysql_connect("localhost", "root", "") OR DIE (mysql_error());
        mysql_select_db ("image") OR DIE ("Unable to select db".mysql_error());
//display all the image present in the database

        $msg="";
        $sql="select * from images";
        if(mysql_query($sql))
        {
            $res=mysql_query($sql);
            while($row=mysql_fetch_array($res))
            {
                    $id=$row['id'];
                    $name=$row['name'];
                    $image=$row['image'];

                  $msg.= '<a href="search.php?id='.$id.'"><img src="data:image/jpeg;base64,'.base64_encode($row['image']). ' " />   </a>';

            }
        }
        else
            $msg.="Query failed";
?>
<div>
<?php
echo $msg;
?>

How to use ClassLoader.getResources() correctly?

There is no way to recursively search through the classpath. You need to know the Full pathname of a resource to be able to retrieve it in this way. The resource may be in a directory in the file system or in a jar file so it is not as simple as performing a directory listing of "the classpath". You will need to provide the full path of the resource e.g. '/com/mypath/bla.xml'.

For your second question, getResource will return the first resource that matches the given resource name. The order that the class path is searched is given in the javadoc for getResource.

Is it possible to insert multiple rows at a time in an SQLite database?

I am able to make the query dynamic. This is my table:

CREATE TABLE "tblPlanner" ("probid" text,"userid" TEXT,"selectedtime" DATETIME,"plannerid" TEXT,"isLocal" BOOL,"applicationid" TEXT, "comment" TEXT, "subject" TEXT)

and I'm getting all data through a JSON, so after getting everything inside an NSArray I followed this:

    NSMutableString *query = [[NSMutableString alloc]init];
    for (int i = 0; i < arr.count; i++)
    {
        NSString *sqlQuery = nil;
        sqlQuery = [NSString stringWithFormat:@" ('%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@'),",
                    [[arr objectAtIndex:i] objectForKey:@"plannerid"],
                    [[arr objectAtIndex:i] objectForKey:@"probid"],
                    [[arr objectAtIndex:i] objectForKey:@"userid"],
                    [[arr objectAtIndex:i] objectForKey:@"selectedtime"],
                    [[arr objectAtIndex:i] objectForKey:@"isLocal"],
                    [[arr objectAtIndex:i] objectForKey:@"subject"],
                    [[arr objectAtIndex:i] objectForKey:@"comment"],
                    [[NSUserDefaults standardUserDefaults] objectForKey:@"applicationid"]
                    ];
        [query appendString:sqlQuery];
    }
    // REMOVING LAST COMMA NOW
    [query deleteCharactersInRange:NSMakeRange([query length]-1, 1)];

    query = [NSString stringWithFormat:@"insert into tblPlanner (plannerid, probid, userid, selectedtime, isLocal, applicationid, subject, comment) values%@",query];

And finally the output query is this:

insert into tblPlanner (plannerid, probid, userid, selectedtime, isLocal, applicationid, subject, comment) values 
<append 1>
('pl1176428260', '', 'US32552', '2013-06-08 12:00:44 +0000', '0', 'subj', 'Hiss', 'ap19788'),
<append 2>
('pl2050411638', '', 'US32552', '2013-05-20 10:45:55 +0000', '0', 'TERI', 'Yahoooooooooo', 'ap19788'), 
<append 3>
('pl1828600651', '', 'US32552', '2013-05-21 11:33:33 +0000', '0', 'test', 'Yest', 'ap19788'),
<append 4>
('pl549085534', '', 'US32552', '2013-05-19 11:45:04 +0000', '0', 'subj', 'Comment', 'ap19788'), 
<append 5>
('pl665538927', '', 'US32552', '2013-05-29 11:45:41 +0000', '0', 'subj', '1234567890', 'ap19788'), 
<append 6>
('pl1969438050', '', 'US32552', '2013-06-01 12:00:18 +0000', '0', 'subj', 'Cmt', 'ap19788'),
<append 7>
('pl672204050', '', 'US55240280', '2013-05-23 12:15:58 +0000', '0', 'aassdd', 'Cmt', 'ap19788'), 
<append 8>
('pl1019026150', '', 'US32552', '2013-06-08 12:15:54 +0000', '0', 'exists', 'Cmt', 'ap19788'), 
<append 9>
('pl790670523', '', 'US55240280', '2013-05-26 12:30:21 +0000', '0', 'qwerty', 'Cmt', 'ap19788')

which is running well through code also and I'm able to save everything in SQLite successfully.

Before this i made UNION query stuff dynamic but that started giving some syntax error. Anyways, this is running well for me.

How do I comment on the Windows command line?

The command you're looking for is rem, short for "remark".

There is also a shorthand version :: that some people use, and this sort of looks like # if you squint a bit and look at it sideways. I originally preferred that variant since I'm a bash-aholic and I'm still trying to forget the painful days of BASIC :-)

Unfortunately, there are situations where :: stuffs up the command line processor (such as within complex if or for statements) so I generally use rem nowadays. In any case, it's a hack, suborning the label infrastructure to make it look like a comment when it really isn't. For example, try replacing rem with :: in the following example and see how it works out:

if 1==1 (
    rem comment line 1
    echo 1 equals 1
    rem comment line 2
)

You should also keep in mind that rem is a command, so you can't just bang it at the end of a line like the # in bash. It has to go where a command would go. For example, only the second of these two will echo the single word hello:

echo hello rem a comment.
echo hello & rem a comment.

Vertically align an image inside a div with responsive height

Try

Html

<div class="responsive-container">
     <div class="img-container">
         <IMG HERE>
     </div>
</div>

CSS

.img-container {
    position: absolute;
    top: 0;
    left: 0;
height:0;
padding-bottom:100%;
}
.img-container img {
width:100%;
}

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

I would like to give you a background on Universal CRT this would help you in understanding as to why the system should be updated before installing vc_redist.x64.exe.

  1. A large portion of the C-runtime moved into the OS in Windows 10 (ucrtbase.dll) and is serviced just like any other OS DLL (e.g. kernel32.dll). It is no longer serviced by Visual Studio directly. MSU packages are the file type for Windows Updates.
  2. In order to get the Windows 10 Universal CRT to earlier OSes, Windows Update packages were created to bring this OS component downlevel. KB2999226 brings the Windows 10 RTM Universal CRT to downlevel platforms (Windows Vista through Windows 8.1). KB3118401 brings Windows 10 November Update to the Universal CRT to downlevel platforms.
    • Windows XP (latest SP) is an exception here. Windows Servicing does not provide downlevel packages for that OS, so Visual Studio (Visual C++) provides a mechanism to install the UCRT into System32 via the VCRedist and MSMs.
  3. The Windows Universal Runtime is included in the VC Redist exe package as it has dependency on the Windows Universal Runtime (KB2999226).
  4. Windows 10 is the only OS that ships the UCRT in-box. All prior OSes obtain the UCRT via Windows Update only. This applies to all Vista->8.1 and associated Server SKUs.

For Windows 7, 8, and 8.1 the Windows Universal Runtime must be installed via KB2999226. However it has a prerequisite update KB2919355 which contains updates that facilitate installing the KB2999226 package.

Why does KB2999226 not always install when the runtime is installed from the redistributable? What could prevent KB2999226 from installing as part of the runtime?

The UCRT MSU included in the VCRedist is installed by making a call into the Windows Update service and the KB can fail to install based upon Windows Update service activity/state:

  1. If the machine has not updated to the required servicing baseline, the UCRT MSU will be viewed as being “Not Applicable”. Ensure KB2919355 is installed. Also, there were known issues with KB2919355 so before this the following hotfix should be installed. KB2939087 KB2975061
  2. If the Windows Update service is installing other updates when the VCRedist installs, you can either see long delays or errors indicating the machine is busy.
    • This one can be resolved by waiting and trying again later (which may be why installing via Windows Update UI at a later time succeeds).
  3. If the Windows Update service is in a non-ready state, you can see errors reflecting that.

    • We recently investigated a failure with an error code indicating the WUSA service was shutting down.
  4. To identify if the prerequisite KB2919355 is installed there are 2 options:

    1. Registry key: 64bit hive

      HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~amd64~~6.3.1.14
      CurrentState = 112
      

      32bit hive

      HKLM\SOFTWARE\[WOW6432Node\]Microsoft\Windows\CurrentVersion\Component Based Servicing\Packages\Package_for_KB2919355~31bf3856ad364e35~x86~~6.3.1.14
      CurrentState = 112
      
    2. Or check the file version of:

      C:\Windows\SysWOW64\wuaueng.dll
      C:\Windows\System32\wuaueng.dll
      

      is 7.9.9600.17031 or later

How to stop (and restart) the Rails Server?

if you are not able to find the rails process to kill it might actually be not running. Delete the tmp folder and its sub-folders from where you are running the rails server and try again.

How to fix docker: Got permission denied issue

It is definitely not the case the question was about, but as it is the first search result while googling the error message, I'll leave it here.

First of all, check if docker service is running using the following command:

systemctl status docker.service

If it is not running, try starting it:

sudo systemctl start docker.service

... and check the status again:

systemctl status docker.service

If it has not started, investigate the reason. Probably, you have modified a config file and made an error (like I did while modifying /etc/docker/daemon.json)

Server Error in '/' Application. ASP.NET

This wont necessarily fix the problem...but it will tell you what the real problem is.
Its currently trying to use a custom error page that doesn't exist.
If you add this line to Web.config (under system.web tag) it should give you the real error.

<system.web>
    <!-- added line -->
    <customErrors mode="Off"/>
    <!-- added  line -->
</system.web>

How to identify whether a grammar is LL(1), LR(0) or SLR(1)?

LL(1) grammar is Context free unambiguous grammar which can be parsed by LL(1) parsers.

In LL(1)

  • First L stands for scanning input from Left to Right. Second L stands for Left Most Derivation. 1 stands for using one input symbol at each step.

For Checking grammar is LL(1) you can draw predictive parsing table. And if you find any multiple entries in table then you can say grammar is not LL(1).

Their is also short cut to check if the grammar is LL(1) or not . Shortcut Technique

How to create an android app using HTML 5

The WebIntoApp.com V.2 allows you to convert HTML5 / JS / CSS into a mobile app for Android APK (free) and iOS.

(I'm the author)

When to use the !important property in CSS

You generally use !important when you've run out of other ways to increase the specificity of a CSS selector.

So once another CSS rule has already dabbled with Ids, inheritance paths and class names, when you need to override that rule then you need to use 'important'.

How do I import .sql files into SQLite 3?

From a sqlite prompt:

sqlite> .read db.sql

Or:

cat db.sql | sqlite3 database.db

Also, your SQL is invalid - you need ; on the end of your statements:

create table server(name varchar(50),ipaddress varchar(15),id init);
create table client(name varchar(50),ipaddress varchar(15),id init);

Python how to plot graph sine wave

import matplotlib.pyplot as plt # For ploting
import numpy as np # to work with numerical data efficiently

fs = 100 # sample rate 
f = 2 # the frequency of the signal

x = np.arange(fs) # the points on the x axis for plotting
# compute the value (amplitude) of the sin wave at the for each sample
y = np.sin(2*np.pi*f * (x/fs)) 

#this instruction can only be used with IPython Notbook. 
% matplotlib inline
# showing the exact location of the smaples
plt.stem(x,y, 'r', )
plt.plot(x,y)

enter image description here

How to read a file line-by-line into a list?

Outline and Summary

With a filename, handling the file from a Path(filename) object, or directly with open(filename) as f, do one of the following:

  • list(fileinput.input(filename))
  • using with path.open() as f, call f.readlines()
  • list(f)
  • path.read_text().splitlines()
  • path.read_text().splitlines(keepends=True)
  • iterate over fileinput.input or f and list.append each line one at a time
  • pass f to a bound list.extend method
  • use f in a list comprehension

I explain the use-case for each below.

In Python, how do I read a file line-by-line?

This is an excellent question. First, let's create some sample data:

from pathlib import Path
Path('filename').write_text('foo\nbar\nbaz')

File objects are lazy iterators, so just iterate over it.

filename = 'filename'
with open(filename) as f:
    for line in f:
        line # do something with the line

Alternatively, if you have multiple files, use fileinput.input, another lazy iterator. With just one file:

import fileinput

for line in fileinput.input(filename): 
    line # process the line

or for multiple files, pass it a list of filenames:

for line in fileinput.input([filename]*2): 
    line # process the line

Again, f and fileinput.input above both are/return lazy iterators. You can only use an iterator one time, so to provide functional code while avoiding verbosity I'll use the slightly more terse fileinput.input(filename) where apropos from here.

In Python, how do I read a file line-by-line into a list?

Ah but you want it in a list for some reason? I'd avoid that if possible. But if you insist... just pass the result of fileinput.input(filename) to list:

list(fileinput.input(filename))

Another direct answer is to call f.readlines, which returns the contents of the file (up to an optional hint number of characters, so you could break this up into multiple lists that way).

You can get to this file object two ways. One way is to pass the filename to the open builtin:

filename = 'filename'

with open(filename) as f:
    f.readlines()

or using the new Path object from the pathlib module (which I have become quite fond of, and will use from here on):

from pathlib import Path

path = Path(filename)

with path.open() as f:
    f.readlines()

list will also consume the file iterator and return a list - a quite direct method as well:

with path.open() as f:
    list(f)

If you don't mind reading the entire text into memory as a single string before splitting it, you can do this as a one-liner with the Path object and the splitlines() string method. By default, splitlines removes the newlines:

path.read_text().splitlines()

If you want to keep the newlines, pass keepends=True:

path.read_text().splitlines(keepends=True)

I want to read the file line by line and append each line to the end of the list.

Now this is a bit silly to ask for, given that we've demonstrated the end result easily with several methods. But you might need to filter or operate on the lines as you make your list, so let's humor this request.

Using list.append would allow you to filter or operate on each line before you append it:

line_list = []
for line in fileinput.input(filename):
    line_list.append(line)

line_list

Using list.extend would be a bit more direct, and perhaps useful if you have a preexisting list:

line_list = []
line_list.extend(fileinput.input(filename))
line_list

Or more idiomatically, we could instead use a list comprehension, and map and filter inside it if desirable:

[line for line in fileinput.input(filename)]

Or even more directly, to close the circle, just pass it to list to create a new list directly without operating on the lines:

list(fileinput.input(filename))

Conclusion

You've seen many ways to get lines from a file into a list, but I'd recommend you avoid materializing large quantities of data into a list and instead use Python's lazy iteration to process the data if possible.

That is, prefer fileinput.input or with path.open() as f.

Importing large sql file to MySql via command line

Guys regarding time taken for importing huge files most importantly it takes more time is because default setting of mysql is "autocommit = true", you must set that off before importing your file and then check how import works like a gem...

First open MySQL:

mysql -u root -p

Then, You just need to do following :

mysql>use your_db

mysql>SET autocommit=0 ; source the_sql_file.sql ; COMMIT ;

Easy way to prevent Heroku idling?

You can also try http://kaffeine.herokuapp.com (made by me), it's made for preventing Heroku apps to go to sleep. It will ping your app every 10 minutes so your app won't go to sleep. It's completely free.

Add to python path mac os x

Modifications to sys.path only apply for the life of that Python interpreter. If you want to do it permanently you need to modify the PYTHONPATH environment variable:

PYTHONPATH="/Me/Documents/mydir:$PYTHONPATH"
export PYTHONPATH

Note that PATH is the system path for executables, which is completely separate.

**You can write the above in ~/.bash_profile and the source it using source ~/.bash_profile

When to favor ng-if vs. ng-show/ng-hide?

Depends on your use case but to summarise the difference:

  1. ng-if will remove elements from DOM. This means that all your handlers or anything else attached to those elements will be lost. For example, if you bound a click handler to one of child elements, when ng-if evaluates to false, that element will be removed from DOM and your click handler will not work any more, even after ng-if later evaluates to true and displays the element. You will need to reattach the handler.
  2. ng-show/ng-hide does not remove the elements from DOM. It uses CSS styles to hide/show elements (note: you might need to add your own classes). This way your handlers that were attached to children will not be lost.
  3. ng-if creates a child scope while ng-show/ng-hide does not

Elements that are not in the DOM have less performance impact and your web app might appear to be faster when using ng-if compared to ng-show/ng-hide. In my experience, the difference is negligible. Animations are possible when using both ng-show/ng-hide and ng-if, with examples for both in the Angular documentation.

Ultimately, the question you need to answer is whether you can remove element from DOM or not?

What is the equivalent of Java's System.out.println() in Javascript?

console.log().

Chrome, Safari, and IE 8+ come with built-in consoles (as part of a larger set of development tools). If you're using Firefox, getfirebug.com.

How to set Spinner default value to null?

Using a custom spinner layout like this:

<?xml version="1.0" encoding="utf-8"?>
<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/spinnerTarget"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:textSize="14dp"         
          android:textColor="#000000"/>

In the activity:

    // populate the list
    ArrayList<String> dataList = new ArrayList<String>();
    for (int i = 0; i < 4; i++) {
        dataList.add("Item");
    }

    // set custom layout spinner_layout.xml and adapter
    Spinner spinnerObject = (Spinner) findViewById(R.id.spinnerObject);
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.drawable.spinner_layout, dataList);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerObject.setAdapter(dataAdapter);
    spinnerObject.setOnTouchListener(new View.OnTouchListener() { 

        public boolean onTouch(View v, MotionEvent event) {
            // to set value of first selection, because setOnItemSelectedListener will not dispatch if the user selects first element
            TextView spinnerTarget = (TextView)v.findViewById(R.id.spinnerTarget);
            spinnerTarget.setText(spinnerObject.getSelectedItem().toString());

            return false;
        }

    });
    spinnerObject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                private boolean selectionControl = true;

                public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                    // just the first time
                    if(selectionControl){

                        // find TextView in layout 
                        TextView spinnerTarget = (TextView)parent.findViewById(R.id.spinnerTarget);
                        // set spinner text empty
                        spinnerTarget.setText("");
                        selectionControl = false;
                    }
                    else{
                        // select object
                    }
                }

                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

HTML5 iFrame Seamless Attribute

It is possible to use the semless attribute right now, here i found a german article http://www.solife.cc/blog/html5-iframe-attribut-seamless-beispiele.html

and here are another presentation about this topic: http://benvinegar.github.com/seamless-talk/

You have to use the window.postMessage method to communicate between the parent and the iframe.

jquery, domain, get URL

jQuery is not needed, use simple javascript:

document.domain

How to check for Is not Null And Is not Empty string in SQL server?

You can use either one of these to check null, whitespace and empty strings.

WHERE COLUMN <> '' 

WHERE LEN(COLUMN) > 0

WHERE NULLIF(LTRIM(RTRIM(COLUMN)), '') IS NOT NULL

How to convert column with string type to int form in pyspark data frame?

You could use cast(as int) after replacing NaN with 0,

data_df = df.withColumn("Plays", df.call_time.cast('float'))

Saving results with headers in Sql Server Management Studio

The settings which has been advised to change in @Diego's accepted answer might be good if you want to set this option permanently for all future query sessions that you open within SQL Server Management Studio(SSMS). This is usually not the case. Also, changing this setting requires restarting SQL Server Management Studio (SSMS) application. This is again a 'not-so-nice' experience if you've many unsaved open query session windows and you are in the middle of some debugging.

SQL Server gives a much slick option of changing it on per session basis which is very quick, handy and convenient. I'm detailing the steps below using query options window:

  1. Right click in query editor window > Click Query Options... at the bottom of the context menu as shown below:

enter image description here

  1. Select Results > Grid in the left navigation pane. Check the Include column headers when copying or saving the results check box in right pane as shown below:

enter image description here

That's it. Your current session will honour your settings with immediate effect without restarting SSMS. Also, this setting won't be propagated to any future session. Effectively changing this setting on a per session basis is much less noisy.

How can I get last characters of a string

Assuming you will compare the substring against the end of another string and use the result as a boolean you may extend the String class to accomplish this:

String.prototype.endsWith = function (substring) {
  if(substring.length > this.length) return false;
  return this.substr(this.length - substring.length) === substring;
};

Allowing you to do the following:

var aSentenceToPonder = "This sentence ends with toad"; 
var frogString = "frog";
var toadString = "toad";
aSentenceToPonder.endsWith(frogString) // false
aSentenceToPonder.endsWith(toadString) // true

How to convert a negative number to positive?

If "keep a positive one" means you want a positive number to stay positive, but also convert a negative number to positive, use abs():

>>> abs(-1)
1
>>> abs(1)
1

Difference between two numpy arrays in python

You can also use numpy.subtract

It has the advantage over the difference operator, -, that you do not have to transform the sequences (list or tuples) into a numpy arrays — you save the two commands:

array1 = np.array([1.1, 2.2, 3.3])
array2 = np.array([1, 2, 3])

Example: (Python 3.5)

import numpy as np
result = np.subtract([1.1, 2.2, 3.3], [1, 2, 3])
print ('the difference =', result)

which gives you

the difference = [ 0.1  0.2  0.3]

Remember, however, that if you try to subtract sequences (lists or tuples) with the - operator you will get an error. In this case, you need the above commands to transform the sequences in numpy arrays

Wrong Code:

print([1.1, 2.2, 3.3] - [1, 2, 3])

Concat all strings inside a List<string> using LINQ

I have done this using LINQ:

var oCSP = (from P in db.Products select new { P.ProductName });

string joinedString = string.Join(",", oCSP.Select(p => p.ProductName));

Create MSI or setup project with Visual Studio 2012

Have you tried the "Publish" method? You just right click on the project file in the solution explorer and select "Publish" from the pop-up menu. This creates an installer in a few very simple steps.

You can do more configuration of the installer from the Publish tab in the project properties window.

NB: This method only works for WPF & Windows Forms apps.

Does React Native styles support gradients?

Just export your gradient as SVG and use it using react-native-svg and when after you import your component set width and height and preserveAspectRatio="xMinYMin slice"to scale an SVG gradient at your needs.

How can I handle the warning of file_get_contents() function in PHP?

Step 1: check the return code: if($content === FALSE) { // handle error here... }

Step 2: suppress the warning by putting an error control operator (i.e. @) in front of the call to file_get_contents(): $content = @file_get_contents($site);

Why doesn't Python have a sign function?

You dont need one, you can just use:

if not number == 0:
    sig = number/abs(number)
else:
    sig = 0

Or create a function as described by others:

sign = lambda x: bool(x > 0) - bool(x < 0)

def sign(x):
    return bool(x > 0) - bool(x < 0)

How can I call a method in Objective-C?

syntax is of objective c is

returnObj = [object functionName: parameters];

Where object is the object which has the method you're calling. If you're calling it from the same object, you'll use 'self'. This tutorial might help you out in learning Obj-C.

In your case it is simply

[self score];

If you want to pass a parameter then it is like that

- (void)score(int x) {
    // some code
}

and I have tried to call it in an other method like this:

- (void)score2 {
    [self score:x];
}

TypeError: 'NoneType' object is not iterable in Python

For me it was a case of having my Groovy hat on instead of the Python 3 one.

Forgot the return keyword at the end of a def function.

Had not been coding Python 3 in earnest for a couple of months. Was thinking last statement evaluated in routine was being returned per the Groovy (or Rust) way.

Took a few iterations, looking at the stack trace, inserting try: ... except TypeError: ... block debugging/stepping thru code to figure out what was wrong.

The solution for the message certainly did not make the error jump out at me.

Alphabet range in Python

Print the Upper and Lower case alphabets in python using a built-in range function

def upperCaseAlphabets():
    print("Upper Case Alphabets")
    for i in range(65, 91):
        print(chr(i), end=" ")
    print()

def lowerCaseAlphabets():
    print("Lower Case Alphabets")
    for i in range(97, 123):
        print(chr(i), end=" ")

upperCaseAlphabets();
lowerCaseAlphabets();

What's the regular expression that matches a square bracket?

In general, when you need a character that is "special" in regexes, just prefix it with a \. So a literal [ would be \[.

Call a python function from jinja2

is there any way to import a whole set of python functions and have them accessible from jinja2 ?

Yes there is, In addition to the other answers above, this works for me.

Create a class and populate it with the associated methods e.g

class Test_jinja_object:

    def __init__(self):
        self.myvar = 'sample_var'

    def clever_function (self):
        return 'hello' 

Then create an instance of your class in your view function and pass the resultant object to your template as a parameter for the render_template function

my_obj = Test_jinja_object()

Now in your template, you can call the class methods in jinja like so

{{ my_obj.clever_function () }}

How can I safely create a nested directory?

In Python 3.4 you can also use the brand new pathlib module:

from pathlib import Path
path = Path("/my/directory/filename.txt")
try:
    if not path.parent.exists():
        path.parent.mkdir(parents=True)
except OSError:
    # handle error; you can also catch specific errors like
    # FileExistsError and so on.

git add only modified changes and ignore untracked files

git commit -a -m "message"

-a : Includes all currently changed/deleted files in this commit. Keep in mind, however, that untracked (new) files are not included.

-m : Sets the commit's message

How to append to New Line in Node.js

use \r\n combination to append a new line in node js

  var stream = fs.createWriteStream("udp-stream.log", {'flags': 'a'});
  stream.once('open', function(fd) {
    stream.write(msg+"\r\n");
  });

round() for float in C++

Best way to rounding off a floating value by "n" decimal places, is as following with in O(1) time:-

We have to round off the value by 3 places i.e. n=3.So,

float a=47.8732355;
printf("%.3f",a);

Deleting an object in C++

Your code is indeed using the normal way to create and delete a dynamic object. Yes, it's perfectly normal (and indeed guaranteed by the language standard!) that delete will call the object's destructor, just like new has to invoke the constructor.

If you weren't instantiating Object1 directly but some subclass thereof, I'd remind you that any class intended to be inherited from must have a virtual destructor (so that the correct subclass's destructor can be invoked in cases analogous to this one) -- but if your sample code is indeed representative of your actual code, this cannot be your current problem -- must be something else, maybe in the destructor code you're not showing us, or some heap-corruption in the code you're not showing within that function or the ones it calls...?

BTW, if you're always going to delete the object just before you exit the function which instantiates it, there's no point in making that object dynamic -- just declare it as a local (storage class auto, as is the default) variable of said function!

Using StringWriter for XML Serialization

<TL;DR> The problem is rather simple, actually: you are not matching the declared encoding (in the XML declaration) with the datatype of the input parameter. If you manually added <?xml version="1.0" encoding="utf-8"?><test/> to the string, then declaring the SqlParameter to be of type SqlDbType.Xml or SqlDbType.NVarChar would give you the "unable to switch the encoding" error. Then, when inserting manually via T-SQL, since you switched the declared encoding to be utf-16, you were clearly inserting a VARCHAR string (not prefixed with an upper-case "N", hence an 8-bit encoding, such as UTF-8) and not an NVARCHAR string (prefixed with an upper-case "N", hence the 16-bit UTF-16 LE encoding).

The fix should have been as simple as:

  1. In the first case, when adding the declaration stating encoding="utf-8": simply don't add the XML declaration.
  2. In the second case, when adding the declaration stating encoding="utf-16": either
    1. simply don't add the XML declaration, OR
    2. simply add an "N" to the input parameter type: SqlDbType.NVarChar instead of SqlDbType.VarChar :-) (or possibly even switch to using SqlDbType.Xml)

(Detailed response is below)


All of the answers here are over-complicated and unnecessary (regardless of the 121 and 184 up-votes for Christian's and Jon's answers, respectively). They might provide working code, but none of them actually answer the question. The issue is that nobody truly understood the question, which ultimately is about how the XML datatype in SQL Server works. Nothing against those two clearly intelligent people, but this question has little to nothing to do with serializing to XML. Saving XML data into SQL Server is much easier than what is being implied here.

It doesn't really matter how the XML is produced as long as you follow the rules of how to create XML data in SQL Server. I have a more thorough explanation (including working example code to illustrate the points outlined below) in an answer on this question: How to solve “unable to switch the encoding” error when inserting XML into SQL Server, but the basics are:

  1. The XML declaration is optional
  2. The XML datatype stores strings always as UCS-2 / UTF-16 LE
  3. If your XML is UCS-2 / UTF-16 LE, then you:
    1. pass in the data as either NVARCHAR(MAX) or XML / SqlDbType.NVarChar (maxsize = -1) or SqlDbType.Xml, or if using a string literal then it must be prefixed with an upper-case "N".
    2. if specifying the XML declaration, it must be either "UCS-2" or "UTF-16" (no real difference here)
  4. If your XML is 8-bit encoded (e.g. "UTF-8" / "iso-8859-1" / "Windows-1252"), then you:
    1. need to specify the XML declaration IF the encoding is different than the code page specified by the default Collation of the database
    2. you must pass in the data as VARCHAR(MAX) / SqlDbType.VarChar (maxsize = -1), or if using a string literal then it must not be prefixed with an upper-case "N".
    3. Whatever 8-bit encoding is used, the "encoding" noted in the XML declaration must match the actual encoding of the bytes.
    4. The 8-bit encoding will be converted into UTF-16 LE by the XML datatype

With the points outlined above in mind, and given that strings in .NET are always UTF-16 LE / UCS-2 LE (there is no difference between those in terms of encoding), we can answer your questions:

Is there a reason why I shouldn't use StringWriter to serialize an Object when I need it as a string afterwards?

No, your StringWriter code appears to be just fine (at least I see no issues in my limited testing using the 2nd code block from the question).

Wouldn't setting the encoding to UTF-16 (in the xml tag) work then?

It isn't necessary to provide the XML declaration. When it is missing, the encoding is assumed to be UTF-16 LE if you pass the string into SQL Server as NVARCHAR (i.e. SqlDbType.NVarChar) or XML (i.e. SqlDbType.Xml). The encoding is assumed to be the default 8-bit Code Page if passing in as VARCHAR (i.e. SqlDbType.VarChar). If you have any non-standard-ASCII characters (i.e. values 128 and above) and are passing in as VARCHAR, then you will likely see "?" for BMP characters and "??" for Supplementary Characters as SQL Server will convert the UTF-16 string from .NET into an 8-bit string of the current Database's Code Page before converting it back into UTF-16 / UCS-2. But you shouldn't get any errors.

On the other hand, if you do specify the XML declaration, then you must pass into SQL Server using the matching 8-bit or 16-bit datatype. So if you have a declaration stating that the encoding is either UCS-2 or UTF-16, then you must pass in as SqlDbType.NVarChar or SqlDbType.Xml. Or, if you have a declaration stating that the encoding is one of the 8-bit options (i.e. UTF-8, Windows-1252, iso-8859-1, etc), then you must pass in as SqlDbType.VarChar. Failure to match the declared encoding with the proper 8 or 16 -bit SQL Server datatype will result in the "unable to switch the encoding" error that you were getting.

For example, using your StringWriter-based serialization code, I simply printed the resulting string of the XML and used it in SSMS. As you can see below, the XML declaration is included (because StringWriter does not have an option to OmitXmlDeclaration like XmlWriter does), which poses no problem so long as you pass the string in as the correct SQL Server datatype:

-- Upper-case "N" prefix == NVARCHAR, hence no error:
DECLARE @Xml XML = N'<?xml version="1.0" encoding="utf-16"?>
<string>Test ?</string>';
SELECT @Xml;
-- <string>Test ?</string>

As you can see, it even handles characters beyond standard ASCII, given that ? is BMP Code Point U+1234, and is Supplementary Character Code Point U+1F638. However, the following:

-- No upper-case "N" prefix on the string literal, hence VARCHAR:
DECLARE @Xml XML = '<?xml version="1.0" encoding="utf-16"?>
<string>Test ?</string>';

results in the following error:

Msg 9402, Level 16, State 1, Line XXXXX
XML parsing: line 1, character 39, unable to switch the encoding

Ergo, all of that explanation aside, the full solution to your original question is:

You were clearly passing the string in as SqlDbType.VarChar. Switch to SqlDbType.NVarChar and it will work without needing to go through the extra step of removing the XML declaration. This is preferred over keeping SqlDbType.VarChar and removing the XML declaration because this solution will prevent data loss when the XML includes non-standard-ASCII characters. For example:

-- No upper-case "N" prefix on the string literal == VARCHAR, and no XML declaration:
DECLARE @Xml2 XML = '<string>Test ?</string>';
SELECT @Xml2;
-- <string>Test ???</string>

As you can see, there is no error this time, but now there is data-loss 🙀.

Confused by python file mode "w+"

I suspect there are two ways to handle what I think you'r trying to achieve.

1) which is obvious, is open the file for reading only, read it into memory then open the file with t, then write your changes.

2) use the low level file handling routines:

# Open file in RW , create if it doesn't exist. *Don't* pass O_TRUNC
 fd = os.open(filename, os.O_RDWR | os.O_CREAT)

Hope this helps..

Differences between Ant and Maven

Maven acts as both a dependency management tool - it can be used to retrieve jars from a central repository or from a repository you set up - and as a declarative build tool. The difference between a "declarative" build tool and a more traditional one like ant or make is you configure what needs to get done, not how it gets done. For example, you can say in a maven script that a project should be packaged as a WAR file, and maven knows how to handle that.

Maven relies on conventions about how project directories are laid out in order to achieve its "declarativeness." For example, it has a convention for where to put your main code, where to put your web.xml, your unit tests, and so on, but also gives the ability to change them if you need to.

You should also keep in mind that there is a plugin for running ant commands from within maven:

http://maven.apache.org/plugins/maven-ant-plugin/

Also, maven's archetypes make getting started with a project really fast. For example, there is a Wicket archetype, which provides a maven command you run to get a whole, ready-to-run hello world-type project.

https://wicket.apache.org/start/quickstart.html

What is the difference between .*? and .* regular expressions?

Let's say you have:

<a></a>

<(.*)> would match a></a where as <(.*?)> would match a. The latter stops after the first match of >. It checks for one or 0 matches of .* followed by the next expression.

The first expression <(.*)> doesn't stop when matching the first >. It will continue until the last match of >.

Assign JavaScript variable to Java Variable in JSP

As JavaScript is client side and JSP is Server side.

So Javascript does not execute until it gets to the browser, But Java executes on the server. So, Java does not know the value of the JavaScript variable.

However you assign value of Java variable to JavaScript variable.

how to make log4j to write to the console as well

This works well for console in debug mode

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p - %m%n

Get checkbox list values with jQuery

You should use map for this.

$('input[type=checkbox]:checked').map(function(i, e) { 
    return $(e).val(); 
});

How do I navigate to a parent route from a child route?

If you are using the uiSref directive then you can do this

uiSref="^"

Apply CSS style attribute dynamically in Angular JS

On a generic note, you can use a combination of ng-if and ng-style incorporate conditional changes with change in background image.

<span ng-if="selectedItem==item.id"
      ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_active.png)',
                'background-size':'52px 57px',
                'padding-top':'70px',
                'background-repeat':'no-repeat',
                'background-position': 'center'}">
 </span>
 <span ng-if="selectedItem!=item.id"
       ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_deactivated.png)',
                'background-size':'52px 57px',
                'padding-top':'70px',
                'background-repeat':'no-repeat',
                'background-position': 'center'}">
 </span>

get jquery `$(this)` id

Do you mean that for a select element with an id of "next" you need to perform some specific script?

$("#next").change(function(){
    //enter code here
});

Html.DropdownListFor selected value not being set

For me general solution :)

@{
     var selectedCity = Model.Cities.Where(k => k.Id == Model.Addres.CityId).FirstOrDefault();
     if (selectedCity != null)
     { 
         @Html.DropDownListFor(model => model.Addres.CityId, new SelectList(Model.Cities, "Id", "Name", selectedCity.Id), new { @class = "form-control" })
     }
     else
     { 
         @Html.DropDownListFor(model => model.Cities, new SelectList(Model.Cities, "Id", "Name", "1"), new { @class = "form-control" })
     }
}

How to compare LocalDate instances Java 8

Using equals() LocalDate does override equals:

int compareTo0(LocalDate otherDate) {
    int cmp = (year - otherDate.year);
    if (cmp == 0) {
        cmp = (month - otherDate.month);
        if (cmp == 0) {
            cmp = (day - otherDate.day);
        }
    }
    return cmp;
}

If you are not happy with the result of equals(), you are good using the predefined methods of LocalDate.

Notice that all of those method are using the compareTo0() method and just check the cmp value. if you are still getting weird result (which you shouldn't), please attach an example of input and output

Difference between window.location.href and top.location.href

The first one adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

The second replaces the current history item so you can't go back to it.

See window.location:

  • assign(url): Load the document at the provided URL.

  • replace(url): Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

window.location.href = url;

is favoured over:

window.location = url;

Java: Getting a substring from a string starting after a particular character

I think that would be better if we use directly the split function

String toSplit = "/abc/def/ghfj.doc";

String result[] = toSplit.split("/");

String returnValue = result[result.length - 1]; //equals "ghfj.doc"

expected assignment or function call: no-unused-expressions ReactJS

In case someone having a problem like i had. I was using the parenthesis with the return statement on the same line at which i had written the rest of the code. Also, i used map function and props so i got so many brackets. In this case, if you're new to React you can avoid the brackets around the props, because now everyone prefers to use the arrow functions. And in the map function you can also avoid the brackets around your function callback.

props.sample.map(function callback => (
   ));

like so. In above code sample you can see there is only opening parenthesis at the left of the function callback.

How can I put a ListView into a ScrollView without it collapsing?

We could not use two scrolling simulteniuosly.We will have get total length of ListView and expand listview with the total height .Then we can add ListView in ScrollView directly or using LinearLayout because ScrollView have directly one child . copy setListViewHeightBasedOnChildren(lv) method in your code and expand listview then you can use listview inside scrollview. \layout xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
 <ScrollView

        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
         android:background="#1D1D1D"
        android:orientation="vertical"
        android:scrollbars="none" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#1D1D1D"
            android:orientation="vertical" >

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="40dip"
                android:background="#333"
                android:gravity="center_vertical"
                android:paddingLeft="8dip"
                android:text="First ListView"
                android:textColor="#C7C7C7"
                android:textSize="20sp" />

            <ListView
                android:id="@+id/first_listview"
                android:layout_width="260dp"
                android:layout_height="wrap_content"
                android:divider="#00000000"
               android:listSelector="#ff0000"
                android:scrollbars="none" />

               <TextView
                android:layout_width="fill_parent"
                android:layout_height="40dip"
                android:background="#333"
                android:gravity="center_vertical"
                android:paddingLeft="8dip"
                android:text="Second ListView"
                android:textColor="#C7C7C7"
                android:textSize="20sp" />

            <ListView
                android:id="@+id/secondList"
                android:layout_width="260dp"
                android:layout_height="wrap_content"
                android:divider="#00000000"
                android:listSelector="#ffcc00"
                android:scrollbars="none" />
  </LinearLayout>
  </ScrollView>

   </LinearLayout>

onCreate method in Activity class:

 import java.util.ArrayList;
  import android.app.Activity;
 import android.os.Bundle;
 import android.view.Menu;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ArrayAdapter;
 import android.widget.ListAdapter;
  import android.widget.ListView;

   public class MainActivity extends Activity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listview_inside_scrollview);
    ListView list_first=(ListView) findViewById(R.id.first_listview);
    ListView list_second=(ListView) findViewById(R.id.secondList);
    ArrayList<String> list=new ArrayList<String>();
    for(int x=0;x<30;x++)
    {
        list.add("Item "+x);
    }

       ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), 
          android.R.layout.simple_list_item_1,list);               
      list_first.setAdapter(adapter);

     setListViewHeightBasedOnChildren(list_first);

      list_second.setAdapter(adapter);

    setListViewHeightBasedOnChildren(list_second);
   }



   public static void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
        // pre-condition
        return;
    }

    int totalHeight = 0;
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(0, 0);
        totalHeight += listItem.getMeasuredHeight();
    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight
            + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
      }

LinkButton Send Value to Code Behind OnClick

Just add to the CommandArgument parameter and read it out on the Click handler:

<asp:LinkButton ID="ENameLinkBtn" runat="server" 
    style="font-weight: 700; font-size: 8pt;" CommandArgument="YourValueHere" 
    OnClick="ENameLinkBtn_Click" >

Then in your click event:

protected void ENameLinkBtn_Click(object sender, EventArgs e)
{
    LinkButton btn = (LinkButton)(sender);
    string yourValue = btn.CommandArgument;
    // do what you need here
}   

Also you can set the CommandArgument argument when binding if you are using the LinkButton in any bindable controls by doing:

CommandArgument='<%# Eval("SomeFieldYouNeedArguementFrom") %>'

How to get values from IGrouping

More clarified version of above answers:

IEnumerable<IGrouping<int, ClassA>> groups = list.GroupBy(x => x.PropertyIntOfClassA);

foreach (var groupingByClassA in groups)
{
    int propertyIntOfClassA = groupingByClassA.Key;

    //iterating through values
    foreach (var classA in groupingByClassA)
    {
        int key = classA.PropertyIntOfClassA;
    }
}

Counting the number of files in a directory using Java

Since Java 8, you can do that in three lines:

try (Stream<Path> files = Files.list(Paths.get("your/path/here"))) {
    long count = files.count();
}

Regarding the 5000 child nodes and inode aspects:

This method will iterate over the entries but as Varkhan suggested you probably can't do better besides playing with JNI or direct system commands calls, but even then, you can never be sure these methods don't do the same thing!

However, let's dig into this a little:

Looking at JDK8 source, Files.list exposes a stream that uses an Iterable from Files.newDirectoryStream that delegates to FileSystemProvider.newDirectoryStream.

On UNIX systems (decompiled sun.nio.fs.UnixFileSystemProvider.class), it loads an iterator: A sun.nio.fs.UnixSecureDirectoryStream is used (with file locks while iterating through the directory).

So, there is an iterator that will loop through the entries here.

Now, let's look to the counting mechanism.

The actual count is performed by the count/sum reducing API exposed by Java 8 streams. In theory, this API can perform parallel operations without much effort (with multihtreading). However the stream is created with parallelism disabled so it's a no go...

The good side of this approach is that it won't load the array in memory as the entries will be counted by an iterator as they are read by the underlying (Filesystem) API.

Finally, for the information, conceptually in a filesystem, a directory node is not required to hold the number of the files that it contains, it can just contain the list of it's child nodes (list of inodes). I'm not an expert on filesystems, but I believe that UNIX filesystems work just like that. So you can't assume there is a way to have this information directly (i.e: there can always be some list of child nodes hidden somewhere).

Comparing two .jar files

Use Java Decompiler to turn the jar file into source code file, and then use WinMerge to perform comparison.

You should consult the copyright holder of the source code, to see whether it is OK to do so.

java : non-static variable cannot be referenced from a static context Error

This is an interesting question, i just want to give another angle by adding a little more info.You can understand why an exception is thrown if you see how static methods operate. These methods can manipulate either static data, local data or data that is sent to it as a parameter.why? because static method can be accessed by any object, from anywhere. So, there can be security issues posed or there can be leaks of information if it can use instance variables.Hence the compiler has to throw such a case out of consideration.

Difference between "include" and "require" in php

As others pointed out, the only difference is that require throws a fatal error, and include - a catchable warning. As for which one to use, my advice is to stick to include. Why? because you can catch a warning and produce a meaningful feedback to end users. Consider

  // Example 1.
  // users see a standard php error message or a blank screen
  // depending on your display_errors setting
  require 'not_there'; 


  // Example 2.
  // users see a meaningful error message
  try {
      include 'not_there';
  } catch(Exception $e) {
     echo "something strange happened!";
  }

NB: for example 2 to work you need to install an errors-to-exceptions handler, as described here http://www.php.net/manual/en/class.errorexception.php

  function exception_error_handler($errno, $errstr, $errfile, $errline ) {
     throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
  }
  set_error_handler("exception_error_handler");   

What is a Java String's default initial value?

It's initialized to null if you do nothing, as are all reference types.

IE8 css selector

CSS style only for IE8:

.divLogRight{color:Blue; color:Red\9; *color:Blue;}

Only IE8 will be Red.

first Blue: for all browsers.

Red: IE6,7,8 Only

Second Blue: IE6,7 Only


So Red = for IE8 only.

For a very complete summary of browser hacks (including Internet Explorer (IE), Safari, Chrome, iPhone, and Opera) visit this link: http://paulirish.com/2009/browser-specific-css-hacks/

Calling a Variable from another Class

That would just be:

 Console.WriteLine(Variables.name);

and it needs to be public also:

public class Variables
{
   public static string name = "";
}

How to install OpenSSL in windows 10?

In case you have Git installed,

you can open the Git Bash (shift pressed + right click in the folder -> Git Bash Here) and use openssl command right in the Bash

Delete all lines starting with # or ; in Notepad++

Find:

^[#;].*

Replace with nothing. The ^ indicates the start of a line, the [#;] is a character class to match either # or ;, and .* matches anything else in the line.

In versions of Notepad++ before 6.0, you won't be able to actually remove the lines due to a limitation in its regex engine; the replacement results in blank lines for each line matched. In other words, this:

# foo
; bar
statement;

Will turn into:



statement;

However, the replacement will work in Notepad++ 6.0 if you add \r, \n or \r\n to the end of the pattern, depending on which line ending your file is using, resulting in:

statement;

How to go to each directory and execute a command?

While one liners are good for quick and dirty usage, I prefer below more verbose version for writing scripts. This is the template I use which takes care of many edge cases and allows you to write more complex code to execute on a folder. You can write your bash code in the function dir_command. Below, dir_coomand implements tagging each repository in git as an example. Rest of the script calls dir_command for each folder in directory. The example of iterating through only given set of folder is also include.

#!/bin/bash

#Use set -x if you want to echo each command while getting executed
#set -x

#Save current directory so we can restore it later
cur=$PWD
#Save command line arguments so functions can access it
args=("$@")

#Put your code in this function
#To access command line arguments use syntax ${args[1]} etc
function dir_command {
    #This example command implements doing git status for folder
    cd $1
    echo "$(tput setaf 2)$1$(tput sgr 0)"
    git tag -a ${args[0]} -m "${args[1]}"
    git push --tags
    cd ..
}

#This loop will go to each immediate child and execute dir_command
find . -maxdepth 1 -type d \( ! -name . \) | while read dir; do
   dir_command "$dir/"
done

#This example loop only loops through give set of folders    
declare -a dirs=("dir1" "dir2" "dir3")
for dir in "${dirs[@]}"; do
    dir_command "$dir/"
done

#Restore the folder
cd "$cur"

When to Redis? When to MongoDB?

Redis is an in memory data store, that can persist it's state to disk (to enable recovery after restart). However, being an in-memory data store means the size of the data store (on a single node) cannot exceed the total memory space on the system (physical RAM + swap space). In reality, it will be much less that this, as Redis is sharing that space with many other processes on the system, and if it exhausts the system memory space it will likely be killed off by the operating system.

Mongo is a disk based data store, that is most efficient when it's working set fits within physical RAM (like all software). Being a disk based data means there are no intrinsic limits on the size of a Mongo database, however configuration options, available disk space, and other concerns may mean that databases sizes over a certain limit may become impractical or inefficient.

Both Redis and Mongo can be clustered for high availability, backup and to increase the overall size of the datastore.

Listing contents of a bucket with boto3

It can also be done as follows:

csv_files = s3.list_objects_v2(s3_bucket_path)
    for obj in csv_files['Contents']:
        key = obj['Key']

How can I disable a specific LI element inside a UL?

Using CSS3: http://www.w3schools.com/cssref/sel_nth-child.asp

If that's not an option for any reason, you could try giving the list items classes:

<ul>
<li class="one"></li>
<li class="two"></li>
<li class="three"></li>
...
</ul>

Then in your css:

li.one{display:none}/*hide first li*/
li.three{display:none}/*hide third li*/

How to get a Char from an ASCII Character Code in c#

Two options:

char c1 = '\u0001';
char c1 = (char) 1;

How can I get an object's absolute position on the page in Javascript?

var cumulativeOffset = function(element) {
    var top = 0, left = 0;
    do {
        top += element.offsetTop  || 0;
        left += element.offsetLeft || 0;
        element = element.offsetParent;
    } while(element);

    return {
        top: top,
        left: left
    };
};

(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)

Mean per group in a data.frame

Here are a variety of ways to do this in base R including an alternative aggregate approach. The examples below return means per month, which I think is what you requested. Although, the same approach could be used to return means per person:

Using ave:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

Rate1.mean <- with(my.data, ave(Rate1, Month, FUN = function(x) mean(x, na.rm = TRUE)))
Rate2.mean <- with(my.data, ave(Rate2, Month, FUN = function(x) mean(x, na.rm = TRUE)))

my.data <- data.frame(my.data, Rate1.mean, Rate2.mean)
my.data

Using by:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

by.month <- as.data.frame(do.call("rbind", by(my.data, my.data$Month, FUN = function(x) colMeans(x[,3:4]))))
colnames(by.month) <- c('Rate1.mean', 'Rate2.mean')
by.month <- cbind(Month = rownames(by.month), by.month)

my.data <- merge(my.data, by.month, by = 'Month')
my.data

Using lapply and split:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

ly.mean <- lapply(split(my.data, my.data$Month), function(x) c(Mean = colMeans(x[,3:4])))
ly.mean <- as.data.frame(do.call("rbind", ly.mean))
ly.mean <- cbind(Month = rownames(ly.mean), ly.mean)

my.data <- merge(my.data, ly.mean, by = 'Month')
my.data

Using sapply and split:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')
my.data

sy.mean <- t(sapply(split(my.data, my.data$Month), function(x) colMeans(x[,3:4])))
colnames(sy.mean) <- c('Rate1.mean', 'Rate2.mean')
sy.mean <- data.frame(Month = rownames(sy.mean), sy.mean, stringsAsFactors = FALSE)
my.data <- merge(my.data, sy.mean, by = 'Month')
my.data

Using aggregate:

my.data <- read.table(text = '
     Name     Month  Rate1     Rate2
     Aira       1      12        23
     Aira       2      18        73
     Aira       3      19        45
     Ben        1      53        19
     Ben        2      22        87
     Ben        3      19        45
     Cat        1      22        87
     Cat        2      67        43
     Cat        3      45        32
', header = TRUE, stringsAsFactors = FALSE, na.strings = 'NA')

my.summary <- with(my.data, aggregate(list(Rate1, Rate2), by = list(Month), 
                   FUN = function(x) { mon.mean = mean(x, na.rm = TRUE) } ))

my.summary <- do.call(data.frame, my.summary)
colnames(my.summary) <- c('Month', 'Rate1.mean', 'Rate2.mean')
my.summary

my.data <- merge(my.data, my.summary, by = 'Month')
my.data

EDIT: June 28, 2020

Here I use aggregate to obtain the column means of an entire matrix by group where group is defined in an external vector:

my.group <- c(1,2,1,2,2,3,1,2,3,3)

my.data <- matrix(c(   1,    2,    3,    4,    5,
                      10,   20,   30,   40,   50,
                       2,    4,    6,    8,   10,
                      20,   30,   40,   50,   60,
                      20,   18,   16,   14,   12,
                    1000, 1100, 1200, 1300, 1400,
                       2,    3,    4,    3,    2,
                      50,   40,   30,   20,   10,
                    1001, 2001, 3001, 4001, 5001,
                    1000, 2000, 3000, 4000, 5000), nrow = 10, ncol = 5, byrow = TRUE)
my.data

my.summary <- aggregate(list(my.data), by = list(my.group), FUN = function(x) { my.mean = mean(x, na.rm = TRUE) } )
my.summary
#  Group.1          X1       X2          X3       X4          X5
#1       1    1.666667    3.000    4.333333    5.000    5.666667
#2       2   25.000000   27.000   29.000000   31.000   33.000000
#3       3 1000.333333 1700.333 2400.333333 3100.333 3800.333333

Numpy - Replace a number with NaN

A[A==NDV]=numpy.nan

A==NDV will produce a boolean array that can be used as an index for A

How do I install the yaml package for Python?

pip install PyYAML

If libyaml is not found or compiled PyYAML can do without it on Mavericks.

How to mock private method for testing using PowerMock?

For some reason Brice's answer is not working for me. I was able to manipulate it a bit to get it to work. It might just be because I have a newer version of PowerMock. I'm using 1.6.5.

import java.util.Random;

public class CodeWithPrivateMethod {

    public void meaningfulPublicApi() {
        if (doTheGamble("Whatever", 1 << 3)) {
            throw new RuntimeException("boom");
        }
    }

    private boolean doTheGamble(String whatever, int binary) {
        Random random = new Random(System.nanoTime());
        boolean gamble = random.nextBoolean();
        return gamble;
    }
}

The test class looks as follows:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.doReturn;

@RunWith(PowerMockRunner.class)
@PrepareForTest(CodeWithPrivateMethod.class)
public class CodeWithPrivateMethodTest {
    private CodeWithPrivateMethod classToTest;

    @Test(expected = RuntimeException.class)
    public void when_gambling_is_true_then_always_explode() throws Exception {
        classToTest = PowerMockito.spy(classToTest);

        doReturn(true).when(classToTest, "doTheGamble", anyString(), anyInt());

        classToTest.meaningfulPublicApi();
    }
}

Customize list item bullets using CSS

Depending on the level of IE support needed, you could also use the :before selector with the bullet style set as the content property.

li {  
  list-style-type: none;
  font-size: small;
}

li:before {
  content: '\2022';
  font-size: x-large;
}

You may have to look up the HTML ASCII for the bullet style you want and use a converter for CSS Hex value.

Java equivalent to JavaScript's encodeURIComponent that produces identical output?

I used String encodedUrl = new URI(null, url, null).toASCIIString(); to encode urls. To add parameters after the existing ones in the url I use UriComponentsBuilder

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

bundle install --path vendor/cache

generally fixes it as that is the more common problem. Basically, your bundler path configuration is messed up. See their documentation (first paragraph) for where to find those configurations and change them manually if needed.

laravel 5.3 new Auth::routes()

Auth::routes() is just a helper class that helps you generate all the routes required for user authentication. You can browse the code here https://github.com/laravel/framework/blob/5.3/src/Illuminate/Routing/Router.php instead.

Here are the routes

// Authentication Routes...
$this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
$this->post('login', 'Auth\LoginController@login');
$this->post('logout', 'Auth\LoginController@logout')->name('logout');

// Registration Routes...
$this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
$this->post('register', 'Auth\RegisterController@register');

// Password Reset Routes...
$this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm');
$this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail');
$this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm');
$this->post('password/reset', 'Auth\ResetPasswordController@reset');

How to write a comment in a Razor view?

This comment syntax should work for you:

@* enter comments here *@

How to get raw text from pdf file using java

Hi we can extract the pdf files using Apache Tika

The Example is :

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;

public class WebPagePdfExtractor {

    public Map<String, Object> processRecord(String url) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream input = null;
            if (entity != null) {
                try {
                    input = entity.getContent();
                    BodyContentHandler handler = new BodyContentHandler();
                    Metadata metadata = new Metadata();
                    AutoDetectParser parser = new AutoDetectParser();
                    ParseContext parseContext = new ParseContext();
                    parser.parse(input, handler, metadata, parseContext);
                    map.put("text", handler.toString().replaceAll("\n|\r|\t", " "));
                    map.put("title", metadata.get(TikaCoreProperties.TITLE));
                    map.put("pageCount", metadata.get("xmpTPg:NPages"));
                    map.put("status_code", response.getStatusLine().getStatusCode() + "");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (input != null) {
                        try {
                            input.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return map;
    }

    public static void main(String arg[]) {
        WebPagePdfExtractor webPagePdfExtractor = new WebPagePdfExtractor();
        Map<String, Object> extractedMap = webPagePdfExtractor.processRecord("http://math.about.com/library/q20.pdf");
        System.out.println(extractedMap.get("text"));
    }

}

Allow docker container to connect to a local/host postgres database

The another solution is service volume, You can define a service volume and mount host's PostgreSQL Data directory in that volume. Check out the given compose file for details.

version: '2'
services:
  db:   
    image: postgres:9.6.1
    volumes:
      - "/var/lib/postgresql/data:/var/lib/postgresql/data" 
    ports:
      - "5432:5432"

By doing this, another PostgreSQL service will run under container but uses same data directory which host PostgreSQL service is using.

GROUP BY having MAX date

There's no need to group in that subquery... a where clause would suffice:

SELECT * FROM tblpm n
WHERE date_updated=(SELECT MAX(date_updated)
    FROM tblpm WHERE control_number=n.control_number)

Also, do you have an index on the 'date_updated' column? That would certainly help.

Shortcut to create properties in Visual Studio?

Place cursor inside your field private int _i; and then Edit menu or RMB - Refactor - Encapsulate Field... (CtrlR, CtrlE) to create the standard property accessors.

How to search for string in an array

Here's another answer. It works fast, reliably (see atomicules' answer) and has compact calling code:

' Returns true if item is in the array; false otherwise.
Function IsInArray(ar, item$) As Boolean
    Dim delimiter$, list$

    ' Chr(7) is the ASCII 'Bell' Character.
    ' It was chosen for being unlikely to be found in a normal array.
    delimiter = Chr(7)

    ' Create a list string containing all the items in the array separated by the delimiter.
    list = delimiter & Join(ar, delimiter) & delimiter

    IsInArray = InStr(list, delimiter & item & delimiter) > 0
End Function

Sample usage:

Sub test()
    Debug.Print "Is 'A' in the list?", IsInArray(Split("A,B", ","), "A")
End Sub

PowerShell: Comparing dates

Late but more complete answer in point of getting the most advanced date from $Output

## Q:\test\2011\02\SO_5097125.ps1
## simulate object input with a here string 
$Output = @"
"Date"
"Monday, April 08, 2013 12:00:00 AM"
"Friday, April 08, 2011 12:00:00 AM"
"@ -split '\r?\n' | ConvertFrom-Csv

## use Get-Date and calculated property in a pipeline
$Output | Select-Object @{n='Date';e={Get-Date $_.Date}} |
    Sort-Object Date | Select-Object -Last 1 -Expand Date

## use Get-Date in a ForEach-Object
$Output.Date | ForEach-Object{Get-Date $_} |
    Sort-Object | Select-Object -Last 1

## use [datetime]::ParseExact
## the following will only work if your locale is English for day, month day abbrev.
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',$Null)
} | Sort-Object | Select-Object -Last 1

## for non English locales
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',[cultureinfo]::InvariantCulture)
} | Sort-Object | Select-Object -Last 1

## in case the day month abbreviations are in other languages, here German
## simulate object input with a here string 
$Output = @"
"Date"
"Montag, April 08, 2013 00:00:00"
"Freidag, April 08, 2011 00:00:00"
"@ -split '\r?\n' | ConvertFrom-Csv
$CIDE = New-Object System.Globalization.CultureInfo("de-DE")
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy HH:mm:ss',$CIDE)
} | Sort-Object | Select-Object -Last 1

Amazon Interview Question: Design an OO parking lot

Here is a quick start to get the gears turning...

ParkingLot is a class.

ParkingSpace is a class.

ParkingSpace has an Entrance.

Entrance has a location or more specifically, distance from Entrance.

ParkingLotSign is a class.

ParkingLot has a ParkingLotSign.

ParkingLot has a finite number of ParkingSpaces.

HandicappedParkingSpace is a subclass of ParkingSpace.

RegularParkingSpace is a subclass of ParkingSpace.

CompactParkingSpace is a subclass of ParkingSpace.

ParkingLot keeps array of ParkingSpaces, and a separate array of vacant ParkingSpaces in order of distance from its Entrance.

ParkingLotSign can be told to display "full", or "empty", or "blank/normal/partially occupied" by calling .Full(), .Empty() or .Normal()

Parker is a class.

Parker can Park().

Parker can Unpark().

Valet is a subclass of Parker that can call ParkingLot.FindVacantSpaceNearestEntrance(), which returns a ParkingSpace.

Parker has a ParkingSpace.

Parker can call ParkingSpace.Take() and ParkingSpace.Vacate().

Parker calls Entrance.Entering() and Entrance.Exiting() and ParkingSpace notifies ParkingLot when it is taken or vacated so that ParkingLot can determine if it is full or not. If it is newly full or newly empty or newly not full or empty, it should change the ParkingLotSign.Full() or ParkingLotSign.Empty() or ParkingLotSign.Normal().

HandicappedParker could be a subclass of Parker and CompactParker a subclass of Parker and RegularParker a subclass of Parker. (might be overkill, actually.)

In this solution, it is possible that Parker should be renamed to be Car.

How do I declare and assign a variable on a single line in SQL

You've nearly got it:

DECLARE @myVariable nvarchar(max) = 'hello world';

See here for the docs

For the quotes, SQL Server uses apostrophes, not quotes:

DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';

Use double apostrophes if you need them in a string:

DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';

Edit seaborn legend

If legend_out is set to True then legend is available thought g._legend property and it is a part of a figure. Seaborn legend is standard matplotlib legend object. Therefore you may change legend texts like:

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = True)

# title
new_title = 'My title'
g._legend.set_title(new_title)
# replace labels
new_labels = ['label 1', 'label 2']
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)

sns.plt.show()

enter image description here

Another situation if legend_out is set to False. You have to define which axes has a legend (in below example this is axis number 0):

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = False)

# check axes and find which is have legend
leg = g.axes.flat[0].get_legend()
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)
sns.plt.show()

enter image description here

Moreover you may combine both situations and use this code:

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = True)

# check axes and find which is have legend
for ax in g.axes.flat:
    leg = g.axes.flat[0].get_legend()
    if not leg is None: break
# or legend may be on a figure
if leg is None: leg = g._legend

# change legend texts
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)

sns.plt.show()

This code works for any seaborn plot which is based on Grid class.

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

From the Apple Developer Forum (account required):

"The compiler and linker are capable of using features and performing optimizations that do not work on older OS versions. -mmacosx-version-min tells the tools what OS versions you need to work with, so the tools can disable optimizations that won't run on those OS versions. If you need to run on older OS versions then you must use this flag.

"The downside to -mmacosx-version-min is that the app's performance may be worse on newer OS versions then it could have been if it did not need to be backwards-compatible. In most cases the differences are small."

How do I merge dictionaries together in Python?

If you want d1 to have priority in the conflicts, do:

d3 = d2.copy()
d3.update(d1)

Otherwise, reverse d2 and d1.

What does the "@" symbol do in SQL?

You may be used to MySQL's syntax: Microsoft SQL @ is the same as the MySQL's ?

Error renaming a column in MySQL

Lone Ranger is very close... in fact, you also need to specify the datatype of the renamed column. For example:

ALTER TABLE `xyz` CHANGE `manufacurerid` `manufacturerid` INT;

Remember :

  • Replace INT with whatever your column data type is (REQUIRED)
  • Tilde/ Backtick (`) is optional

How do you convert CString and std::string std::wstring to each other?

Solve that by using std::basic_string<TCHAR> instead of std::string and it should work fine regardless of your character setting.

How to override application.properties during production in Spring-Boot?

I know you asked how to do this, but the answer is you should not do this.

Instead, have a application.properties, application-default.properties application-dev.properties etc., and switch profiles via args to the JVM: e.g. -Dspring.profiles.active=dev

You can also override some things at test time using @TestPropertySource

Ideally everything should be in source control so that there are no surprises e.g. How do you know what properties are sitting there in your server location, and which ones are missing? What happens if developers introduce new things?

Spring Boot is already giving you enough ways to do this right.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

Finding all cycles in a directed graph

Depth first search with backtracking should work here. Keep an array of boolean values to keep track of whether you visited a node before. If you run out of new nodes to go to (without hitting a node you have already been), then just backtrack and try a different branch.

The DFS is easy to implement if you have an adjacency list to represent the graph. For example adj[A] = {B,C} indicates that B and C are the children of A.

For example, pseudo-code below. "start" is the node you start from.

dfs(adj,node,visited):  
  if (visited[node]):  
    if (node == start):  
      "found a path"  
    return;  
  visited[node]=YES;  
  for child in adj[node]:  
    dfs(adj,child,visited)
  visited[node]=NO;

Call the above function with the start node:

visited = {}
dfs(adj,start,visited)

Swift add icon/image in UITextField

I Just want to add some more thing here:

If you want to add the image on UITextField on left side use leftView property of UITextField

NOTE: Don't forget to set leftViewMode to UITextFieldViewMode.Always and for right rightViewMode to UITextFieldViewMode.Always anddefault is UITextFieldViewModeNever

for e.g

For adding an image on left side

textField.leftViewMode = UITextFieldViewMode.Always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
let image = UIImage(named: imageName)
imageView.image = image
textField.leftView = imageView

For adding an image on right side

textField.rightViewMode = UITextFieldViewMode.Always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
let image = UIImage(named: imageName)
imageView.image = image
textField.rightView = imageView

NOTE: some things you need to take care while adding an image on UITextField either on the left side or right side.

  • Don't forget to give a frame of ImageView which are you going to add on UITextField

    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))

  • if your image background is white then image won't visible on UITextField

  • if you want to add an image to the specific position you need to add ImageView as the subview of UITextField.

Update For Swift 3.0

@Mark Moeykens Beautifully expended it and make it @IBDesignable.

I modified and added some more features (add Bottom Line and padding for right image) in this.

NOTE if you want to add an image on the right side you can select the Force Right-to-Left option in semantic in interface builder(But for right image padding won't work until you will override rightViewRect method ).

enter image description here

I have modified this and can download the source from here ImageTextField

enter image description here

How to replace part of string by position?

I was looking for a solution with following requirements:

  1. use only a single, one-line expression
  2. use only system builtin methods (no custom implemented utility)

Solution 1

The solution that best suits me is this:

// replace `oldString[i]` with `c`
string newString = new StringBuilder(oldString).Replace(oldString[i], c, i, 1).ToString();

This uses StringBuilder.Replace(oldChar, newChar, position, count)

Solution 2

The other solution that satisfies my requirements is to use Substring with concatenation:

string newString = oldStr.Substring(0, i) + c + oldString.Substring(i+1, oldString.Length);

This is OK too. I guess it's not as efficient as the first one performance wise (due to unnecessary string concatenation). But premature optimization is the root of all evil.

So pick the one that you like the most :)

What's the point of the X-Requested-With header?

Make sure you read SilverlightFox's answer. It highlights a more important reason.

The reason is mostly that if you know the source of a request you may want to customize it a little bit.

For instance lets say you have a website which has many recipes. And you use a custom jQuery framework to slide recipes into a container based on a link they click. The link may be www.example.com/recipe/apple_pie

Now normally that returns a full page, header, footer, recipe content and ads. But if someone is browsing your website some of those parts are already loaded. So you can use an AJAX to get the recipe the user has selected but to save time and bandwidth don't load the header/footer/ads.

Now you can just write a secondary endpoint for the data like www.example.com/recipe_only/apple_pie but that's harder to maintain and share to other people.

But it's easier to just detect that it is an ajax request making the request and then returning only a part of the data. That way the user wastes less bandwidth and the site appears more responsive.

The frameworks just add the header because some may find it useful to keep track of which requests are ajax and which are not. But it's entirely dependent on the developer to use such techniques.

It's actually kind of similar to the Accept-Language header. A browser can request a website please show me a Russian version of this website without having to insert /ru/ or similar in the URL.

Converting between java.time.LocalDateTime and java.util.Date

I think below approach will solve the conversion without taking time-zone into consideration. Please comment if it has any pitfalls.

    LocalDateTime datetime //input
    public static final DateTimeFormatter yyyyMMddHHmmss_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String formatDateTime = datetime.format(yyyyMMddHHmmss_DATE_FORMAT);
    Date outputDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(formatDateTime); //output

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

use this filter:

(dns.flags.response == 0) and (ip.src == 159.25.78.7)

what this query does is it only gives dns queries originated from your ip

Why is a primary-foreign key relation required when we can join without it?

You don't need a FK, you can join arbitrary columns.

But having a foreign key ensures that the join will actually succeed in finding something.

Foreign key give you certain guarantees that would be extremely difficult and error prone to implement otherwise.

For example, if you don't have a foreign key, you might insert a detail record in the system and just after you checked that the matching master record is present somebody else deletes it. So in order to prevent this you need to lock the master table, when ever you modify the detail table (and vice versa). If you don't need/want that guarantee, screw the FKs.

Depending on your RDBMS a foreign key also might improve performance of select (but also degrades performance of updates, inserts and deletes)

"Unmappable character for encoding UTF-8" error

I'm in the process of setting up a CI build server on a Linux box for a legacy system started in 2000. There is a section that generates a PDF that contains non-UTF8 characters. We are in the final steps of a release, so I cannot replace the characters giving me grief, yet for Dilbertesque reasons, I cannot wait a week to solve this issue after the release. Fortunately, the "javac" command in Ant has an "encoding" parameter.

 <javac destdir="${classes.dir}" classpathref="production-classpath" debug="on"
     includeantruntime="false" source="${java.level}" target="${java.level}"

     encoding="iso-8859-1">

     <src path="${production.dir}" />
 </javac>

Most concise way to convert a Set<T> to a List<T>

List<String> l = new ArrayList<String>(listOfTopicAuthors);

Find and replace Android studio

If you use refactor->rename for the name of the file, everywhere the file is used in your project the refactor will replace it.

I have already rename variables, xml file, java file, multiple drawable and after the operation I could build directly without error.

Do a back-up of your project and try to see if it work for you.

Access mysql remote database from command line

Try this, Its working:

mysql -h {hostname} -u{username} -p{password} -N -e "{query to execute}"

Better way to find control in ASP.NET

https://blog.codinghorror.com/recursive-pagefindcontrol/

Page.FindControl("DataList1:_ctl0:TextBox3");

OR

private Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id)
    {
        return root;
    }
    foreach (Control c in root.Controls)
    {
        Control t = FindControlRecursive(c, id);
        if (t != null)
        {
            return t;
        }
    }
    return null;
}

Passing null arguments to C# methods

Starting from C# 2.0, you can use the nullable generic type Nullable, and in C# there is a shorthand notation the type followed by ?

e.g.

private void Example(int? arg1, int? arg2)
{
    if(arg1 == null)
    {
        //do something
    }
    if(arg2 == null)
    {
        //do something else
    }
}

how to dynamically add options to an existing select in vanilla javascript

.add() also works.

var daySelect = document.getElementById("myDaySelect");
var myOption = document.createElement("option");
myOption.text = "test";
myOption.value = "value";
daySelect.add(option);

W3 School - try

JavaScript DOM remove element

Seems I don't have enough rep to post a comment, so another answer will have to do.

When you unlink a node using removeChild() or by setting the innerHTML property on the parent, you also need to make sure that there is nothing else referencing it otherwise it won't actually be destroyed and will lead to a memory leak. There are lots of ways in which you could have taken a reference to the node before calling removeChild() and you have to make sure those references that have not gone out of scope are explicitly removed.

Doug Crockford writes here that event handlers are known a cause of circular references in IE and suggests removing them explicitly as follows before calling removeChild()

function purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        for (i = a.length - 1; i >= 0; i -= 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}

And even if you take a lot of precautions you can still get memory leaks in IE as described by Jens-Ingo Farley here.

And finally, don't fall into the trap of thinking that Javascript delete is the answer. It seems to be suggested by many, but won't do the job. Here is a great reference on understanding delete by Kangax.

How to overlay images

A simple way of doing that with CSS only without modifying the content with additional tags is shown here (with code and example): http://soukie.net/2009/08/20/typography-and-css/#example

This works, as long as the parent element is not using static positioning. Simply setting it to relative positioning does the trick. Also, IE <8 don't support the :before selector or content.

What is the best/safest way to reinstall Homebrew?

Update 10/11/2020 to reflect the latest brew changes.

Brew already provide a command to uninstall itself (this will remove everything you installed with Homebrew):

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"

If you failed to run this command due to permission (like run as second user), run again with sudo

Then you can install again:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

How to overwrite files with Copy-Item in PowerShell

How about calling the .NET Framework methods?

You can do ANYTHING with them... :

[System.IO.File]::Copy($src, $dest, $true);

The $true argument makes it overwrite.

Python vs. Java performance (runtime speed)

There is no good answer as Python and Java are both specifications for which there are many different implementations. For example, CPython, IronPython, Jython, and PyPy are just a handful of Python implementations out there. For Java, there is the HotSpot VM, the Mac OS X Java VM, OpenJRE, etc. Jython generates Java bytecode, and so it would be using more-or-less the same underlying Java. CPython implements quite a handful of things directly in C, so it is very fast, but then again Java VMs also implement many functions in C. You would probably have to measure on a function-by-function basis and across a variety of interpreters and VMs in order to make any reasonable statement.

How to Write text file Java

I would like to add a bit more to MadProgrammer's Answer.

In case of multiple line writing, when executing the command

writer.write(string);

one may notice that the newline characters are omitted or skipped in the written file even though they appear during debugging or if the same text is printed onto the terminal with,

System.out.println("\n");

Thus, the whole text comes as one big chunk of text which is undesirable in most cases. The newline character can be dependent on the platform, so it is better to get this character from the java system properties using

String newline = System.getProperty("line.separator");

and then using the newline variable instead of "\n". This will get the output in the way you want it.

What is the difference between concurrent programming and parallel programming?

They're two phrases that describe the same thing from (very slightly) different viewpoints. Parallel programming is describing the situation from the viewpoint of the hardware -- there are at least two processors (possibly within a single physical package) working on a problem in parallel. Concurrent programming is describing things more from the viewpoint of the software -- two or more actions may happen at exactly the same time (concurrently).

The problem here is that people are trying to use the two phrases to draw a clear distinction when none really exists. The reality is that the dividing line they're trying to draw has been fuzzy and indistinct for decades, and has grown ever more indistinct over time.

What they're trying to discuss is the fact that once upon a time, most computers had only a single CPU. When you executed multiple processes (or threads) on that single CPU, the CPU was only really executing one instruction from one of those threads at a time. The appearance of concurrency was an illusion--the CPU switching between executing instructions from different threads quickly enough that to human perception (to which anything less than 100 ms or so looks instantaneous) it looked like it was doing many things at once.

The obvious contrast to this is a computer with multiple CPUs, or a CPU with multiple cores, so the machine is executing instructions from multiple threads and/or processes at exactly the same time; code executing one can't/doesn't have any effect on code executing in the other.

Now the problem: such a clean distinction has almost never existed. Computer designers are actually fairly intelligent, so they noticed a long time ago that (for example) when you needed to read some data from an I/O device such as a disk, it took a long time (in terms of CPU cycles) to finish. Instead of leaving the CPU idle while that happened, they figured out various ways of letting one process/thread make an I/O request, and let code from some other process/thread execute on the CPU while the I/O request completed.

So, long before multi-core CPUs became the norm, we had operations from multiple threads happening in parallel.

That's only the tip of the iceberg though. Decades ago, computers started providing another level of parallelism as well. Again, being fairly intelligent people, computer designers noticed that in a lot of cases, they had instructions that didn't affect each other, so it was possible to execute more than one instruction from the same stream at the same time. One early example that became pretty well known was the Control Data 6600. This was (by a fairly wide margin) the fastest computer on earth when it was introduced in 1964--and much of the same basic architecture remains in use today. It tracked the resources used by each instruction, and had a set of execution units that executed instructions as soon as the resources on which they depended became available, very similar to the design of most recent Intel/AMD processors.

But (as the commercials used to say) wait--that's not all. There's yet another design element to add still further confusion. It's been given quite a few different names (e.g., "Hyperthreading", "SMT", "CMP"), but they all refer to the same basic idea: a CPU that can execute multiple threads simultaneously, using a combination of some resources that are independent for each thread, and some resources that are shared between the threads. In a typical case this is combined with the instruction-level parallelism outlined above. To do that, we have two (or more) sets of architectural registers. Then we have a set of execution units that can execute instructions as soon as the necessary resources become available. These often combine well because the instructions from the separate streams virtually never depend on the same resources.

Then, of course, we get to modern systems with multiple cores. Here things are obvious, right? We have N (somewhere between 2 and 256 or so, at the moment) separate cores, that can all execute instructions at the same time, so we have clear-cut case of real parallelism--executing instructions in one process/thread doesn't affect executing instructions in another.

Well, sort of. Even here we have some independent resources (registers, execution units, at least one level of cache) and some shared resources (typically at least the lowest level of cache, and definitely the memory controllers and bandwidth to memory).

To summarize: the simple scenarios people like to contrast between shared resources and independent resources virtually never happen in real life. With all resources shared, we end up with something like MS-DOS, where we can only run one program at a time, and we have to stop running one before we can run the other at all. With completely independent resources, we have N computers running MS-DOS (without even a network to connect them) with no ability to share anything between them at all (because if we can even share a file, well, that's a shared resource, a violation of the basic premise of nothing being shared).

Every interesting case involves some combination of independent resources and shared resources. Every reasonably modern computer (and a lot that aren't at all modern) has at least some ability to carry out at least a few independent operations simultaneously, and just about anything more sophisticated than MS-DOS has taken advantage of that to at least some degree.

The nice, clean division between "concurrent" and "parallel" that people like to draw just doesn't exist, and almost never has. What people like to classify as "concurrent" usually still involves at least one and often more different types of parallel execution. What they like to classify as "parallel" often involves sharing resources and (for example) one process blocking another's execution while using a resource that's shared between the two.

People trying to draw a clean distinction between "parallel" and "concurrent" are living in a fantasy of computers that never actually existed.

How to add a named sheet at the end of all Excel sheets?

Try this:

Public Enum iSide
iBefore
iAfter
End Enum
Private Function addSheet(ByRef inWB As Workbook, ByVal inBeforeOrAfter As iSide, ByRef inNamePrefix As String, ByVal inName As String) As Worksheet
    On Error GoTo the_dark

    Dim wsSheet As Worksheet
    Dim bFoundWS As Boolean
    bFoundWS = False
    If inNamePrefix <> "" Then
        Set wsSheet = findWS(inWB, inNamePrefix, bFoundWS)
    End If

    If inBeforeOrAfter = iAfter Then
        If wsSheet Is Nothing Or bFoundWS = False Then
            Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = inName
        Else
            Worksheets.Add(After:=wsSheet).Name = inName
        End If
    Else
        If wsSheet Is Nothing Or bFoundWS = False Then
            Worksheets.Add(Before:=Worksheets(1)).Name = inName
        Else
            Worksheets.Add(Before:=wsSheet).Name = inName
        End If
    End If

    Set addSheet = findWS(inWB, inName, bFoundWS)         ' just to confirm it exists and gets it handle

    the_light:
    Exit Function
    the_dark:
    MsgBox "addSheet: " & inName & ": " & Err.Description, vbOKOnly, "unexpected error"
    Err.Clear
    GoTo the_light
End Function

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

Posting 2021 answer in JSON using openapi 3.0.0:

{
  "openapi": "3.0.0",
  ...
  "servers": [
    {
      "url": "/"
    }
  ],
  ...
  "paths": {
    "/skills": {
      "put": {
        "security": [
           {
              "bearerAuth": []
           }
        ],
       ...
  },


  "components": {        
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT"
      }
    }
  }
}

Select first and last row from grouped data

Not dplyr, but it's much more direct using data.table:

library(data.table)
setDT(df)
df[ df[order(id, stopSequence), .I[c(1L,.N)], by=id]$V1 ]
#    id stopId stopSequence
# 1:  1      a            1
# 2:  1      c            3
# 3:  2      b            1
# 4:  2      c            4
# 5:  3      b            1
# 6:  3      a            3

More detailed explanation:

# 1) get row numbers of first/last observations from each group
#    * basically, we sort the table by id/stopSequence, then,
#      grouping by id, name the row numbers of the first/last
#      observations for each id; since this operation produces
#      a data.table
#    * .I is data.table shorthand for the row number
#    * here, to be maximally explicit, I've named the variable V1
#      as row_num to give other readers of my code a clearer
#      understanding of what operation is producing what variable
first_last = df[order(id, stopSequence), .(row_num = .I[c(1L,.N)]), by=id]
idx = first_last$row_num

# 2) extract rows by number
df[idx]

Be sure to check out the Getting Started wiki for getting the data.table basics covered

Git copy changes from one branch to another

git checkout BranchB
git merge BranchA
git push origin BranchB

This is all if you intend to not merge your changes back to master. Generally it is a good practice to merge all your changes back to master, and create new branches off of that.

Also, after the merge command, you will have some conflicts, which you will have to edit manually and fix.

Make sure you are in the branch where you want to copy all the changes to. git merge will take the branch you specify and merge it with the branch you are currently in.

How to get the first day of the current week and month?

You can use the java.time package (since Java8 and late) to get start/end of day/week/month.
The util class example below:

import org.junit.Test;

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;

public class DateUtil {
    private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("UTC");

    public static LocalDateTime startOfDay() {
        return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MIN);
    }

    public static LocalDateTime endOfDay() {
        return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MAX);
    }

    public static boolean belongsToCurrentDay(final LocalDateTime localDateTime) {
        return localDateTime.isAfter(startOfDay()) && localDateTime.isBefore(endOfDay());
    }

    //note that week starts with Monday
    public static LocalDateTime startOfWeek() {
        return LocalDateTime.now(DEFAULT_ZONE_ID)
                .with(LocalTime.MIN)
                .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
    }

    //note that week ends with Sunday
    public static LocalDateTime endOfWeek() {
        return LocalDateTime.now(DEFAULT_ZONE_ID)
                .with(LocalTime.MAX)
                .with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
    }

    public static boolean belongsToCurrentWeek(final LocalDateTime localDateTime) {
        return localDateTime.isAfter(startOfWeek()) && localDateTime.isBefore(endOfWeek());
    }

    public static LocalDateTime startOfMonth() {
        return LocalDateTime.now(DEFAULT_ZONE_ID)
                .with(LocalTime.MIN)
                .with(TemporalAdjusters.firstDayOfMonth());
    }

    public static LocalDateTime endOfMonth() {
        return LocalDateTime.now(DEFAULT_ZONE_ID)
                .with(LocalTime.MAX)
                .with(TemporalAdjusters.lastDayOfMonth());
    }

    public static boolean belongsToCurrentMonth(final LocalDateTime localDateTime) {
        return localDateTime.isAfter(startOfMonth()) && localDateTime.isBefore(endOfMonth());
    }

    public static long toMills(final LocalDateTime localDateTime) {
        return localDateTime.atZone(DEFAULT_ZONE_ID).toInstant().toEpochMilli();
    }

    public static Date toDate(final LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(DEFAULT_ZONE_ID).toInstant());
    }

    public static String toString(final LocalDateTime localDateTime) {
        return localDateTime.format(DateTimeFormatter.ISO_DATE_TIME);
    }

    @Test
    public void test() {
        //day
        final LocalDateTime now = LocalDateTime.now();
        System.out.println("Now: " + toString(now) + ", in mills: " + toMills(now));
        System.out.println("Start of day: " + toString(startOfDay()));
        System.out.println("End of day: " + toString(endOfDay()));
        System.out.println("Does '" + toString(now) + "' belong to the current day? > " + belongsToCurrentDay(now));
        final LocalDateTime yesterday = now.minusDays(1);
        System.out.println("Does '" + toString(yesterday) + "' belong to the current day? > " + belongsToCurrentDay(yesterday));
        final LocalDateTime tomorrow = now.plusDays(1);
        System.out.println("Does '" + toString(tomorrow) + "' belong to the current day? > " + belongsToCurrentDay(tomorrow));
        //week
        System.out.println("Start of week: " + toString(startOfWeek()));
        System.out.println("End of week: " + toString(endOfWeek()));
        System.out.println("Does '" + toString(now) + "' belong to the current week? > " + belongsToCurrentWeek(now));
        final LocalDateTime previousWeek = now.minusWeeks(1);
        System.out.println("Does '" + toString(previousWeek) + "' belong to the current week? > " + belongsToCurrentWeek(previousWeek));
        final LocalDateTime nextWeek = now.plusWeeks(1);
        System.out.println("Does '" + toString(nextWeek) + "' belong to the current week? > " + belongsToCurrentWeek(nextWeek));
        //month
        System.out.println("Start of month: " + toString(startOfMonth()));
        System.out.println("End of month: " + toString(endOfMonth()));
        System.out.println("Does '" + toString(now) + "' belong to the current month? > " + belongsToCurrentMonth(now));
        final LocalDateTime previousMonth = now.minusMonths(1);
        System.out.println("Does '" + toString(previousMonth) + "' belong to the current month? > " + belongsToCurrentMonth(previousMonth));
        final LocalDateTime nextMonth = now.plusMonths(1);
        System.out.println("Does '" + toString(nextMonth) + "' belong to the current month? > " + belongsToCurrentMonth(nextMonth));
    }
}

Test output:

Now: 2020-02-16T22:12:49.957, in mills: 1581891169957
Start of day: 2020-02-16T00:00:00
End of day: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current day? > true
Does '2020-02-15T22:12:49.957' belong to the current day? > false
Does '2020-02-17T22:12:49.957' belong to the current day? > false
Start of week: 2020-02-10T00:00:00
End of week: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current week? > true
Does '2020-02-09T22:12:49.957' belong to the current week? > false
Does '2020-02-23T22:12:49.957' belong to the current week? > false
Start of month: 2020-02-01T00:00:00
End of month: 2020-02-29T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current month? > true
Does '2020-01-16T22:12:49.957' belong to the current month? > false
Does '2020-03-16T22:12:49.957' belong to the current month? > false

How do you get assembler output from C/C++ source in gcc?

The following command line is from Christian Garbin's blog

g++ -g -O -Wa,-aslh horton_ex2_05.cpp >list.txt

I ran G++ from a DOS window on Win-XP, against a routine that contains an implicit cast

c:\gpp_code>g++ -g -O -Wa,-aslh horton_ex2_05.cpp >list.txt
horton_ex2_05.cpp: In function `int main()':
horton_ex2_05.cpp:92: warning: assignment to `int' from `double'

The output is asssembled generated code iterspersed with the original C++ code (the C++ code is shown as comments in the generated asm stream)

  16:horton_ex2_05.cpp **** using std::setw;
  17:horton_ex2_05.cpp ****
  18:horton_ex2_05.cpp **** void disp_Time_Line (void);
  19:horton_ex2_05.cpp ****
  20:horton_ex2_05.cpp **** int main(void)
  21:horton_ex2_05.cpp **** {
 164                    %ebp
 165                            subl $128,%esp
?GAS LISTING C:\DOCUME~1\CRAIGM~1\LOCALS~1\Temp\ccx52rCc.s
166 0128 55                    call ___main
167 0129 89E5          .stabn 68,0,21,LM2-_main
168 012b 81EC8000      LM2:
168      0000
169 0131 E8000000      LBB2:
169      00
170                    .stabn 68,0,25,LM3-_main
171                    LM3:
172                            movl $0,-16(%ebp)

What is key=lambda

In Python, lambda is a keyword used to define anonymous functions(functions with no name) and that's why they are known as lambda functions.

Basically it is used for defining anonymous functions that can/can't take argument(s) and returns value of data/expression. Let's see an example.

>>> # Defining a lambda function that takes 2 parameters(as integer) and returns their sum
... 
>>> lambda num1, num2: num1 + num2 
<function <lambda> at 0x1004b5de8>
>>> 
>>> # Let's store the returned value in variable & call it(1st way to call)
... 
>>> addition = lambda num1, num2: num1 + num2
>>> addition(62, 5)
67
>>> addition(1700, 29)
1729
>>> 
>>> # Let's call it in other way(2nd way to call, one line call )
... 
>>> (lambda num1, num2: num1 + num2)(120, 1)
121
>>> (lambda num1, num2: num1 + num2)(-68, 2)
-66
>>> (lambda num1, num2: num1 + num2)(-68, 2**3)
-60
>>> 

Now let me give an answer of your 2nd question. The 1st answer is also great. This is my own way to explain with another example.

Suppose we have a list of items(integers and strings with numeric contents) as follows,

nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]

and I want to sort it using sorted() function, lets see what happens.

>>> nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
>>> sorted(nums)
[1, 3, 4, '-1', '-10', '2', '5', '8']
>>>

It didn't give me what I expected as I wanted like below,

['-10', '-1', 1, '2', 3, 4, '5', '8']

It means we need some strategy(so that sorted could treat our string items as an ints) to achieve this. This is why the key keyword argument is used. Please look at the below one.

>>> nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
>>> sorted(nums, key=int)
['-10', '-1', 1, '2', 3, 4, '5', '8']
>>> 

Lets use lambda function as a value of key

>>> names = ["Rishikesh", "aman", "Ajay", "Hemkesh", "sandeep", "Darshan", "Virendra", "Shwetabh"]
>>> names2 = sorted(names)
>>> names2
['Ajay', 'Darshan', 'Hemkesh', 'Rishikesh', 'Shwetabh', 'Virendra', 'aman', 'sandeep']
>>> # But I don't want this o/p(here our intention is to treat 'a' same as 'A')
...
>>> names3 = sorted(names, key=lambda name:name.lower())
>>> names3
['Ajay', 'aman', 'Darshan', 'Hemkesh', 'Rishikesh', 'sandeep', 'Shwetabh', 'Virendra']
>>>

You can define your own function(callable) and provide it as value of key.

Dear programers, I have written the below code for you, just try to understand it and comment your explanation. I would be glad to see your explanation(it's simple).

>>> def validator(item):
...     try:
...         return int(item)
...     except:
...         return 0
... 
>>> sorted(['gurmit', "0", 5, 2, 1, "front", -2, "great"], key=validator)
[-2, 'gurmit', '0', 'front', 'great', 1, 2, 5]
>>>

I hope it would be useful.

Difference between text and varchar (character varying)

There is no difference, under the hood it's all varlena (variable length array).

Check this article from Depesz: http://www.depesz.com/index.php/2010/03/02/charx-vs-varcharx-vs-varchar-vs-text/

A couple of highlights:

To sum it all up:

  • char(n) – takes too much space when dealing with values shorter than n (pads them to n), and can lead to subtle errors because of adding trailing spaces, plus it is problematic to change the limit
  • varchar(n) – it's problematic to change the limit in live environment (requires exclusive lock while altering table)
  • varchar – just like text
  • text – for me a winner – over (n) data types because it lacks their problems, and over varchar – because it has distinct name

The article does detailed testing to show that the performance of inserts and selects for all 4 data types are similar. It also takes a detailed look at alternate ways on constraining the length when needed. Function based constraints or domains provide the advantage of instant increase of the length constraint, and on the basis that decreasing a string length constraint is rare, depesz concludes that one of them is usually the best choice for a length limit.

Get the first key name of a JavaScript object

In Javascript you can do the following:

Object.keys(ahash)[0];

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

It is recommended to override equals() and hashCode() to work with hash-based collections, including HashMap, HashSet, and Hashtable, So doing this you can easily remove duplicates by initiating HashSet object with Blog list.

List<Blog> blogList = getBlogList();
Set<Blog> noDuplication = new HashSet<Blog>(blogList);

But Thanks to Java 8 which have very cleaner version to do this as you mentioned you can not change code to add equals() and hashCode()

Collection<Blog> uniqueBlogs = getUniqueBlogList(blogList);

private Collection<Blog> getUniqueBlogList(List<Blog> blogList) {
    return blogList.stream()
            .collect(Collectors.toMap(createUniqueKey(), Function.identity(), (blog1, blog2) -> blog1))
            .values();
}
List<Blog> updatedBlogList = new ArrayList<>(uniqueBlogs);

Third parameter of Collectors.toMap() is merge Function (functional interface) used to resolve collisions between values associated with the same key.

check if a std::vector contains a certain object?

If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x) runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - that's much more efficient with large numbers of elements

std::set also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()....

How to exit if a command failed?

You can also use, if you want to preserve exit error status, and have a readable file with one command per line:

my_command1 || exit $?
my_command2 || exit $?

This, however will not print any additional error message. But in some cases, the error will be printed by the failed command anyway.

How can I read comma separated values from a text file in Java?

//lat=3434&lon=yy38&rd=1.0&| in that format o/p is displaying

public class ReadText {
    public static void main(String[] args) throws Exception {
        FileInputStream f= new FileInputStream("D:/workplace/sample/bookstore.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(f));
        String strline;
        StringBuffer sb = new StringBuffer();
        while ((strline = br.readLine()) != null)
        {
            String[] arraylist=StringUtils.split(strline, ",");
            if(arraylist.length == 2){
                sb.append("lat=").append(StringUtils.trim(arraylist[0])).append("&lon=").append(StringUtils.trim(arraylist[1])).append("&rt=1.0&|");

            } else {
                System.out.println("Error: "+strline);
            }
        }
        System.out.println("Data: "+sb.toString());
    }
}

Execute PowerShell Script from C# with Commandline Arguments

I had trouble passing parameters to the Commands.AddScript method.

C:\Foo1.PS1 Hello World Hunger
C:\Foo2.PS1 Hello World

scriptFile = "C:\Foo1.PS1"

parameters = "parm1 parm2 parm3" ... variable length of params

I Resolved this by passing null as the name and the param as value into a collection of CommandParameters

Here is my function:

private static void RunPowershellScript(string scriptFile, string scriptParameters)
{
    RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
    Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
    runspace.Open();
    RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
    Pipeline pipeline = runspace.CreatePipeline();
    Command scriptCommand = new Command(scriptFile);
    Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
    foreach (string scriptParameter in scriptParameters.Split(' '))
    {
        CommandParameter commandParm = new CommandParameter(null, scriptParameter);
        commandParameters.Add(commandParm);
        scriptCommand.Parameters.Add(commandParm);
    }
    pipeline.Commands.Add(scriptCommand);
    Collection<PSObject> psObjects;
    psObjects = pipeline.Invoke();
}

Composer: how can I install another dependency without updating old ones?

Actually, the correct solution is:

composer require vendor/package

Taken from the CLI documentation for Composer:

The require command adds new packages to the composer.json file from the current directory.

php composer.phar require

After adding/changing the requirements, the modified requirements will be installed or updated.

If you do not want to choose requirements interactively, you can just pass them to the command.

php composer.phar require vendor/package:2.* vendor/package2:dev-master

While it is true that composer update installs new packages found in composer.json, it will also update the composer.lock file and any installed packages according to any fuzzy logic (> or * chars after the colons) found in composer.json! This can be avoided by using composer update vendor/package, but I wouldn't recommend making a habit of it, as you're one forgotten argument away from a potentially broken project…

Keep things sane and stick with composer require vendor/package for adding new dependencies!

Last non-empty cell in a column

Inspired by the great lead given by Doug Glancy's answer, I came up with a way to do the same thing without the need of an array-formula. Do not ask me why, but I am keen to avoid the use of array formulae if at all possible (not for any particular reason, it's just my style).

Here it is:

=SUMPRODUCT(MAX(($A:$A<>"")*(ROW(A:A))))

For finding the last non-empty row using Column A as the reference column

=SUMPRODUCT(MAX(($1:$1<>"")*(COLUMN(1:1))))

For finding the last non-empty column using row 1 as the reference row

This can be further utilized in conjunction with the index function to efficiently define dynamic named ranges, but this is something for another post as this is not related to the immediate question addressed herein.

I've tested the above methods with Excel 2010, both "natively" and in "Compatibility Mode" (for older versions of Excel) and they work. Again, with these you do not need to do any of the Ctrl+Shift+Enter. By leveraging the way sumproduct works in Excel we can get our arms around the need to carry array-operations but we do it without an array-formula. I hope someone out there may appreciate the beauty, simplicity and elegance of these proposed sumproduct solutions as much as I do. I do not attest to the memory-efficiency of the above solutions though. Just that they are simple, look beautiful, help the intended purpose and are flexible enough to extend their use to other purposes :)

Hope this helps!

All the best!

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

I had just the one troublesome file with the changed permissions. To roll it back individually, I just deleted it manually with rm <file> and then did a checkout to pull a fresh copy.

Luckily I had not staged it yet.

If I had I could have run git reset -- <file> before running git checkout -- <file>

When is it appropriate to use C# partial classes?

Service references are another example where partial classes are useful to separate generated code from user-created code.

You can "extend" the service classes without having them overwritten when you update the service reference.

Error 1053 the service did not respond to the start or control request in a timely fashion

In my case, I was publishing service while it was in debug mode.

Solution was:

  • Changing solution to release mode
  • Uninstall old service with command InstallUtil -u WindowsServiceName.exe
  • installing service again InstallUtil -i WindowsServiceName.exe

It worked perfectly after.

java.util.zip.ZipException: duplicate entry during packageAllDebugClassesForMultiDex

I also came across this kind issue when re import old eclipse project. It occurred some old dependency as jar file in the project.

just remove

compile fileTree(dir: 'libs', include: '*.jar')

in gradle file

and add dependency in the gradle file.

It works for me ..

How to resolve "Waiting for Debugger" message?

I had the same issue, fixed it by explicitly selecting desired device in debug configuration. Unfortunately, even after that log sometimes stops when debugger tries to connect. In this case in DDMS perspective find the desired process. It will be highlighted with green bug. Click stop and then debug it again.

Iterate over values of object

EcmaScript 2017 introduced Object.entries that allows you to iterate over values and keys. Documentation

var map = { key1 : 'value1', key2 : 'value2' }

for (let [key, value] of Object.entries(map)) {
    console.log(`${key}: ${value}`);
}

The result will be:

key1: value1
key2: value2

Can't Find Theme.AppCompat.Light for New Android ActionBar Support

You need to do next:

  1. File->Import (android-sdk\extras\android\support\v7). Choose "AppCompat"
  2. Project-> properties->Android. In the section library "Add" and choose "AppCompat"
  3. That is all!

Note: if you are using "android:showAsAction" in menu item, you need to change prefix android as in the example http://developer.android.com/guide/topics/ui/actionbar.html

What is the best project structure for a Python application?

Doesn't too much matter. Whatever makes you happy will work. There aren't a lot of silly rules because Python projects can be simple.

  • /scripts or /bin for that kind of command-line interface stuff
  • /tests for your tests
  • /lib for your C-language libraries
  • /doc for most documentation
  • /apidoc for the Epydoc-generated API docs.

And the top-level directory can contain README's, Config's and whatnot.

The hard choice is whether or not to use a /src tree. Python doesn't have a distinction between /src, /lib, and /bin like Java or C has.

Since a top-level /src directory is seen by some as meaningless, your top-level directory can be the top-level architecture of your application.

  • /foo
  • /bar
  • /baz

I recommend putting all of this under the "name-of-my-product" directory. So, if you're writing an application named quux, the directory that contains all this stuff is named /quux.

Another project's PYTHONPATH, then, can include /path/to/quux/foo to reuse the QUUX.foo module.

In my case, since I use Komodo Edit, my IDE cuft is a single .KPF file. I actually put that in the top-level /quux directory, and omit adding it to SVN.

How can I open Java .class files in a human-readable way?

what you are looking for is a java de-compiler. I recommend JAD http://www.kpdus.com/jad.html It's free for non commercial use and gets the job done.

Note: this isn't going to make the code exactly the same as what was written. i.e. you're going to lose comments and possibly variable names, so it's going to be a little bit harder than just reading normal source code. If the developer is really secretive they will have obfuscated their code as well, making it even harder to read.

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

It has been fun reading the answers to this question. Once you've achieved the 'wow' factor from the students, illustrate the daisy-chaining affect of the results of one becoming the input of another. Learning how input and output works will illustrate the idea of building blocks and how software grows from lots of little things solving specific problems to larger applications solving bigger problems. If a few 10 line programs can be cool, how cool would it be to then put a bunch of them together? That is non-linear cool.

Print the stack trace of an exception

Apache commons provides utility to convert the stack trace from throwable to string.

Usage:

ExceptionUtils.getStackTrace(e)

For complete documentation refer to https://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html

Multiple conditions in ngClass - Angular 4

You are trying to assign an array to ngClass, but the syntax for the array elements is wrong since you separate them with a || instead of a ,.

Try this:

<section [ngClass]="[menu1 ? 'class1' : '',  menu2 ? 'class1' : '', (something && (menu1 || menu2)) ? 'class2' : '']">

This other option should also work:

<section [ngClass.class1]="menu1 || menu2" [ngClass.class2] = "(menu1 || menu2) && something">    

List all employee's names and their managers by manager name using an inner join

Select e.lastname as employee ,m.lastname as manager
  from employees e,employees m
 where e.managerid=m.employyid(+)

Deserializing JSON Object Array with Json.net

Slight modification to what was stated above. My Json format, which validates was

{
    mycollection:{[
           {   
               property0:value,
               property1:value,
             },
             {   
               property0:value,
               property1:value,
             }
           ]

         }
       }

Using AlexDev's response, I did this Looping each child, creating reader from it

 public partial class myModel
{
    public static List<myModel> FromJson(string json) => JsonConvert.DeserializeObject<myModelList>(json, Converter.Settings).model;
}

 public class myModelList {
    [JsonConverter(typeof(myModelConverter))]
    public List<myModel> model { get; set; }

}

class myModelConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.Load(reader);
        var list = Activator.CreateInstance(objectType) as System.Collections.IList;
        var itemType = objectType.GenericTypeArguments[0];
        foreach (var child in token.Children())  //mod here
        {
            var newObject = Activator.CreateInstance(itemType);
            serializer.Populate(child.CreateReader(), newObject); //mod here
            list.Add(newObject);
        }
        return list;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
    }
    public override bool CanWrite => false;
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();

}

Sending mail attachment using Java

If you allow me, it works fine also for multi-attachments, the 1st above answer of NINCOMPOOP, with just a little modification like follows:

DataSource source,source2,source3,source4, ...;  
source = new FileDataSource(myfile);  
messageBodyPart.setDataHandler(new DataHandler(source));  
messageBodyPart.setFileName(myfile);  
multipart.addBodyPart(messageBodyPart);  

source2 = new FileDataSource(myfile2);  
messageBodyPart.setDataHandler(new DataHandler(source2));  
messageBodyPart.setFileName(myfile2);  
multipart.addBodyPart(messageBodyPart);  

source3 = new FileDataSource(myfile3);  
messageBodyPart.setDataHandler(new DataHandler(source3));  
messageBodyPart.setFileName(myfile3);  
multipart.addBodyPart(messageBodyPart);  

source4 = new FileDataSource(myfile4);  
messageBodyPart.setDataHandler(new DataHandler(source4));  
messageBodyPart.setFileName(myfile4);  
multipart.addBodyPart(messageBodyPart);  

...

message.setContent(multipart);

Spring MVC 4: "application/json" Content Type is not being set correctly

First thing to understand is that the RequestMapping#produces() element in

@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")

serves only to restrict the mapping for your request handlers. It does nothing else.

Then, given that your method has a return type of String and is annotated with @ResponseBody, the return value will be handled by StringHttpMessageConverter which sets the Content-type header to text/plain. If you want to return a JSON string yourself and set the header to application/json, use a return type of ResponseEntity (get rid of @ResponseBody) and add appropriate headers to it.

@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> bar() {
    final HttpHeaders httpHeaders= new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>("{\"test\": \"jsonResponseExample\"}", httpHeaders, HttpStatus.OK);
}

Note that you should probably have

<mvc:annotation-driven /> 

in your servlet context configuration to set up your MVC configuration with the most suitable defaults.

How can query string parameters be forwarded through a proxy_pass with nginx?

you have to use rewrite to pass params using proxy_pass here is example I did for angularjs app deployment to s3

S3 Static Website Hosting Route All Paths to Index.html

adopted to your needs would be something like

location /service/ {
    rewrite ^\/service\/(.*) /$1 break;
    proxy_pass http://apache;
}

if you want to end up in http://127.0.0.1:8080/query/params/

if you want to end up in http://127.0.0.1:8080/service/query/params/ you'll need something like

location /service/ {
    rewrite ^\/(.*) /$1 break;
    proxy_pass http://apache;
}

Display all items in array using jquery

for (var i = 0; i < array.length; i++) {
    $(".element").append('<span>' + array[i] + '</span>');
}