Programs & Examples On #Sslstream

.NET class that provides a stream used for client-server communication that uses TLS/SSL security protocols to authenticate the server and optionally the client.

Authentication failed because remote party has closed the transport stream

using (var client = new HttpClient(handler))
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, apiEndPoint)).ConfigureAwait(false);
                await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            }

This worked for me

What is the equivalent of 'describe table' in SQL Server?

Just in case you don't want to use stored proc, here's a simple query version

select * 
  from information_schema.columns 
 where table_name = 'aspnet_Membership'
 order by ordinal_position

Java - Best way to print 2D array?

@Ashika's answer works fantastically if you want (0,0) to be represented in the top, left corner, per normal CS convention. If however you would prefer to use normal mathematical convention and put (0,0) in the lower left hand corner, you could use this:

LinkedList<String> printList = new LinkedList<String>();
for (char[] row: array) {
    printList.addFirst(Arrays.toString(row));;
}
while (!printList.isEmpty())
    System.out.println(printList.removeFirst());

This used LIFO (Last In First Out) to reverse the order at print time.

GetElementByID - Multiple IDs

Vulgo has the right idea on this thread. I believe his solution is the easiest of the bunch, although his answer could have been a little more in-depth. Here is something that worked for me. I have provided an example.

<h1 id="hello1">Hello World</h1>
<h2 id="hello2">Random</h2>
<button id="click">Click To Hide</button>

<script>

  document.getElementById('click').addEventListener('click', function(){
    doStuff();
  });

  function doStuff() {
    for(var i=1; i<=2; i++){
        var el = document.getElementById("hello" + i);
        el.style.display = 'none';
    }
  }

</script>

Obviously just change the integers in the for loop to account for however many elements you are targeting, which in this example was 2.

Dump all tables in CSV format using 'mysqldump'

First, I can give you the answer for one table:

The trouble with all these INTO OUTFILE or --tab=tmpfile (and -T/path/to/directory) answers is that it requires running mysqldump on the same server as the MySQL server, and having those access rights.

My solution was simply to use mysql (not mysqldump) with the -B parameter, inline the SELECT statement with -e, then massage the ASCII output with sed, and wind up with CSV including a header field row:

Example:

 mysql -B -u username -p password database -h dbhost -e "SELECT * FROM accounts;" \
 | sed "s/\"/\"\"/g;s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g"

"id","login","password","folder","email" "8","mariana","xxxxxxxxxx","mariana","" "3","squaredesign","xxxxxxxxxxxxxxxxx","squaredesign","[email protected]" "4","miedziak","xxxxxxxxxx","miedziak","[email protected]" "5","Sarko","xxxxxxxxx","Sarko","" "6","Logitrans Poland","xxxxxxxxxxxxxx","LogitransPoland","" "7","Amos","xxxxxxxxxxxxxxxxxxxx","Amos","" "9","Annabelle","xxxxxxxxxxxxxxxx","Annabelle","" "11","Brandfathers and Sons","xxxxxxxxxxxxxxxxx","BrandfathersAndSons","" "12","Imagine Group","xxxxxxxxxxxxxxxx","ImagineGroup","" "13","EduSquare.pl","xxxxxxxxxxxxxxxxx","EduSquare.pl","" "101","tmp","xxxxxxxxxxxxxxxxxxxxx","_","[email protected]"

Add a > outfile.csv at the end of that one-liner, to get your CSV file for that table.

Next, get a list of all your tables with

mysql -u username -ppassword dbname -sN -e "SHOW TABLES;"

From there, it's only one more step to make a loop, for example, in the Bash shell to iterate over those tables:

 for tb in $(mysql -u username -ppassword dbname -sN -e "SHOW TABLES;"); do
     echo .....;
 done

Between the do and ; done insert the long command I wrote in Part 1 above, but substitute your tablename with $tb instead.

What is the fastest way to transpose a matrix in C++?

template <class T>
void transpose( const std::vector< std::vector<T> > & a,
std::vector< std::vector<T> > & b,
int width, int height)
{
    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j < height; j++)
        {
            b[j][i] = a[i][j];
        }
    }
} 

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

For the easiest scenario when you hide cells at the very bottom of table view, you could adjust tableView's contentInset after you hide cell:

- (void)adjustBottomInsetForHiddenSections:(NSInteger)numberOfHiddenSections
{
    CGFloat bottomInset = numberOfHiddenSections * 44.0; // or any other 'magic number
    self.tableView.contentInset = UIEdgeInsetsMake(self.tableView.contentInset.top, self.tableView.contentInset.left, -bottomInset, self.tableView.contentInset.right);
}

How to ignore conflicts in rpm installs

Try Freshen command:

rpm -Fvh *.rpm

Editing dictionary values in a foreach loop

You can't modify the collection, not even the values. You could save these cases and remove them later. It would end up like this:

Dictionary<string, int> colStates = new Dictionary<string, int>();
// ...
// Some code to populate colStates dictionary
// ...

int OtherCount = 0;
List<string> notRelevantKeys = new List<string>();

foreach (string key in colStates.Keys)
{

    double Percent = colStates[key] / colStates.Count;

    if (Percent < 0.05)
    {
        OtherCount += colStates[key];
        notRelevantKeys.Add(key);
    }
}

foreach (string key in notRelevantKeys)
{
    colStates[key] = 0;
}

colStates.Add("Other", OtherCount);

How to get ER model of database from server with Workbench

I want to enhance Mr. Kamran Ali's answer with pictorial view.

Pictorial View is given step by step:

  1. Go to "Database" Menu option
  2. Select the "Reverse Engineer" option.

enter image description here

  1. A wizard will come. Select from "Stored Connection" and press "Next" button.

enter image description here

  1. Then "Next"..to.."Finish"

Enjoy :)

macOS on VMware doesn't recognize iOS device

This solution for Ubuntu Host, Macos Guest

  1. disable SIP
  2. install mac ports
  3. sudo launchctl unload /Library/Apple/System/Library/LaunchDaemons/com.apple.usbmuxd.plist
  4. sudo port install usbmuxd
  5. sudo usbmuxd --foreground
  6. then connect iPhone and let the guest to take control

Disabling SIP

  1. Start vmware
  2. select guest and "power to firmware"
  3. in efi menu, enter setup > config boot options > add boot options > select recovery partition > select boot.efi
  4. at input file description hit and type in label e.g. "recovery" > commit changes and exit
  5. boot from recovery and be patient
  6. follow prompt until you see OS X Utilities menu
  7. At the very top menu select Utilities > Terminal
  8. In terminal enter "csrutil status"
  9. then csrutil disable
  10. then csrutil status
  11. then reboot > hit enter once or twice
  12. Double check in OSX Terminal app to ensure SIP is disabled

Finally, disable HiDPI:

$ sudo defaults write /Library/Preferences/com.apple.windowserver DisplayResolutionEnabled -bool NO

Referenced from:

Gradle: How to Display Test Results in the Console in Real Time?

For those using Kotlin DSL, you can do:

tasks {
  named<Test>("test") {
    testLogging.showStandardStreams = true
  }
}

How to clear https proxy setting of NPM?

None of the above helped me, but this did:

npm config rm proxy
npm config rm https-proxy

Source: http://jonathanblog2000.blogspot.ch/2013/11/set-and-reset-proxy-for-git-and-npm.html

Floating divs in Bootstrap layout

From all I have read you cannot do exactly what you want without javascript. If you float left before text

<div style="float:left;">widget</div> here is some CONTENT, etc.

Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content

here is some CONTENT, etc. <div style="float:left;">widget</div>

Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:

here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>

In your question you are using bootstrap which just adds row-fluid::after { content: ""} which resolves the border/background issue.

Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/

  <div class="container-fluid">
  <div class="row-fluid">
    <div class="offset1 span8 pull-right">
    ... Widget 1...
    </div>
    .... a lot of content ....
    <div class="span8" style="margin-left: 0;">
    ... Widget 2...
    </div>


  </div>

</div><!--/.fluid-container-->

Difference between Subquery and Correlated Subquery

when it comes to subquery and co-related query both have inner query and outer query the only difference is in subquery the inner query doesn't depend on outer query, whereas in co-related inner query depends on outer.

Convert integer to binary in C#

class Program
{
    static void Main(string[] args)
    {
        var @decimal = 42;
        var binaryVal = ToBinary(@decimal, 2);

        var binary = "101010";
        var decimalVal = ToDecimal(binary, 2);

        Console.WriteLine("Binary value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of binary '{0}' is {1}", binary, decimalVal);
        Console.WriteLine();

        @decimal = 6;
        binaryVal = ToBinary(@decimal, 3);

        binary = "20";
        decimalVal = ToDecimal(binary, 3);

        Console.WriteLine("Base3 value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of base3 '{0}' is {1}", binary, decimalVal);
        Console.WriteLine();


        @decimal = 47;
        binaryVal = ToBinary(@decimal, 4);

        binary = "233";
        decimalVal = ToDecimal(binary, 4);

        Console.WriteLine("Base4 value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of base4 '{0}' is {1}", binary, decimalVal);
        Console.WriteLine();

        @decimal = 99;
        binaryVal = ToBinary(@decimal, 5);

        binary = "344";
        decimalVal = ToDecimal(binary, 5);

        Console.WriteLine("Base5 value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of base5 '{0}' is {1}", binary, decimalVal);
        Console.WriteLine();

        Console.WriteLine("And so forth.. excluding after base 10 (decimal) though :)");
        Console.WriteLine();


        @decimal = 16;
        binaryVal = ToBinary(@decimal, 11);

        binary = "b";
        decimalVal = ToDecimal(binary, 11);

        Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
        Console.WriteLine();
        Console.WriteLine("Uh oh.. this aint right :( ... but let's cheat :P");
        Console.WriteLine();

        @decimal = 11;
        binaryVal = Convert.ToString(@decimal, 16);

        binary = "b";
        decimalVal = Convert.ToInt32(binary, 16);

        Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);

        Console.ReadLine();
    }


    static string ToBinary(decimal number, int @base)
    {
        var round = 0;
        var reverseBinary = string.Empty;

        while (number > 0)
        {
            var remainder = number % @base;
            reverseBinary += remainder;

            round = (int)(number / @base);
            number = round;
        }

        var binaryArray = reverseBinary.ToCharArray();
        Array.Reverse(binaryArray);

        var binary = new string(binaryArray);
        return binary;
    }

    static double ToDecimal(string binary, int @base)
    {
        var val = 0d;

        if (!binary.All(char.IsNumber))
            return 0d;

        for (int i = 0; i < binary.Length; i++)
        {
            var @char = Convert.ToDouble(binary[i].ToString());

            var pow = (binary.Length - 1) - i;
            val += Math.Pow(@base, pow) * @char;
        }

        return val;
    }
}

Learning sources:

Everything you need to know about binary

including algorithm to convert decimal to binary

How do I check (at runtime) if one class is a subclass of another?

You can use isinstance if you have an instance, or issubclass if you have a class. Normally thought its a bad idea. Normally in Python you work out if an object is capable of something by attempting to do that thing to it.

How can I connect to Android with ADB over TCP?

Here is a one-liner for Mac/Linux to connect to an Android device over Wi-Fi, but first you must connect to the device via USB.

# sleep 5 is to wait for the device to restart listening.
adb kill-server && adb tcpip 5555 && sleep 5 && adb shell ip route | awk '{print $9}' | xargs adb connect

Adding script tag to React/JSX

componentDidMount() {
  const head = document.querySelector("head");
  const script = document.createElement("script");
  script.setAttribute(
    "src",
    "https://assets.calendly.com/assets/external/widget.js"
  );
  head.appendChild(script);
}

In Gradle, is there a better way to get Environment Variables?

In android gradle 0.4.0 you can just do:

println System.env.HOME

classpath com.android.tools.build:gradle-experimental:0.4.0

How to resolve the error "Unable to access jarfile ApacheJMeter.jar errorlevel=1" while initiating Jmeter?

If you'll go through these steps:

  1. In the Terminal type brew install jmeter and hit Enter
  2. When it'll be done type jmeter and hit Enter again

You won't have to solve any kind of issue. Don't thank

Disable submit button when form invalid with AngularJS

If you are using Reactive Forms you can use this:

<button [disabled]="!contactForm.valid" type="submit" class="btn btn-lg btn primary" (click)="printSomething()">Submit</button>

How to select the first row of each group?

The solution below does only one groupBy and extract the rows of your dataframe that contain the maxValue in one shot. No need for further Joins, or Windows.

import org.apache.spark.sql.Row
import org.apache.spark.sql.catalyst.encoders.RowEncoder
import org.apache.spark.sql.DataFrame

//df is the dataframe with Day, Category, TotalValue

implicit val dfEnc = RowEncoder(df.schema)

val res: DataFrame = df.groupByKey{(r) => r.getInt(0)}.mapGroups[Row]{(day: Int, rows: Iterator[Row]) => i.maxBy{(r) => r.getDouble(2)}}

Check if a number is int or float

how about this solution?

if type(x) in (float, int):
    # do whatever
else:
    # do whatever

Create sequence of repeated values, in sequence?

Another base R option could be gl():

gl(5, 3)

Where the output is a factor:

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Levels: 1 2 3 4 5

If integers are needed, you can convert it:

as.numeric(gl(5, 3))

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5

How does Python's super() work with multiple inheritance?

class First(object):
  def __init__(self, a):
    print "first", a
    super(First, self).__init__(20)

class Second(object):
  def __init__(self, a):
    print "second", a
    super(Second, self).__init__()

class Third(First, Second):
  def __init__(self):
    super(Third, self).__init__(10)
    print "that's it"

t = Third()

Output is

first 10
second 20
that's it

Call to Third() locates the init defined in Third. And call to super in that routine invokes init defined in First. MRO=[First, Second]. Now call to super in init defined in First will continue searching MRO and find init defined in Second, and any call to super will hit the default object init. I hope this example clarifies the concept.

If you don't call super from First. The chain stops and you will get the following output.

first 10
that's it

How to run jenkins as a different user

The "Issue 2" answer given by @Sagar works for the majority of git servers such as gitorious.

However, there will be a name clash in a system like gitolite where the public ssh keys are checked in as files named with the username, ie keydir/jenkins.pub. What if there are multiple jenkins servers that need to access the same gitolite server?

(Note: this is about running the Jenkins daemon not running a build job as a user (addressed by @Sagar's "Issue 1").)

So in this case you do need to run the Jenkins daemon as a different user.

There are two steps:

Step 1

The main thing is to update the JENKINS_USER environment variable. Here's a patch showing how to change the user to ptran.

BEGIN PATCH
--- etc/default/jenkins.old     2011-10-28 17:46:54.410305099 -0700
+++ etc/default/jenkins 2011-10-28 17:47:01.670369300 -0700
@@ -13,7 +13,7 @@
 PIDFILE=/var/run/jenkins/jenkins.pid

 # user id to be invoked as (otherwise will run as root; not wise!)
-JENKINS_USER=jenkins
+JENKINS_USER=ptran

 # location of the jenkins war file
 JENKINS_WAR=/usr/share/jenkins/jenkins.war
--- etc/init.d/jenkins.old      2011-10-28 17:47:20.878539172 -0700
+++ etc/init.d/jenkins  2011-10-28 17:47:47.510774714 -0700
@@ -23,7 +23,7 @@

 #DAEMON=$JENKINS_SH
 DAEMON=/usr/bin/daemon
-DAEMON_ARGS="--name=$NAME --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG -   -pidfile=$PIDFILE" 
+DAEMON_ARGS="--name=$JENKINS_USER --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG --pidfile=$PIDFILE" 

 SU=/bin/su
END PATCH

Step 2

Update ownership of jenkins directories:

chown -R ptran /var/log/jenkins
chown -R ptran /var/lib/jenkins
chown -R ptran /var/run/jenkins
chown -R ptran /var/cache/jenkins

Step 3

Restart jenkins

sudo service jenkins restart

Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError.

I got the solution

download Xuggler 5.4 here

and some more jar to make it work...

commons-cli-1.1.jar

commons-lang-2.1.jar

logback-classic-1.0.0.jar

logback-core-1.0.0.jar

slf4j-api-1.6.4.jar

Reference Libraries

You can check which dependencies xuggler needs from here:

Add this jars and xuggle-xuggler-5.4.jar to your project's build path and it s ready.

**version numbers may change

Jquery in React is not defined

Add "ref" to h1 tag :

<h1 ref="source">Hey there.</h1>

and
const { source } = this.props; change to const { source } = this.refs;

Selecting only numeric columns from a data frame

library(purrr)
x <- x %>% keep(is.numeric)

Javascript receipt printing using POS Printer

EDIT: NOV 27th, 2017 - BROKEN LINKS

Links below about the posts written by David Kelley are broken.

There are cached versions of the repository, just add cache: before the URL in the Chrome Browser and hit enter.


This solution is only for Google Chrome and Chromium-based browsers.

EDIT:

(*)The links are broken. Fortunately I found this repository that contains the source of the post in the following markdown files: A | B

This link* explains how to make a Javascript Interface for ESC/POS printers using Chrome/Chromium USB API (1)(2). This link* explains how to Connect to USB devices using the chrome.usb.* API.

How to add a ScrollBar to a Stackpanel

It works like this:

<ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Disabled" Width="340" HorizontalAlignment="Left" Margin="12,0,0,0">
        <StackPanel Name="stackPanel1" Width="311">

        </StackPanel>
</ScrollViewer>

TextBox tb = new TextBox();
tb.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
stackPanel1.Children.Add(tb);

Brew doctor says: "Warning: /usr/local/include isn't writable."

Go into the /bin directory and type:

chown -R $(whoami):admin /usr/local/bin

C# Inserting Data from a form into an access Database

My Code to insert data is not working. It showing no error but data is not showing in my database.

public partial class Form1 : Form { OleDbConnection connection = new OleDbConnection(check.Properties.Settings.Default.KitchenConnectionString); public Form1() { InitializeComponent(); }

    private void Form1_Load(object sender, EventArgs e)
    {
        
    }

    private void btn_add_Click(object sender, EventArgs e)
    {
        OleDbDataAdapter items = new OleDbDataAdapter();
        connection.Open();
        OleDbCommand command = new OleDbCommand("insert into Sets(SetId, SetName,  SetPassword) values('"+txt_id.Text+ "','" + txt_setname.Text + "','" + txt_password.Text + "');", connection);
        command.CommandType = CommandType.Text;
        command.ExecuteReader();
        connection.Close();
        MessageBox.Show("Insertd!");
    }
}

What is the difference between 127.0.0.1 and localhost

some applications will treat "localhost" specially. the mysql client will treat localhost as a request to connect to the local unix domain socket instead of using tcp to connect to the server on 127.0.0.1. This may be faster, and may be in a different authentication zone.

I don't know of other apps that treat localhost differently than 127.0.0.1, but there probably are some.

Attach event to dynamic elements in javascript

You must attach the event after insert elements, like that you don't attach a global event on your document but a specific event on the inserted elements.

e.g.

_x000D_
_x000D_
document.getElementById('form').addEventListener('submit', function(e) {_x000D_
  e.preventDefault();_x000D_
  var name = document.getElementById('txtName').value;_x000D_
  var idElement = 'btnPrepend';_x000D_
  var html = `_x000D_
    <ul>_x000D_
      <li>${name}</li>_x000D_
    </ul>_x000D_
    <input type="button" value="prepend" id="${idElement}" />_x000D_
  `;_x000D_
  /* Insert the html into your DOM */_x000D_
  insertHTML('form', html);_x000D_
  /* Add an event listener after insert html */_x000D_
  addEvent(idElement);_x000D_
});_x000D_
_x000D_
const insertHTML = (tag = 'form', html, position = 'afterend', index = 0) => {_x000D_
  document.getElementsByTagName(tag)[index].insertAdjacentHTML(position, html);_x000D_
}_x000D_
const addEvent = (id, event = 'click') => {_x000D_
  document.getElementById(id).addEventListener(event, function() {_x000D_
    insertHTML('ul', '<li>Prepending data</li>', 'afterbegin')_x000D_
  });_x000D_
}
_x000D_
<form id="form">_x000D_
  <div>_x000D_
    <label for="txtName">Name</label>_x000D_
    <input id="txtName" name="txtName" type="text" />_x000D_
  </div>_x000D_
  <input type="submit" value="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Fitting empirical distribution to theoretical ones with Scipy (Python)?

Try the distfit library.

pip install distfit

# Create 1000 random integers, value between [0-50]
X = np.random.randint(0, 50,1000)

# Retrieve P-value for y
y = [0,10,45,55,100]

# From the distfit library import the class distfit
from distfit import distfit

# Initialize.
# Set any properties here, such as alpha.
# The smoothing can be of use when working with integers. Otherwise your histogram
# may be jumping up-and-down, and getting the correct fit may be harder.
dist = distfit(alpha=0.05, smooth=10)

# Search for best theoretical fit on your empirical data
dist.fit_transform(X)

> [distfit] >fit..
> [distfit] >transform..
> [distfit] >[norm      ] [RSS: 0.0037894] [loc=23.535 scale=14.450] 
> [distfit] >[expon     ] [RSS: 0.0055534] [loc=0.000 scale=23.535] 
> [distfit] >[pareto    ] [RSS: 0.0056828] [loc=-384473077.778 scale=384473077.778] 
> [distfit] >[dweibull  ] [RSS: 0.0038202] [loc=24.535 scale=13.936] 
> [distfit] >[t         ] [RSS: 0.0037896] [loc=23.535 scale=14.450] 
> [distfit] >[genextreme] [RSS: 0.0036185] [loc=18.890 scale=14.506] 
> [distfit] >[gamma     ] [RSS: 0.0037600] [loc=-175.505 scale=1.044] 
> [distfit] >[lognorm   ] [RSS: 0.0642364] [loc=-0.000 scale=1.802] 
> [distfit] >[beta      ] [RSS: 0.0021885] [loc=-3.981 scale=52.981] 
> [distfit] >[uniform   ] [RSS: 0.0012349] [loc=0.000 scale=49.000] 

# Best fitted model
best_distr = dist.model
print(best_distr)

# Uniform shows best fit, with 95% CII (confidence intervals), and all other parameters
> {'distr': <scipy.stats._continuous_distns.uniform_gen at 0x16de3a53160>,
>  'params': (0.0, 49.0),
>  'name': 'uniform',
>  'RSS': 0.0012349021241149533,
>  'loc': 0.0,
>  'scale': 49.0,
>  'arg': (),
>  'CII_min_alpha': 2.45,
>  'CII_max_alpha': 46.55}

# Ranking distributions
dist.summary

# Plot the summary of fitted distributions
dist.plot_summary()

enter image description here

# Make prediction on new datapoints based on the fit
dist.predict(y)

# Retrieve your pvalues with 
dist.y_pred
# array(['down', 'none', 'none', 'up', 'up'], dtype='<U4')
dist.y_proba
array([0.02040816, 0.02040816, 0.02040816, 0.        , 0.        ])

# Or in one dataframe
dist.df

# The plot function will now also include the predictions of y
dist.plot()

Best fit

Note that in this case, all points will be significant because of the uniform distribution. You can filter with the dist.y_pred if required.

Docker-Compose can't connect to Docker Daemon

I got this error when there were files in the Dockerfile directory that were not accessible by the current user. docker could thus not upload the full context to the daemon and brought the "Couldn't connect to Docker daemon at http+docker://localunixsocket" message.

IsNullOrEmpty with Object

You can simply compare it with System.DBNull.Value

Detect rotation of Android phone in the browser with JavaScript

You could always listen to the window resize event. If, on that event, the window went from being taller than it is wide to wider than it is tall (or vice versa), you can be pretty sure the phone orientation was just changed.

How do you check that a number is NaN in JavaScript?

The exact way to check is:

//takes care of boolen, undefined and empty

isNaN(x) || typeof(x) ==='boolean' || typeof(x) !=='undefined' || x!=='' ? 'is really a nan' : 'is a number'

How to find out whether a file is at its `eof`?

f = open(filename,'r')
f.seek(-1,2)     # go to the file end.
eof = f.tell()   # get the end of file location
f.seek(0,0)      # go back to file beginning

while(f.tell() != eof):
    <body>

You can use the file methods seek() and tell() to determine the position of the end of file. Once the position is found, seek back to the file beginning

Comparing two dataframes and getting the differences

Hope this would be useful to you. ^o^

df1 = pd.DataFrame({'date': ['0207', '0207'], 'col1': [1, 2]})
df2 = pd.DataFrame({'date': ['0207', '0207', '0208', '0208'], 'col1': [1, 2, 3, 4]})
print(f"df1(Before):\n{df1}\ndf2:\n{df2}")
"""
df1(Before):
   date  col1
0  0207     1
1  0207     2

df2:
   date  col1
0  0207     1
1  0207     2
2  0208     3
3  0208     4
"""

old_set = set(df1.index.values)
new_set = set(df2.index.values)
new_data_index = new_set - old_set
new_data_list = []
for idx in new_data_index:
    new_data_list.append(df2.loc[idx])

if len(new_data_list) > 0:
    df1 = df1.append(new_data_list)
print(f"df1(After):\n{df1}")
"""
df1(After):
   date  col1
0  0207     1
1  0207     2
2  0208     3
3  0208     4
"""

label or @html.Label ASP.net MVC 4

@html.label and @html.textbox are use when you want bind it to your model in a easy way...which cannot be achieve by input etc. in one line

Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0

To fix this issue, I simply let Tortoise Git install its update.

Qt - reading from a text file

You have to replace string line

QString line = in.readLine();

into while:

QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", file.errorString());
}

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();    
    QStringList fields = line.split(",");    
    model->appendRow(fields);    
}

file.close();

jQuery - select all text from a textarea

I ended up using this:

$('.selectAll').toggle(function() {
  $(this).select();
}, function() {
  $(this).unselect();
});

How do I install a pip package globally instead of locally?

Are you using virtualenv? If yes, deactivate the virtualenv. If you are not using, it is already installed widely (system level). Try to upgrade package.

pip install flake8 --upgrade

How to remove only 0 (Zero) values from column in excel 2010

Press Control + H, then select Options and check Match entire cell contents and Match case. In the Find what field type a 0, and leave the Replace with field blank. Then Replace All. This will remove all of the zeros that are stand alone.

Rolling or sliding window iterator?

>>> n, m = 6, 3
>>> k = n - m+1
>>> print ('{}\n'*(k)).format(*[range(i, i+m) for i in xrange(k)])
[0, 1, 2]
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]

How to insert an object in an ArrayList at a specific position

This method Appends the specified element to the end of this list.

add(E e) //append element to the end of the arraylist.

This method Inserts the specified element at the specified position in this list.

void add(int index, E element) //inserts element at the given position in the array list.

This method Replaces the element at the specified position in this list with the specified element.

set(int index, E element) //Replaces the element at the specified position in this list with the specified element.
      

      

Why do I get AttributeError: 'NoneType' object has no attribute 'something'?

Consider the code below.

def return_something(someint):
 if  someint > 5:
    return someint

y = return_something(2)
y.real()

This is going to give you the error

AttributeError: 'NoneType' object has no attribute 'real'

So points are as below.

  1. In the code, a function or class method is not returning anything or returning the None
  2. Then you try to access an attribute of that returned object(which is None), causing the error message.

How can I pass a parameter to a setTimeout() callback?

After doing some research and testing, the only correct implementation is:

setTimeout(yourFunctionReference, 4000, param1, param2, paramN);

setTimeout will pass all extra parameters to your function so they can be processed there.

The anonymous function can work for very basic stuff, but within instance of a object where you have to use "this", there is no way to make it work. Any anonymous function will change "this" to point to window, so you will lose your object reference.

How to embed a SWF file in an HTML page?

The best approach to embed a SWF into an HTML page is to use SWFObject.

It is a simple open-source JavaScript library that is easy-to-use and standards-friendly method to embed Flash content.

It also offers Flash player version detection. If the user does not have the version of Flash required or has JavaScript disabled, they will see an alternate content. You can also use this library to trigger a Flash player upgrade. Once the user has upgraded, they will be redirected back to the page.

An example from the documentation:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
  <head>
    <title>SWFObject dynamic embed - step 3</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <script type="text/javascript" src="swfobject.js"></script>

    <script type="text/javascript">
        swfobject.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0");
    </script>

  </head>
  <body>
    <div id="myContent">
      <p>Alternative content</p>
    </div>
  </body>
</html>

A good tool to use along with this is the SWFObject HTML and JavaScript generator. It basically generates the HTML and JavaScript you need to embed the Flash using SWFObject. Comes with a very simple UI for you to input your parameters.

It Is highly recommended and very simple to use.

git diff between cloned and original remote repository

1) Add any remote repositories you want to compare:

git remote add foobar git://github.com/user/foobar.git

2) Update your local copy of a remote:

git fetch foobar

Fetch won't change your working copy.

3) Compare any branch from your local repository to any remote you've added:

git diff master foobar/master

How to get some values from a JSON string in C#?

my string

var obj = {"Status":0,"Data":{"guid":"","invitationGuid":"","entityGuid":"387E22AD69-4910-430C-AC16-8044EE4A6B24443545DD"},"Extension":null}

Following code to get guid:

var userObj = JObject.Parse(obj);
var userGuid = Convert.ToString(userObj["Data"]["guid"]);

How to open the Chrome Developer Tools in a new window?

As of Chrome 52, the UI has changed. When the Developer Tools dialog is open, you select the vertical ellipsis and can then choose the docking position:

enter image description here

Select the icon on the left to open the Chrome Developer Tools in a new window: multiple windows icon


Previously

Click and hold the button next to the close button of the Developer Tool in order to reveal the "Undock into separate window" option.

enter image description here

Note: A "press" is not enough in that state.

Save the console.log in Chrome to a file

On Linux (at least) you can set CHROME_LOG_FILE in the environment to have chrome write a log of the Console activity to the named file each time it runs. The log is overwritten every time chrome starts. This way, if you have an automated session that runs chrome, you don't have a to change the way chrome is started, and the log is there after the session ends.

export CHROME_LOG_FILE=chrome.log

How to use index in select statement?

If you want to test the index to see if it works, here is the syntax:

SELECT *
FROM Table WITH(INDEX(Index_Name))

The WITH statement will force the index to be used.

How to exit when back button is pressed?

Add this code in the activity from where you want to exit from the app on pressing back button:

@Override
public void onBackPressed() {
    super.onBackPressed();
    exitFromApp();
}

private void exitFromApp() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    startActivity(intent);
}

Dump Mongo Collection into JSON format

Mongo includes a mongoexport utility (see docs) which can dump a collection. This utility uses the native libmongoclient and is likely the fastest method.

mongoexport -d <database> -c <collection_name>

Also helpful:

-o: write the output to file, otherwise standard output is used (docs)

--jsonArray: generates a valid json document, instead of one json object per line (docs)

--pretty: outputs formatted json (docs)

In Python how should I test if a variable is None, True or False

Never, never, never say

if something == True:

Never. It's crazy, since you're redundantly repeating what is redundantly specified as the redundant condition rule for an if-statement.

Worse, still, never, never, never say

if something == False:

You have not. Feel free to use it.

Finally, doing a == None is inefficient. Do a is None. None is a special singleton object, there can only be one. Just check to see if you have that object.

Making the main scrollbar always visible

body { 
    min-height: 101vh; 
} 

works the best for me

Android design support library for API 28 (P) not working

Had similar problem. Added in build.gradle and it worked for me.

 compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

How to reset the state of a Redux store?

The following solution worked for me.

I added resetting state function to meta reducers.The key was to use

return reducer(undefined, action);

to set all reducers to initial state. Returning undefined instead was causing errors due to the fact that the structure of the store has been destroyed.

/reducers/index.ts

export function resetState(reducer: ActionReducer<State>): ActionReducer<State> {
  return function (state: State, action: Action): State {

    switch (action.type) {
      case AuthActionTypes.Logout: {
        return reducer(undefined, action);
      }
      default: {
        return reducer(state, action);
      }
    }
  };
}

export const metaReducers: MetaReducer<State>[] = [ resetState ];

app.module.ts

import { StoreModule } from '@ngrx/store';
import { metaReducers, reducers } from './reducers';

@NgModule({
  imports: [
    StoreModule.forRoot(reducers, { metaReducers })
  ]
})
export class AppModule {}

Generate random int value from 3 to 6

This generates a random number between 0-9

SELECT ABS(CHECKSUM(NEWID()) % 10)

1 through 6

SELECT ABS(CHECKSUM(NEWID()) % 6) + 1

3 through 6

SELECT ABS(CHECKSUM(NEWID()) % 4) + 3

Dynamic (Based on Eilert Hjelmeseths Comment, updated to fix bug( + to -))

SELECT ABS(CHECKSUM(NEWID()) % (@max - @min - 1)) + @min

Updated based on comments:

  • NEWID generates random string (for each row in return)
  • CHECKSUM takes value of string and creates number
  • modulus (%) divides by that number and returns the remainder (meaning max value is one less than the number you use)
  • ABS changes negative results to positive
  • then add one to the result to eliminate 0 results (to simulate a dice roll)

How add unique key to existing table (with non uniques rows)

Set Multiple Unique key into table

ALTER TABLE table_name
ADD CONSTRAINT UC_table_name UNIQUE (field1,field2);

Why isn't my Pandas 'apply' function referencing multiple columns working?

If you just want to compute (column a) % (column b), you don't need apply, just do it directly:

In [7]: df['a'] % df['c']                                                                                                                                                        
Out[7]: 
0   -1.132022                                                                                                                                                                    
1   -0.939493                                                                                                                                                                    
2    0.201931                                                                                                                                                                    
3    0.511374                                                                                                                                                                    
4   -0.694647                                                                                                                                                                    
5   -0.023486                                                                                                                                                                    
Name: a

How to align a div inside td element using CSS class

div { margin: auto; }

This will center your div.

Div by itself is a blockelement. Therefor you need to define the style to the div how to behave.

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

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

Happy coding..

How do I specify new lines on Python, when writing on files?

The new line character is \n. It is used inside a string.

Example:

    print('First line \n Second line') 

where \n is the newline character.

This would yield the result:

First line
 Second line

If you use Python 2, you do not use the parentheses on the print function.

Hive: Filtering Data between Specified Dates when Date is a String

Hive has a lot of good date parsing UDFs: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

Just doing the string comparison as Nigel Tufnel suggests is probably the easiest solution, although technically it's unsafe. But you probably don't need to worry about that unless your tables have historical data about the medieval ages (dates with only 3 year digits) or dates from scifi novels (dates with more than 4 year digits).

Anyway, if you ever find yourself in a situation where you would want to do fancier date comparisons, or if your date format is not in a "biggest to smallest" order, e.g. the American convention of "mm/dd/yyyy", then you could use unix_timestamp with two arguments:

select *
from your_table
where unix_timestamp(your_date_column, 'yyyy-MM-dd') >= unix_timestamp('2010-09-01', 'yyyy-MM-dd')
and unix_timestamp(your_date_column, 'yyyy-MM-dd') <= unix_timestamp('2013-08-31', 'yyyy-MM-dd')

Html.RenderPartial() syntax with Razor

If you are given this format it takes like a link to another page or another link.partial view majorly used for renduring the html files from one place to another.

Visual Studio replace tab with 4 spaces?

For Visual Studio 2019 users:

By the comment under accepted answer, link:

Well... This is "almost" still the same in VS 2019... if you already done that and seems not to work, go to: Tools > Options, and then Text Editor > Advanced > Uncheck "Use adaptive formatting" as seen here

How can I find out if I have Xcode commandline tools installed?

I was able to find my version of Xcode on maxOS Sierra using this command:

pkgutil --pkg-info=com.apple.pkg.CLTools_Executables | grep version

as per this answer.

Are HTTP headers case-sensitive?

tldr; both HTTP/1.1 and HTTP/2 headers are case-insensitive.

According to RFC 7230 (HTTP/1.1):

Each header field consists of a case-insensitive field name followed by a colon (":"), optional leading whitespace, the field value, and optional trailing whitespace.

https://tools.ietf.org/html/rfc7230#section-3.2

Also, RFC 7540 (HTTP/2):

Just as in HTTP/1.x, header field names are strings of ASCII
characters that are compared in a case-insensitive fashion.

https://tools.ietf.org/html/rfc7540#section-8.1.2

Run a command over SSH with JSch

I struggled for half a day to get JSCH to work without using the System.in as the input stream to no avail. I tried Ganymed http://www.ganymed.ethz.ch/ssh2/ and had it going in 5 minutes. All the examples seem to be aimed at one usage of the app and none of the examples showed what i needed. Ganymed's example Basic.java Baaaboof Has everything i need.

Simple Vim commands you wish you'd known earlier

:qall and :wqall to close all the split screens.

trigger body click with jQuery

Interestingly, when I replaced this:

$("body").trigger("click")

With this:

jQuery("body").trigger("click")

It works!

How to load image to WPF in runtime?

In WPF an image is typically loaded from a Stream or an Uri.

BitmapImage supports both and an Uri can even be passed as constructor argument:

var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);

If the image file is located in a local folder, you would have to use a file:// Uri. You could create such a Uri from a path like this:

var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);

If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:

var uri = new Uri("pack://application:,,,/Bilder/sas.png");

In this case the Visual Studio Build Action for sas.png would have to be Resource.

Once you have created a BitmapImage and also have an Image control like in this XAML

<Image Name="image1" />

you would simply assign the BitmapImage to the Source property of that Image control:

image1.Source = bitmap;

How do I link a JavaScript file to a HTML file?

This is how you link a JS file in HTML

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<script> - tag is used to define a client-side script, such as a JavaScript.

type - specify the type of the script

src - script file name and path

converting string to long in python

Well, longs can't hold anything but integers.

One option is to use a float: float('234.89')

The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))

>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

Found transport-attribute in binding-element which tells us that this is the WSDL 1.1 binding for the SOAP 1.1 HTTP binding.

ex.

<wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>

How to set entire application in portrait mode only?

As from Android developer guide :

"orientation" The screen orientation has changed — the user has rotated the device. Note: If your application targets API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), then you should also declare the "screenSize" configuration, because it also changes when a device switches between portrait and landscape orientations.

"screenSize" The current available screen size has changed. This represents a change in the currently available size, relative to the current aspect ratio, so will change when the user switches between landscape and portrait. However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device). Added in API level 13.

So, in the AndroidManifest.xml file, we can put:

<activity
            android:name=".activities.role_activity.GeneralViewPagerActivity"
            android:label="@string/title_activity_general_view_pager"
            android:screenOrientation="portrait"
            android:configChanges="orientation|keyboardHidden|screenSize"
            >
        </activity> 

Printf long long int in C with GCC?

You can try settings of code::block, there is a complier..., then you select in C mode.

enter image description here

Multiple Order By with LINQ

You can use the ThenBy and ThenByDescending extension methods:

foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)

Android Fragment onClick button Method

For Kotlin users:

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?, 
    savedInstanceState: Bundle?) : View?
{
    // Inflate the layout for this fragment
    var myView = inflater.inflate(R.layout.fragment_home, container, false)
    var btn_test = myView.btn_test as Button
    btn_test.setOnClickListener {
        textView.text = "hunny home fragment"
    }

    return myView
}

Print string to text file

In case you want to pass multiple arguments you can use a tuple

price = 33.3
with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))

More: Print multiple arguments in python

How can one print a size_t variable portably using the printf family?

if you want to print the value of a size_t as a string you can do this:

char text[] = "Lets go fishing in stead of sitting on our but !!";
size_t line = 2337200120702199116;

/* on windows I64x or I64d others %lld or %llx if it works %zd or %zx */
printf("number: %I64d\n",*(size_t*)&text);
printf("text: %s\n",*(char(*)[])&line);

result is:

number: 2337200120702199116

text: Lets go fishing in stead of sitting on our but !!

Edit: rereading the question because of the down votes i noted his problem is not %llu or %I64d but the size_t type on different machines see this question https://stackoverflow.com/a/918909/1755797
http://www.cplusplus.com/reference/cstdio/printf/

size_t is unsigned int on a 32bit machine and unsigned long long int on 64bit
but %ll always expects a unsigned long long int.

size_t varies in length on different operating systems while %llu is the same

How to output a multiline string in Bash?

Also with indented source code you can use <<- (with a trailing dash) to ignore leading tabs (but not leading spaces).

For example this:

if [ some test ]; then
    cat <<- xx
        line1
        line2
xx
fi

Outputs indented text without the leading whitespace:

line1
line2

How to get the last characters in a String in Java, regardless of String size

You can achieve it using this single line code :

String numbers = text.substring(text.length() - 7, text.length());

But be sure to catch Exception if the input string length is less than 7.

You can replace 7 with any number say N, if you want to get last 'N' characters.

Linux - Install redis-cli only

To install 3.0 which is the latest stable version:

$ git clone http://github.com/antirez/redis.git 
$ cd redis && git checkout 3.0 
$ make redis-cli 

Optionally, you can put the compiled executable in your load path for convenience:

$ ln -s src/redis-cli /usr/local/bin/redis-cli

How can I use jQuery in Greasemonkey?

If you want to use jQuery on a site where it is already included, this is the way to go (inspired by BrunoLM):

var $ = unsafeWindow.jQuery;

I know this wasn't the original intent of the question, but it is increasingly becoming a common case and you didn't explicitly exclude this case. ;)

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

I liked galloglas's code, and I changed the main function so that it shows a sorted list of total size by application:

verbose = True
if __name__ == '__main__':
    mbdb = process_mbdb_file("Manifest.mbdb")
    mbdx = process_mbdx_file("Manifest.mbdx")
    sizes = {}
    for offset, fileinfo in mbdb.items():
        if offset in mbdx:
            fileinfo['fileID'] = mbdx[offset]
        else:
            fileinfo['fileID'] = "<nofileID>"
            print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
        print fileinfo_str(fileinfo, verbose)
        if (fileinfo['mode'] & 0xE000) == 0x8000:
        sizes[fileinfo['domain']]= sizes.get(fileinfo['domain'],0) + fileinfo['filelen']
    for domain in sorted(sizes, key=sizes.get):
        print "%-60s %11d (%dMB)" % (domain, sizes[domain], int(sizes[domain]/1024/1024))

That way you can figure out what application is eating all that space.

Java: How to read a text file

You can use Files#readAllLines() to get all lines of a text file into a List<String>.

for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
    // ...
}

Tutorial: Basic I/O > File I/O > Reading, Writing and Creating text files


You can use String#split() to split a String in parts based on a regular expression.

for (String part : line.split("\\s+")) {
    // ...
}

Tutorial: Numbers and Strings > Strings > Manipulating Characters in a String


You can use Integer#valueOf() to convert a String into an Integer.

Integer i = Integer.valueOf(part);

Tutorial: Numbers and Strings > Strings > Converting between Numbers and Strings


You can use List#add() to add an element to a List.

numbers.add(i);

Tutorial: Interfaces > The List Interface


So, in a nutshell (assuming that the file doesn't have empty lines nor trailing/leading whitespace).

List<Integer> numbers = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
    for (String part : line.split("\\s+")) {
        Integer i = Integer.valueOf(part);
        numbers.add(i);
    }
}

If you happen to be at Java 8 already, then you can even use Stream API for this, starting with Files#lines().

List<Integer> numbers = Files.lines(Paths.get("/path/to/test.txt"))
    .map(line -> line.split("\\s+")).flatMap(Arrays::stream)
    .map(Integer::valueOf)
    .collect(Collectors.toList());

Tutorial: Processing data with Java 8 streams

Running Selenium WebDriver python bindings in chrome

For Windows' IDE:

If your path doesn't work, you can try to add the chromedriver.exe to your project, like in this project structure.

chromedriver.exe

Then you should load the chromedriver.exe in your main file. As for me, I loaded the driver.exe in driver.py.

def get_chrome_driver():
return webdriver.Chrome("..\\content\\engine\\chromedriver.exe",
                            chrome_options='--no-startup-window')

.. means driver.py's upper directory

. means the directory where the driver.py is located

Hope this will be helpful.

WHERE statement after a UNION in SQL?

If you want to apply the WHERE clause to the result of the UNION, then you have to embed the UNION in the FROM clause:

SELECT *
  FROM (SELECT * FROM TableA
        UNION
        SELECT * FROM TableB
       ) AS U
 WHERE U.Col1 = ...

I'm assuming TableA and TableB are union-compatible. You could also apply a WHERE clause to each of the individual SELECT statements in the UNION, of course.

Unzipping files in Python

If you want to do it in shell, instead of writing code.

 python3 -m zipfile -e myfiles.zip myfiles/

myfiles.zip is the zip archive and myfiles is the path to extract the files.

How to run a C# application at Windows startup?

I think there is a specific Win32 API call which takes the application path and puts it in the registry automatically for you in the proper location, I've used it in the past but I don't remember the function name anymore.

Why maven? What are the benefits?

I've never come across point 2? Can you explain why you think this affects deployment in any way. If anything maven allows you to structure your projects in a modularised way that actually allows hot fixes for bugs in a particular tier, and allows independent development of an API from the remainder of the project for example.

It is possible that you are trying to cram everything into a single module, in which case the problem isn't really maven at all, but the way you are using it.

How to quietly remove a directory with content in PowerShell

2018 Update

In the current version of PowerShell (tested with v5.1 on Windows 10 1809) one can use the simpler Unix syntax rm -R .\DirName to silently delete the directory .\DirName with all subdirectories and files it may contain. In fact many common Unix commands work in the same way in PowerShell as in a Linux command line.

Parsing ISO 8601 date in Javascript

datejs could parse following, you might want to try out.

Date.parse('1997-07-16T19:20:15')           // ISO 8601 Formats
Date.parse('1997-07-16T19:20:30+01:00')     // ISO 8601 with Timezone offset

Edit: Regex version

x = "2011-01-28T19:30:00EST"

MM = ["January", "February","March","April","May","June","July","August","September","October","November", "December"]

xx = x.replace(
    /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):\d{2}(\w{3})/,
    function($0,$1,$2,$3,$4,$5,$6){
        return MM[$2-1]+" "+$3+", "+$1+" - "+$4%12+":"+$5+(+$4>12?"PM":"AM")+" "+$6
    }
)

Result

January 28, 2011 - 7:30PM EST

Edit2: I changed my timezone to EST and now I got following

x = "2011-01-28T19:30:00-05:00"

MM = {Jan:"January", Feb:"February", Mar:"March", Apr:"April", May:"May", Jun:"June", Jul:"July", Aug:"August", Sep:"September", Oct:"October", Nov:"November", Dec:"December"}

xx = String(new Date(x)).replace(
    /\w{3} (\w{3}) (\d{2}) (\d{4}) (\d{2}):(\d{2}):[^(]+\(([A-Z]{3})\)/,
    function($0,$1,$2,$3,$4,$5,$6){
        return MM[$1]+" "+$2+", "+$3+" - "+$4%12+":"+$5+(+$4>12?"PM":"AM")+" "+$6 
    }
)

return

January 28, 2011 - 7:30PM EST

Basically

String(new Date(x))

return

Fri Jan 28 2011 19:30:00 GMT-0500 (EST)

regex parts just converting above string to your required format.

January 28, 2011 - 7:30PM EST

Are querystring parameters secure in HTTPS (HTTP + SSL)?

I disagree with the advice given here - even the reference for the accepted answer concludes:

You can of course use query string parameters with HTTPS, but don’t use them for anything that could present a security problem. For example, you could safely use them to identity part numbers or types of display like ‘accountview’ or ‘printpage’, but don’t use them for passwords, credit card numbers or other pieces of information that should not be publicly available.

So, no they aren't really safe...!

Forward declaration of a typedef in C++

In C++ (but not plain C), it's perfectly legal to typedef a type twice, so long as both definitions are completely identical:

// foo.h
struct A{};
typedef A *PA;

// bar.h
struct A;  // forward declare A
typedef A *PA;
void func(PA x);

// baz.cc
#include "bar.h"
#include "foo.h"
// We've now included the definition for PA twice, but it's ok since they're the same
...
A x;
func(&x);

How do I output coloured text to a Linux terminal?

This is an old topic, but I wrote a class with nested subclasses and static members for colors defined by simple C macros.

I got the color function from this post Color Text In C Programming in dreamincode.net by user no2pencil.

I made it this way so to be able to use the static constants in std::cout stream like this:

cout << zkr::cc::fore::red << "This is red text. " 
     << zkr::cc::console << "And changing to console default colors, fg, bg."
     << endl;

The class and a test program source code can be downloaded here.

cc::console will reset to console default colors and attributes, cc::underline will underline the text, which works on putty which I've tested the test program.

Colors:

black
blue
red
magenta
green
cyan
yellow
white

lightblack
lightblue
lightred
lightmagenta
lightgreen
lightcyan
lightyellow
lightwhite

Which can be used with both fore and back static subclasses of the cc static class.

EDIT 2017

I'm just adding the class code here to be more practical.

The color code macros:

#define CC_CONSOLE_COLOR_DEFAULT "\033[0m"
#define CC_FORECOLOR(C) "\033[" #C "m"
#define CC_BACKCOLOR(C) "\033[" #C "m"
#define CC_ATTR(A) "\033[" #A "m"

and the main color function that defines a color or an attribute to the screen:

char *cc::color(int attr, int fg, int bg)
{
    static char command[13];

    /* Command is the control command to the terminal */
    sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
    return command;
}

ccolor.h

#include <stdio.h>

#define CC_CONSOLE_COLOR_DEFAULT "\033[0m"
#define CC_FORECOLOR(C) "\033[" #C "m"
#define CC_BACKCOLOR(C) "\033[" #C "m"
#define CC_ATTR(A) "\033[" #A "m"

namespace zkr
{
    class cc
    {
    public:

        class fore
        {
        public:
            static const char *black;
            static const char *blue;
            static const char *red;
            static const char *magenta;
            static const char *green;
            static const char *cyan;
            static const char *yellow;
            static const char *white;
            static const char *console;

            static const char *lightblack;
            static const char *lightblue;
            static const char *lightred;
            static const char *lightmagenta;
            static const char *lightgreen;
            static const char *lightcyan;
            static const char *lightyellow;
            static const char *lightwhite;
        };

        class back
        {
        public:
            static const char *black;
            static const char *blue;
            static const char *red;
            static const char *magenta;
            static const char *green;
            static const char *cyan;
            static const char *yellow;
            static const char *white;
            static const char *console;

            static const char *lightblack;
            static const char *lightblue;
            static const char *lightred;
            static const char *lightmagenta;
            static const char *lightgreen;
            static const char *lightcyan;
            static const char *lightyellow;
            static const char *lightwhite;
        };

        static char *color(int attr, int fg, int bg);
        static const char *console;
        static const char *underline;
        static const char *bold;
    };
}

ccolor.cpp

#include "ccolor.h"

using namespace std;

namespace zkr
{
    enum Color
    {
        Black,
        Red,
        Green,
        Yellow,
        Blue,
        Magenta,
        Cyan,
        White,
        Default = 9
    };

    enum Attributes
    {
        Reset,
        Bright,
        Dim,
        Underline,
        Blink,
        Reverse,
        Hidden
    };

    char *cc::color(int attr, int fg, int bg)
    {
        static char command[13];
        /* Command is the control command to the terminal */
        sprintf(command, "%c[%d;%d;%dm", 0x1B, attr, fg + 30, bg + 40);
        return command;
    }

    const char *cc::console = CC_CONSOLE_COLOR_DEFAULT;
    const char *cc::underline = CC_ATTR(4);
    const char *cc::bold = CC_ATTR(1);

    const char *cc::fore::black = CC_FORECOLOR(30);
    const char *cc::fore::blue = CC_FORECOLOR(34);
    const char *cc::fore::red = CC_FORECOLOR(31);
    const char *cc::fore::magenta = CC_FORECOLOR(35);
    const char *cc::fore::green = CC_FORECOLOR(92);
    const char *cc::fore::cyan = CC_FORECOLOR(36);
    const char *cc::fore::yellow = CC_FORECOLOR(33);
    const char *cc::fore::white = CC_FORECOLOR(37);
    const char *cc::fore::console = CC_FORECOLOR(39);

    const char *cc::fore::lightblack = CC_FORECOLOR(90);
    const char *cc::fore::lightblue = CC_FORECOLOR(94);
    const char *cc::fore::lightred = CC_FORECOLOR(91);
    const char *cc::fore::lightmagenta = CC_FORECOLOR(95);
    const char *cc::fore::lightgreen = CC_FORECOLOR(92);
    const char *cc::fore::lightcyan = CC_FORECOLOR(96);
    const char *cc::fore::lightyellow = CC_FORECOLOR(93);
    const char *cc::fore::lightwhite = CC_FORECOLOR(97);

    const char *cc::back::black = CC_BACKCOLOR(40);
    const char *cc::back::blue = CC_BACKCOLOR(44);
    const char *cc::back::red = CC_BACKCOLOR(41);
    const char *cc::back::magenta = CC_BACKCOLOR(45);
    const char *cc::back::green = CC_BACKCOLOR(42);
    const char *cc::back::cyan = CC_BACKCOLOR(46);
    const char *cc::back::yellow = CC_BACKCOLOR(43);
    const char *cc::back::white = CC_BACKCOLOR(47);
    const char *cc::back::console = CC_BACKCOLOR(49);

    const char *cc::back::lightblack = CC_BACKCOLOR(100);
    const char *cc::back::lightblue = CC_BACKCOLOR(104);
    const char *cc::back::lightred = CC_BACKCOLOR(101);
    const char *cc::back::lightmagenta = CC_BACKCOLOR(105);
    const char *cc::back::lightgreen = CC_BACKCOLOR(102);
    const char *cc::back::lightcyan = CC_BACKCOLOR(106);
    const char *cc::back::lightyellow = CC_BACKCOLOR(103);
    const char *cc::back::lightwhite = CC_BACKCOLOR(107);
}

Using for loop inside of a JSP

You concrete problem is caused because you're mixing discouraged and old school scriptlets <% %> with its successor EL ${}. They do not share the same variable scope. The allFestivals is not available in scriptlet scope and the i is not available in EL scope.

You should install JSTL (<-- click the link for instructions) and declare it in top of JSP as follows:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

and then iterate over the list as follows:

<c:forEach items="${allFestivals}" var="festival">
    <tr>      
        <td>${festival.festivalName}</td>
        <td>${festival.location}</td>
        <td>${festival.startDate}</td>
        <td>${festival.endDate}</td>
        <td>${festival.URL}</td>  
    </tr>
</c:forEach>

(beware of possible XSS attack holes, use <c:out> accordingly)

Don't forget to remove the <jsp:useBean> as it has no utter value here when you're using a servlet as model-and-view controller. It would only lead to confusion. See also our servlets wiki page. Further you would do yourself a favour to disable scriptlets by the following entry in web.xml so that you won't accidently use them:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
</jsp-config>

Why is Node.js single threaded?

Node.js was created explicitly as an experiment in async processing. The theory was that doing async processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation.

And you know what? In my opinion that theory's been borne out. A node.js app that isn't doing CPU intensive stuff can run thousands more concurrent connections than Apache or IIS or other thread-based servers.

The single threaded, async nature does make things complicated. But do you honestly think it's more complicated than threading? One race condition can ruin your entire month! Or empty out your thread pool due to some setting somewhere and watch your response time slow to a crawl! Not to mention deadlocks, priority inversions, and all the other gyrations that go with multithreading.

In the end, I don't think it's universally better or worse; it's different, and sometimes it's better and sometimes it's not. Use the right tool for the job.

Using external images for CSS custom cursors

I found out that you need to add the pointer eg:

div{
    cursor: url('cursorurl.png'), pointer;
}

How to send an email from JavaScript

window.open('mailto:[email protected]'); as above does nothing to hide the "[email protected]" email address from being harvested by spambots. I used to constantly run into this problem.

var recipient="test";
var at = String.fromCharCode(64);
var dotcom="example.com";
var mail="mailto:";
window.open(mail+recipient+at+dotcom);

What's the difference between fill_parent and wrap_content?

  • fill_parent will make the width or height of the element to be as large as the parent element, in other words, the container.

  • wrap_content will make the width or height be as large as needed to contain the elements within it.

Click here for ANDROID DOC Reference

Using true and false in C

I don't know you specific situation. Back when I was writing C programs, we have always used #2.

#define FALSE = 0
#define TRUE = !FALSE

This might be otherwise under alien platform to DOS or Intel-based processors. But I used to use both C and ASM together writing graphic libraries and graphical IDE. I was a true fan of Micheal Abrash and was intending to learn about texture mapping and so. Anyway! That's not the subject of the question here!

This was the most commonly used form to define boolean values in C, as this headerfile stdbool.h did not exist then.

In AngularJS, what's the difference between ng-pristine and ng-dirty?

Both directives obviously serve the same purpose, and though it seems that the decision of the angular team to include both interfere with the DRY principle and adds to the payload of the page, it still is rather practical to have them both around. It is easier to style your input elements as you have both .ng-pristine and .ng-dirty available for styling in your css files. I guess this was the primary reason for adding both directives.

How to iterate through a table rows and get the cell values using jQuery

Looping through a table for each row and reading the 1st column value works by using JQuery and DOM logic.

var i = 0;
var t = document.getElementById('flex1');

$("#flex1 tr").each(function() {
    var val1 = $(t.rows[i].cells[0]).text();
    alert(val1) ;
    i++;
});

How to get Enum Value from index in Java?

Try this

Months.values()[index]

Where does this come from: -*- coding: utf-8 -*-

This way of specifying the encoding of a Python file comes from PEP 0263 - Defining Python Source Code Encodings.

It is also recognized by GNU Emacs (see Python Language Reference, 2.1.4 Encoding declarations), though I don't know if it was the first program to use that syntax.

Remove style attribute from HTML tags

I'm using such thing to clean-up the style='...' section out of tags with keeping of other attributes at the moment.

$output = preg_replace('/<([^>]+)(\sstyle=(?P<stq>["\'])(.*)\k<stq>)([^<]*)>/iUs', '<$1$5>', $input);

HAX kernel module is not installed

Try installing it again with the stand alone installer https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager-end-user-license-agreement - assuming you have a CPU that supports Virtualization, have turned off antivirus and any hypervisor.

EL access a map value by Integer key

If you just happen to have a Map with Integer keys you cannot change, you could write a custom EL function to convert a Long to Integer. This would allow you to do something like:

<c:out value="${map[myLib:longToInteger(1)]}"/>

How do you create a custom AuthorizeAttribute in ASP.NET Core?

It seems that with ASP.NET Core 2, you can again inherit AuthorizeAttribute, you just need to also implement IAuthorizationFilter (or IAsyncAuthorizationFilter):

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    private readonly string _someFilterParameter;

    public CustomAuthorizeAttribute(string someFilterParameter)
    {
        _someFilterParameter = someFilterParameter;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var user = context.HttpContext.User;

        if (!user.Identity.IsAuthenticated)
        {
            // it isn't needed to set unauthorized result 
            // as the base class already requires the user to be authenticated
            // this also makes redirect to a login page work properly
            // context.Result = new UnauthorizedResult();
            return;
        }

        // you can also use registered services
        var someService = context.HttpContext.RequestServices.GetService<ISomeService>();

        var isAuthorized = someService.IsUserAuthorized(user.Identity.Name, _someFilterParameter);
        if (!isAuthorized)
        {
            context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
            return;
        }
    }
}

What's the difference between JPA and Hibernate?

JPA is just a specification while Hibernate is one of the JPA provider i.e hibernate is implementing various things mentioned in JPA contract.

How do I make an attributed string using Swift?

I did a function that takes array of strings and returns attributed string with the attributes you give.

func createAttributedString(stringArray: [String], attributedPart: Int, attributes: [NSAttributedString.Key: Any]) -> NSMutableAttributedString? {
    let finalString = NSMutableAttributedString()
    for i in 0 ..< stringArray.count {
        var attributedString = NSMutableAttributedString(string: stringArray[i], attributes: nil)
        if i == attributedPart {
            attributedString = NSMutableAttributedString(string: attributedString.string, attributes: attributes)
            finalString.append(attributedString)
        } else {
            finalString.append(attributedString)
        }
    }
    return finalString
}

In the example above you specify what part of string you want to get attributed with attributedPart: Int

And then you give the attributes for it with attributes: [NSAttributedString.Key: Any]

USE EXAMPLE

if let attributedString = createAttributedString(stringArray: ["Hello ", "how ", " are you?"], attributedPart: 2, attributes: [NSAttributedString.Key.foregroundColor: UIColor.systemYellow]) {
      myLabel.attributedText = attributedString
}

Will do:

Failed to execute removeChild on Node

For me, a hint to wrap the troubled element in another HTML tag helped. However I also needed to add a key to that HTML tag. For example:

// Didn't work
<div>
     <TroubledComponent/>
</div>

// Worked
<div key='uniqueKey'>
     <TroubledComponent/>
</div>

INSERT INTO from two different server database

USE [mydb1]

SELECT *
INTO mytable1
FROM OPENDATASOURCE (
        'SQLNCLI'
        ,'Data Source=XXX.XX.XX.XXX;Initial Catalog=mydb2;User ID=XXX;Password=XXXX'
        ).[mydb2].dbo.mytable2
    /*  steps - 
            1-  [mydb1] means our opend connection database 
            2-  mytable1 means create copy table in mydb1 database where we want insert record
            3-  XXX.XX.XX.XXX - another server name.
            4-  mydb2 another server database.
            5-  write User id and Password of another server credential
            6-  mytable2 is another server table where u fetch record from it. */

Call a VBA Function into a Sub Procedure

Procedures in a Module start being useful and generic when you pass in arguments.

For example:

Public Function DoSomethingElse(strMessage As String)  
    MsgBox strMessage
End Function

Can now display any message that is passed in with the string variable called strMessage.

What is an MvcHtmlString and when should I use it?

A nice practical use of this is if you want to make your own HtmlHelper extensions. For example, I hate trying to remember the <link> tag syntax, so I've created my own extension method to make a <link> tag:

<Extension()> _
Public Function CssBlock(ByVal html As HtmlHelper, ByVal src As String, ByVal Optional ByVal htmlAttributes As Object = Nothing) As MvcHtmlString
    Dim tag = New TagBuilder("link")
    tag.MergeAttribute("type", "text/css")
    tag.MergeAttribute("rel", "stylesheet")
    tag.MergeAttribute("href", src)
    tag.MergeAttributes(New RouteValueDictionary(htmlAttributes))
    Dim result = tag.ToString(TagRenderMode.Normal)
    Return MvcHtmlString.Create(result)
End Function

I could have returned String from this method, but if I had the following would break:

<%: Html.CssBlock(Url.Content("~/sytles/mysite.css")) %>

With MvcHtmlString, using either <%: ... %> or <%= ... %> will both work correctly.

React Native TextInput that only accepts numeric characters

That is the correct way to do it till such a component (or attribute on the TextInput) is specifically developed.

The web has the ‘number’ type for the input element, but that is web based and react-native does not use a web view.

You could consider to create that input as a react component on it’s own (maybe call NumberInput): that’ll enable you to reuse it or maybe even open source it since you can create many TextInputs that has different value filters/checkers.

The downside to immediate correction is to ensure correct feedback is given to the user as to prevent confusion as to what happened to his value

How do I combine 2 select statements into one?

select t1.* from 
(select * from TABLE Where CCC='D' AND DDD='X') as t1,
(select * from TABLE Where CCC<>'D' AND DDD='X') as t2

Another way to do this!

How can I login to a website with Python?

Typically you'll need cookies to log into a site, which means cookielib, urllib and urllib2. Here's a class which I wrote back when I was playing Facebook web games:

import cookielib
import urllib
import urllib2

# set these to whatever your fb account is
fb_username = "[email protected]"
fb_password = "secretpassword"

class WebGamePlayer(object):

    def __init__(self, login, password):
        """ Start up... """
        self.login = login
        self.password = password

        self.cj = cookielib.CookieJar()
        self.opener = urllib2.build_opener(
            urllib2.HTTPRedirectHandler(),
            urllib2.HTTPHandler(debuglevel=0),
            urllib2.HTTPSHandler(debuglevel=0),
            urllib2.HTTPCookieProcessor(self.cj)
        )
        self.opener.addheaders = [
            ('User-agent', ('Mozilla/4.0 (compatible; MSIE 6.0; '
                           'Windows NT 5.2; .NET CLR 1.1.4322)'))
        ]

        # need this twice - once to set cookies, once to log in...
        self.loginToFacebook()
        self.loginToFacebook()

    def loginToFacebook(self):
        """
        Handle login. This should populate our cookie jar.
        """
        login_data = urllib.urlencode({
            'email' : self.login,
            'pass' : self.password,
        })
        response = self.opener.open("https://login.facebook.com/login.php", login_data)
        return ''.join(response.readlines())

You won't necessarily need the HTTPS or Redirect handlers, but they don't hurt, and it makes the opener much more robust. You also might not need cookies, but it's hard to tell just from the form that you've posted. I suspect that you might, purely from the 'Remember me' input that's been commented out.

How can I set up an editor to work with Git on Windows?

Update September 2015 (6 years later)

The last release of git-for-Windows (2.5.3) now includes:

By configuring git config core.editor notepad, users can now use notepad.exe as their default editor.
Configuring git config format.commitMessageColumns 72 will be picked up by the notepad wrapper and line-wrap the commit message after the user edits it.

See commit 69b301b by Johannes Schindelin (dscho).

And Git 2.16 (Q1 2018) will show a message to tell the user that it is waiting for the user to finish editing when spawning an editor, in case the editor opens to a hidden window or somewhere obscure and the user gets lost.

See commit abfb04d (07 Dec 2017), and commit a64f213 (29 Nov 2017) by Lars Schneider (larsxschneider).
Helped-by: Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 0c69a13, 19 Dec 2017)

launch_editor(): indicate that Git waits for user input

When a graphical GIT_EDITOR is spawned by a Git command that opens and waits for user input (e.g. "git rebase -i"), then the editor window might be obscured by other windows.
The user might be left staring at the original Git terminal window without even realizing that s/he needs to interact with another window before Git can proceed. To this user Git appears hanging.

Print a message that Git is waiting for editor input in the original terminal and get rid of it when the editor returns, if the terminal supports erasing the last line


Original answer

I just tested it with git version 1.6.2.msysgit.0.186.gf7512 and Notepad++5.3.1

I prefer to not have to set an EDITOR variable, so I tried:

git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\""
# or
git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\" %*"

That always gives:

C:\prog\git>git config --global --edit
"c:\Program Files\Notepad++\notepad++.exe" %*: c:\Program Files\Notepad++\notepad++.exe: command not found
error: There was a problem with the editor '"c:\Program Files\Notepad++\notepad++.exe" %*'.

If I define a npp.bat including:

"c:\Program Files\Notepad++\notepad++.exe" %*

and I type:

C:\prog\git>git config --global core.editor C:\prog\git\npp.bat

It just works from the DOS session, but not from the git shell.
(not that with the core.editor configuration mechanism, a script with "start /WAIT..." in it would not work, but only open a new DOS window)


Bennett's answer mentions the possibility to avoid adding a script, but to reference directly the program itself between simple quotes. Note the direction of the slashes! Use / NOT \ to separate folders in the path name!

git config --global core.editor \
"'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

Or if you are in a 64 bit system:

git config --global core.editor \
"'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

But I prefer using a script (see below): that way I can play with different paths or different options without having to register again a git config.


The actual solution (with a script) was to realize that:
what you refer to in the config file is actually a shell (/bin/sh) script, not a DOS script.

So what does work is:

C:\prog\git>git config --global core.editor C:/prog/git/npp.bat

with C:/prog/git/npp.bat:

#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst "$*"

or

#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst -notabbar -nosession -noPlugin "$*"

With that setting, I can do 'git config --global --edit' from DOS or Git Shell, or I can do 'git rebase -i ...' from DOS or Git Shell.
Bot commands will trigger a new instance of notepad++ (hence the -multiInst' option), and wait for that instance to be closed before going on.

Note that I use only '/', not \'. And I installed msysgit using option 2. (Add the git\bin directory to the PATH environment variable, but without overriding some built-in windows tools)

The fact that the notepad++ wrapper is called .bat is not important.
It would be better to name it 'npp.sh' and to put it in the [git]\cmd directory though (or in any directory referenced by your PATH environment variable).


See also:


lightfire228 adds in the comments:

For anyone having an issue where N++ just opens a blank file, and git doesn't take your commit message, see "Aborting commit due to empty message": change your .bat or .sh file to say:

"<path-to-n++" .git/COMMIT_EDITMSG -<arguments>. 

That will tell notepad++ to open the temp commit file, rather than a blank new one.

Calling other function in the same controller?

Yes. Problem is in wrong notation. Use:

$this->sendRequest($uri)

Instead. Or

self::staticMethod()

for static methods. Also read this for getting idea of OOP - http://www.php.net/manual/en/language.oop5.basic.php

Could not connect to Redis at 127.0.0.1:6379: Connection refused with homebrew

I found this question while trying to figure out why I could not connect to redis after starting it via brew services start redis.

tl;dr

Depending on how fresh your machine or install is you're likely missing a config file or a directory for the redis defaults.

  1. You need a config file at /usr/local/etc/redis.conf. Without this file redis-server will not start. You can copy over the default config file and modify it from there with

    cp /usr/local/etc/redis.conf.default /usr/local/etc/redis.conf
    
  2. You need /usr/local/var/db/redis/ to exist. You can do this easily with

    mkdir -p /usr/local/var/db/redis
    

Finally just restart redis with brew services restart redis.

How do you find this out!?

I wasted a lot of time trying to figure out if redis wasn't using the defaults through homebrew and what port it was on. Services was misleading because even though redis-server had not actually started, brew services list would still show redis as "started." The best approach is to use brew services --verbose start redis which will show you that the log file is at /usr/local/var/log/redis.log. Looking in there I found the smoking gun(s)

Fatal error, can't open config file '/usr/local/etc/redis.conf'

or

Can't chdir to '/usr/local/var/db/redis/': No such file or directory

Thankfully the log made the solution above obvious.

Can't I just run redis-server?

You sure can. It'll just take up a terminal or interrupt your terminal occasionally if you run redis-server &. Also it will put dump.rdb in whatever directory you run it in (pwd). I got annoyed having to remove the file or ignore it in git so I figured I'd let brew do the work with services.

first-child and last-child with IE8

If your table is only 2 columns across, you can easily reach the second td with the adjacent sibling selector, which IE8 does support along with :first-child:

.editor td:first-child
{
    width: 150px; 
}

.editor td:first-child + td input,
.editor td:first-child + td textarea
{
    width: 500px;
    padding: 3px 5px 5px 5px;
    border: 1px solid #CCC; 
}

Otherwise, you'll have to use a JS selector library like jQuery, or manually add a class to the last td, as suggested by James Allardice.

UIGestureRecognizer on UIImageView

You can also drag a tap gesture recogniser to the image view in Storyboard. Then create an action by ctrl + drag to the code.

How to get a random number in Ruby

range = 10..50

rand(range)

or

range.to_a.sample

or

range.to_a.shuffle(this will shuffle whole array and you can pick a random number by first or last or any from this array to pick random one)

SELECTING with multiple WHERE conditions on same column

Try to use this alternate query:

SELECT A.CONTACTID 
FROM (SELECT CONTACTID FROM TESTTBL WHERE FLAG = 'VOLUNTEER')A , 
(SELECT CONTACTID FROM TESTTBL WHERE FLAG = 'UPLOADED') B WHERE A.CONTACTID = B.CONTACTID;

Create PostgreSQL ROLE (user) if it doesn't exist

Here is a generic solution using plpgsql:

CREATE OR REPLACE FUNCTION create_role_if_not_exists(rolename NAME) RETURNS TEXT AS
$$
BEGIN
    IF NOT EXISTS (SELECT * FROM pg_roles WHERE rolname = rolename) THEN
        EXECUTE format('CREATE ROLE %I', rolename);
        RETURN 'CREATE ROLE';
    ELSE
        RETURN format('ROLE ''%I'' ALREADY EXISTS', rolename);
    END IF;
END;
$$
LANGUAGE plpgsql;

Usage:

posgres=# SELECT create_role_if_not_exists('ri');
 create_role_if_not_exists 
---------------------------
 CREATE ROLE
(1 row)
posgres=# SELECT create_role_if_not_exists('ri');
 create_role_if_not_exists 
---------------------------
 ROLE 'ri' ALREADY EXISTS
(1 row)

How can I create a simple index.html file which lists all files/directories?

This can't be done with pure HTML.

However if you have access to PHP on the Apache server (you tagged the post "apache") it can be done easilly - se the PHP glob function. If not - you might try Server Side Include - it's an Apache thing, and I don't know much about it.

UILabel font size?

Answers above helped greatly.

Here is the Swift version.

@IBOutlet weak var priceLabel: UILabel!

*.... lines of code later*

self.priceLabel.font = self.priceLabel.font.fontWithSize(22)

What is the difference between ( for... in ) and ( for... of ) statements?

Everybody did explain why this problem occurs, but it's still very easy to forget about it and then scratching your head why you got wrong results. Especially when you're working on big sets of data when the results seem to be fine at first glance.

Using Object.entries you ensure to go trough all properties:

var arr = [3, 5, 7];
arr.foo = "hello";

for ( var [key, val] of Object.entries( arr ) ) {
   console.log( val );
}

/* Result:

3
5
7
hello

*/

Remove trailing newline from the elements of a string list

If you need to remove just trailing whitespace, you could use str.rstrip(), which should be slightly more efficient than str.strip():

>>> lst = ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']
>>> [x.rstrip() for x in lst]
['this', 'is', 'a', 'list', 'of', 'words']
>>> list(map(str.rstrip, lst))
['this', 'is', 'a', 'list', 'of', 'words']

Remap values in pandas column with a dict

A more native pandas approach is to apply a replace function as below:

def multiple_replace(dict, text):
  # Create a regular expression  from the dictionary keys
  regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))

  # For each match, look-up corresponding value in dictionary
  return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text) 

Once you defined the function, you can apply it to your dataframe.

di = {1: "A", 2: "B"}
df['col1'] = df.apply(lambda row: multiple_replace(di, row['col1']), axis=1)

Python recursive folder read

Agree with Dave Webb, os.walk will yield an item for each directory in the tree. Fact is, you just don't have to care about subFolders.

Code like this should work:

import os
import sys

rootdir = sys.argv[1]

for folder, subs, files in os.walk(rootdir):
    with open(os.path.join(folder, 'python-outfile.txt'), 'w') as dest:
        for filename in files:
            with open(os.path.join(folder, filename), 'r') as src:
                dest.write(src.read())

"No X11 DISPLAY variable" - what does it mean?

Initial Check.

1) When you are exporting the DISPLAY to other machine, ensure you entered the command xhost + on that machine. This command allows to other machine to export their DISPLAY on this machine. There may be security constraints, just know about it. Need to check ssh -X MachineIP will not require xhost + ?

2) Some times JCONSOLE won't show all its process, since those JVM process may run with different user and you are exporting the DISPLAY with another user. so better follow CD_DIR>sudo ./jconsole

3) In WAS (WEBSPHERE); jconsole won't be able to connect its java server process, that time just go till the link, then try connecting it. This worked for me. May be this page is initializing some variables to enable jconsole to connect with that server.

WAS console > Application servers > server1 > Process definition > Java Virtual Machine


I have faced the same issue with AIX (where command line interface only available, There is no DISPLAY UI) machine. I resolved by installing

NX Client for Windows

Step 1: Through that Windows machine, I connected with unix box where GUI console is available.
Step 2: SSH to the AIX box from that UNIX box.
Step 3: set DISPLAY like "export DISPLAY=UNIXMACHINE:NXClientPORTConnectedMentionedOnTitle"
Step 4: Now if we launch any programs which requires DISPLAY; it will be launched on this UNIX box.

VNC

If you installed VNC on UNIX box where display is available; then Windows and NX Client is not required. Step 1: Use VNC to connect with Unix box where GUI console is available.
Step 2: SSH to the AIX box from that UNIX box.
Step 3: set DISPLAY like "export DISPLAY=UNIXMACHINE:VNCPORT"
Step 4: Now if we launch any programs which requires DISPLAY; it will be launched on this UNIX box.

ELSE

Step 1: SSH to the AIX box from that UNIX box.
Step 2: set DISPLAY like "export DISPLAY=UNIXMACHINE:VNCPORT"
Step 3: Now if we launch any programs which requires DISPLAY; it will be launched on this UNIX box.

How can I specify the default JVM arguments for programs I run from eclipse?

Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:

-Xmx512m -ea -Djava.awt.headless=true

Why can't I display a pound (£) symbol in HTML?

Have you tried displaying a &pound; ?

Here is an overwhelming list.

Animate element transform rotate

To add to the answers of Ryley and atonyc, you don't actually have to use a real CSS property, like text-index or border-spacing, but instead you can specify a fake CSS property, like rotation or my-awesome-property. It might be a good idea to use something that does not risk becoming an actual CSS property in the future.

Also, somebody asked how to animate other things at the same time. This can be done as usual, but remember that the step function is called for every animated property, so you'll have to check for your property, like so:

$('#foo').animate(
    {
        opacity: 0.5,
        width: "100px",
        height: "100px",
        myRotationProperty: 45
    },
    {
        step: function(now, tween) {
            if (tween.prop === "myRotationProperty") {
                $(this).css('-webkit-transform','rotate('+now+'deg)');
                $(this).css('-moz-transform','rotate('+now+'deg)'); 
                // add Opera, MS etc. variants
                $(this).css('transform','rotate('+now+'deg)');  
            }
        }
    });

(Note: I can't find the documentation for the "Tween" object in the jQuery documentation; from the animate documentation page there is a link to http://api.jquery.com/Types#Tween which is a section that doesn't appear to exist. You can find the code for the Tween prototype on Github here).

Laravel 4: how to run a raw SQL?

This is my simplified example of how to run RAW SELECT, get result and access the values.

$res = DB::select('
        select count(id) as c
        from prices p 
        where p.type in (2,3)
    ');
    if ($res[0]->c > 10)
    {
        throw new Exception('WOW');
    }

If you want only run sql script with no return resutl use this

DB::statement('ALTER TABLE products MODIFY COLUMN physical tinyint(1) AFTER points;');

Tested in laravel 5.1

Java: convert List<String> to a String

Java 8 does bring the

Collectors.joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

method, that is nullsafe by using prefix + suffix for null values.

It can be used in the following manner:

String s = stringList.stream().collect(Collectors.joining(" and ", "prefix_", "_suffix"))

The Collectors.joining(CharSequence delimiter) method just calls joining(delimiter, "", "") internally.

Check if list contains element that contains a string and get that element

for (int i = 0; i < myList.Length; i++)
{
    if (myList[i].Contains(myString)) // (you use the word "contains". either equals or indexof might be appropriate)
    {
        return i;
    }
}

Old fashion loops are almost always the fastest.

load Js file in HTML

I had the same problem, and found the answer. If you use node.js with express, you need to give it its own function in order for the js file to be reached. For example:

const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))

git pull error "The requested URL returned error: 503 while accessing"

The solution:

error : The requested URL returned error : 503 while Accessing

The error might be resolved by deleting the existing git folder.

Woocommerce, get current product id

Retrieve the ID of the current item in the WordPress Loop.

echo get_the_ID(); 

hence works for the product id too. #tested #woo-commerce

Spring Data JPA Update @Query not updating?

I struggled with the same problem where I was trying to execute an update query like the same as you did-

@Modifying
@Transactional
@Query(value = "UPDATE SAMPLE_TABLE st SET st.status=:flag WHERE se.referenceNo in :ids")
public int updateStatus(@Param("flag")String flag, @Param("ids")List<String> references);

This will work if you have put @EnableTransactionManagement annotation on the main class. Spring 3.1 introduces the @EnableTransactionManagement annotation to be used in on @Configuration classes and enable transactional support.

What does the shrink-to-fit viewport meta attribute do?

As stats on iOS usage, indicating that iOS 9.0-9.2.x usage is currently at 0.17%. If these numbers are truly indicative of global use of these versions, then it’s even more likely to be safe to remove shrink-to-fit from your viewport meta tag.

After 9.2.x. IOS remove this tag check on its' browser.

You can check this page https://www.scottohara.me/blog/2018/12/11/shrink-to-fit.html

Remove duplicates from a dataframe in PySpark

It is not an import problem. You simply call .dropDuplicates() on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...) is pyspark.sql.dataframe.DataFrame, after you apply .collect() it is a plain Python list, and lists don't provide dropDuplicates method. What you want is something like this:

 (df1 = sqlContext
     .createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
     .dropDuplicates())

 df1.collect()

Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

Short answer:

In common use, space " ", Tab "\t" and newline "\n" are the difference:

string.IsNullOrWhiteSpace("\t"); //true
string.IsNullOrEmpty("\t"); //false

string.IsNullOrWhiteSpace(" "); //true
string.IsNullOrEmpty(" "); //false

string.IsNullOrWhiteSpace("\n"); //true
string.IsNullOrEmpty("\n"); //false

https://dotnetfiddle.net/4hkpKM

also see this answer about: whitespace characters


Long answer:

There are also a few other white space characters, you probably never used before

https://docs.microsoft.com/en-us/dotnet/api/system.char.iswhitespace

Calculating a directory's size using Python?

Get directory size

Properties of the solution:

  • returns both: the apparent size (number of bytes in the file) and the actual disk space the files uses.
  • counts hard linked files only once
  • counts symlinks the same way du does
  • does not use recursion
  • uses st.st_blocks for disk space used, thus works only on Unix-like systems

The code:

import os


def du(path):
    if os.path.islink(path):
        return (os.lstat(path).st_size, 0)
    if os.path.isfile(path):
        st = os.lstat(path)
        return (st.st_size, st.st_blocks * 512)
    apparent_total_bytes = 0
    total_bytes = 0
    have = []
    for dirpath, dirnames, filenames in os.walk(path):
        apparent_total_bytes += os.lstat(dirpath).st_size
        total_bytes += os.lstat(dirpath).st_blocks * 512
        for f in filenames:
            fp = os.path.join(dirpath, f)
            if os.path.islink(fp):
                apparent_total_bytes += os.lstat(fp).st_size
                continue
            st = os.lstat(fp)
            if st.st_ino in have:
                continue  # skip hardlinks which were already counted
            have.append(st.st_ino)
            apparent_total_bytes += st.st_size
            total_bytes += st.st_blocks * 512
        for d in dirnames:
            dp = os.path.join(dirpath, d)
            if os.path.islink(dp):
                apparent_total_bytes += os.lstat(dp).st_size
    return (apparent_total_bytes, total_bytes)

Example usage:

>>> du('/lib')
(236425839, 244363264)

$ du -sb /lib
236425839   /lib
$ du -sB1 /lib
244363264   /lib

Human readable file size

Properties of the solution:

The code:

def humanized_size(num, suffix='B', si=False):
    if si:
        units = ['','K','M','G','T','P','E','Z']
        last_unit = 'Y'
        div = 1000.0
    else:
        units = ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']
        last_unit = 'Yi'
        div = 1024.0
    for unit in units:
        if abs(num) < div:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= div
    return "%.1f%s%s" % (num, last_unit, suffix)

Example usage:

>>> humanized_size(236425839)
'225.5MiB'
>>> humanized_size(236425839, si=True)
'236.4MB'
>>> humanized_size(236425839, si=True, suffix='')
'236.4M'

Button Listener for button in fragment in android

Use your code

public class FragmentOne extends Fragment implements OnClickListener{

    View view;
    Fragment fragmentTwo;
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_one, container, false);
        Button buttonSayHi = (Button) view.findViewById(R.id.buttonSayHi);
        buttonSayHi.setOnClickListener(this);
        return view;
    }

But I think is better handle the buttons in this way:

@Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.buttonSayHi:
            /** Do things you need to..
               fragmentTwo = new FragmentTwo();

               fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo);
               fragmentTransaction.addToBackStack(null);

               fragmentTransaction.commit();  
            */
            break;
        }   
    }

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

As Filburt says; but also note that it's usually better to write

test="not(Count = 'N/A')"

If there's exactly one Count element they mean the same thing, but if there's no Count, or if there are several, then the meanings are different.

6 YEARS LATER

Since this answer seems to have become popular, but may be a little cryptic to some readers, let me expand it.

The "=" and "!=" operator in XPath can compare two sets of values. In general, if A and B are sets of values, then "=" returns true if there is any pair of values from A and B that are equal, while "!=" returns true if there is any pair that are unequal.

In the common case where A selects zero-or-one nodes, and B is a constant (say "NA"), this means that not(A = "NA") returns true if A is either absent, or has a value not equal to "NA". By contrast, A != "NA" returns true if A is present and not equal to "NA". Usually you want the "absent" case to be treated as "not equal", which means that not(A = "NA") is the appropriate formulation.

Daylight saving time and time zone best practices

In dealing with databases (in particular MySQL, but this applies to most databases), I found it hard to store UTC.

  • Databases usually work with server datetime by default (that is, CURRENT_TIMESTAMP).
  • You may not be able to change the server timezone.
  • Even if you are able to change the timezone, you may have third-party code that expects server timezone to be local.

I found it easier to just store server datetime in the database, then let the database convert the stored datetime back to UTC (that is, UNIX_TIMESTAMP()) in the SQL statements. After that you can use the datetime as UTC in your code.

If you have 100% control over the server and all code, it's probably better to change server timezone to UTC.

Unable to access JSON property with "-" dash

jsonObj.profile-id is a subtraction expression (i.e. jsonObj.profile - id).

To access a key that contains characters that cannot appear in an identifier, use brackets:

jsonObj["profile-id"]

libpng warning: iCCP: known incorrect sRGB profile

To add to Glenn's great answer, here's what I did to find which files were faulty:

find . -name "*.png" -type f -print0 | xargs \
       -0 pngcrush_1_8_8_w64.exe -n -q > pngError.txt 2>&1

I used the find and xargs because pngcrush could not handle lots of arguments (which were returned by **/*.png). The -print0 and -0 is required to handle file names containing spaces.

Then search in the output for these lines: iCCP: Not recognizing known sRGB profile that has been edited.

./Installer/Images/installer_background.png:    
Total length of data found in critical chunks            =     11286  
pngcrush: iCCP: Not recognizing known sRGB profile that has been edited

And for each of those, run mogrify on it to fix them.

mogrify ./Installer/Images/installer_background.png

Doing this prevents having a commit changing every single png file in the repository when only a few have actually been modified. Plus it has the advantage to show exactly which files were faulty.

I tested this on Windows with a Cygwin console and a zsh shell. Thanks again to Glenn who put most of the above, I'm just adding an answer as it's usually easier to find than comments :)

How to convert an Instant to a date format?

If you want to convert an Instant to a Date:

Date myDate = Date.from(instant);

And then you can use SimpleDateFormat for the formatting part of your question:

SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
String formattedDate = formatter.format(myDate);

How do I check the operating system in Python?

You can get a pretty coarse idea of the OS you're using by checking sys.platform.

Once you have that information you can use it to determine if calling something like os.uname() is appropriate to gather more specific information. You could also use something like Python System Information on unix-like OSes, or pywin32 for Windows.

There's also psutil if you want to do more in-depth inspection without wanting to care about the OS.

Forwarding port 80 to 8080 using NGINX

This is how you can achieve this.

upstream {
    nodeapp 127.0.0.1:8080;
}

server {
    listen 80;

    # The host name to respond to
    server_name cdn.domain.com;

    location /(.*) {
        proxy_pass http://nodeapp/$1$is_args$args;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Real-Port $server_port;
        proxy_set_header X-Real-Scheme $scheme;
    }
}

You can also use this configuration to load balance amongst multiple Node processes like so:

upstream {
    nodeapp 127.0.0.1:8081;
    nodeapp 127.0.0.1:8082;
    nodeapp 127.0.0.1:8083;
}

Where you are running your node server on ports 8081, 8082 and 8083 in separate processes. Nginx will easily load balance your traffic amongst these server processes.

How do I set specific environment variables when debugging in Visual Studio?

In Visual Studio for Mac and C# you can use:

Environment.SetEnvironmentVariable("<Variable_name>", "<Value>");

But you will need the following namespace

using System.Collections;

you can check the full list of variables with this:

foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
            Console.WriteLine("  {0} = {1}", de.Key, de.Value);

Rank function in MySQL

The most straight forward solution to determine the rank of a given value is to count the number of values before it. Suppose we have the following values:

10 20 30 30 30 40
  • All 30 values are considered 3rd
  • All 40 values are considered 6th (rank) or 4th (dense rank)

Now back to the original question. Here is some sample data which is sorted as described in OP (expected ranks are added on the right):

+------+-----------+------+--------+    +------+------------+
| id   | firstname | age  | gender |    | rank | dense_rank |
+------+-----------+------+--------+    +------+------------+
|   11 | Emily     |   20 | F      |    |    1 |          1 |
|    3 | Grace     |   25 | F      |    |    2 |          2 |
|   20 | Jill      |   25 | F      |    |    2 |          2 |
|   10 | Megan     |   26 | F      |    |    4 |          3 |
|    8 | Lucy      |   27 | F      |    |    5 |          4 |
|    6 | Sarah     |   30 | F      |    |    6 |          5 |
|    9 | Zoe       |   30 | F      |    |    6 |          5 |
|   14 | Kate      |   35 | F      |    |    8 |          6 |
|    4 | Harry     |   20 | M      |    |    1 |          1 |
|   12 | Peter     |   20 | M      |    |    1 |          1 |
|   13 | John      |   21 | M      |    |    3 |          2 |
|   16 | Cole      |   25 | M      |    |    4 |          3 |
|   17 | Dennis    |   27 | M      |    |    5 |          4 |
|    5 | Scott     |   30 | M      |    |    6 |          5 |
|    7 | Tony      |   30 | M      |    |    6 |          5 |
|    2 | Matt      |   31 | M      |    |    8 |          6 |
|   15 | James     |   32 | M      |    |    9 |          7 |
|    1 | Adams     |   33 | M      |    |   10 |          8 |
|   18 | Smith     |   35 | M      |    |   11 |          9 |
|   19 | Zack      |   35 | M      |    |   11 |          9 |
+------+-----------+------+--------+    +------+------------+

To calculate RANK() OVER (PARTITION BY Gender ORDER BY Age) for Sarah, you can use this query:

SELECT COUNT(id) + 1 AS rank, COUNT(DISTINCT age) + 1 AS dense_rank
FROM testdata
WHERE gender = (SELECT gender FROM testdata WHERE id = 6)
AND age < (SELECT age FROM testdata WHERE id = 6)

+------+------------+
| rank | dense_rank |
+------+------------+
|    6 |          5 |
+------+------------+

To calculate RANK() OVER (PARTITION BY Gender ORDER BY Age) for All rows you can use this query:

SELECT testdata.id, COUNT(lesser.id) + 1 AS rank, COUNT(DISTINCT lesser.age) + 1 AS dense_rank
FROM testdata
LEFT JOIN testdata AS lesser ON lesser.age < testdata.age AND lesser.gender = testdata.gender
GROUP BY testdata.id

And here is the result (joined values are added on right):

+------+------+------------+    +-----------+-----+--------+
| id   | rank | dense_rank |    | firstname | age | gender |
+------+------+------------+    +-----------+-----+--------+
|   11 |    1 |          1 |    | Emily     |  20 | F      |
|    3 |    2 |          2 |    | Grace     |  25 | F      |
|   20 |    2 |          2 |    | Jill      |  25 | F      |
|   10 |    4 |          3 |    | Megan     |  26 | F      |
|    8 |    5 |          4 |    | Lucy      |  27 | F      |
|    6 |    6 |          5 |    | Sarah     |  30 | F      |
|    9 |    6 |          5 |    | Zoe       |  30 | F      |
|   14 |    8 |          6 |    | Kate      |  35 | F      |
|    4 |    1 |          1 |    | Harry     |  20 | M      |
|   12 |    1 |          1 |    | Peter     |  20 | M      |
|   13 |    3 |          2 |    | John      |  21 | M      |
|   16 |    4 |          3 |    | Cole      |  25 | M      |
|   17 |    5 |          4 |    | Dennis    |  27 | M      |
|    5 |    6 |          5 |    | Scott     |  30 | M      |
|    7 |    6 |          5 |    | Tony      |  30 | M      |
|    2 |    8 |          6 |    | Matt      |  31 | M      |
|   15 |    9 |          7 |    | James     |  32 | M      |
|    1 |   10 |          8 |    | Adams     |  33 | M      |
|   18 |   11 |          9 |    | Smith     |  35 | M      |
|   19 |   11 |          9 |    | Zack      |  35 | M      |
+------+------+------------+    +-----------+-----+--------+

Trim Cells using VBA in Excel

This should accomplish what you want to do. I just tested it on a sheet of mine; let me know if this doesn't work. LTrim is if you only have leading spaces; the Trim function can be used as well as it takes care of leading and trailing spaces. Replace the range of cells in the area I have as "A1:C50" and also make sure to change "Sheet1" to the name of the sheet you're working on.

Dim cell As Range, areaToTrim As Range
Set areaToTrim = Sheet1.Range("A1:C50")
For Each cell In areaToTrim
    cell.Value = LTrim(cell.Value)
Next cell

Get image data url in JavaScript?

shiv / shim / sham

If your image(s) are already loaded (or not), this "tool" may come in handy:

Object.defineProperty
(
    HTMLImageElement.prototype,'toDataURL',
    {enumerable:false,configurable:false,writable:false,value:function(m,q)
    {
        let c=document.createElement('canvas');
        c.width=this.naturalWidth; c.height=this.naturalHeight;
        c.getContext('2d').drawImage(this,0,0); return c.toDataURL(m,q);
    }}
);

.. but why?

This has the advantage of using the "already loaded" image data, so no extra request in needed. Aditionally it lets the end-user (programmer like you) decide the CORS and/or mime-type and quality -OR- you can leave out these arguments/parameters as described in the MDN specification here.

If you have this JS loaded (prior to when it's needed), then converting to dataURL is as simple as:

examples

HTML
<img src="/yo.jpg" onload="console.log(this.toDataURL('image/jpeg'))">
JS
console.log(document.getElementById("someImgID").toDataURL());

GPU fingerprinting

If you are concerned about the "preciseness" of the bits then you can alter this tool to suit your needs as provided by @Kaiido's answer.

PHP string concatenation

This should be faster.

while ($personCount < 10) {
    $result .= "{$personCount} people ";
    $personCount++;
}

echo $result;

Why can't I inherit static classes?

Citation from here:

This is actually by design. There seems to be no good reason to inherit a static class. It has public static members that you can always access via the class name itself. The only reasons I have seen for inheriting static stuff have been bad ones, such as saving a couple of characters of typing.

There may be reason to consider mechanisms to bring static members directly into scope (and we will in fact consider this after the Orcas product cycle), but static class inheritance is not the way to go: It is the wrong mechanism to use, and works only for static members that happen to reside in a static class.

(Mads Torgersen, C# Language PM)

Other opinions from channel9

Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...

Static methods are only held once in memory. There is no virtual table etc. that is created for them.

If you invoke an instance method in .NET, you always give it the current instance. This is hidden by the .NET runtime, but it happens. Each instance method has as first argument a pointer (reference) to the object that the method is run on. This doesn't happen with static methods (as they are defined on type level). How should the compiler decide to select the method to invoke?

(littleguru)

And as a valuable idea, littleguru has a partial "workaround" for this issue: the Singleton pattern.

Spring Boot REST service exception handling

I think ResponseEntityExceptionHandler meets your requirements. A sample piece of code for HTTP 400:

@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {

  @ResponseStatus(value = HttpStatus.BAD_REQUEST)
  @ExceptionHandler({HttpMessageNotReadableException.class, MethodArgumentNotValidException.class,
      HttpRequestMethodNotSupportedException.class})
  public ResponseEntity<Object> badRequest(HttpServletRequest req, Exception exception) {
    // ...
  }
}

You can check this post

How to show first commit by 'git log'?

git log --format="%h" | tail -1 gives you the commit hash (ie 0dd89fb), which you can feed into other commands, by doing something like

git diff `git log --format="%h" --after="1 day"| tail -1`..HEAD to view all the commits in the last day.

SMTP error 554

Just had this issue with an Outlook client going through a Exchange server to an external address on Windows XP. Clearing the temp files seemed to do the trick.

Deleting multiple elements from a list

I can actually think of two ways to do it:

  1. slice the list like (this deletes the 1st,3rd and 8th elements)

    somelist = somelist[1:2]+somelist[3:7]+somelist[8:]

  2. do that in place, but one at a time:

    somelist.pop(2) somelist.pop(0)

HTML page disable copy/paste

You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:

<body oncopy="return false" oncut="return false" onpaste="return false">

How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers

A more advanced aproach:

How to detect Ctrl+V, Ctrl+C using JavaScript?

Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.

Why does Python code use len() function instead of a length method?

Strings do have a length method: __len__()

The protocol in Python is to implement this method on objects which have a length and use the built-in len() function, which calls it for you, similar to the way you would implement __iter__() and use the built-in iter() function (or have the method called behind the scenes for you) on objects which are iterable.

See Emulating container types for more information.

Here's a good read on the subject of protocols in Python: Python and the Principle of Least Astonishment

Difference between IISRESET and IIS Stop-Start command

The following was tested for IIS 8.5 and Windows 8.1.

As of IIS 7, Windows recommends restarting IIS via net stop/start. Via the command prompt (as Administrator):

> net stop WAS
> net start W3SVC

net stop WAS will stop W3SVC as well. Then when starting, net start W3SVC will start WAS as a dependency.

How to get past the login page with Wget?

If they're using basic authentication:

wget http://username:[email protected]/page.html

If they're using POSTed form data, you'll need to use something like cURL instead.

WebView and Cookies on Android

If you are using Android Lollipop i.e. SDK 21, then:

CookieManager.getInstance().setAcceptCookie(true);

won't work. You need to use:

CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);

I ran into same issue and the above line worked as a charm.

How to take MySQL database backup using MySQL Workbench?

In workbench 6.0 Connect to any of the database. You will see two tabs.

1.Management 2. Schemas

By default Schemas tab is selected. Select Management tab then select Data Export . You will get list of all databases. select the desired database and and the file name and ther options you wish and start export. You are done with backup.

How to include quotes in a string

I use:

var value = "'Field1','Field2','Field3'".Replace("'", "\""); 

as opposed to the equivalent

var value = "\"Field1\",\"Field2\",\"Field3\"";

Because the former has far less noise than the latter, making it easier to see typo's etc.

I use it a lot in unit tests.

Get checkbox values using checkbox name using jquery

// get checkbox values using checkbox's name

<head>
        <script>
        function getCheckBoxValues(){
            $('[name="checkname"]').each( function (){
                alert($(this).val());
            });
        }
        </script>
    </head>
    <body>
        <input type="checkbox" name="checkname" value='1'/>
        <input type="checkbox" name="checkname" value='2'/>
        <input type="checkbox" name="checkname" value='3'/>
        <input type="button" value="CheckBoxValues" onclick="getCheckBoxValues()"/>
    </body>

// get only the values witch are checked

function getCheckBoxValues(){
        $('[name="checkname"]').each( function (){
            if($(this).prop('checked') == true){
                alert($(this).val());
            }
        });
    }

How to delete/remove nodes on Firebase

To remove a record.

 var db = firebase.database();                   
 var ref = db.ref(); 
 var survey=db.ref(path+'/'+path);    //Eg path is company/employee                
 survey.child(key).remove();          //Eg key is employee id

How to determine tables size in Oracle

Here is a query, you can run it in SQL Developer (or SQL*Plus):

SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
  FROM DBA_SEGMENTS DS
  WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
 GROUP BY DS.TABLESPACE_NAME,
       SEGMENT_NAME;

Insert current date/time using now() in a field using MySQL/PHP

These both work fine for me...

<?php
  $db = mysql_connect('localhost','user','pass');
  mysql_select_db('test_db');

  $stmt = "INSERT INTO `test` (`first`,`last`,`whenadded`) VALUES ".
          "('{$first}','{$last}','NOW())";
  $rslt = mysql_query($stmt);

  $stmt = "INSERT INTO `users` (`first`,`last`,`whenadded`) VALUES ".
          "('{$first}', '{$last}', CURRENT_TIMESTAMP)";
  $rslt = mysql_query($stmt);

?>

Side note: mysql_query() is not the best way to connect to MySQL in current versions of PHP.

Adding null values to arraylist

You could create Util class:

public final class CollectionHelpers {
    public static <T> boolean addNullSafe(List<T> list, T element) {
        if (list == null || element == null) {
            return false;
        }

        return list.add(element);
    }
}

And then use it:

Element element = getElementFromSomeWhere(someParameter);
List<Element> arrayList = new ArrayList<>();
CollectionHelpers.addNullSafe(list, element);

How to fix "Incorrect string value" errors?

If you happen to process the value with some string function before saving, make sure the function can properly handle multibyte characters. String functions that cannot do that and are, say, attempting to truncate might split one of the single multibyte characters in the middle, and that can cause such string error situations.

In PHP for instance, you would need to switch from substr to mb_substr.

Switch on Enum in Java

First, you can switch on an enum in Java. I'm guessing you intended to say you can’t, but you can. chars have a set range of values, so it's easy to compare. Strings can be anything.

A switch statement is usually implemented as a jump table (branch table) in the underlying compilation, which is only possible with a finite set of values. C# can switch on strings, but it causes a performance decrease because a jump table cannot be used.

Java 7 and later supports String switches with the same characteristics.

Dealing with multiple Python versions and PIP?

For windows specifically: \path\to\python.exe -m pip install PackageName works.

How can I serve static html from spring boot?

You can quickly serve static content in JAVA Spring-boot App via thymeleaf (ref: source)

I assume you have already added Spring Boot plugin apply plugin: 'org.springframework.boot' and the necessary buildscript

Then go ahead and ADD thymeleaf to your build.gradle ==>

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    compile("org.springframework.boot:spring-boot-starter-thymeleaf")
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

Lets assume you have added home.html at src/main/resources To serve this file, you will need to create a controller.

package com.ajinkya.th.controller;

  import org.springframework.stereotype.Controller;
  import org.springframework.web.bind.annotation.RequestMapping;

  @Controller
  public class HomePageController {

      @RequestMapping("/")
      public String homePage() {
        return "home";
      }

  }

Thats it ! Now restart your gradle server. ./gradlew bootRun

Reading content from URL with Node.js

HTTP and HTTPS:

const getScript = (url) => {
    return new Promise((resolve, reject) => {
        const http      = require('http'),
              https     = require('https');

        let client = http;

        if (url.toString().indexOf("https") === 0) {
            client = https;
        }

        client.get(url, (resp) => {
            let data = '';

            // A chunk of data has been recieved.
            resp.on('data', (chunk) => {
                data += chunk;
            });

            // The whole response has been received. Print out the result.
            resp.on('end', () => {
                resolve(data);
            });

        }).on("error", (err) => {
            reject(err);
        });
    });
};

(async (url) => {
    console.log(await getScript(url));
})('https://sidanmor.com/');

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

 function GetTime(date) {
        var currentTime = (new Date(date))
        var hours = currentTime.getHours()
        //Note: before converting into 12 hour format
        var suffix = '';
        if (hours > 11) {
            suffix += "PM";
        } else {
            suffix += "AM";
        }
        var minutes = currentTime.getMinutes()
        if (minutes < 10) {
            minutes = "0" + minutes
        }
        if (hours > 12) {
            hours -= 12;
        } else if (hours === 0) {
            hours = 12;
        }
        var time = hours + ":" + minutes + " " + suffix;
        return time;
    }

jQuery : select all element with custom attribute

As described by the link I've given in comment, this

$('p[MyTag]').each(function(index) {
  document.write(index + ': ' + $(this).text() + "<br>");});

works (playable example).

Converting NumPy array into Python List structure?

tolist() works fine even if encountered a nested array, say a pandas DataFrame;

my_list = [0,1,2,3,4,5,4,3,2,1,0]
my_dt = pd.DataFrame(my_list)
new_list = [i[0] for i in my_dt.values.tolist()]

print(type(my_list),type(my_dt),type(new_list))

How do I fix a merge conflict due to removal of a file in a branch?

If you are using Git Gui on windows,

  1. Abort the merge
  2. Make sure you are on your target branch
  3. Delete the conflicting file from explorer
  4. Rescan for changes in Git Gui (F5)
  5. Notice that conflicting file is deleted
  6. Select Stage Changed Files To Commit (Ctrl-I) from Commit menu
  7. Enter a commit comment like "deleted conflicting file"
  8. Commit (ctrl-enter)
  9. Now if you restart the merge it will (hopefully) work.

Disable browser 'Save Password' functionality

Not really - the only thing you could realistically do is offer advice on the site; maybe, before their first time signing in, you could show them a form with information indicating that it is not recommended that they allow the browser to store the password.

Then the user will immediately follow the advice, write down the password on a post-it note and tape it to their monitor.

Find the most popular element in int[] array

below code can be put inside a main method

    // TODO Auto-generated method stub
    Integer[] a = { 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 1, 2, 2, 2, 2, 3, 4, 2 };
    List<Integer> list = new ArrayList<Integer>(Arrays.asList(a));
    Set<Integer> set = new HashSet<Integer>(list);
    int highestSeq = 0;
    int seq = 0;
    for (int i : set) {
        int tempCount = 0;
        for (int l : list) {
            if (i == l) {
                tempCount = tempCount + 1;
            }
            if (tempCount > highestSeq) {
                highestSeq = tempCount;
                seq = i;
            }
        }

    }

    System.out.println("highest sequence is " + seq + " repeated for " + highestSeq);

Changing route doesn't scroll to top in the new page

Setting autoScroll to true did not the trick for me, so I did choose another solution. I built a service that hooks in every time the route changes and that uses the built-in $anchorScroll service to scroll to top. Works for me :-).

Service:

 (function() {
    "use strict";

    angular
        .module("mymodule")
        .factory("pageSwitch", pageSwitch);

    pageSwitch.$inject = ["$rootScope", "$anchorScroll"];

    function pageSwitch($rootScope, $anchorScroll) {
        var registerListener = _.once(function() {
            $rootScope.$on("$locationChangeSuccess", scrollToTop);
        });

        return {
            registerListener: registerListener
        };

        function scrollToTop() {
            $anchorScroll();
        }
    }
}());

Registration:

angular.module("mymodule").run(["pageSwitch", function (pageSwitch) {
    pageSwitch.registerListener();
}]);

How to implement if-else statement in XSLT?

You have to reimplement it using <xsl:choose> tag:

       <xsl:choose>
         <xsl:when test="$CreatedDate > $IDAppendedDate">
           <h2> mooooooooooooo </h2>
         </xsl:when>
         <xsl:otherwise>
          <h2> dooooooooooooo </h2>
         </xsl:otherwise>
       </xsl:choose>