Programs & Examples On #Hyphen

0

How to import module when module name has a '-' dash or hyphen in it?

If you can't rename the original file, you could also use a symlink:

ln -s foo-bar.py foo_bar.py

Then you can just:

from foo_bar import *

Creating csv file with php

Its blank because you are writing to file. you should write to output using php://output instead and also send header information to indicate that it's csv.

Example

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
        'aaa,bbb,ccc,dddd',
        '123,456,789',
        '"aaa","bbb"'
);

$fp = fopen('php://output', 'wb');
foreach ( $data as $line ) {
    $val = explode(",", $line);
    fputcsv($fp, $val);
}
fclose($fp);

Connecting to SQL Server with Visual Studio Express Editions

My guess is that with VWD your solutions are more likely to be deployed to third party servers, many of which do not allow for a dynamically attached SQL Server database file. Thus the allowing of the other connection type.

This difference in IDE behavior is one of the key reasons for upgrading to a full version.

What is the difference between up-casting and down-casting with respect to class variable

We can create object to Downcasting. In this type also. : calling the base class methods

Animal a=new Dog();
a.callme();
((Dog)a).callme2();

ORA-01950: no privileges on tablespace 'USERS'

You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run

ALTER USER <user> quota unlimited on <tablespace name>;

or

ALTER USER <user> quota 100M on <tablespace name>;

as a DBA user (depending on how much space you need / want to grant).

PHP check if date between two dates

If hours matter:

$paymentDate = strtotime(date("Y-m-d H:i:s"));
$contractDateBegin = strtotime("2014-01-22 12:42:00");
$contractDateEnd = strtotime("2014-01-22 12:50:00");

if($paymentDate > $contractDateBegin && $paymentDate < $contractDateEnd) {
   echo "is between";
} else {
    echo "NO GO!";  
}    

how to convert string into time format and add two hours

This will give you the time you want (eg: 21:31 PM)

//Add 2 Hours to just TIME
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss a");
Date date2 = formatter.parse("19:31:51 PM");
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
cal2.add(Calendar.HOUR_OF_DAY, 2);
SimpleDateFormat printTimeFormat = new SimpleDateFormat("HH:mm a");
System.out.println(printTimeFormat.format(cal2.getTime())); 

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

For me, I changed class='carousel-item' to class='item' like this

<div class="item">
    <img class="img-responsive" src="..." alt="...">
</div>

Node.js - use of module.exports as a constructor

In my opinion, some of the node.js examples are quite contrived.

You might expect to see something more like this in the real world

// square.js
function Square(width) {

  if (!(this instanceof Square)) {
    return new Square(width);
  }

  this.width = width;
};

Square.prototype.area = function area() {
  return Math.pow(this.width, 2);
};

module.exports = Square;

Usage

var Square = require("./square");

// you can use `new` keyword
var s = new Square(5);
s.area(); // 25

// or you can skip it!
var s2 = Square(10);
s2.area(); // 100

For the ES6 people

class Square {
  constructor(width) {
    this.width = width;
  }
  area() {
    return Math.pow(this.width, 2);
  }
}

export default Square;

Using it in ES6

import Square from "./square";
// ...

When using a class, you must use the new keyword to instatiate it. Everything else stays the same.

DSO missing from command line

DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

That is, try adding -lpthread to your command line.

How to plot two histograms together in R?

So many great answers but since I've just written a function (plotMultipleHistograms() in 'basicPlotteR' package) function to do this, I thought I would add another answer.

The advantage of this function is that it automatically sets appropriate X and Y axis limits and defines a common set of bins that it uses across all the distributions.

Here's how to use it:

# Install the plotteR package
install.packages("devtools")
devtools::install_github("JosephCrispell/basicPlotteR")
library(basicPlotteR)

# Set the seed
set.seed(254534)

# Create random samples from a normal distribution
distributions <- list(rnorm(500, mean=5, sd=0.5), 
                      rnorm(500, mean=8, sd=5), 
                      rnorm(500, mean=20, sd=2))

# Plot overlapping histograms
plotMultipleHistograms(distributions, nBins=20, 
                       colours=c(rgb(1,0,0, 0.5), rgb(0,0,1, 0.5), rgb(0,1,0, 0.5)), 
                       las=1, main="Samples from normal distribution", xlab="Value")

enter image description here

The plotMultipleHistograms() function can take any number of distributions, and all the general plotting parameters should work with it (for example: las, main, etc.).

filters on ng-model in an input

I had a similar problem and used

ng-change="handler(objectInScope)" 

in my handler I call a method of the objectInScope to modify itself correctly (coarse input). In the controller I have initiated somewhere that

$scope.objectInScope = myObject; 

I know this doesn't use any fancy filters or watchers... but it's simple and works great. The only down-side to this is that the objectInScope is sent in the call to the handler...

warning: control reaches end of non-void function [-Wreturn-type]

You just need to return from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.

  /* .... */
  if (Date1 == Date2)  
     fprintf (stderr , "Indicating that the first date is equal to second date.\n"); 

  return 0;
}

Circular dependency in Spring

If two beans are dependent on each other then we should not use Constructor injection in both the bean definitions. Instead we have to use setter injection in any one of the beans. (of course we can use setter injection n both the bean definitions, but constructor injections in both throw 'BeanCurrentlyInCreationException'

Refer Spring doc at "https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#resources-resource"

Convert InputStream to JSONObject

InputStream inputStreamObject = PositionKeeperRequestTest.class.getResourceAsStream(jsonFileName);
JSONObject jsonObject = new JSONObject(IOUtils.toString(inputStreamObject));

How do I add the contents of an iterable to a set?

You can use the set() function to convert an iterable into a set, and then use standard set update operator (|=) to add the unique values from your new set into the existing one.

>>> a = { 1, 2, 3 }
>>> b = ( 3, 4, 5 )
>>> a |= set(b)
>>> a
set([1, 2, 3, 4, 5])

How can I get the number of records affected by a stored procedure?

For Microsoft SQL Server you can return the @@ROWCOUNT variable to return the number of rows affected by the last statement in the stored procedure.

Android studio doesn't list my phone under "Choose Device"

I had the same issue and couldn't get my Nexus 6P to show up as an available device until I changed the connection type from "Charging" to "Photo Transfer(PTP)" and installed the Google USB driver while in PTP mode. Installing the driver prior to that while in Charging mode yielded no results.

How to ignore ansible SSH authenticity checking?

Changing host_key_checking to false for all hosts is a very bad idea.

The only time you want to ignore it, is on "first contact", which these two tasks will accomplish:

    - name: Check SSH known_hosts for {{ inventory_hostname }}
      local_action: shell ssh-keygen -F {{ inventory_hostname }}
      register: checkForKnownHostsEntry
      failed_when: false
      changed_when: false
      ignore_errors: yes
    - name: Add {{ inventory_hostname }} to SSH known hosts automatically
      when: checkForKnownHostsEntry.rc == 1
      changed_when: checkForKnownHostsEntry.rc == 1
      set_fact:
        ansible_ssh_common_args: '-o StrictHostKeyChecking=no'

So we only turn off host key checking if we don't have the host key in our known_hosts file.

Detect if string contains any spaces

var string  = 'hello world';
var arr = string.split(''); // converted the string to an array and then checked: 
if(arr[i] === ' '){
   console.log(i);
}

I know regex can do the trick too!

What is 'Currying'?

Curry can simplify your code. This is one of the main reasons to use this. Currying is a process of converting a function that accepts n arguments into n functions that accept only one argument.

The principle is to pass the arguments of the passed function, using the closure (closure) property, to store them in another function and treat it as a return value, and these functions form a chain, and the final arguments are passed in to complete the operation.

The benefit of this is that it can simplify the processing of parameters by dealing with one parameter at a time, which can also improve the flexibility and readability of the program. This also makes the program more manageable. Also dividing the code into smaller pieces would make it reuse-friendly.

For example:

function curryMinus(x) 
{
  return function(y) 
  {
    return x - y;
  }
}

var minus5 = curryMinus(1);
minus5(3);
minus5(5);

I can also do...

var minus7 = curryMinus(7);
minus7(3);
minus7(5);

This is very great for making complex code neat and handling of unsynchronized methods etc.

Attempted to read or write protected memory

I usually get "Attempted to read or write protected memory" when calling the "Show" method on some WinForms. I checked and there doesn't appear anything special about those forms. I don't know why this works (maybe someone can tell me) but usually moving the code that gets executed in the "Load" event of the form to the "Shown" event fixes it for me and I never see it again.

How does C#'s random number generator work?

I've been searching the internet for RNG for a while now. Everything I saw was either TOO complex or was just not what I was looking for. After reading a few articles I was able to come up with this simple code.

{
  Random rnd = new Random(DateTime.Now.Millisecond);
  int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
  textBox1.Text = Convert.ToString(b[rnd.Next(10)])
}

Simple explanation,

  1. create a 1 dimensional integer array.
  2. full up the array with unordered numbers.
  3. use the rnd.Next to get the position of the number that will be picked.

This works well.

To obtain a random number less than 100 use

{
  Random rnd = new Random(DateTime.Now.Millisecond);
  int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
  int[] d = new int[10] { 9, 4, 7, 2, 8, 0, 5, 1, 3, 4 };
  textBox1.Text = Convert.ToString(b[rnd.Next(10)]) + Convert.ToString(d[rnd.Next(10)]);
}

and so on for 3, 4, 5, and 6 ... digit random numbers.

Hope this assists someone positively.

Read/write to file using jQuery

Cookies are your best bet. Look for the jquery cookie plugin.

Cookies are designed for this sort of situation -- you want to keep some information about this client on client side. Just be aware that cookies are passed back and forth on every web request so you can't store large amounts of data in there. But just a simple answer to a question should be fine.

What does if __name__ == "__main__": do?

if __name__ == "__main__" is the part that runs when the script is run from (say) the command line using a command like python myscript.py.

Reverse a string without using reversed() or [::-1]?

I created different versions of how to reverse a string in python in my repo: https://github.com/fedmich/Python-Codes/tree/master/Reverse%20a%20String

You can do it by using list-comprehension or lambda technique:

# Reverse a string without using reverse() function
s = 'Federico';
li = list( s )  #convert string to list

ret = [ li[i-1] for i in xrange(len(li),0,-1)  ]    #1 liner lambda
print ( "".join( ret ) )

or by doing a backward for loop

# Reverse a string without using reverse() function
s = 'Federico';
r = []

length = len(s)
for i in xrange(length,0,-1):
    r.append( s[ i - 1] )

print ( "".join(r) )

How to see my Eclipse version?

Open .eclipseproduct in the product installation folder. Or open Configuration\config.ini and check property eclipse.buildId if exist.

How to determine previous page URL in Angular?

I had some struggle to access the previous url inside a guard.
Without implementing a custom solution, this one is working for me.

public constructor(private readonly router: Router) {
};

public ngOnInit() {
   this.router.getCurrentNavigation().previousNavigation.initialUrl.toString();
}

The initial url will be the previous url page.

how to change any data type into a string in python

str is meant to produce a string representation of the object's data. If you're writing your own class and you want str to work for you, add:

def __str__(self):
    return "Some descriptive string"

print str(myObj) will call myObj.__str__().

repr is a similar method, which generally produces information on the class info. For most core library object, repr produces the class name (and sometime some class information) between angle brackets. repr will be used, for example, by just typing your object into your interactions pane, without using print or anything else.

You can define the behavior of repr for your own objects just like you can define the behavior of str:

def __repr__(self):
    return "Some descriptive string"

>>> myObj in your interactions pane, or repr(myObj), will result in myObj.__repr__()

Assigning multiple styles on an HTML element

You needed to do it like this:

_x000D_
_x000D_
<h2 style="text-align: center;font-family: Tahoma">TITLE</h2>
_x000D_
_x000D_
_x000D_

Hope it helped.

Sourcetree - undo unpushed commits

If you want to delete a commit you can do it as part of an interactive rebase. But do it with caution, so you don't end up messing up your repo.

In Sourcetree:

  1. Right click a commit that's older than the one you want to delete, and choose "Rebase children of xxxx interactively...". The one you click will be your "base" and you can make changes to every commit made after that one.

Screenshot-1

  1. In the new window, select the commit you want gone, and press the "Delete"-button at the bottom, or right click the commit and click "Delete commit".
  2. List item
  3. Click "OK" (or "Cancel" if you want to abort).

Check out this Atlassian blog post for more on interactive rebasing in Sourcetree.

Get current cursor position

GetCursorPos() will return to you the x/y if you pass in a pointer to a POINT structure.

Hiding the cursor can be done with ShowCursor().

How do you kill a Thread in Java?

Generally you don't kill, stop, or interrupt a thread (or check wheter it is interrupted()), but let it terminate naturally.

It is simple. You can use any loop together with (volatile) boolean variable inside run() method to control thread's activity. You can also return from active thread to the main thread to stop it.

This way you gracefully kill a thread :) .

Convert string to nullable type (int, double, etc...)

Let's add one more similar solution to the stack. This one also parses enums, and it looks nice. Very safe.

/// <summary>
    /// <para>More convenient than using T.TryParse(string, out T). 
    /// Works with primitive types, structs, and enums.
    /// Tries to parse the string to an instance of the type specified.
    /// If the input cannot be parsed, null will be returned.
    /// </para>
    /// <para>
    /// If the value of the caller is null, null will be returned.
    /// So if you have "string s = null;" and then you try "s.ToNullable...",
    /// null will be returned. No null exception will be thrown. 
    /// </para>
    /// <author>Contributed by Taylor Love (Pangamma)</author>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="p_self"></param>
    /// <returns></returns>
    public static T? ToNullable<T>(this string p_self) where T : struct
    {
        if (!string.IsNullOrEmpty(p_self))
        {
            var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
            if (converter.IsValid(p_self)) return (T)converter.ConvertFromString(p_self);
            if (typeof(T).IsEnum) { T t; if (Enum.TryParse<T>(p_self, out t)) return t;}
        }

        return null;
    }

https://github.com/Pangamma/PangammaUtilities-CSharp/blob/master/PangammaUtilities/Extensions/ToNullableStringExtension.cs

How can I remove an element from a list, with lodash?

You can use removeItemFromArrayByPath function which includes some lodash functions and splice

/**
 * Remove item from array by given path and index
 *
 * Note: this function mutates array.
 *
 * @param {Object|Array} data (object or array)
 * @param {Array|String} The array path to remove given index
 * @param {Number} index to be removed from given data by path
 *
 * @returns {undefined}
 */

const removeItemFromArrayByPath = (data, arrayPath, indexToRemove) => {
  const array = _.get(data, arrayPath, []);
  if (!_.isEmpty(array)) {
    array.splice(indexToRemove, 1);
  }
};

You can check the examples here: https://codepen.io/fatihturgut/pen/NWbxLNv

How to extract svg as file from web page

Unless I am misunderstanding you, this could be as easy as inspecting (F12) the icon on the page to reveal its .svg source file path, going to that path directly (Example), and then viewing the page source code with Control+u. Then just save that code.

How to set the "Content-Type ... charset" in the request header using a HTML link

This is not possible from HTML on. The closest what you can get is the accept-charset attribute of the <form>. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.

To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).


Update: Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.

alt text

Stretch child div height to fill parent that has dynamic height

You can do it easily with a bit of jQuery

$(document).ready(function(){
  var parentHeight = $("#parentDiv").parent().height();
  $("#childDiv").height(parentHeight);
});

Handling a timeout error in python sockets

Here is a solution I use in one of my project.

network_utils.telnet

import socket
from timeit import default_timer as timer

def telnet(hostname, port=23, timeout=1):
    start = timer()
    connection = socket.socket()
    connection.settimeout(timeout)
    try:
        connection.connect((hostname, port))
        end = timer()
        delta = end - start
    except (socket.timeout, socket.gaierror) as error:
        logger.debug('telnet error: ', error)
        delta = None
    finally:
        connection.close()

    return {
        hostname: delta
    }

Tests

def test_telnet_is_null_when_host_unreachable(self):
    hostname = 'unreachable'

    response = network_utils.telnet(hostname)

    self.assertDictEqual(response, {'unreachable': None})

def test_telnet_give_time_when_reachable(self):
    hostname = '127.0.0.1'

    response = network_utils.telnet(hostname, port=22)

    self.assertGreater(response[hostname], 0)

Jquery to get SelectedText from dropdown

Get text from a dropdown multiple

var texts = [];
$('#list :selected').each(function(){
    texts.push($(this).text());
});

texts now contains a list of selected text

Warning - Build path specifies execution environment J2SE-1.4

Did you setup your project to be compiled with 1.4 compliance? If so, do what krock said. Or to be more exact you need to select the J2SE-1.4 execution environment and check one of the installed JRE that you want to use in 1.4 compliance mode; most likely you'll have a 1.6 JRE installed, just check that one. Or install a 1.4 JRE if you have a setup kit, and use that one.

Otherwise go to your Eclipse preferences, Java -> Compiler and check if the compliance is set to 1.4. If it is change it back to 1.6. If it's not go to the project properties, and check if it has project specific settings. Go to Java Compiler, and uncheck that if you want to use the general eclipse preferences. Or set the project specific settings to 1.6, so that it's always 1.6 regardless of eclipse preferences.

How to convert Base64 String to javascript file object like as from file input form?

This is the latest async/await pattern solution.

export async function dataUrlToFile(dataUrl: string, fileName: string): Promise<File> {

    const res: Response = await fetch(dataUrl);
    const blob: Blob = await res.blob();
    return new File([blob], fileName, { type: 'image/png' });
}

latex large division sign in a math formula

I found the answer I was looking for. The thing to use here is the construct of

\left \middle \right

For example, in this case, two possible solutions are:

$\left( {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right) $

Or, in case the brackets are not necessary:

$\left. {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right. $

How to change webservice url endpoint?

To change the end address property edit your wsdl file

<wsdl:definitions.......
  <wsdl:service name="serviceMethodName">
    <wsdl:port binding="tns:serviceMethodNameSoapBinding" name="serviceMethodName">
      <soap:address location="http://service_end_point_adress"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>

Adding headers when using httpClient.GetAsync

When using GetAsync with the HttpClient you can add the authorization headers like so:

httpClient.DefaultRequestHeaders.Authorization 
                         = new AuthenticationHeaderValue("Bearer", "Your Oauth token");

This does add the authorization header for the lifetime of the HttpClient so is useful if you are hitting one site where the authorization header doesn't change.

Here is an detailed SO answer

pthread function from a class

The above answers are good, but in my case, 1st approach that converts the function to be a static didn't work. I was trying to convert exiting code to move into thread function but that code had lots to references to non-static class members already. The second solution of encapsulating into C++ object works, but has 3-level wrappers to run a thread.

I had an alternate solution that uses existing C++ construct - 'friend' function, and it worked perfect for my case. An example of how I used 'friend' (will use the above same example for names showing how it can be converted into a compact form using friend)

    class MyThreadClass
    {
    public:
       MyThreadClass() {/* empty */}
       virtual ~MyThreadClass() {/* empty */}

       bool Init()
       {
          return (pthread_create(&_thread, NULL, &ThreadEntryFunc, this) == 0);
       }

       /** Will not return until the internal thread has exited. */
       void WaitForThreadToExit()
       {
          (void) pthread_join(_thread, NULL);
       }

    private:
       //our friend function that runs the thread task
       friend void* ThreadEntryFunc(void *);

       pthread_t _thread;
    };

    //friend is defined outside of class and without any qualifiers
    void* ThreadEntryFunc(void *obj_param) {
    MyThreadClass *thr  = ((MyThreadClass *)obj_param); 

    //access all the members using thr->

    return NULL;
    }

Ofcourse, we can use boost::thread and avoid all these, but I was trying to modify the C++ code to not use boost (the code was linking against boost just for this purpose)

How to use "Share image using" sharing Intent to share images in android?

I found the easiest way to do this is by using the MediaStore to temporarily store the image that you want to share:

Drawable mDrawable = mImageView.getDrawable();
Bitmap mBitmap = ((BitmapDrawable) mDrawable).getBitmap();

String path = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "Image Description", null);
Uri uri = Uri.parse(path);

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "Share Image"));

From: Sharing Content With Intents

Capitalize the first letter of both words in a two word string

This gives capital Letters to all major words

library(lettercase)
xString = str_title_case(xString)

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

Cast string to ObjectId

import mongoose from "mongoose"; // ES6 or above
const mongoose = require('mongoose'); // ES5 or below

let userid = _id
console.log(mongoose.Types.ObjectId(userid)) //5c516fae4e6a1c1cfce18d77

Classpath including JAR within a JAR

Well, there is a very easy way if you're using Eclipse.

Export your project as a "Runnable" Jar file (right-click project folder from within Eclipse, select "Export..."). When you configure the export settings, be sure to select "Extract required libraries into generated Jar." Keep in mind, select "Extract..." and not "Package required libraries...".

Additionally: You must select a run-configuration in your export settings. So, you could always create an empty main( ) in some class and use it for your run configuration.

Anyway, it isn't guaranteed to work 100% of the time - as you will notice a pop-up message telling you to make sure you check the licenses of the Jar files you're including and something about not copying signature files. However, I have been doing this for years and have never encountered a problem.

How to filter rows in pandas by regex

Using str slice

foo[foo.b.str[0]=='f']
Out[18]: 
   a    b
1  2  foo
2  3  fat

How can I match a string with a regex in Bash?

shopt -s nocasematch

if [[ sed-4.2.2.$LINE =~ (yes|y)$ ]]
 then exit 0 
fi

How would I access variables from one class to another?

var1 and var2 is an Instance variables of ClassA. Create an Instance of ClassB and when calling the methodA it will check the methodA in Child class (ClassB) first, If methodA is not present in ClassB you need to invoke the ClassA by using the super() method which will get you all the methods implemented in ClassA. Now, you can access all the methods and attributes of ClassB.

class ClassA(object):
    def __init__(self):
        self.var1 = 1
        self.var2 = 2

    def methodA(self):
        self.var1 = self.var1 + self.var2
        return self.var1


class ClassB(ClassA):
    def __init__(self):
        super().__init__()
        print("var1",self.var1)
        print("var2",self.var2)


object1 = ClassB()
sum = object1.methodA()
print(sum)

Remove empty elements from an array in Javascript

You can use filter with index and in operator

_x000D_
_x000D_
let a = [1,,2,,,3];
let b = a.filter((x,i)=> i in a);

console.log({a,b});
_x000D_
_x000D_
_x000D_

Disable button after click in JQuery

You can do this in jquery by setting the attribute disabled to 'disabled'.

$(this).prop('disabled', true);

I have made a simple example http://jsfiddle.net/4gnXL/2/

Spark: subtract two DataFrames

From spark 3.0

data_cl = reg_data.exceptAll(data_fr)

How to change legend title in ggplot

I noticed there are two ways to change/specify legend.title for ggboxplot():

library(ggpubr)

bxp.defaultLegend <- ggboxplot(ToothGrowth, x = "dose", y = "len",
                               color = "dose", palette = "jco")

# Solution 1, setup legend.title directly in ggboxplot()
bxp.legend <- ggboxplot(ToothGrowth, x = "dose", y = "len",
                 color = "dose", palette = "jco", legend.title="Dose (mg)")

# Solution 2: Change legend title and appearnace in ggboxplot() using labs() and theme() option:
plot1 <-  bxp.defaultLegend + labs(color = "Dose (mg)") +
  theme(legend.title = element_text(color = "blue", size = 10), legend.text = element_text(color = "red"))

ggarrange(list(bxp.legend, bxp.defaultLegend, plot1), nrow = 1, ncol = 3,  common.legend = TRUE)

The code is modified based on the example from GitHub.

Get href attribute on jQuery

var a_href = $('div.cpt').find('h2 a').attr('href');

should be

var a_href = $(this).find('div.cpt').find('h2 a').attr('href');

In the first line, your query searches the entire document. In the second, the query starts from your tr element and only gets the element underneath it. (You can combine the finds if you like, I left them separate to illustrate the point.)

How do I start PowerShell from Windows Explorer?

Just to add in the reverse as a trick, at a PowerShell prompt you can do:

ii .

or

start .

to open a Windows Explorer window in your current directory.

How do I read the first line of a file using cat?

Use the below command to get the first row from a CSV file or any file formats.

head -1 FileName.csv

When does a cookie with expiration time 'At end of session' expire?

When you use setcookie, you can either set the expiration time to 0 or simply omit the parametre - the cookie will then expire at the end of session (ie, when you close the browser).

PHP: How to remove specific element from an array?

A better approach would maybe be to keep your values as keys in an associative array, and then call array_keys() on it when you want to actual array. That way you don't need to use array_search to find your element.

What is an MvcHtmlString and when should I use it?

This is a late answer but if anyone reading this question is using razor, what you should remember is that razor encodes everything by default, but by using MvcHtmlString in your html helpers you can tell razor that it doesn't need to encode it.

If you want razor to not encode a string use

@Html.Raw("<span>hi</span>")

Decompiling Raw(), shows us that it's wrapping the string in a HtmlString

public IHtmlString Raw(string value) {
    return new HtmlString(value); 
}

"HtmlString only exists in ASP.NET 4.

MvcHtmlString was a compatibility shim added to MVC 2 to support both .NET 3.5 and .NET 4. Now that MVC 3 is .NET 4 only, it's a fairly trivial subclass of HtmlString presumably for MVC 2->3 for source compatibility." source

Trimming text strings in SQL Server 2008

You do have an RTRIM and an LTRIM function. You can combine them to get the trim function you want.

UPDATE Table
SET Name = RTRIM(LTRIM(Name))

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

if you are using visual 2012 right-click on project name -> properties -> configuration properties -> general -> platform toolset -> Visual Studio 2012 (v110)

Decoding and verifying JWT token using System.IdentityModel.Tokens.Jwt

Within the package there is a class called JwtSecurityTokenHandler which derives from System.IdentityModel.Tokens.SecurityTokenHandler. In WIF this is the core class for deserialising and serialising security tokens.

The class has a ReadToken(String) method that will take your base64 encoded JWT string and returns a SecurityToken which represents the JWT.

The SecurityTokenHandler also has a ValidateToken(SecurityToken) method which takes your SecurityToken and creates a ReadOnlyCollection<ClaimsIdentity>. Usually for JWT, this will contain a single ClaimsIdentity object that has a set of claims representing the properties of the original JWT.

JwtSecurityTokenHandler defines some additional overloads for ValidateToken, in particular, it has a ClaimsPrincipal ValidateToken(JwtSecurityToken, TokenValidationParameters) overload. The TokenValidationParameters argument allows you to specify the token signing certificate (as a list of X509SecurityTokens). It also has an overload that takes the JWT as a string rather than a SecurityToken.

The code to do this is rather complicated, but can be found in the Global.asax.cx code (TokenValidationHandler class) in the developer sample called "ADAL - Native App to REST service - Authentication with ACS via Browser Dialog", located at

http://code.msdn.microsoft.com/AAL-Native-App-to-REST-de57f2cc

Alternatively, the JwtSecurityToken class has additional methods that are not on the base SecurityToken class, such as a Claims property that gets the contained claims without going via the ClaimsIdentity collection. It also has a Payload property that returns a JwtPayload object that lets you get at the raw JSON of the token. It depends on your scenario which approach it most appropriate.

The general (i.e. non JWT specific) documentation for the SecurityTokenHandler class is at

http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.aspx

Depending on your application, you can configure the JWT handler into the WIF pipeline exactly like any other handler.

There are 3 samples of it in use in different types of application at

http://code.msdn.microsoft.com/site/search?f%5B0%5D.Type=SearchText&f%5B0%5D.Value=aal&f%5B1%5D.Type=User&f%5B1%5D.Value=Azure%20AD%20Developer%20Experience%20Team&f%5B1%5D.Text=Azure%20AD%20Developer%20Experience%20Team

Probably, one will suite your needs or at least be adaptable to them.

how to POST/Submit an Input Checkbox that is disabled?

Don't disable it; instead set it to readonly, though this has no effect as per not allowing the user to change the state. But you can use jQuery to enforce this (prevent the user from changing the state of the checkbox:

$('input[type="checkbox"][readonly="readonly"]').click(function(e){
    e.preventDefault();
});

This assumes that all the checkboxes you don't want to be modified have the "readonly" attribute. eg.

<input type="checkbox" readonly="readonly">

How to compare two JSON objects with the same elements in a different order equal?

If you want two objects with the same elements but in a different order to compare equal, then the obvious thing to do is compare sorted copies of them - for instance, for the dictionaries represented by your JSON strings a and b:

import json

a = json.loads("""
{
    "errors": [
        {"error": "invalid", "field": "email"},
        {"error": "required", "field": "name"}
    ],
    "success": false
}
""")

b = json.loads("""
{
    "success": false,
    "errors": [
        {"error": "required", "field": "name"},
        {"error": "invalid", "field": "email"}
    ]
}
""")
>>> sorted(a.items()) == sorted(b.items())
False

... but that doesn't work, because in each case, the "errors" item of the top-level dict is a list with the same elements in a different order, and sorted() doesn't try to sort anything except the "top" level of an iterable.

To fix that, we can define an ordered function which will recursively sort any lists it finds (and convert dictionaries to lists of (key, value) pairs so that they're orderable):

def ordered(obj):
    if isinstance(obj, dict):
        return sorted((k, ordered(v)) for k, v in obj.items())
    if isinstance(obj, list):
        return sorted(ordered(x) for x in obj)
    else:
        return obj

If we apply this function to a and b, the results compare equal:

>>> ordered(a) == ordered(b)
True

What Vim command(s) can be used to quote/unquote words?

If you use the vim plugin https://github.com/tpope/vim-surround (or use VSCode Vim plugin, which comes with vim-surround pre-installed), its pretty convinient!

add

ysiw' // surround in word `'`

drop

ds' // drop surround `'`

change

cs'" // change surround from `'` to `"`

It even works for html tags!

cst<em> // change surround from current tag to `<em>`

check out the readme on github for better examples

How to compare two dates?

Other answers using datetime and comparisons also work for time only, without a date.

For example, to check if right now it is more or less than 8:00 a.m., we can use:

import datetime

eight_am = datetime.time( 8,0,0 ) # Time, without a date

And later compare with:

datetime.datetime.now().time() > eight_am  

which will return True

What is the difference between screenX/Y, clientX/Y and pageX/Y?

What helped me was to add an event directly to this page and click around for myself! Open up your console in developer tools/Firebug etc and paste this:

_x000D_
_x000D_
document.addEventListener('click', function(e) {_x000D_
  console.log(_x000D_
    'page: ' + e.pageX + ',' + e.pageY,_x000D_
    'client: ' + e.clientX + ',' + e.clientY,_x000D_
    'screen: ' + e.screenX + ',' + e.screenY)_x000D_
}, false);
_x000D_
Click anywhere
_x000D_
_x000D_
_x000D_

With this snippet, you can track your click position as you scroll, move the browser window, etc.

Notice that pageX/Y and clientX/Y are the same when you're scrolled all the way to the top!

Git Remote: Error: fatal: protocol error: bad line length character: Unab

i also encounter that error once in a while, but when it does, it means that my branch is not up-to-date so i have to do git pull origin <current_branch>

How to change TextBox's Background color?

Setting textbox backgroundcolor with multiple colors on single click.

Note:- using HTML and Javscript.

< input id="ClickMe_btn" onclick="setInterval(function () { ab() }, 3000);" type="button" value="ClickMe" />

var arr, i = 0; arr = ["Red", "Blue", "Green", " Orange ", "Purple", "Yellow", "Brown", "Lime", "Grey"]; // We provide array as input.

    function ab()
     {   document.getElementById("Text").style.backgroundColor = arr[i];
          window.alert(arr[i]);
          i++;
     }

Note: You can change milliseconds, with setInterval 2nd parameter.

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

What I did in my case was to update

"lib": [
      "es2020",
      "dom"
    ]

with

"lib": [
  "es2016",
  "dom"
]

in my tsconfig.json file

Python Pandas - Find difference between two data frames

import pandas as pd
# given
df1 = pd.DataFrame({'Name':['John','Mike','Smith','Wale','Marry','Tom','Menda','Bolt','Yuswa',],
    'Age':[23,45,12,34,27,44,28,39,40]})
df2 = pd.DataFrame({'Name':['John','Smith','Wale','Tom','Menda','Yuswa',],
    'Age':[23,12,34,44,28,40]})

# find elements in df1 that are not in df2
df_1notin2 = df1[~(df1['Name'].isin(df2['Name']) & df1['Age'].isin(df2['Age']))].reset_index(drop=True)

# output:
print('df1\n', df1)
print('df2\n', df2)
print('df_1notin2\n', df_1notin2)

# df1
#     Age   Name
# 0   23   John
# 1   45   Mike
# 2   12  Smith
# 3   34   Wale
# 4   27  Marry
# 5   44    Tom
# 6   28  Menda
# 7   39   Bolt
# 8   40  Yuswa
# df2
#     Age   Name
# 0   23   John
# 1   12  Smith
# 2   34   Wale
# 3   44    Tom
# 4   28  Menda
# 5   40  Yuswa
# df_1notin2
#     Age   Name
# 0   45   Mike
# 1   27  Marry
# 2   39   Bolt

Python script to copy text to clipboard

This is an altered version of @Martin Thoma's answer for GTK3. I found that the original solution resulted in the process never ending and my terminal hung when I called the script. Changing the script to the following resolved the issue for me.

#!/usr/bin/python3

from gi.repository import Gtk, Gdk
import sys
from time import sleep

class Hello(Gtk.Window):

    def __init__(self):
        super(Hello, self).__init__()

        clipboardText = sys.argv[1]
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text(clipboardText, -1)
        clipboard.store()


def main():
    Hello()



if __name__ == "__main__":
    main()

You will probably want to change what clipboardText gets assigned to, in this script it is assigned to the parameter that the script is called with.

On a fresh ubuntu 16.04 installation, I found that I had to install the python-gobject package for it to work without a module import error.

Split text with '\r\n'

This worked for me.

string stringSeparators = "\r\n";
string text = sr.ReadToEnd();
string lines = text.Replace(stringSeparators, "");
lines = lines.Replace("\\r\\n", "\r\n");
Console.WriteLine(lines);

The first replace replaces the \r\n from the text file's new lines, and the second replaces the actual \r\n text that is converted to \\r\\n when the files is read. (When the file is read \ becomes \\).

How to set the From email address for mailx command?

In case you also want to include your real name in the from-field, you can use the following format

mailx -r "[email protected] (My Name)" -s "My Subject" ...

If you happen to have non-ASCII characters in you name, like My AEÆoeøaaå (Æ= C3 86, ø= C3 B8, å= C3 A5), you have to encode them like this:

mailx -r "[email protected] (My =?utf-8?Q?AE=C3=86oe=C3=B8aa=C3=A5?=)" -s "My Subject" ...

Hope this can save someone an hour of hard work/research!

How to unmerge a Git merge?

You can reset your branch to the state it was in just before the merge if you find the commit it was on then.

One way is to use git reflog, it will list all the HEADs you've had. I find that git reflog --relative-date is very useful as it shows how long ago each change happened.

Once you find that commit just do a git reset --hard <commit id> and your branch will be as it was before.

If you have SourceTree, you can look up the <commit id> there if git reflog is too overwhelming.

Unable to open debugger port in IntelliJ IDEA

Just restart the Android studio before try these all. I face same right now and i fix it by this way.

Happy coding :)

Center content in responsive bootstrap navbar

it because it apply flex. you can use this code

@media (min-width: 992px){
.navbar-expand-lg .navbar-collapse {
    display: -ms-flexbox!important;
    display: flex!important;
    -ms-flex-preferred-size: auto;
    flex-basis: auto;
    justify-content: center;
}

in my case it workded correctly.

Detect if Android device has Internet connection

public boolean isInternetWorking() {
    boolean success = false;
    try {
        URL url = new URL("https://google.com");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(10000);
        connection.connect();
        success = connection.getResponseCode() == 200;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return success;
}

return true if internet is actually available

Make sure you have these two permission

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

if http does not work its because of the new android security they donot allow plain text communication now. for now just to by pass it.

android:usesCleartextTraffic="true"

How to set multiple commands in one yaml file with Kubernetes?

Here is another way to run multi line commands.

apiVersion: batch/v1
kind: Job
metadata:
  name: multiline
spec:
  template:
    spec:
      containers:
      - command:
        - /bin/bash
        - -exc
        - |
          set +x
          echo "running below scripts"
          if [[ -f "if-condition.sh" ]]; then
            echo "Running if success"
          else
            echo "Running if failed"
          fi
        name: ubuntu
        image: ubuntu
      restartPolicy: Never
  backoffLimit: 1

SVN 405 Method Not Allowed

My "disappeared" folder was libraries/fof.

If I deleted it, then ran an update, it wouldn't show up.

cd libaries
svn up

(nothing happens).

But updating with the actual name:

svn update fof

did the trick and it was updated. So I exploded my (manually tar-archived) working copy over it and recommitted. Easiest solution.

String.Format not work in TypeScript

I solved it like this;

1.Created a function

export function FormatString(str: string, ...val: string[]) {
  for (let index = 0; index < val.length; index++) {
    str = str.replace(`{${index}}`, val[index]);
  }
  return str;
}

2.Used it like the following;

FormatString("{0} is {1} {2}", "This", "formatting", "hack");

What is the Eclipse shortcut for "public static void main(String args[])"?

As bmargulies mentioned:

Preferences>Java>Editor>Templates>New...

enter image description here

enter image description here

Now, type psvm then Ctrl + Space on Mac or Windows.

Create Directory When Writing To File In Node.js

Since I cannot comment yet, I'm posting an enhanced answer based on @tiago-peres-frança fantastic solution (thanks!). His code does not make directory in a case where only the last directory is missing in the path, e.g. the input is "C:/test/abc" and "C:/test" already exists. Here is a snippet that works:

function mkdirp(filepath) {
    var dirname = path.dirname(filepath);

    if (!fs.existsSync(dirname)) {
        mkdirp(dirname);
    }

    fs.mkdirSync(filepath);
}

Using LINQ to concatenate strings

Here is the combined Join/Linq approach I settled on after looking at the other answers and the issues addressed in a similar question (namely that Aggregate and Concatenate fail with 0 elements).

string Result = String.Join(",", split.Select(s => s.Name));

or (if s is not a string)

string Result = String.Join(",", split.Select(s => s.ToString()));

  • Simple
  • easy to read and understand
  • works for generic elements
  • allows using objects or object properties
  • handles the case of 0-length elements
  • could be used with additional Linq filtering
  • performs well (at least in my experience)
  • doesn't require (manual) creation of an additional object (e.g. StringBuilder) to implement

And of course Join takes care of the pesky final comma that sometimes sneaks into other approaches (for, foreach), which is why I was looking for a Linq solution in the first place.

Android Linear Layout - How to Keep Element At Bottom Of View?

DO LIKE THIS

 <LinearLayout
android:id="@+id/LinearLayouts02"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom|end">

<TextView
    android:id="@+id/texts1"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:layout_weight="2"
    android:text="@string/forgotpass"
    android:padding="7dp"
    android:gravity="bottom|center_horizontal"
    android:paddingLeft="10dp"
    android:layout_marginBottom="30dp"
    android:bottomLeftRadius="10dp"
    android:bottomRightRadius="50dp"
    android:fontFamily="sans-serif-condensed"
    android:textColor="@color/colorAccent"
    android:textStyle="bold"
    android:textSize="16sp"
    android:topLeftRadius="10dp"
    android:topRightRadius="10dp"
   />

</LinearLayout>

How to trim white space from all elements in array?

Try this:

String[] trimmedArray = new String[array.length];
for (int i = 0; i < array.length; i++)
    trimmedArray[i] = array[i].trim();

Now trimmedArray contains the same strings as array, but without leading and trailing whitespace. Alternatively, you could write this for modifying the strings in-place in the same array:

for (int i = 0; i < array.length; i++)
    array[i] = array[i].trim();

How do I get the n-th level parent of an element in jQuery?

Since parents() returns the ancestor elements ordered from the closest to the outer ones, you can chain it into eq():

$('#element').parents().eq(0);  // "Father".
$('#element').parents().eq(2);  // "Great-grandfather".

Writing file to web server - ASP.NET

protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
    using (StreamWriter w = new StreamWriter(Server.MapPath("~/data.txt"), true))
    {
        w.WriteLine(TextBox1.Text); // Write the text
    }
}

Shadow Effect for a Text in Android?

TextView textv = (TextView) findViewById(R.id.textview1);
textv.setShadowLayer(1, 0, 0, Color.BLACK);

Getting Hour and Minute in PHP

print date('H:i');

You have to set the correct timezone in php.ini .

Look for these lines:

[Date]

; Defines the default timezone used by the date functions

;date.timezone =

It will be something like :

date.timezone ="Europe/Lisbon"

Don't forget to restart your webserver.

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

From my experience, the way I do it is create a snapshot of your current image, then once its done you'll see it as an option when launching new instances. Simply launch it as a large instance at that point.

This is my approach if I do not want any downtime(i.e. production server) because this solution only takes a server offline only after the new one is up and running(I also use it to add new machines to my clusters by using this approach to only add new machines). If Downtime is acceptable then see Marcel Castilho's answer.

Styling a disabled input with css only

Let's just say you have 3 buttons:

<input type="button" disabled="disabled" value="hello world">
<input type="button" disabled value="hello world">
<input type="button" value="hello world">

To style the disabled button you can use the following css:

input[type="button"]:disabled{
    color:#000;
}

This will only affect the button which is disabled.

To stop the color changing when hovering you can use this too:

input[type="button"]:disabled:hover{
    color:#000;
}

You can also avoid this by using a css-reset.

How can I execute a PHP function in a form action?

<?php
require_once ( 'username.php' );

if (isset($_POST['textfield'])) {
    echo username();
    return;
}

echo '
<form name="form1" method="post" action="">
  <p>
    <label>
      <input type="text" name="textfield" id="textfield">
    </label>
  </p>
  <p>
    <label>
      <input type="submit" name="button" id="button" value="Submit">
    </label>
  </p>
</form>';
?>

You need to run the function in the page the form is sent to.

How to document Python code using Doxygen

The doxypy input filter allows you to use pretty much all of Doxygen's formatting tags in a standard Python docstring format. I use it to document a large mixed C++ and Python game application framework, and it's working well.

Rails and PostgreSQL: Role postgres does not exist

You might be able to workaround this by running initdb -U postgres -D /path/to/data or running it as user postgres, since it defaults to the current user. GL!

Writing an mp4 video using python opencv

What worked for me was to make sure the input 'frame' size is equal to output video's size (in this case, (680, 480) ).

http://answers.opencv.org/question/27902/how-to-record-video-using-opencv-and-python/

Here is my working code (Mac OSX Sierra 10.12.6):

cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)

fourcc = cv2.VideoWriter_fourcc(*'MP4V')
out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (640,480))

while(True):
    ret, frame = cap.read()
    out.write(frame)
    cv2.imshow('frame', frame)
    c = cv2.waitKey(1)
    if c & 0xFF == ord('q'):
        break

cap.release()
out.release()
cv2.destroyAllWindows()

Note: I installed openh264 as suggested by @10SecTom but I'm not sure if that was relevant to the problem.

Just in case:

brew install openh264

Sum values from multiple rows using vlookup or index/match functions

You should use Ctrl+shift+enter when using the =SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE)) that results in {=SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE))} en also works.

How to set iframe size dynamically

The height is different depending on the browser's window size. It should be set dynamically depending on the size of the browser window

<!DOCTYPE html>
    <html>
    <body>
    
    <center><h2>Heading</h2></center>
    <center><p>Paragraph</p></center>
    
    <iframe src="url" height="600" width="1350" title="Enter Here"></iframe>
    
    </body>
    </html>

Create a nonclustered non-unique index within the CREATE TABLE statement with SQL Server

It's a separate statement.

It's also not possible to insert into a table and select from it and build an index in the same statement either.

The BOL entry contains the information you need:

CLUSTERED | NONCLUSTERED
Indicate that a clustered or a nonclustered index is created for the PRIMARY KEY or UNIQUE constraint. PRIMARY KEY constraints default to CLUSTERED, and UNIQUE constraints default to NONCLUSTERED.

In a CREATE TABLE statement, CLUSTERED can be specified for only one constraint. If CLUSTERED is specified for a UNIQUE constraint and a PRIMARY KEY constraint is also specified, the PRIMARY KEY defaults to NONCLUSTERED.

You can create an index on a PK field, but not a non-clustered index on a non-pk non-unique-constrained field.

A NCL index is not relevant to the structure of the table, and is not a constraint on the data inside the table. It's a separate entity that supports the table but is not integral to it's functionality or design.

That's why it's a separate statement. The NCL index is irrelevant to the table from a design perspective (query optimization notwithstanding).

How can I find the first and last date in a month using PHP?

$month=01;
$year=2015;
$num = cal_days_in_month(CAL_GREGORIAN, $month, $year);
echo $num;

display 31 last day of date

How to loop through all elements of a form jQuery

pure JavaScript is not that difficult:

for(var i=0; i < form.elements.length; i++){
    var e = form.elements[i];
    console.log(e.name+"="+e.value);
}

Note: because form.elements is a object for-in loop does not work as expected.

Answer found here (by Chris Pietschmann), documented here (W3S).

How to get a user's time zone?

edit/update:

Xcode 8 or later • Swift 3 or later

var secondsFromGMT: Int { return TimeZone.current.secondsFromGMT() }
secondsFromGMT  // -7200

if you need the abbreviation:

var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "" }
localTimeZoneAbbreviation   // "GMT-2"

if you need the timezone identifier:

var localTimeZoneIdentifier: String { return TimeZone.current.identifier }

localTimeZoneIdentifier // "America/Sao_Paulo"

To know all timezones abbreviations available:

var timeZoneAbbreviations: [String:String] { return TimeZone.abbreviationDictionary }
timeZoneAbbreviations   // ["CEST": "Europe/Paris", "WEST": "Europe/Lisbon", "CDT": "America/Chicago", "EET": "Europe/Istanbul", "BRST": "America/Sao_Paulo", "EEST": "Europe/Istanbul", "CET": "Europe/Paris", "MSD": "Europe/Moscow", "MST": "America/Denver", "KST": "Asia/Seoul", "PET": "America/Lima", "NZDT": "Pacific/Auckland", "CLT": "America/Santiago", "HST": "Pacific/Honolulu", "MDT": "America/Denver", "NZST": "Pacific/Auckland", "COT": "America/Bogota", "CST": "America/Chicago", "SGT": "Asia/Singapore", "CAT": "Africa/Harare", "BRT": "America/Sao_Paulo", "WET": "Europe/Lisbon", "IST": "Asia/Calcutta", "HKT": "Asia/Hong_Kong", "GST": "Asia/Dubai", "EDT": "America/New_York", "WIT": "Asia/Jakarta", "UTC": "UTC", "JST": "Asia/Tokyo", "IRST": "Asia/Tehran", "PHT": "Asia/Manila", "AKDT": "America/Juneau", "BST": "Europe/London", "PST": "America/Los_Angeles", "ART": "America/Argentina/Buenos_Aires", "PDT": "America/Los_Angeles", "WAT": "Africa/Lagos", "EST": "America/New_York", "BDT": "Asia/Dhaka", "CLST": "America/Santiago", "AKST": "America/Juneau", "ADT": "America/Halifax", "AST": "America/Halifax", "PKT": "Asia/Karachi", "GMT": "GMT", "ICT": "Asia/Bangkok", "MSK": "Europe/Moscow", "EAT": "Africa/Addis_Ababa"]

To know all timezones names (identifiers) available:

var timeZoneIdentifiers: [String] { return TimeZone.knownTimeZoneIdentifiers }
timeZoneIdentifiers           // ["Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers", "Africa/Asmara", "Africa/Bamako", "Africa/Bangui", "Africa/Banjul", "Africa/Bissau", "Africa/Blantyre", "Africa/Brazzaville", "Africa/Bujumbura", "Africa/Cairo", "Africa/Casablanca", "Africa/Ceuta", "Africa/Conakry", "Africa/Dakar", "Africa/Dar_es_Salaam", "Africa/Djibouti", "Africa/Douala", "Africa/El_Aaiun", "Africa/Freetown", "Africa/Gaborone", "Africa/Harare", "Africa/Johannesburg", "Africa/Juba", "Africa/Kampala", "Africa/Khartoum", "Africa/Kigali", "Africa/Kinshasa", "Africa/Lagos", "Africa/Libreville", "Africa/Lome", "Africa/Luanda", "Africa/Lubumbashi", "Africa/Lusaka", "Africa/Malabo", "Africa/Maputo", "Africa/Maseru", "Africa/Mbabane", "Africa/Mogadishu", "Africa/Monrovia", "Africa/Nairobi", "Africa/Ndjamena", "Africa/Niamey", "Africa/Nouakchott", "Africa/Ouagadougou", "Africa/Porto-Novo", "Africa/Sao_Tome", "Africa/Tripoli", "Africa/Tunis", "Africa/Windhoek", "America/Adak", "America/Anchorage", "America/Anguilla", "America/Antigua", "America/Araguaina", "America/Argentina/Buenos_Aires", "America/Argentina/Catamarca", "America/Argentina/Cordoba", "America/Argentina/Jujuy", "America/Argentina/La_Rioja", "America/Argentina/Mendoza", "America/Argentina/Rio_Gallegos", "America/Argentina/Salta", "America/Argentina/San_Juan", "America/Argentina/San_Luis", "America/Argentina/Tucuman", "America/Argentina/Ushuaia", "America/Aruba", "America/Asuncion", "America/Atikokan", "America/Bahia", "America/Bahia_Banderas", "America/Barbados", "America/Belem", "America/Belize", "America/Blanc-Sablon", "America/Boa_Vista", "America/Bogota", …, "Pacific/Marquesas", "Pacific/Midway", "Pacific/Nauru", "Pacific/Niue", "Pacific/Norfolk", "Pacific/Noumea", "Pacific/Pago_Pago", "Pacific/Palau", "Pacific/Pitcairn", "Pacific/Pohnpei", "Pacific/Ponape", "Pacific/Port_Moresby", "Pacific/Rarotonga", "Pacific/Saipan", "Pacific/Tahiti", "Pacific/Tarawa", "Pacific/Tongatapu", "Pacific/Truk", "Pacific/Wake", "Pacific/Wallis"]

There is a few other info you may need:

var isDaylightSavingTime: Bool { return TimeZone.current.isDaylightSavingTime(for: Date()) }
print(isDaylightSavingTime) // true (in effect)

var daylightSavingTimeOffset: TimeInterval { return TimeZone.current.daylightSavingTimeOffset() }
print(daylightSavingTimeOffset)  // 3600 seconds (1 hour - daylight savings time)


var nextDaylightSavingTimeTransition: Date? { return TimeZone.current.nextDaylightSavingTimeTransition }    //  "Feb 18, 2017, 11:00 PM"
 print(nextDaylightSavingTimeTransition?.description(with: .current) ?? "none")
nextDaylightSavingTimeTransition   // "Saturday, February 18, 2017 at 11:00:00 PM Brasilia Standard Time\n"

var nextDaylightSavingTimeTransitionAfterNext: Date? {
    guard
        let nextDaylightSavingTimeTransition = nextDaylightSavingTimeTransition
        else { return nil }
    return TimeZone.current.nextDaylightSavingTimeTransition(after: nextDaylightSavingTimeTransition)
}

nextDaylightSavingTimeTransitionAfterNext  //   "Oct 15, 2017, 1:00 AM"

TimeZone - Apple Developer Swift Documentation

How to convert currentTimeMillis to a date in Java?

The SimpleDateFormat class has a method called SetTimeZone(TimeZone) that is inherited from the DateFormat class. http://docs.oracle.com/javase/6/docs/api/java/text/DateFormat.html

initializing strings as null vs. empty string

Empty-ness and "NULL-ness" are two different concepts. As others mentioned the former can be achieved via std::string::empty(), the latter can be achieved with boost::optional<std::string>, e.g.:

boost::optional<string> myStr;
if (myStr) { // myStr != NULL
    // ...
}

How do I add a bullet symbol in TextView?

Another best way to add bullet in any text view is stated below two steps:

First, create a drawable

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <!--set color of the bullet-->
   <solid 
       android:color="#666666"/> //set color of bullet

    <!--set size of the bullet-->
   <size 
       android:width="120dp"
        android:height="120dp"/>
</shape>

Then add this drawable in textview and set its pedding by using below properties

android:drawableStart="@drawable/bullet"
android:drawablePadding="10dp"

ios simulator: how to close an app

You can also kill the app by process id

ps -cx -o pid,command | awk '$2 == "YourAppNameCaseSensitive" { print $1 }' | xargs kill -9

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

In my case the error was caused by the lack of space on my machine. Deleting old builds fixed the problem.

Android Camera : data intent returns null

I´ve had experienced this problem, the intent is not null but the information sent via this intent is not received in onActionActivit()

enter image description here

This is a better solution using getContentResolver() :

    private Uri imageUri;
    private ImageView myImageView;
    private Bitmap thumbnail;

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

      ...
      ...    
      ...
      myImageview = (ImageView) findViewById(R.id.pic); 

      values = new ContentValues();
      values.put(MediaStore.Images.Media.TITLE, "MyPicture");
      values.put(MediaStore.Images.Media.DESCRIPTION, "Photo taken on " + System.currentTimeMillis());
      imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
      Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
      startActivityForResult(intent, PICTURE_RESULT);

  }

the onActivityResult() get a bitmap stored by getContentResolver() :

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_TAKE_PHOTO && resultCode == RESULT_OK) {

            Bitmap bitmap;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
                myImageView.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

introducir la descripción de la imagen aquí introducir la descripción de la imagen aquí

Check my example in github:

https://github.com/Jorgesys/TakePicture

When to use the different log levels

Here's a list of what "the loggers" have.


Apache log4j: §1, §2

  1. FATAL:

    [v1.2: ..] very severe error events that will presumably lead the application to abort.

    [v2.0: ..] severe error that will prevent the application from continuing.

  2. ERROR:

    [v1.2: ..] error events that might still allow the application to continue running.

    [v2.0: ..] error in the application, possibly recoverable.

  3. WARN:

    [v1.2: ..] potentially harmful situations.

    [v2.0: ..] event that might possible [sic] lead to an error.

  4. INFO:

    [v1.2: ..] informational messages that highlight the progress of the application at coarse-grained level.

    [v2.0: ..] event for informational purposes.

  5. DEBUG:

    [v1.2: ..] fine-grained informational events that are most useful to debug an application.

    [v2.0: ..] general debugging event.

  6. TRACE:

    [v1.2: ..] finer-grained informational events than the DEBUG.

    [v2.0: ..] fine-grained debug message, typically capturing the flow through the application.


Apache Httpd (as usual) likes to go for the overkill: §

  1. emerg:

    Emergencies – system is unusable.

  2. alert:

    Action must be taken immediately [but system is still usable].

  3. crit:

    Critical Conditions [but action need not be taken immediately].

    • "socket: Failed to get a socket, exiting child"
  4. error:

    Error conditions [but not critical].

    • "Premature end of script headers"
  5. warn:

    Warning conditions. [close to error, but not error]

  6. notice:

    Normal but significant [notable] condition.

    • "httpd: caught SIGBUS, attempting to dump core in ..."
  7. info:

    Informational [and unnotable].

    • ["Server has been running for x hours."]
  8. debug:

    Debug-level messages [, i.e. messages logged for the sake of de-bugging)].

    • "Opening config file ..."
  9. trace1trace6:

    Trace messages [, i.e. messages logged for the sake of tracing].

    • "proxy: FTP: control connection complete"
    • "proxy: CONNECT: sending the CONNECT request to the remote proxy"
    • "openssl: Handshake: start"
    • "read from buffered SSL brigade, mode 0, 17 bytes"
    • "map lookup FAILED: map=rewritemap key=keyname"
    • "cache lookup FAILED, forcing new map lookup"
  10. trace7trace8:

    Trace messages, dumping large amounts of data

    • "| 0000: 02 23 44 30 13 40 ac 34 df 3d bf 9a 19 49 39 15 |"
    • "| 0000: 02 23 44 30 13 40 ac 34 df 3d bf 9a 19 49 39 15 |"

Apache commons-logging: §

  1. fatal:

    Severe errors that cause premature termination. Expect these to be immediately visible on a status console.

  2. error:

    Other runtime errors or unexpected conditions. Expect these to be immediately visible on a status console.

  3. warn:

    Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console.

  4. info:

    Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum.

  5. debug:

    detailed information on the flow through the system. Expect these to be written to logs only.

  6. trace:

    more detailed information. Expect these to be written to logs only.

Apache commons-logging "best practices" for enterprise usage makes a distinction between debug and info based on what kind of boundaries they cross.

Boundaries include:

  • External Boundaries - Expected Exceptions.

  • External Boundaries - Unexpected Exceptions.

  • Internal Boundaries.

  • Significant Internal Boundaries.

(See commons-logging guide for more info on this.)

How do I check in python if an element of a list is empty?

I got around this with len() and a simple if/else statement.

List elements will come back as an integer when wrapped in len() (1 for present, 0 for absent)

l = []

print(len(l)) # Prints 0

if len(l) == 0:
    print("Element is empty")
else:
    print("Element is NOT empty")

Output:

Element is empty    

Java: Casting Object to Array type

What you've got (according to the debug image) is an object array containing a string array. So you need something like:

Object[] objects = (Object[]) values;
String[] strings = (String[]) objects[0];

You haven't shown the type of values - if this is already Object[] then you could just use (String[])values[0].

Of course even with the cast to Object[] you could still do it in one statement, but it's ugly:

String[] strings = (String[]) ((Object[])values)[0];

Images can't contain alpha channels or transparencies

On Pixelmator you can use 'Share > Export for Web...' (? + ? + E)

enter image description here

and deselect Transparency in the Tool Options Bar.

enter image description here

how to add script src inside a View when using Layout

If you are using Razor view engine then edit the _Layout.cshtml file. Move the @Scripts.Render("~/bundles/jquery") present in footer to the header section and write the javascript / jquery code as you want:

@Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
    $(document).ready(function () {
        var divLength = $('div').length;
        alert(divLength);
    });
</script>

How to convert a table to a data frame

While the results vary in this case because the column names are numbers, another way I've used is data.frame(rbind(mytable)). Using the example from @X.X:

> freq_t = table(cyl = mtcars$cyl, gear = mtcars$gear)

> freq_t
   gear
cyl  3  4  5
  4  1  8  2
  6  2  4  1
  8 12  0  2

> data.frame(rbind(freq_t))
  X3 X4 X5
4  1  8  2
6  2  4  1
8 12  0  2

If the column names do not start with numbers, the X won't get added to the front of them.

Absolute vs relative URLs

If it is for use within your website, it's better practice to use relative URL, like this if you need to move the website to another domain name or just debug locally, you can.

Take a look at what's stackoverflow is doing (ctrl+U in firefox):

<a href="/users/recent/90691"> // Link to an internal element

In some cases they use absolute urls :

<link rel="stylesheet" href="http://sstatic.net/so/all.css?v=5934">

... but this is only it's a best practice to improve speed. In your case, it doesn't look like you're doing anything like that so I wouldn't worry about it.

How to check if DST (Daylight Saving Time) is in effect, and if so, the offset?

This answer is quite similar to the accepted answer, but doesn't override the Date prototype, and only uses one function call to check if Daylight Savings Time is in effect, rather than two.


The idea is that, since no country observes DST that lasts for 7 months[1], in an area that observes DST the offset from UTC time in January will be different to the one in July.

While Daylight Savings Time moves clocks forwards, JavaScript always returns a greater value during Standard Time. Therefore, getting the minimum offset between January and July will get the timezone offset during DST.

We then check if the dates timezone is equal to that minimum value. If it is, then we are in DST; otherwise we are not.

The following function uses this algorithm. It takes a date object, d, and returns true if daylight savings time is in effect for that date, and false if it is not:

function isDST(d) {
    let jan = new Date(d.getFullYear(), 0, 1).getTimezoneOffset();
    let jul = new Date(d.getFullYear(), 6, 1).getTimezoneOffset();
    return Math.max(jan, jul) != d.getTimezoneOffset(); 
}

Executing multiple SQL queries in one statement with PHP

With mysqli you're able to use multiple statements for real using mysqli_multi_query().

Read more on multiple statements in the PHP Docs.

is there any PHP function for open page in new tab

You can simply use target="_blank" to open a page in a new tab

<a href="whatever.php" target="_blank">Opens On Another Tab</a>

Or you can simply use a javascript for onload

<body onload="window.open(url, '_blank');">

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

Just download and install the latest version of Virtual box, run it then run the emulator and viola, it will be up and running. This one worked for me.

Notice: Undefined offset: 0 in

If you leave out the brackets then PHP will assign the keys by default.

Try this:

$votes = $row['votes_up']; 
$votes = $row['votes_down']; 

Passing an array of parameters to a stored procedure

this is the best source:

http://www.sommarskog.se/arrays-in-sql.html

create a split function using the link, and use it like:

DELETE YourTable
    FROM YourTable                           d
    LEFT OUTER JOIN dbo.splitFunction(@Parameter) s ON d.ID=s.Value
    WHERE s.Value IS NULL

I prefer the number table approach

This is code based on the above link that should do it for you...

Before you use my function, you need to set up a "helper" table, you only need to do this one time per database:

CREATE TABLE Numbers
(Number int  NOT NULL,
    CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
DECLARE @x int
SET @x=0
WHILE @x<8000
BEGIN
    SET @x=@x+1
    INSERT INTO Numbers VALUES (@x)
END

use this function to split your string, which does not loop and is very fast:

CREATE FUNCTION [dbo].[FN_ListToTable]
(
     @SplitOn              char(1)              --REQUIRED, the character to split the @List string on
    ,@List                 varchar(8000)        --REQUIRED, the list to split apart
)
RETURNS
@ParsedList table
(
    ListValue varchar(500)
)
AS
BEGIN

/**
Takes the given @List string and splits it apart based on the given @SplitOn character.
A table is returned, one row per split item, with a column name "ListValue".
This function workes for fixed or variable lenght items.
Empty and null items will not be included in the results set.


Returns a table, one row per item in the list, with a column name "ListValue"

EXAMPLE:
----------
SELECT * FROM dbo.FN_ListToTable(',','1,12,123,1234,54321,6,A,*,|||,,,,B')

    returns:
        ListValue  
        -----------
        1
        12
        123
        1234
        54321
        6
        A
        *
        |||
        B

        (10 row(s) affected)

**/



----------------
--SINGLE QUERY-- --this will not return empty rows
----------------
INSERT INTO @ParsedList
        (ListValue)
    SELECT
        ListValue
        FROM (SELECT
                  LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(@SplitOn, List2, number+1)-number - 1))) AS ListValue
                  FROM (
                           SELECT @SplitOn + @List + @SplitOn AS List2
                       ) AS dt
                      INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
                  WHERE SUBSTRING(List2, number, 1) = @SplitOn
             ) dt2
        WHERE ListValue IS NOT NULL AND ListValue!=''



RETURN

END --Function FN_ListToTable

you can use this function as a table in a join:

SELECT
    Col1, COl2, Col3...
    FROM  YourTable
        INNER JOIN dbo.FN_ListToTable(',',@YourString) s ON  YourTable.ID = s.ListValue

here is your delete:

DELETE YourTable
    FROM YourTable                                d
    LEFT OUTER JOIN dbo.FN_ListToTable(',',@Parameter) s ON d.ID=s.ListValue
    WHERE s.ListValue IS NULL

Getting error "No such module" using Xcode, but the framework is there

I actually solved this much more easily by adding to the end of build-debug.xconfig

#include "../Pods/Target Support Files/Pods-IAP/Pods-IAP.debug.xcconfig"

And to the end of build-release.xconfig

#include "../Pods/Target Support Files/Pods-IAP/Pods-IAP.release.xcconfig"

since those files already define PODS_ROOT and the related build variables.

Python extending with - using super() Python 3 vs Python 2

  • super() (without arguments) was introduced in Python 3 (along with __class__):

    super() -> same as super(__class__, self)
    

    so that would be the Python 2 equivalent for new-style classes:

    super(CurrentClass, self)
    
  • for old-style classes you can always use:

     class Classname(OldStyleParent):
        def __init__(self, *args, **kwargs):
            OldStyleParent.__init__(self, *args, **kwargs)
    

How to output MySQL query results in CSV format?

The following bash script works for me. It optionally also gets the schema for the requested tables.

#!/bin/bash
#
# export mysql data to CSV
#https://stackoverflow.com/questions/356578/how-to-output-mysql-query-results-in-csv-format
#

#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'
red='\033[0;31m'
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'

#
# a colored message 
#   params:
#     1: l_color - the color of the message
#     2: l_msg - the message to display
#
color_msg() {
  local l_color="$1"
  local l_msg="$2"
  echo -e "${l_color}$l_msg${endColor}"
}


#
# error
#
# show the given error message on stderr and exit
#
#   params:
#     1: l_msg - the error message to display
#
error() {
  local l_msg="$1"
  # use ansi red for error
  color_msg $red "Error:" 1>&2
  color_msg $red "\t$l_msg" 1>&2
  usage
}

#
# display usage 
#
usage() {
  echo "usage: $0 [-h|--help]" 1>&2
  echo "               -o  | --output      csvdirectory"    1>&2
  echo "               -d  | --database    database"   1>&2
  echo "               -t  | --tables      tables"     1>&2
  echo "               -p  | --password    password"   1>&2
  echo "               -u  | --user        user"       1>&2
  echo "               -hs | --host        host"       1>&2
  echo "               -gs | --get-schema"             1>&2
  echo "" 1>&2
  echo "     output: output csv directory to export mysql data into" 1>&2
  echo "" 1>&2
  echo "         user: mysql user" 1>&2
  echo "     password: mysql password" 1>&2
  echo "" 1>&2
  echo "     database: target database" 1>&2
  echo "       tables: tables to export" 1>&2
  echo "         host: host of target database" 1>&2
  echo "" 1>&2
  echo "  -h|--help: show help" 1>&2
  exit 1
}

#
# show help 
#
help() {
  echo "$0 Help" 1>&2
  echo "===========" 1>&2
  echo "$0 exports a csv file from a mysql database optionally limiting to a list of tables" 1>&2
  echo "   example: $0 --database=cms --user=scott --password=tiger  --tables=person --output person.csv" 1>&2
  echo "" 1>&2
  usage
}

domysql() {
  mysql --host $host -u$user --password=$password $database
}

getcolumns() {
  local l_table="$1"
  echo "describe $l_table" | domysql | cut -f1 | grep -v "Field" | grep -v "Warning" | paste -sd "," - 2>/dev/null
}

host="localhost"
mysqlfiles="/var/lib/mysql-files/"

# parse command line options
while true; do
  #echo "option $1"
  case "$1" in
    # options without arguments
    -h|--help) usage;;
    -d|--database)     database="$2" ; shift ;;
    -t|--tables)       tables="$2" ; shift ;;
    -o|--output)       csvoutput="$2" ; shift ;;
    -u|--user)         user="$2" ; shift ;;
    -hs|--host)        host="$2" ; shift ;;
    -p|--password)     password="$2" ; shift ;;
    -gs|--get-schema)  option="getschema";; 
    (--) shift; break;;
    (-*) echo "$0: error - unrecognized option $1" 1>&2; usage;;
    (*) break;;
  esac
  shift
done

# checks
if [ "$csvoutput" == "" ]
then
  error "ouput csv directory not set"
fi
if [ "$database" == "" ]
then
  error "mysql database not set"
fi
if [ "$user" == "" ]
then
  error "mysql user not set"
fi
if [ "$password" == "" ]
then
  error "mysql password not set"
fi

color_msg $blue "exporting tables of database $database"
if [ "$tables" = "" ]
then
tables=$(echo "show tables" | domysql)
fi

case $option in
  getschema) 
   rm $csvoutput$database.schema
   for table in $tables
   do
     color_msg $blue "getting schema for $table"
     echo -n "$table:" >> $csvoutput$database.schema
     getcolumns $table >> $csvoutput$database.schema
   done  
   ;;
  *)
for table in $tables
do
  color_msg $blue "exporting table $table"
  cols=$(grep "$table:" $csvoutput$database.schema | cut -f2 -d:)
  if [  "$cols" = "" ]
  then
    cols=$(getcolumns $table)
  fi
  ssh $host rm $mysqlfiles/$table.csv
cat <<EOF | mysql --host $host -u$user --password=$password $database 
SELECT $cols FROM $table INTO OUTFILE '$mysqlfiles$table.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
EOF
  scp $host:$mysqlfiles/$table.csv $csvoutput$table.csv.raw
  (echo "$cols"; cat $csvoutput$table.csv.raw) > $csvoutput$table.csv
  rm $csvoutput$table.csv.raw
done
  ;;
esac

How to style HTML5 range input to have different color before and after slider?

It's now supported with pseudo elements in each of WebKit, Firefox and IE. But, of course, it's different in each one. : (

See this question's answers and/or search for a CodePen titled prettify <input type=range> #101 for some solutions.

What causing this "Invalid length for a Base-64 char array"

This is because of a huge view state, In my case I got lucky since I was not using the viewstate. I just added enableviewstate="false" on the form tag and view state went from 35k to 100 chars

ConnectionTimeout versus SocketTimeout

A connection timeout occurs only upon starting the TCP connection. This usually happens if the remote machine does not answer. This means that the server has been shut down, you used the wrong IP/DNS name, wrong port or the network connection to the server is down.

A socket timeout is dedicated to monitor the continuous incoming data flow. If the data flow is interrupted for the specified timeout the connection is regarded as stalled/broken. Of course this only works with connections where data is received all the time.

By setting socket timeout to 1 this would require that every millisecond new data is received (assuming that you read the data block wise and the block is large enough)!

If only the incoming stream stalls for more than a millisecond you are running into a timeout.

Still Reachable Leak detected by Valgrind

For future readers, "Still Reachable" might mean you forgot to close something like a file. While it doesn't seem that way in the original question, you should always make sure you've done that.

How to overplot a line on a scatter plot in python?

A one-line version of this excellent answer to plot the line of best fit is:

plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))

Using np.unique(x) instead of x handles the case where x isn't sorted or has duplicate values.

The call to poly1d is an alternative to writing out m*x + b like in this other excellent answer.

Python: How exactly can you take a string, split it, reverse it and join it back together again?

Not fitting 100% to this particular question but if you want to split from the back you can do it like this:

theStringInQuestion[::-1].split('/', 1)[1][::-1]

This code splits once at symbol '/' from behind.

How to make an input type=button act like a hyperlink and redirect using a get request?

Do not do it. I might want to run my car on monkey blood. I have my reasons, but sometimes it's better to stick with using things the way they were designed even if it doesn't "absolutely perfectly" match the exact look you are driving for.

To back up my argument I submit the following.

  • See how this image lacks the status bar at the bottom. This link is using the onclick="location.href" model. (This is a real-life production example from my predecessor) This can make users hesitant to click on the link, since they have no idea where it is taking them, for starters.

Image

You are also making Search engine optimization more difficult IMO as well as making the debugging and reading of your code/HTML more complex. A submit button should submit a form. Why should you(the development community) try to create a non-standard UI?

How would you make two <div>s overlap?

If you want the logo to take space, you are probably better of floating it left and then moving down the content using margin, sort of like this:

#logo {
    float: left;
    margin: 0 10px 10px 20px;
}

#content {
    margin: 10px 0 0 10px;
}

or whatever margin you want.

Substitute multiple whitespace with single whitespace in Python

A regular expression can be used to offer more control over the whitespace characters that are combined.

To match unicode whitespace:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"\s+")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str).strip()

To match ASCII whitespace only:

import re

_RE_COMBINE_WHITESPACE = re.compile(r"(?a:\s+)")
_RE_STRIP_WHITESPACE = re.compile(r"(?a:^\s+|\s+$)")

my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str)
my_str = _RE_STRIP_WHITESPACE.sub("", my_str)

Matching only ASCII whitespace is sometimes essential for keeping control characters such as x0b, x0c, x1c, x1d, x1e, x1f.

Reference:

About \s:

For Unicode (str) patterns: Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.

About re.ASCII:

Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).

strip() will remote any leading and trailing whitespaces.

Difference between parameter and argument

Arguments and parameters are different in that parameters are used to different values in the program and The arguments are passed the same value in the program so they are used in c++. But no difference in c. It is the same for arguments and parameters in c.

curl.h no such file or directory

If after the installation curl-dev luarocks does not see the headers:

find /usr -name 'curl.h'
Example: /usr/include/x86_64-linux-gnu/curl/curl.h

luarocks install lua-cURL CURL_INCDIR=/usr/include/x86_64-linux-gnu/

How to check if the user can go back in browser history or not

the browser has back and forward button. I come up a solution on this question. but It will affect browser forward action and cause bug with some browsers.

It works like that: If the browser open a new url, that has never opened, the history.length will be grow.

so you can change hash like

  location.href = '#__transfer__' + new Date().getTime() 

to get a never shown url, then history.length will get the true length.

  var realHistoryLength = history.length - 1

but, It not always work well, and I don't known why ,especially the when url auto jump quickly.

How do I pass multiple parameters into a function in PowerShell?

If you don't know (or care) how many arguments you will be passing to the function, you could also use a very simple approach like;

Code:

function FunctionName()
{
    Write-Host $args
}

That would print out all arguments. For example:

FunctionName a b c 1 2 3

Output

a b c 1 2 3

I find this particularly useful when creating functions that use external commands that could have many different (and optional) parameters, but relies on said command to provide feedback on syntax errors, etc.

Here is a another real-world example (creating a function to the tracert command, which I hate having to remember the truncated name);

Code:

Function traceroute
{
    Start-Process -FilePath "$env:systemroot\system32\tracert.exe" -ArgumentList $args -NoNewWindow
}

Difference between Inheritance and Composition

Inheritances Vs Composition.

Inheritances and composition both are used to re-usability and extension of class behavior.

Inheritances mainly use in a family algorithm programming model such as IS-A relation type means similar kind of object. Example.

  1. Duster is a Car
  2. Safari is a Car

These are belongs to Car family.

Composition represents HAS-A relationship Type.It shows the ability of an object such as Duster has Five Gears , Safari has four Gears etc. Whenever we need to extend the ability of an existing class then use composition.Example we need to add one more gear in Duster object then we have to create one more gear object and compose it to the duster object.

We should not make the changes in base class until/unless all the derived classes needed those functionality.For this scenario we should use Composition.Such as

class A Derived by Class B

Class A Derived by Class C

Class A Derived by Class D.

When we add any functionality in class A then it is available to all sub classes even when Class C and D don't required those functionality.For this scenario we need to create a separate class for those functionality and compose it to the required class(here is class B).

Below is the example:

          // This is a base class
                 public abstract class Car
                    {
                       //Define prototype
                       public abstract void color();
                       public void Gear() {
                           Console.WriteLine("Car has a four Gear");
                       }
                    }


           // Here is the use of inheritence
           // This Desire class have four gears.
          //  But we need to add one more gear that is Neutral gear.

          public class Desire : Car
                   {
                       Neutral obj = null;
                       public Desire()
                       {
     // Here we are incorporating neutral gear(It is the use of composition). 
     // Now this class would have five gear. 

                           obj = new Neutral();
                           obj.NeutralGear();
                       }

                       public override void color()
                       {
                           Console.WriteLine("This is a white color car");
                       }

                   }


             // This Safari class have four gears and it is not required the neutral
             //  gear and hence we don't need to compose here.

                   public class Safari :Car{
                       public Safari()
                       { }

                       public override void color()
                       {
                           Console.WriteLine("This is a red color car");
                       }


                   }

   // This class represents the neutral gear and it would be used as a composition.

   public class Neutral {
                      public void NeutralGear() {
                           Console.WriteLine("This is a Neutral Gear");
                       }
                   }

How can I dismiss the on screen keyboard?

try using a text editing controller. at the begining,

    final myController = TextEditingController();
     @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }

and in the on press event,

onPressed: () {
            commentController.clear();}

this will dismiss the keybord.

Regular Expression for alphanumeric and underscores

I believe you are not taking Latin and Unicode characters in your matches. For example, if you need to take "ã" or "ü" chars, the use of "\w" won't work.

You can, alternatively, use this approach:

^[A-ZÀ-Ýa-zà-ý0-9_]+$

Hope it helps!

Convert character to Date in R

The easiest way is to use lubridate:

library(lubridate)
prods.all$Date2 <- mdy(prods.all$Date2)

This function automatically returns objects of class POSIXct and will work with either factors or characters.

Binding objects defined in code-behind

You can set the DataContext for your control, form, etc. like so:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

Clarification:

The data context being set to the value above should be done at whatever element "owns" the code behind -- so for a Window, you should set it in the Window declaration.

I have your example working with this code:

<Window x:Class="MyClass"
  Title="{Binding windowname}"
  DataContext="{Binding RelativeSource={RelativeSource Self}}"
  Height="470" Width="626">

The DataContext set at this level then is inherited by any element in the window (unless you explicitly change it for a child element), so after setting the DataContext for the Window you should be able to just do straight binding to CodeBehind properties from any control on the window.

How to compare 2 files fast using .NET?

My experiments show that it definitely helps to call Stream.ReadByte() fewer times, but using BitConverter to package bytes does not make much difference against comparing bytes in a byte array.

So it is possible to replace that "Math.Ceiling and iterations" loop in the comment above with the simplest one:

            for (int i = 0; i < count1; i++)
            {
                if (buffer1[i] != buffer2[i])
                    return false;
            }

I guess it has to do with the fact that BitConverter.ToInt64 needs to do a bit of work (check arguments and then perform the bit shifting) before you compare and that ends up being the same amount of work as compare 8 bytes in two arrays.

Change onclick action with a Javascript function

You could try changing the button attribute like this:

element.setAttribute( "onClick", "javascript: Boo();" );

Using import fs from 'fs'

Building on RobertoNovelo's answer:

import * as fs from 'fs';

is currently the simplest way to do it.

It was tested with a Node.js project (Node.js v10.15.3), with esm, allowing to use import.

Preferred Java way to ping an HTTP URL for availability

The following code performs a HEAD request to check whether the website is available or not.

public static boolean isReachable(String targetUrl) throws IOException
{
    HttpURLConnection httpUrlConnection = (HttpURLConnection) new URL(
            targetUrl).openConnection();
    httpUrlConnection.setRequestMethod("HEAD");

    try
    {
        int responseCode = httpUrlConnection.getResponseCode();

        return responseCode == HttpURLConnection.HTTP_OK;
    } catch (UnknownHostException noInternetConnection)
    {
        return false;
    }
}

How to run Spring Boot web application in Eclipse itself?

If you are doing code in STS you just need to add the devtools dependency in your maven file. After that it will run itself whenever you will do some change.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>

Best way to implement multi-language/globalization in large .NET project

We use a custom provider for multi language support and put all texts in a database table. It works well except we sometimes face caching problems when updating texts in the database without updating the web application.

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

Its because of wrong path provided. It may be that the url contains space and if the case url has to be properly constructed.

The correct url should be in the format with file name included like "http://server name/document library name/new file name"

So if report.xlsx is the file that has to be uploaded at "http://server name/Team/Dev Team" then path comes out to be is "http://server name/Team/Dev Team/report.xlsx". It contains space so it should be reconstructed as "http://server name/Team/Dev%20Team/report.xlsx" and should be used.

How to dynamically create a class?

I don't know the intended usage of such dynamic classes, and code generation and run time compilation can be done, but takes some effort. Maybe Anonymous Types would help you, something like:

var v = new { EmployeeID = 108, EmployeeName = "John Doe" };

How to refresh Gridview after pressed a button in asp.net

All you have to do is In your bLoanButton_Click , add a line to rebind the Grid to the SqlDataSource :

protected void bLoanButton_Click(object sender, EventArgs e)
{

//your same code
........

GridView1.DataBind();


}

regards

Best way to get the max value in a Spark dataframe column

First add the import line:

from pyspark.sql.functions import min, max

To find the min value of age in the dataframe:

df.agg(min("age")).show()

+--------+
|min(age)|
+--------+
|      29|
+--------+

To find the max value of age in the dataframe:

df.agg(max("age")).show()

+--------+
|max(age)|
+--------+
|      77|
+--------+

How to insert table values from one database to another database?

You can try

Insert into your_table_in_db1 select * from your_table_in_db2@db2SID 

db2SID is the sid of other DB. It will be present in tnsnames.ora file

Install Application programmatically on Android

Try this - Write on Manifest:

uses-permission android:name="android.permission.INSTALL_PACKAGES"
        tools:ignore="ProtectedPermissions"

Write the Code:

File sdCard = Environment.getExternalStorageDirectory();
String fileStr = sdCard.getAbsolutePath() + "/Download";// + "app-release.apk";
File file = new File(fileStr, "app-release.apk");
Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(file),
                        "application/vnd.android.package-archive");

startActivity(promptInstall);

IIS_IUSRS and IUSR permissions in IIS8

I hate to post my own answer, but some answers recently have ignored the solution I posted in my own question, suggesting approaches that are nothing short of foolhardy.

In short - you do not need to edit any Windows user account privileges at all. Doing so only introduces risk. The process is entirely managed in IIS using inherited privileges.

Applying Modify/Write Permissions to the Correct User Account

  1. Right-click the domain when it appears under the Sites list, and choose Edit Permissions

    enter image description here

    Under the Security tab, you will see MACHINE_NAME\IIS_IUSRS is listed. This means that IIS automatically has read-only permission on the directory (e.g. to run ASP.Net in the site). You do not need to edit this entry.

    enter image description here

  2. Click the Edit button, then Add...

  3. In the text box, type IIS AppPool\MyApplicationPoolName, substituting MyApplicationPoolName with your domain name or whatever application pool is accessing your site, e.g. IIS AppPool\mydomain.com

    enter image description here

  4. Press the Check Names button. The text you typed will transform (notice the underline):

    enter image description here

  5. Press OK to add the user

  6. With the new user (your domain) selected, now you can safely provide any Modify or Write permissions

    enter image description here

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

Node.js: get path from the request

Combining solutions above when using express request:

let url=url.parse(req.originalUrl);
let page = url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '';

this will handle all cases like

localhost/page
localhost:3000/page/
/page?item_id=1
localhost:3000/
localhost/

etc. Some examples:

> urls
[ 'http://localhost/page',
  'http://localhost:3000/page/',
  'http://localhost/page?item_id=1',
  'http://localhost/',
  'http://localhost:3000/',
  'http://localhost/',
  'http://localhost:3000/page#item_id=2',
  'http://localhost:3000/page?item_id=2#3',
  'http://localhost',
  'http://localhost:3000' ]
> urls.map(uri => url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '' )
[ 'page', 'page', 'page', '', '', '', 'page', 'page', '', '' ]

Replace a value in a data frame based on a conditional (`if`) statement

another useful way to replace values

library(plyr)
junk$nm <- revalue(junk$nm, c("B"="b"))

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

I was facing same error with Django Rest Framework, It was nothing to do with UI, still was getting this error. I applied below solution, worked for me.

  • Restarted Machine.
  • Restarted Virtual Environment.

How to prevent text in a table cell from wrapping

<th nowrap="nowrap">

or

<th style="white-space:nowrap;">

or

<th class="nowrap">
<style type="text/css">
.nowrap { white-space: nowrap; }
</style>

How to send a “multipart/form-data” POST in Android with Volley

Here is Simple Solution And Complete Example for Uploading File Using Volley Android

1) Gradle Import

compile 'dev.dworks.libs:volleyplus:+'

2)Now Create a Class RequestManager

public class RequestManager {
    private static RequestManager mRequestManager;
    /**
     * Queue which Manages the Network Requests :-)
     */
    private static RequestQueue mRequestQueue;
    // ImageLoader Instance

    private RequestManager() {

    }

    public static RequestManager get(Context context) {

        if (mRequestManager == null)
            mRequestManager = new RequestManager();

        return mRequestManager;
    }

    /**
     * @param context application context
     */
    public static RequestQueue getnstance(Context context) {

        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(context);
        }

        return mRequestQueue;

    }


}

3)Now Create a Class to handle Request for uploading File WebService

public class WebService {
    private RequestQueue mRequestQueue;
    private static WebService apiRequests = null;

    public static WebService getInstance() {
        if (apiRequests == null) {
            apiRequests = new WebService();
            return apiRequests;
        }
        return apiRequests;
    }
    public void updateProfile(Context context, String doc_name, String doc_type, String appliance_id, File file, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        SimpleMultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, "YOUR URL HERE", listener, errorListener);
//        request.setParams(data);
        mRequestQueue = RequestManager.getnstance(context);
        request.addMultipartParam("token", "text", "tdfysghfhsdfh");
        request.addMultipartParam("parameter_1", "text", doc_name);
        request.addMultipartParam("dparameter_2", "text", doc_type);
        request.addMultipartParam("parameter_3", "text", appliance_id);
            request.addFile("document_file", file.getPath());

        request.setFixedStreamingMode(true);
        mRequestQueue.add(request);
    }
}

4) And Now Call The method Like This to Hit the service

public class Main2Activity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<String>{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Button button=(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadData();
            }
        });
    }

    private void uploadData() {
        WebService.getInstance().updateProfile(getActivity(), "appl_doc", "appliance", "1", mChoosenFile, this, this);
    }

    @Override
    public void onErrorResponse(VolleyError error) {

    }

    @Override
    public void onResponse(String response) {
     //Your response here 
    }
}

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

This question has clearly been answered a number of times, but i thought i'd share my solution as I haven't seen it in the given answers.

var lower_case = function(letter){
    lowers = "abcdefghijklmnopqrstuvwxyz";
    return letter === letter.toLowerCase() && lowers.indexOf(letter) >= 0
};

var upper_case = function(letter){
    uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    return letter === letter.toUpperCase() && uppers.indexOf(letter) >= 0
};

"No backupset selected to be restored" SQL Server 2012

I think I get the award for the most bone headed reason to get this error. In the Restore Database dialog, the database dropdown under Source is gray and I thought it was disabled. I skipped down to the database dropdown under Destination thinking it was the source and made a selection. Doing this will cause this error message to be displayed.

HTML table headers always visible at top of window when viewing a large table

Craig, I refined your code a bit (among a few other things it's now using position:fixed) and wrapped it as a jQuery plugin.

Try it out here: http://jsfiddle.net/jmosbech/stFcx/

And get the source here: https://github.com/jmosbech/StickyTableHeaders

Android - SMS Broadcast receiver

Also note that the Hangouts application will currently block my BroadcastReceiver from receiving SMS messages. I had to disable SMS functionality in the Hangouts application (Settings->SMS->Turn on SMS), before my SMS BroadcastReceived started getting fired.

Edit: It appears as though some applications will abortBroadcast() on the intent which will prevent other applications from receiving the intent. The solution is to increase the android:priority attribute in the intent-filter tag:

<receiver android:name="com.company.application.SMSBroadcastReceiver" >
  <intent-filter android:priority="500">
    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
  </intent-filter>
</receiver>

See more details here: Enabling SMS support in Hangouts 2.0 breaks the BroadcastReceiver of SMS_RECEIVED in my app

How to grep (search) committed code in the Git history

git rev-list --all | xargs -n 5 git grep EXPRESSION

is a tweak to Jeet's solution, so it shows results while it searches and not just at the end (which can take a long time in a large repository).

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

I know this is going to be a late answer, however here is the most correct answer.

In MySQL database, change your timestamp default value into CURRENT_TIMESTAMP. If you have old records with the fake value, you will have to manually fix them.

How to remove an appended element with Jquery and why bind or live is causing elements to repeat

I would do something like:

$(documento).on('click', '#answer', function() {
  feedback('hey there');
});

In c# what does 'where T : class' mean?

'T' represents a generic type. It means it can accept any type of class. The following article might help:

http://www.15seconds.com/issue/031024.htm

How can I implement custom Action Bar with custom buttons in Android?

Please write following code in menu.xml file:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:my_menu_tutorial_app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="com.example.mymenus.menu_app.MainActivity">
<item android:id="@+id/item_one"
      android:icon="@drawable/menu_icon"
      android:orderInCategory="l01"
      android:title="Item One"
      my_menu_tutorial_app:showAsAction="always">
      <!--sub-menu-->
      <menu>
          <item android:id="@+id/sub_one"
                android:title="Sub-menu item one" />
          <item android:id="@+id/sub_two"
                android:title="Sub-menu item two" />
      </menu>

Also write this java code in activity class file:

public boolean onOptionsItemSelected(MenuItem item)
{
    super.onOptionsItemSelected(item);
    Toast.makeText(this, "Menus item selected: " +
        item.getTitle(), Toast.LENGTH_SHORT).show();
    switch (item.getItemId())
    {
        case R.id.sub_one:
            isItemOneSelected = true;
            supportInvalidateOptionsMenu();
            return true;
        case MENU_ITEM + 1:
            isRemoveItem = true;
            supportInvalidateOptionsMenu();
            return true;
        default:
            return false;
    }
}

This is the easiest way to display menus in action bar.

How to "z-index" to make a menu always on top of the content

Ok, Im assuming you want to put the .left inside the container so I suggest you edit your html. The key is the position:absolute and right:0

#right { 
    background-color: red;
    height: 300px;
    width: 300px;
    z-index: 999999;
    margin-top: 0px;
    position: absolute;
    right:0;
}

here is the full code: http://jsfiddle.net/T9FJL/

Delete first character of a string in Javascript

You can remove the first character of a string using substring:

var s1 = "foobar";
var s2 = s1.substring(1);
alert(s2); // shows "oobar"

To remove all 0's at the start of the string:

var s = "0000test";
while(s.charAt(0) === '0')
{
 s = s.substring(1);
}

How to set a Postgresql default value datestamp like 'YYYYMM'?

Please bear in mind that the formatting of the date is independent of the storage. If it's essential to you that the date is stored in that format you will need to either define a custom data type or store it as a string. Then you can use a combination of extract, typecasting and concatenation to get that format.

However, I suspect that you want to store a date and get the format on output. So, something like this will do the trick for you:

    CREATE TABLE my_table
    (
    id serial PRIMARY KEY not null,
    my_date date not null default CURRENT_DATE
    );

(CURRENT_DATE is basically a synonym for now() and a cast to date).

(Edited to use to_char).

Then you can get your output like:

SELECT id, to_char(my_date, 'yyyymm') FROM my_table;

Now, if you did really need to store that field as a string and ensure the format you could always do:

CREATE TABLE my_other_table
(
id serial PRIMARY KEY not null,
my_date varchar(6) default to_char(CURRENT_DATE, 'yyyymm')
);

Cannot attach the file *.mdf as database

To fix this using SQL SERVER Management Studio

Your problem: You get an error such as 'Cannot attach the file 'YourDB.mdf' as database 'YourConnStringNamedContext';

Reason: happens because you deleted the backing files .mdf, ldf without actually deleting the database within the running instance of SqlLocalDb; re-running the code in VS won't help because you cannot re-create a DB with the same name (and that's why renaming works, but leaves the old phantom db name lying around).

The Fix: I am using VS2012, adopt similarly for a different version.

Navigate to below path and enter

c:\program files\microsoft sql server\110\Tools\Binn>sqllocaldb info

Above cmd shows the instance names, including 'v11.0'

If the instance is already running, enter at the prompt

sqllocaldb info v11.0

Note the following info Owner: YourPCName\Username , State: Running , Instance pipe name: np:\.\pipe\LOCALDB#12345678\tsql\query , where 123456789 is some random alphanumeric

If State is not running or stopped, start the instance with

sqllocaldb start v11.0

and extract same info as above.

In the SS Management Studio 'Connect' dialog box enter

server name: np:\.\pipe\LOCALDB#12345678\tsql\query

auth: Windows auth

user name: (same as Owner, it is grayed out for Win. auth.)

Once connected, find the phantom DB which you deleted (e.g. YourDB.mdf should have created a db named YourDB), and really delete it.

Done! Once it's gone, VS EF should have no problem re-creating it.

Xcode - iPhone - profile doesn't match any valid certificate-/private-key pair in the default keychain

This also can happen if the device you are trying to run on has some older version of the provisioning profile you are using that points to an old, expired or revoked certificate or a certificate without associated private key. Delete any invalid Provisioning Profiles under your device section in Xcode organizer.

Recursively list files in Java

base on @Michael answer, add check whether listFiles return null

static Stream<File> files(File file) {
    return file.isDirectory()
            ? Optional.ofNullable(file.listFiles()).map(Stream::of).orElseGet(Stream::empty).flatMap(MainActivity::files)
            : Stream.of(file);
}

or use Lightweight-Stream-API, which support Android5 & Android6

static Stream<File> files(File f) {
    return f.isDirectory() ? Stream.ofNullable(f.listFiles()).flatMap(MainActivity::files) : Stream.of(f);
}

How to avoid "StaleElementReferenceException" in Selenium?

Kenny's solution is deprecated use this, i'm using actions class to double click but you can do anything.

new FluentWait<>(driver).withTimeout(30, TimeUnit.SECONDS).pollingEvery(5, TimeUnit.SECONDS)
                    .ignoring(StaleElementReferenceException.class)
                    .until(new Function() {

                    @Override
                    public Object apply(Object arg0) {
                        WebElement e = driver.findelement(By.xpath(locatorKey));
                        Actions action = new Actions(driver);
                        action.moveToElement(e).doubleClick().perform();
                        return true;
                    }
                });

'module' object has no attribute 'DataFrame'

There may be two causes:

  1. It is case-sensitive: DataFrame .... Dataframe, dataframe will not work.

  2. You have not install pandas (pip install pandas) in the python path.

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

Generate ER Diagram from existing MySQL database, created for CakePHP

Use MySQL Workbench. create SQL dump file of your database

Follow below steps:

  1. Click File->Import->Reverse Engineer MySQL Create Script
  2. Click Browse and select your SQL create script.
  3. Make Sure "Place Imported Objects on a diagram" is checked.
  4. Click Execute Button.
  5. You are done.

What is the equivalent to getch() & getche() in Linux?

As said above getch() is in the ncurses library. ncurses has to be initialized, see i.e. getchar() returns the same value (27) for up and down arrow keys for this

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

Yes. The querystring is also encrypted with SSL. Nevertheless, as this article shows, it isn't a good idea to put sensitive information in the URL. For example:

URLs are stored in web server logs - typically the whole URL of each request is stored in a server log. This means that any sensitive data in the URL (e.g. a password) is being saved in clear text on the server

Add leading zeroes to number in Java?

In case of your jdk version less than 1.5, following option can be used.

    int iTest = 2;
    StringBuffer sTest = new StringBuffer("000000"); //if the string size is 6
    sTest.append(String.valueOf(iTest));
    System.out.println(sTest.substring(sTest.length()-6, sTest.length()));

How to write console output to a txt file

PrintWriter out = null;
try {
    out = new PrintWriter(new FileWriter("C:\\testing.txt"));
    } catch (IOException e) {
            e.printStackTrace();
    }
out.println("output");
out.close();

I am using absolute path for the FileWriter. It is working for me like a charm. Also Make sure the file is present in the location. Else It will throw a FileNotFoundException. This method does not create a new file in the target location if the file is not found.

Settings to Windows Firewall to allow Docker for Windows to share drive

Even after ensuring that the inbound firewall rule is set up properly and even after uninstalling and reinstalling the File and Printing Sharing Service it didn't work for me.

Solution: on top of that I also had to do a third thing. I had to deactivate the checkbox Prevent incoming connections when on a public network in the specific firewall settings for public networks. After doing that it started working for me as well. See screenshots attached at the end of this message.

Don't know how long this option has been there already. I'm currently working on Win 10 Pro 1709 16299.402.


1. Open specific firewall settings for public networks Open specific firewall settings for public networks

2. Uncheck this checkbox Uncheck this checkbox

Java Comparator class to sort arrays

[...] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order [...]

Here's a complete example using Java 8:

import java.util.*;

public class Test {

    public static void main(String args[]) {

        int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };

        Arrays.sort(twoDim, Comparator.comparingInt(a -> a[0])
                                      .reversed());

        System.out.println(Arrays.deepToString(twoDim));
    }
}

Output:

[[8, 9], [5, 3], [4, 2], [3, 7], [1, 2]]

For Java 7 you can do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return Integer.compare(o2[0], o1[0]);
    }
});

If you unfortunate enough to work on Java 6 or older, you'd do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return ((Integer) o2[0]).compareTo(o1[0]);
    }
});

Check if key exists in JSON object using jQuery

if(typeof theObject['key'] != 'undefined'){
     //key exists, do stuff
}

//or

if(typeof theObject.key != 'undefined'){
    //object exists, do stuff
}

I'm writing here because no one seems to give the right answer..

I know it's old...

Somebody might question the same thing..

nvarchar(max) vs NText

You should apparently use nvarchar(max):

MSDN

How to reference a method in javadoc?

you can use @see to do that:

sample:

interface View {
        /**
         * @return true: have read contact and call log permissions, else otherwise
         * @see #requestReadContactAndCallLogPermissions()
         */
        boolean haveReadContactAndCallLogPermissions();

        /**
         * if not have permissions, request to user for allow
         * @see #haveReadContactAndCallLogPermissions()
         */
        void requestReadContactAndCallLogPermissions();
    }

How to read a PEM RSA private key from .NET

Check http://msdn.microsoft.com/en-us/library/dd203099.aspx

under Cryptography Application Block.

Don't know if you will get your answer, but it's worth a try.

Edit after Comment.

Ok then check this code.

using System.Security.Cryptography;


public static string DecryptEncryptedData(stringBase64EncryptedData, stringPathToPrivateKeyFile) { 
    X509Certificate2 myCertificate; 
    try{ 
        myCertificate = new X509Certificate2(PathToPrivateKeyFile); 
    } catch{ 
        throw new CryptographicException("Unable to open key file."); 
    } 

    RSACryptoServiceProvider rsaObj; 
    if(myCertificate.HasPrivateKey) { 
         rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey; 
    } else 
        throw new CryptographicException("Private key not contained within certificate."); 

    if(rsaObj == null) 
        return String.Empty; 

    byte[] decryptedBytes; 
    try{ 
        decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false); 
    } catch { 
        throw new CryptographicException("Unable to decrypt data."); 
    } 

    //    Check to make sure we decrpyted the string 
   if(decryptedBytes.Length == 0) 
        return String.Empty; 
    else 
        return System.Text.Encoding.UTF8.GetString(decryptedBytes); 
} 

Get the decimal part from a double

 string input = "0.55";
    var regex1 = new System.Text.RegularExpressions.Regex("(?<=[\\.])[0-9]+");
    if (regex1.IsMatch(input))
    {
        string dp= regex1.Match(input ).Value;
    }

How do you do natural logs (e.g. "ln()") with numpy in Python?

I usually do like this:

from numpy import log as ln

Perhaps this can make you more comfortable.