Programs & Examples On #Mpmediaitem

Class form Apple MediaPlayer framework. A media item represents a single piece of media (such as one song or one video podcast) in the iPod library.

Extracting jar to specified directory

This worked for me.

I created a folder then changed into the folder using CD option from command prompt.

Then executed the jar from there.

d:\LS\afterchange>jar xvf ..\mywar.war

Detect Safari using jQuery

A very useful way to fix this is to detect the browsers webkit version and check if it is at least the one we need, else do something else.

Using jQuery it goes like this:

_x000D_
_x000D_
"use strict";_x000D_
_x000D_
$(document).ready(function() {_x000D_
    var appVersion                  = navigator.appVersion;_x000D_
    var webkitVersion_positionStart = appVersion.indexOf("AppleWebKit/") + 12;_x000D_
    var webkitVersion_positionEnd   = webkitVersion_positionStart + 3;_x000D_
    var webkitVersion               = appVersion.slice(webkitVersion_positionStart, webkitVersion_positionEnd);_x000D_
 _x000D_
    console.log(webkitVersion);_x000D_
_x000D_
    if (webkitVersion < 537) {_x000D_
        console.log("webkit outdated.");_x000D_
    } else {_x000D_
        console.log("webkit ok.");_x000D_
    };_x000D_
});
_x000D_
_x000D_
_x000D_

This provides a safe and permanent fix for dealing with problems with browser's different webkit implementations.

Happy coding!

not:first-child selector

not(:first-child) does not seem to work anymore. At least with the more recent versions of Chrome and Firefox.

Instead, try this:

ul:not(:first-of-type) {}

Default Values to Stored Procedure in Oracle

Default values are only used if the arguments are not specified. In your case you did specify the arguments - both were supplied, with a value of NULL. (Yes, in this case NULL is considered a real value :-). Try:

EXEC TEST()

Share and enjoy.

Addendum: The default values for procedure parameters are certainly buried in a system table somewhere (see the SYS.ALL_ARGUMENTS view), but getting the default value out of the view involves extracting text from a LONG field, and is probably going to prove to be more painful than it's worth. The easy way is to add some code to the procedure:

CREATE OR REPLACE PROCEDURE TEST(X IN VARCHAR2 DEFAULT 'P',
                                 Y IN NUMBER DEFAULT 1)
AS
  varX VARCHAR2(32767) := NVL(X, 'P');
  varY NUMBER          := NVL(Y, 1);
BEGIN
  DBMS_OUTPUT.PUT_LINE('X=' || varX || ' -- ' || 'Y=' || varY);
END TEST;

New features in java 7

In addition to what John Skeet said, here's an overview of the Java 7 project. It includes a list and description of the features.

Note: JDK 7 was released on July 28, 2011, so you should now go to the official java SE site.

How to style icon color, size, and shadow of Font Awesome Icons

Simply you can define a class in your css file and cascade it into html file like

<i class="fa fa-plus fa-lg green"></i> 

now write down in css

.green{ color:green}

bootstrap popover not showing on top of all elements

It could have to do with the z-index master list on variables.less. In general, be sure that your variables.less file is correct and up-to-date.

How to fix "Headers already sent" error in PHP

Instead of the below line

//header("Location:".ADMIN_URL."/index.php");

write

echo("<script>location.href = '".ADMIN_URL."/index.php?msg=$msg';</script>");

or

?><script><?php echo("location.href = '".ADMIN_URL."/index.php?msg=$msg';");?></script><?php

It'll definitely solve your problem. I faced the same problem but I solved through writing header location in the above way.

In Ruby on Rails, what's the difference between DateTime, Timestamp, Time and Date?

The difference between different date/time formats in ActiveRecord has little to do with Rails and everything to do with whatever database you're using.

Using MySQL as an example (if for no other reason because it's most popular), you have DATE, DATETIME, TIME and TIMESTAMP column data types; just as you have CHAR, VARCHAR, FLOAT and INTEGER.

So, you ask, what's the difference? Well, some of them are self-explanatory. DATE only stores a date, TIME only stores a time of day, while DATETIME stores both.

The difference between DATETIME and TIMESTAMP is a bit more subtle: DATETIME is formatted as YYYY-MM-DD HH:MM:SS. Valid ranges go from the year 1000 to the year 9999 (and everything in between. While TIMESTAMP looks similar when you fetch it from the database, it's really a just a front for a unix timestamp. Its valid range goes from 1970 to 2038. The difference here, aside from the various built-in functions within the database engine, is storage space. Because DATETIME stores every digit in the year, month day, hour, minute and second, it uses up a total of 8 bytes. As TIMESTAMP only stores the number of seconds since 1970-01-01, it uses 4 bytes.

You can read more about the differences between time formats in MySQL here.

In the end, it comes down to what you need your date/time column to do. Do you need to store dates and times before 1970 or after 2038? Use DATETIME. Do you need to worry about database size and you're within that timerange? Use TIMESTAMP. Do you only need to store a date? Use DATE. Do you only need to store a time? Use TIME.

Having said all of this, Rails actually makes some of these decisions for you. Both :timestamp and :datetime will default to DATETIME, while :date and :time corresponds to DATE and TIME, respectively.

This means that within Rails, you only have to decide whether you need to store date, time or both.

Order data frame rows according to vector with specific order

If you don't want to use any libraries and you have reoccurrences in your data, you can use which with sapply as well.

new_order <- sapply(target, function(x,df){which(df$name == x)}, df=df)
df        <- df[new_order,]

How to change facet labels?

Just extending naught101's answer -- credit goes to him

plot_labeller <- function(variable,value, facetVar1='<name-of-1st-facetting-var>', var1NamesMapping=<pass-list-of-name-mappings-here>, facetVar2='', var2NamesMapping=list() )
{
  #print (variable)
  #print (value)
  if (variable==facetVar1) 
    {
      value <- as.character(value)
      return(var1NamesMapping[value])
    } 
  else if (variable==facetVar2) 
    {
      value <- as.character(value)
      return(var2NamesMapping[value])
    } 
  else 
    {
      return(as.character(value))
    }
}

What you have to do is create a list with name-to-name mapping

clusteringDistance_names <- list(
  '100'="100",
  '200'="200",
  '300'="300",
  '400'="400",
  '600'="500"
)

and redefine plot_labeller() with new default arguments:

plot_labeller <- function(variable,value, facetVar1='clusteringDistance', var1NamesMapping=clusteringDistance_names, facetVar2='', var1NamesMapping=list() )

And then:

ggplot() + 
  facet_grid(clusteringDistance ~ . , labeller=plot_labeller) 

Alternatively you can create a dedicated function for each of the label changes you want to have.

Is there an "if -then - else " statement in XPath?

Yes, there is a way to do it in XPath 1.0:

concat(
  substring($s1, 1, number($condition)      * string-length($s1)),
  substring($s2, 1, number(not($condition)) * string-length($s2))
)

This relies on the concatenation of two mutually exclusive strings, the first one being empty if the condition is false (0 * string-length(...)), the second one being empty if the condition is true. This is called "Becker's method", attributed to Oliver Becker.

In your case:

concat(
  substring(
    substring-before(//div[@id='head']/text(), ': '),
    1, 
    number(
      ends-with(//div[@id='head']/text(), ': ')
    )
    * string-length(substring-before(//div [@id='head']/text(), ': '))
  ),
  substring(
    //div[@id='head']/text(), 
    1, 
    number(not(
      ends-with(//div[@id='head']/text(), ': ')
    ))
    * string-length(//div[@id='head']/text())
  )
)

Though I would try to get rid of all the "//" before.

Also, there is the possibility that //div[@id='head'] returns more than one node.
Just be aware of that — using //div[@id='head'][1] is more defensive.

Telegram Bot - how to get a group chat id?

Here is the sequence that worked for me after struggling for several hours:

Assume the bot name is my_bot.

1- Add the bot to the group.
Go to the group, click on group name, click on Add members, in the searchbox search for your bot like this: @my_bot, select your bot and click add.

2- Send a dummy message to the bot.
You can use this example: /my_id @my_bot
(I tried a few messages, not all the messages work. The example above works fine. Maybe the message should start with /)

3- Go to following url: https://api.telegram.org/botXXX:YYYY/getUpdates
replace XXX:YYYY with your bot token

4- Look for "chat":{"id":-zzzzzzzzzz,
-zzzzzzzzzz is your chat id (with the negative sign).

5- Testing: You can test sending a message to the group with a curl:

curl -X POST "https://api.telegram.org/botXXX:YYYY/sendMessage" -d "chat_id=-zzzzzzzzzz&text=my sample text"

If you miss step 2, there would be no update for the group you are looking for. Also if there are multiple groups, you can look for the group name in the response ("title":"group_name").

Hope this helps.

How can I calculate the difference between two dates?

Swift 4
Try this and see (date range with String):

// Start & End date string
let startingAt = "01/01/2018"
let endingAt = "08/03/2018"

// Sample date formatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"

// start and end date object from string dates
var startDate = dateFormatter.date(from: startingAt) ?? Date()
let endDate = dateFormatter.date(from: endingAt) ?? Date()


// Actual operational logic
var dateRange: [String] = []
while startDate <= endDate {
    let stringDate = dateFormatter.string(from: startDate)
    startDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate) ?? Date()
    dateRange.append(stringDate)
}

print("Resulting Array - \(dateRange)")

Swift 3

var date1 = Date(string: "2010-01-01 00:00:00 +0000")
var date2 = Date(string: "2010-02-03 00:00:00 +0000")
var secondsBetween: TimeInterval = date2.timeIntervalSince(date1)
var numberOfDays: Int = secondsBetween / 86400
print(numberOfDays)

How does the bitwise complement operator (~ tilde) work?

~ flips the bits in the value.

Why ~2 is -3 has to do with how numbers are represented bitwise. Numbers are represented as two's complement.

So, 2 is the binary value

00000010

And ~2 flips the bits so the value is now:

11111101

Which, is the binary representation of -3.

How to prevent going back to the previous activity?

There are two solutions for your case, activity A starts activity B, but you do not want to back to activity A in activity B.

1. Removed previous activity A from back stack.

    Intent intent = new Intent(activityA.this, activityB.class);
    startActivity(intent);
    finish(); // Destroy activity A and not exist in Back stack

2. Disabled go back button action in activity B.

There are two ways to prevent go back event as below,

1) Recommend approach

@Override
public void onBackPressed() {
}

2)Override onKeyDown method

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode==KeyEvent.KEYCODE_BACK) {
        return false;
    }
    return super.onKeyDown(keyCode, event);
}

Hope that it is useful, but still depends on your situations.

HttpContext.Current.User.Identity.Name is Empty

These might resolve the issue(It did for me). In IIS Express change the project property values, "Anonymous Authentication" and "Windows Authentication". To do this, when project is selected, press F4 and then change these properties.

enter image description here

In case you are deploying it on IIS locally, make sure local machines "Windows Authentication" feature is enabled and "Anonymous Authentication" is disabled.

Refer to

https://grekai.wordpress.com/2011/03/31/httpcontext-current-user-identity-name-is-empty/

Remove background drawable programmatically in Android

In addition to the excellent answers, if you want to achieve this via xml then you can add:

android:background="@android:color/transparent

to your view.

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

In your case here is a implementation using directions service.

function displayRoute() {

    var start = new google.maps.LatLng(28.694004, 77.110291);
    var end = new google.maps.LatLng(28.72082, 77.107241);

    var directionsDisplay = new google.maps.DirectionsRenderer();// also, constructor can get "DirectionsRendererOptions" object
    directionsDisplay.setMap(map); // map should be already initialized.

    var request = {
        origin : start,
        destination : end,
        travelMode : google.maps.TravelMode.DRIVING
    };
    var directionsService = new google.maps.DirectionsService(); 
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}

Setting cursor at the end of any text of a textbox

For Windows Forms you can control cursor position (and selection) with txtbox.SelectionStart and txtbox.SelectionLength properties. If you want to set caret to end try this:

txtbox.SelectionStart = txtbox.Text.Length;
txtbox.SelectionLength = 0;

For WPF see this question.

How to parse XML and count instances of a particular node attribute?

Just to add another possibility, you can use untangle, as it is a simple xml-to-python-object library. Here you have an example:

Installation:

pip install untangle

Usage:

Your XML file (a little bit changed):

<foo>
   <bar name="bar_name">
      <type foobar="1"/>
   </bar>
</foo>

Accessing the attributes with untangle:

import untangle

obj = untangle.parse('/path_to_xml_file/file.xml')

print obj.foo.bar['name']
print obj.foo.bar.type['foobar']

The output will be:

bar_name
1

More information about untangle can be found in "untangle".

Also, if you are curious, you can find a list of tools for working with XML and Python in "Python and XML". You will also see that the most common ones were mentioned by previous answers.

SQL Greater than, Equal to AND Less Than

Supposing you use sql server:

WHERE StartTime BETWEEN DATEADD(HOUR, -1, GetDate())
                    AND DATEADD(HOUR, 1, GetDate())

How can I convert a DOM element to a jQuery element?

So far best solution that I've made:

function convertHtmlToJQueryObject(html){
    var htmlDOMObject = new DOMParser().parseFromString(html, "text/html");
    return $(htmlDOMObject.documentElement);
}

IF-THEN-ELSE statements in postgresql

case when field1>0 then field2/field1 else 0 end as field3

Python match a string with regex

One Liner implementation:

a=[1,3]
b=[1,2,3,4]
all(i in b for i in a)

How to normalize a 2-dimensional numpy array in python less verbose?

Broadcasting is really good for this:

row_sums = a.sum(axis=1)
new_matrix = a / row_sums[:, numpy.newaxis]

row_sums[:, numpy.newaxis] reshapes row_sums from being (3,) to being (3, 1). When you do a / b, a and b are broadcast against each other.

You can learn more about broadcasting here or even better here.

Execute the setInterval function without delay the first time

You can set a very small initial delay-time (e.g. 100) and set it to your desired delay-time within the function:

_x000D_
_x000D_
var delay = 100;_x000D_
_x000D_
function foo() {_x000D_
  console.log("Change initial delay-time to what you want.");_x000D_
  delay = 12000;_x000D_
  setTimeout(foo, delay);_x000D_
}
_x000D_
_x000D_
_x000D_

double free or corruption (!prev) error in c program

I didn't check all the code but my guess is that the error is in the malloc call. You have to replace

 double *ptr = malloc(sizeof(double*) * TIME);

for

 double *ptr = malloc(sizeof(double) * TIME);

since you want to allocate size for a double (not the size of a pointer to a double).

How do I change the number of open files limit in Linux?

You could always try doing a ulimit -n 2048. This will only reset the limit for your current shell and the number you specify must not exceed the hard limit

Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system.

set rlim_fd_max = 166384
set rlim_fd_cur = 8192

On OS X, this same data must be set in /etc/sysctl.conf.

kern.maxfilesperproc=166384
kern.maxfiles=8192

Under Linux, these settings are often in /etc/security/limits.conf.

There are two kinds of limits:

  • soft limits are simply the currently enforced limits
  • hard limits mark the maximum value which cannot be exceeded by setting a soft limit

Soft limits could be set by any user while hard limits are changeable only by root. Limits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam_limits.

There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default.

Android Layout Weight

Think it that way, will be simpler

If you have 3 buttons and their weights are 1,3,1 accordingly, it will work like table in HTML

Provide 5 portions for that line: 1 portion for button 1, 3 portion for button 2 and 1 portion for button 1

Angular 2 http post params and body

The 2nd parameter of http.post is the body of the message, ie the payload and not the url search parameters. Pass data in that parameter.

From the documentation

post(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response>

public post(cmd: string, data: object): Observable<any> {

    const params = new URLSearchParams();
    params.set('cmd', cmd);

    const options = new RequestOptions({
      headers: this.getAuthorizedHeaders(),
      responseType: ResponseContentType.Json,
      params: params,
      withCredentials: false
    });

    console.log('Options: ' + JSON.stringify(options));

    return this.http.post(this.BASE_URL, data, options)
      .map(this.handleData)
      .catch(this.handleError);
  }

Edit

You should also check out the 1st parameter (BASE_URL). It must contain the complete url (minus query string) that you want to reach. I mention in due to the name you gave it and I can only guess what the value currently is (maybe just the domain?).

Also there is no need to call JSON.stringify on the data/payload that is sent in the http body.

If you still can't reach your end point look in the browser's network activity in the development console to see what is being sent. You can then further determine if the correct end point is being called wit the correct header and body. If it appears that is correct then use POSTMAN or Fiddler or something similar to see if you can hit your endpoint that way (outside of Angular).

Getting "cannot find Symbol" in Java project in Intellij

Make sure the source file of the java class you are trying to refer to has a .java extension. It was .aj in my case (I must have hit "Create aspect" instead of "Create class" when creating it). IntelliJ shows the same icon for this file as for "normal" class, but compiler does not see it when building.

Changing .aj to .java fixed it in my case.

CSS smooth bounce animation

In case you're already using the transform property for positioning your element (as I currently am), you can also animate the top margin:

.ball {
  animation: bounce 1s infinite alternate;
  -webkit-animation: bounce 1s infinite alternate;
}

@keyframes bounce {
  from {
    margin-top: 0;
  }
  to {
    margin-top: -15px;
  }
}

Asynchronous file upload (AJAX file upload) using jsp and javascript

The latest dwr (http://directwebremoting.org/dwr/index.html) has ajax file uploads, complete with examples and nice stuff for users (like progress indicators and such).

It looks pretty nifty and dwr is fairly easy to use in general so this will be pretty good as well.

Image encryption/decryption using AES256 symmetric block ciphers

For AES/CBC/PKCS7 encryption/decryption, Just Copy and paste the following code and replace SecretKey and IV with your own.

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import android.util.Base64;


public class CryptoHandler {

    String SecretKey = "xxxxxxxxxxxxxxxxxxxx";
    String IV = "xxxxxxxxxxxxxxxx";

    private static CryptoHandler instance = null;

    public static CryptoHandler getInstance() {

        if (instance == null) {
            instance = new CryptoHandler();
        }
        return instance;
    }

    public String encrypt(String message) throws NoSuchAlgorithmException,
            NoSuchPaddingException, IllegalBlockSizeException,
            BadPaddingException, InvalidKeyException,
            UnsupportedEncodingException, InvalidAlgorithmParameterException {

        byte[] srcBuff = message.getBytes("UTF8");
        //here using substring because AES takes only 16 or 24 or 32 byte of key 
        SecretKeySpec skeySpec = new 
        SecretKeySpec(SecretKey.substring(0,32).getBytes(), "AES");
        IvParameterSpec ivSpec = new 
        IvParameterSpec(IV.substring(0,16).getBytes());
        Cipher ecipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        ecipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
        byte[] dstBuff = ecipher.doFinal(srcBuff);
        String base64 = Base64.encodeToString(dstBuff, Base64.DEFAULT);
        return base64;
    }

    public String decrypt(String encrypted) throws NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException,
            InvalidAlgorithmParameterException, IllegalBlockSizeException,
            BadPaddingException, UnsupportedEncodingException {

        SecretKeySpec skeySpec = new 
        SecretKeySpec(SecretKey.substring(0,32).getBytes(), "AES");
        IvParameterSpec ivSpec = new 
        IvParameterSpec(IV.substring(0,16).getBytes());
        Cipher ecipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        ecipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
        byte[] raw = Base64.decode(encrypted, Base64.DEFAULT);
        byte[] originalBytes = ecipher.doFinal(raw);
        String original = new String(originalBytes, "UTF8");
        return original;
    }
}

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

Since the name is likely to change in future versions of Android (currently the latest is AppCompatActivity but it will probably change at some point), I believe a good thing to have is a class Activity that extends AppCompatActivity and then all your activities extend from that one. If tomorrow, they change the name to AppCompatActivity2 for instance you will have to change it just in one place.

Set System.Drawing.Color values

The Color structure is immutable (as all structures should really be), meaning that the values of its properties cannot be changed once that particular instance has been created.

Instead, you need to create a new instance of the structure with the property values that you want. Since you want to create a color using its component RGB values, you need to use the FromArgb method:

Color myColor = Color.FromArgb(100, 150, 75);

How to encode text to base64 in python

Use the below code:

import base64

#Taking input through the terminal.
welcomeInput= raw_input("Enter 1 to convert String to Base64, 2 to convert Base64 to String: ") 

if(int(welcomeInput)==1 or int(welcomeInput)==2):
    #Code to Convert String to Base 64.
    if int(welcomeInput)==1:
        inputString= raw_input("Enter the String to be converted to Base64:") 
        base64Value = base64.b64encode(inputString.encode())
        print "Base64 Value = " + base64Value
    #Code to Convert Base 64 to String.
    elif int(welcomeInput)==2:
        inputString= raw_input("Enter the Base64 value to be converted to String:") 
        stringValue = base64.b64decode(inputString).decode('utf-8')
        print "Base64 Value = " + stringValue

else:
    print "Please enter a valid value."

Responsive css styles on mobile devices ONLY

Yes, this can be done via javascript feature detection ( or browser detection , e.g. Modernizr ) . Then, use yepnope.js to load required resources ( JS and/or CSS )

Open an image using URI in Android's default gallery image viewer

I use this it works for me

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), 1);

Print content of JavaScript object?

You can give your objects their own toString methods in their prototypes.

How to set a maximum execution time for a mysql query?

You can find the answer on this other S.O. question:

MySQL - can I limit the maximum time allowed for a query to run?

a cron job that runs every second on your database server, connecting and doing something like this:

  • SHOW PROCESSLIST
  • Find all connections with a query time larger than your maximum desired time
  • Run KILL [process id] for each of those processes

Git reset --hard and push to remote repository

The whole git resetting business looked far to complicating for me.

So I did something along the lines to get my src folder in the state i had a few commits ago

# reset the local state
git reset <somecommit> --hard 
# copy the relevant part e.g. src (exclude is only needed if you specify .)
tar cvfz /tmp/current.tgz --exclude .git  src
# get the current state of git
git pull
# remove what you don't like anymore
rm -rf src
# restore from the tar file
tar xvfz /tmp/current.tgz
# commit everything back to git
git commit -a
# now you can properly push
git push

This way the state of affairs in the src is kept in a tar file and git is forced to accept this state without too much fiddling basically the src directory is replaced with the state it had several commits ago.

Extract a single (unsigned) integer from a string

$value = '25%';

Or

$value = '25.025$';

Or

$value = 'I am numeric 25';
$onlyNumeric = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

This will return only the numeric value

Increase Tomcat memory settings

try setting this

CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"

in {$tomcat-folder}\bin\setenv.sh (create it if necessary).

See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.

SQLDataReader Row Count

Maybe you can try this: though please note - This pulls the column count, not the row count

 using (SqlDataReader reader = command.ExecuteReader())
 {
     while (reader.Read())
     {
         int count = reader.VisibleFieldCount;
         Console.WriteLine(count);
     }
 }

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

On OS X, it's necessary to make sure Sandbox capabilities are set-up properly in order to use WKWebView.

This link made this clear to me: https://forums.developer.apple.com/thread/92265

Sharing hoping that it will help someone.


Select the Project File in the Navigator, select Capabilities, then make sure that:
* App Sandbox is OFF,
OR
* App Sandbox is ON AND Outgoing Connections (Client) is checked.

Do a "git export" (like "svn export")?

If you're not excluding files with .gitattributes export-ignore then try git checkout

mkdir /path/to/checkout/
git --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout -f -q

-f
When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.

and

-q
Avoid verbose

Additionally you can get any Branch or Tag or from a specific Commit Revision like in SVN just adding the SHA1 (SHA1 in Git is the equivalent to the Revision Number in SVN)

mkdir /path/to/checkout/
git --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout 2ef2e1f2de5f3d4f5e87df7d8 -f -q -- ./

The /path/to/checkout/ must be empty, Git will not delete any file, but will overwrite files with the same name without any warning

UPDATE: To avoid the beheaded problem or to leave intact the working repository when using checkout for export with tags, branches or SHA1, you need to add -- ./ at the end

The double dash -- tells git that everything after the dashes are paths or files, and also in this case tells git checkout to not change the HEAD

Examples:

This command will get just the libs directory and also the readme.txt file from that exactly commit

git --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout fef2e1f2de5f3d4f5e87df7d8 -f -q -- ./libs ./docs/readme.txt

This will create(overwrite) my_file_2_behind_HEAD.txt two commits behind the head HEAD^2

git --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout HEAD^2 -f -q -- ./my_file_2_behind_HEAD.txt

To get the export of another branch

git --git-dir=/path/to/repo/.git --work-tree=/path/to/checkout/ checkout myotherbranch -f -q -- ./

Notice that ./ is relative to the root of the repository

Print number of keys in Redis

Go to redis-cli and use below command

info keyspace

It may help someone

Windows batch: echo without new line

Echo with preceding space and without newline

As stated by Pedro earlier, echo without new line and with preceding space works (provided "9" is a true [BackSpace]).

<nul set /p=.9    Hello everyone

I had some issues getting it to work in Windows 10 with the new console but managed the following way.
In CMD type:

echo .?>bs.txt

I got "?" by pressing [Alt] + [8]
(the actual symbol may vary depending upon codepage).

Then it's easy to copy the result from "bs.txt" using Notepad.exe to where it's needed.

@echo off
<nul set /p "_s=.?    Hello everyone"
echo: here

join list of lists in python

l = []
map(l.extend, list_of_lists)

shortest!

shared global variables in C

You put the declaration in a header file, e.g.

 extern int my_global;

In one of your .c files you define it at global scope.

int my_global;

Every .c file that wants access to my_global includes the header file with the extern in.

How to tell which row number is clicked in a table?

A simple and jQuery free solution:

document.querySelector('#elitable').onclick = function(ev) {
   // ev.target <== td element
   // ev.target.parentElement <== tr
   var index = ev.target.parentElement.rowIndex;
}

Bonus: It works even if rows are added/removed dynamically

Codesign error: Provisioning profile cannot be found after deleting expired profile

One suggestion I'll make since no one yet has said it: PLEASE PLEASE PLEASE make a backup of your whole .xcodeproj file BEFORE you start modifying it's contents. Screwing up the project file and having no backup will lead to a very very unpleasant experience.

Being able to back out of an edit can be a godsend.

Classes residing in App_Code is not accessible

Right click on the .cs file in the App_Code folder and check its properties.

Make sure the "Build Action" is set to "Compile".

What version of javac built my jar?

I as well wrote my own bash script to dump the Java version required by all the jars passed at the command line... Mine is a bit rough, but works for me ;-)

example usage

$ jar_dump_version_of_jvm_required.sh *.jar
JVM VERSION REQUIRED: 46.0, /private/tmp/jars/WEB-INF/lib/json-simple-1.1.jar
JVM VERSION REQUIRED: 49.0, /private/tmp/jars/WEB-INF/lib/json-smart-1.1.1.jar
JVM VERSION REQUIRED: 50.0, /private/tmp/jars/WEB-INF/lib/jsontoken-1.0.jar
JVM VERSION REQUIRED: 50.0, /private/tmp/jars/WEB-INF/lib/jsr166y-1.7.0.jar

jar_dump_version_of_jvm_required.sh

#!/bin/bash

DIR=$(PWD)
function show_help()
{
  ME=$(basename $0)
  IT=$(cat <<EOF

  Dumps the version of the JVM required to run the classes in a jar file

  usage: $ME JAR_FILE

  e.g. 

  $ME myFile.jar    ->  VERSION: 50.0     myFile.jar

  Java versions are:
  54 = Java 10
  53 = Java 9
  52 = Java 8
  51 = Java 7
  50 = Java 6
  49 = Java 5
  48 = Java 1.4
  47 = Java 1.3
  46 = Java 1.2
  45.3 = Java 1.1

EOF
  )
  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$1" ]
then
  show_help
fi

function unzipJarToTmp()
{
  JAR=$1
  CLASS_FILE=$(jar -tf "$JAR" | grep \.class$ | grep -v '\$' | head -n1 | awk '{print $NF}')
  OUT_FILE="$CLASS_FILE"
  #echo "J=$JAR C=$CLASS_FILE O=$OUT_FILE"
  jar xf "$JAR" "$CLASS_FILE"

  MAJOR=$(javap -v "$OUT_FILE" 2>&1 | grep major | awk -F' ' '{print $3'})
  MINOR=$(javap -v "$OUT_FILE" 2>&1 | grep minor | awk -F' ' '{print $3'})
  if [ -z "$MAJOR" ]
  then
    echo "JVM VERSION REQUIRED: NA as no classes in $JAR"
  else
    echo "JVM VERSION REQUIRED: $MAJOR.$MINOR, $JAR"
  fi
}

# loop over cmd line args
for JAR in "$@"
do
  cd "$DIR"
  JAR_UID=$(basename "$JAR" | sed s/.jar//g)
  TMPDIR=/tmp/jar_dump/$JAR_UID/
  mkdir -p "$TMPDIR"
  JAR_ABS_PATH=$(realpath $JAR)

  cd "$TMPDIR"

  #echo "$JAR_ABS_PATH"
  unzipJarToTmp "$JAR_ABS_PATH"
  #sleep 2
done

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

How to retrieve a user environment variable in CMake (Windows)

You need to have your variables exported. So for example in Linux:

export EnvironmentVariableName=foo

Unexported variables are empty in CMAKE.

How to compare dates in datetime fields in Postgresql?

Use the range type. If the user enter a date:

select *
from table
where
    update_date
    <@
    tsrange('2013-05-03', '2013-05-03'::date + 1, '[)');

If the user enters timestamps then you don't need the ::date + 1 part

http://www.postgresql.org/docs/9.2/static/rangetypes.html

http://www.postgresql.org/docs/9.2/static/functions-range.html

Remove leading comma from a string

One-liner

str = str.replace(/^,/, '');

I'll be back.

Is header('Content-Type:text/plain'); necessary at all?

Say you want to answer a request with a 204: No Content HTTP status. Firefox will complain with "no element found" in the console of the browser. This is a bug in Firefox that has been reported, but never fixed, for several years. By sending a "Content-type: text/plain" header, you can prevent this error in Firefox.

How to test the type of a thrown exception in Jest

It is a little bit weird, but it works and IMHO is good readable:

it('should throw Error with message \'UNKNOWN ERROR\' when no parameters were passed', () => {
  try {
      throwError();
      // Fail test if above expression doesn't throw anything.
      expect(true).toBe(false);
  } catch (e) {
      expect(e.message).toBe("UNKNOWN ERROR");
  }
});

The Catch block catches your exception, and then you can test on your raised Error. Strange expect(true).toBe(false); is needed to fail your test if the expected Error will be not thrown. Otherwise, this line is never reachable (Error should be raised before them).

@Kenny Body suggested a better solution which improve a code quality if you use expect.assertions():

it('should throw Error with message \'UNKNOWN ERROR\' when no parameters were passed', () => {
  expect.assertions(1);
  try {
      throwError();
  } catch (e) {
      expect(e.message).toBe("UNKNOWN ERROR");
  }
});

See the original answer with more explanations: How to test the type of a thrown exception in Jest

Programmatically Install Certificate into Mozilla

Here is an alternative way that doesn't override the existing certificates: [bash fragment for linux systems]

certificateFile="MyCa.cert.pem"
certificateName="MyCA Name" 
for certDB in $(find  ~/.mozilla* ~/.thunderbird -name "cert8.db")
do
  certDir=$(dirname ${certDB});
  #log "mozilla certificate" "install '${certificateName}' in ${certDir}"
  certutil -A -n "${certificateName}" -t "TCu,Cuw,Tuw" -i ${certificateFile} -d ${certDir}
done

You may find certutil in the libnss3-tools package (debian/ubuntu).

Source:
http://web.archive.org/web/20150622023251/http://www.computer42.org:80/xwiki-static/exported/DevNotes/xwiki.DevNotes.Firefox.html

See also:
https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/tools/NSS_Tools_certutil

hide div tag on mobile view only?

Set the display property to none as the default, then use a media query to apply the desired styles to the div when the browser reaches a certain width. Replace 768px in the media query with whatever the minimum px value is where your div should be visible.

#title_message {
    display: none;
}

@media screen and (min-width: 768px) {
    #title_message {
        clear: both;
        display: block;
        float: left;
        margin: 10px auto 5px 20px;
        width: 28%;
    }
}

Spring MVC @PathVariable with dot (.) is getting truncated

As far as i know this issue appears only for the pathvariable at the end of the requestmapping.

We were able to solve that by defining the regex addon in the requestmapping.

 /somepath/{variable:.+}

How to display loading message when an iFrame is loading?

If it's only a placeholder you are trying to achieve: a crazy approach is to inject text as an svg-background. It allows for some flexbility, and from what I've read the browser support should be fairly decent (haven't tested it though):

  • Chrome >= 27
  • FireFox >= 30
  • Internet Explorer >= 9
  • Safari >= 5.1

html:

<iframe class="iframe-placeholder" src=""></iframe>

css:

.iframe-placeholder
{
   background: url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 100% 100%"><text fill="%23FF0000" x="50%" y="50%" font-family="\'Lucida Grande\', sans-serif" font-size="24" text-anchor="middle">PLACEHOLDER</text></svg>') 0px 0px no-repeat;
}

What can you change?

Inside the background-value:

  • font size: look for font-size="" and change the value to anything you want

  • font color: look for fill="". Don't forget to replace the # with %23 if you're using hexadecimal color notation. %23 stands for a # in URL encoding which is necessary for the svg-string to be able to be parsed in FireFox.

  • font family: look for font-family="" remember to escape the single quotes if you have a font that consists of multiple words (like with \'Lucida Grande\')

  • text: look for the element value of the text-element where you see the PLACEHOLDER string. You can replace the PLACEHOLDER string with anything that is url-compliant (special characters need to be converted to percent notation)

Example on fiddle

Pros:

  • No extra HTML-elements
  • No js
  • Text can easily (...) be adjusted without the need of an external program
  • It's SVG, so you can easily put any SVG you want in there.

Cons:

  • Browser support
  • It's complex
  • It's hacky
  • If the iframe-src doesn't have a background set, the placeholder will shine through (which is not inherent to this method, but just standard behaviour when you use a bg on the iframe)

I would only recommend this only if it's absolutely necessary to show text as a placeholder in an iframe which requires a little bit of flexbility (multiple languages, ...). Just take a moment and reflect on it: is all this really necessary? If I had a choice, I'd go for @Christina's method

IIS w3svc error

As for me - I just restarted the computer.

Read CSV with Scanner()

Please stop writing faulty CSV parsers!

I've seen hundreds of CSV parsers and so called tutorials for them online.

Nearly every one of them gets it wrong!

This wouldn't be such a bad thing as it doesn't affect me but people who try to write CSV readers and get it wrong tend to write CSV writers, too. And get them wrong as well. And these ones I have to write parsers for.

Please keep in mind that CSV (in order of increasing not so obviousness):

  1. can have quoting characters around values
  2. can have other quoting characters than "
  3. can even have other quoting characters than " and '
  4. can have no quoting characters at all
  5. can even have quoting characters on some values and none on others
  6. can have other separators than , and ;
  7. can have whitespace between seperators and (quoted) values
  8. can have other charsets than ascii
  9. should have the same number of values in each row, but doesn't always
  10. can contain empty fields, either quoted: "foo","","bar" or not: "foo",,"bar"
  11. can contain newlines in values
  12. can not contain newlines in values if they are not delimited
  13. can not contain newlines between values
  14. can have the delimiting character within the value if properly escaped
  15. does not use backslash to escape delimiters but...
  16. uses the quoting character itself to escape it, e.g. Frodo's Ring will be 'Frodo''s Ring'
  17. can have the quoting character at beginning or end of value, or even as only character ("foo""", """bar", """")
  18. can even have the quoted character within the not quoted value; this one is not escaped

If you think this is obvious not a problem, then think again. I've seen every single one of these items implemented wrongly. Even in major software packages. (e.g. Office-Suites, CRM Systems)

There are good and correctly working out-of-the-box CSV readers and writers out there:

If you insist on writing your own at least read the (very short) RFC for CSV.

Refresh/reload the content in Div using jquery/ajax

What you want is to load the data again but not reload the div.

You need to make an Ajax query to get data from the server and fill the DIV.

http://api.jquery.com/jQuery.ajax/

Merge up to a specific commit

Run below command into the current branch folder to merge from this <commit-id> to current branch, --no-commit do not make a new commit automatically

git merge --no-commit <commit-id>

git merge --continue can only be run after the merge has resulted in conflicts.

git merge --abort Abort the current conflict resolution process, and try to reconstruct the pre-merge state.

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

member names cannot be the same as their enclosing type C#

The problem is with the method:

private void Flow()
{
    X = x;
    Y = y;
}

Your class is named Flow so this method can't also be named Flow. You will have to change the name of the Flow method to something else to make this code compile.

Or did you mean to create a private constructor to initialize your class? If that's the case, you will have to remove the void keyword to let the compiler know that your declaring a constructor.

Updating a dataframe column in spark

Just as maasg says you can create a new DataFrame from the result of a map applied to the old DataFrame. An example for a given DataFrame df with two rows:

val newDf = sqlContext.createDataFrame(df.map(row => 
  Row(row.getInt(0) + SOMETHING, applySomeDef(row.getAs[Double]("y")), df.schema)

Note that if the types of the columns change, you need to give it a correct schema instead of df.schema. Check out the api of org.apache.spark.sql.Row for available methods: https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/Row.html

[Update] Or using UDFs in Scala:

import org.apache.spark.sql.functions._

val toLong = udf[Long, String] (_.toLong)

val modifiedDf = df.withColumn("modifiedColumnName", toLong(df("columnName"))).drop("columnName")

and if the column name needs to stay the same you can rename it back:

modifiedDf.withColumnRenamed("modifiedColumnName", "columnName")

How to set page content to the middle of screen?

HTML

<!DOCTYPE html>
<html>
    <head>
        <title>Center</title>        
    </head>
    <body>
        <div id="main_body">
          some text
        </div>
    </body>
</html>

CSS

body
{
   width: 100%;
   Height: 100%;
}
#main_body
{
    background: #ff3333;
    width: 200px;
    position: absolute;
}?

JS ( jQuery )

$(function(){
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    var main = $("#main_body");    
    $("#main_body").css({ top: ((windowHeight / 2) - (main.height() / 2)) + "px",
                          left:((windowWidth / 2) - (main.width() / 2)) + "px" });
});

See example here

The network path was not found

As others pointed out this could be more to do with the connectionstring config Make sure,

  1. user id and password are correct
  2. Data Source is pointing to correct one , for example if you are using SQL express it will be .\SQLEXPRESS
  3. Database is pointing to correct name of database Hope that helps.

How can I use "." as the delimiter with String.split() in java

If performance is an issue, you should consider using StringTokenizer instead of split. StringTokenizer is much much faster than split, even though it is a "legacy" class (but not deprecated).

WPF User Control Parent

Use VisualTreeHelper.GetParent or the recursive function below to find the parent window.

public static Window FindParentWindow(DependencyObject child)
{
    DependencyObject parent= VisualTreeHelper.GetParent(child);

    //CHeck if this is the end of the tree
    if (parent == null) return null;

    Window parentWindow = parent as Window;
    if (parentWindow != null)
    {
        return parentWindow;
    }
    else
    {
        //use recursion until it reaches a Window
        return FindParentWindow(parent);
    }
}

how to create a login page when username and password is equal in html

Doing password checks on client side is unsafe especially when the password is hard coded.

The safest way is password checking on server side, but even then the password should not be transmitted plain text.

Checking the password client side is possible in a "secure way":

  • The password needs to be hashed
  • The hashed password is used as part of a new url

Say "abc" is your password so your md5 would be "900150983cd24fb0d6963f7d28e17f72" (consider salting!). Now build a url containing the hash (like http://yourdomain.com/90015...f72.html).

CodeIgniter - accessing $config variable in view

Example, if you have:

$config['base_url'] = 'www.example.com'

set in your config.php then

echo base_url();

This works very well almost at every place.
/* Edit */
This might work for the latest versions of codeigniter (4 and above).

Difference between mkdir() and mkdirs() in java for java.io.File

mkdirs() also creates parent directories in the path this File represents.

javadocs for mkdirs():

Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

javadocs for mkdir():

Creates the directory named by this abstract pathname.

Example:

File  f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());

will yield false for the first [and no dir will be created], and true for the second, and you will have created non_existing_dir/someDir

How to fix request failed on channel 0

PTY allocation request failed on channel 0

There is a limit of 256 pseudo terminals on a system. Maybe you have an application that is leaking pseudo terminals. Use

lsof /dev/pts/*

to see what processes have open pseudo-terminals

shell request failed on channel 0

I was getting this error (without PTY allocation error). It turns out that one of my applications (QtCreator 3.0.?) was leaking Zombie processes. Other users were able to log in so I might have been hitting my per user process quota (if there is such a thing). I've updated to QtCreator 3.3. So far so good.

Get the first N elements of an array?

array_slice() is best thing to try, following are the examples:

<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);      // returns "c", "d", and "e"
$output = array_slice($input, -2, 1);  // returns "d"
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>

Can you install and run apps built on the .NET framework on a Mac?

Yes you can!

As of November 2016, Microsoft now has integrated .NET Core in it's official .NET Site

They even have a new Visual Studio app that runs on MacOS

How to find which columns contain any NaN value in Pandas dataframe

This worked for me,

1. For getting Columns having at least 1 null value. (column names)

data.columns[data.isnull().any()]

2. For getting Columns with count, with having at least 1 null value.

data[data.columns[data.isnull().any()]].isnull().sum()

[Optional] 3. For getting percentage of the null count.

data[data.columns[data.isnull().any()]].isnull().sum() * 100 / data.shape[0]

how to iterate through dictionary in a dictionary in django template?

This answer didn't work for me, but I found the answer myself. No one, however, has posted my question. I'm too lazy to ask it and then answer it, so will just put it here.

This is for the following query:

data = Leaderboard.objects.filter(id=custom_user.id).values(
    'value1',
    'value2',
    'value3')

In template:

{% for dictionary in data %}
  {% for key, value in dictionary.items %}
    <p>{{ key }} : {{ value }}</p>
  {% endfor %}
{% endfor %}

How do you create a REST client for Java?

Since no one mentioned, here is another one: Feign, which is used by Spring Cloud.

Why "no projects found to import"?

In new updated eclipse the option "create project from existing source" is found here, File>New>Project>Android>Android Project from Existing Code. Then browse to root directory.

enter image description here

Accessing attributes from an AngularJS directive

Although using '@' is more appropriate than using '=' for your particular scenario, sometimes I use '=' so that I don't have to remember to use attrs.$observe():

<su-label tooltip="field.su_documentation">{{field.su_name}}</su-label>

Directive:

myApp.directive('suLabel', function() {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        scope: {
            title: '=tooltip'
        },
        template: '<label><a href="#" rel="tooltip" title="{{title}}" data-placement="right" ng-transclude></a></label>',
        link: function(scope, element, attrs) {
            if (scope.title) {
                element.addClass('tooltip-title');
            }
        },
    }
});

Fiddle.

With '=' we get two-way databinding, so care must be taken to ensure scope.title is not accidentally modified in the directive. The advantage is that during the linking phase, the local scope property (scope.title) is defined.

Sql select rows containing part of string

you can use CHARINDEX in t-sql.

select * from table where CHARINDEX(url, 'http://url.com/url?url...') > 0

invalid command code ., despite escaping periods, using sed

On OS X nothing helps poor builtin sed to become adequate. The solution is:

brew install gnu-sed

And then use gsed instead of sed, which will just work as expected.

Use CSS to make a span not clickable

Using CSS you cannot, CSS will only change the appearance of the span. However you can do it without changing the structure of the div by adding an onclick handler to the span:

<html>
<head>
</head>
<body>
<div>
<a href="http://www.google.com">
  <span>title<br></span>
  <span onclick='return false;'>description<br></span>
  <span>some url</span>
</a>
</div>
</body>
</html>

You can then style it so that it looks un-clickable too:

<html>
<head>
     <style type='text/css'>
     a span.unclickable  { text-decoration: none; }
     a span.unclickable:hover { cursor: default; }
     </style>
</head>
<body>
<div>
<a href="http://www.google.com">
  <span>title<br></span>
  <span class='unclickable' onclick='return false;'>description<br></span>
  <span>some url</span>
</a>
</div>
</body>
</html>

What good are SQL Server schemas?

I tend to agree with Brent on this one... see this discussion here. http://www.brentozar.com/archive/2010/05/why-use-schemas/

In short... schemas aren't terribly useful except for very specific use cases. Makes things messy. Do not use them if you can help it. And try to obey the K(eep) I(t) S(imple) S(tupid) rule.

std::wstring VS std::string

I recommend avoiding std::wstring on Windows or elsewhere, except when required by the interface, or anywhere near Windows API calls and respective encoding conversions as a syntactic sugar.

My view is summarized in http://utf8everywhere.org of which I am a co-author.

Unless your application is API-call-centric, e.g. mainly UI application, the suggestion is to store Unicode strings in std::string and encoded in UTF-8, performing conversion near API calls. The benefits outlined in the article outweigh the apparent annoyance of conversion, especially in complex applications. This is doubly so for multi-platform and library development.

And now, answering your questions:

  1. A few weak reasons. It exists for historical reasons, where widechars were believed to be the proper way of supporting Unicode. It is now used to interface APIs that prefer UTF-16 strings. I use them only in the direct vicinity of such API calls.
  2. This has nothing to do with std::string. It can hold whatever encoding you put in it. The only question is how You treat its content. My recommendation is UTF-8, so it will be able to hold all Unicode characters correctly. It's a common practice on Linux, but I think Windows programs should do it also.
  3. No.
  4. Wide character is a confusing name. In the early days of Unicode, there was a belief that a character can be encoded in two bytes, hence the name. Today, it stands for "any part of the character that is two bytes long". UTF-16 is seen as a sequence of such byte pairs (aka Wide characters). A character in UTF-16 takes either one or two pairs.

How to show an alert box in PHP?

echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';

Div width 100% minus fixed amount of pixels

I had a similar issue where I wanted a banner across the top of the screen that had one image on the left and a repeating image on the right to the edge of the screen. I ended up resolving it like so:

CSS:

.banner_left {
position: absolute;
top: 0px;
left: 0px;
width: 131px;
height: 150px;
background-image: url("left_image.jpg");
background-repeat: no-repeat;
}

.banner_right {
position: absolute;
top: 0px;
left: 131px;
right: 0px;
height: 150px;
background-image: url("right_repeating_image.jpg");
background-repeat: repeat-x;
background-position: top left;
}

The key was the right tag. I'm basically specifying that I want it to repeat from 131px in from the left to 0px from the right.

How to write a test which expects an Error to be thrown in Jasmine?

For anyone who still might be facing this issue, for me the posted solution didn't work and it kept on throwing this error: Error: Expected function to throw an exception. I later realised that the function which I was expecting to throw an error was an async function and was expecting promise to be rejected and then throw error and that's what I was doing in my code:

throw new Error('REQUEST ID NOT FOUND');

and thats what I did in my test and it worked:

it('Test should throw error if request not found', willResolve(() => {
         const promise = service.getRequestStatus('request-id');
                return expectToReject(promise).then((err) => {
                    expect(err.message).toEqual('REQUEST NOT FOUND');
                });
            }));

Proper way to exit iPhone application?

Its not really a way to quit the program, but a way to force people to quit.

UIAlertView *anAlert = [[UIAlertView alloc] initWithTitle:@"Hit Home Button to Exit" message:@"Tell em why they're quiting" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[anAlert show];

Send auto email programmatically

Sending email programmatically with Kotlin.

  • simple email sending, not all the other features (like attachments).
  • TLS is always on
  • Only 1 gradle email dependency needed also.

I also found this list of email POP services really helpful:

https://support.office.com/en-gb/article/pop-and-imap-email-settings-for-outlook-8361e398-8af4-4e97-b147-6c6c4ac95353

How to use:

    val auth = EmailService.UserPassAuthenticator("yourUser", "yourPass")
    val to = listOf(InternetAddress("[email protected]"))
    val from = InternetAddress("[email protected]")
    val email = EmailService.Email(auth, to, from, "Test Subject", "Hello Body World")
    val emailService = EmailService("yourSmtpServer", 587)

    GlobalScope.launch { // or however you do background threads
        emailService.send(email)
    }

The code:

import java.util.*
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart

class EmailService(private var server: String, private var port: Int) {

    data class Email(
        val auth: Authenticator,
        val toList: List<InternetAddress>,
        val from: Address,
        val subject: String,
        val body: String
    )

    class UserPassAuthenticator(private val username: String, private val password: String) : Authenticator() {
        override fun getPasswordAuthentication(): PasswordAuthentication {
            return PasswordAuthentication(username, password)
        }
    }

    fun send(email: Email) {
        val props = Properties()
        props["mail.smtp.auth"] = "true"
        props["mail.user"] = email.from
        props["mail.smtp.host"] = server
        props["mail.smtp.port"] = port
        props["mail.smtp.starttls.enable"] = "true"
        props["mail.smtp.ssl.trust"] = server
        props["mail.mime.charset"] = "UTF-8"
        val msg: Message = MimeMessage(Session.getDefaultInstance(props, email.auth))
        msg.setFrom(email.from)
        msg.sentDate = Calendar.getInstance().time
        msg.setRecipients(Message.RecipientType.TO, email.toList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.CC, email.ccList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.BCC, email.bccList.toTypedArray())
        msg.replyTo = arrayOf(email.from)

        msg.addHeader("X-Mailer", CLIENT_NAME)
        msg.addHeader("Precedence", "bulk")
        msg.subject = email.subject

        msg.setContent(MimeMultipart().apply {
            addBodyPart(MimeBodyPart().apply {
                setText(email.body, "iso-8859-1")
                //setContent(email.htmlBody, "text/html; charset=UTF-8")
            })
        })
        Transport.send(msg)
    }

    companion object {
        const val CLIENT_NAME = "Android StackOverflow programmatic email"
    }
}

Gradle:

dependencies {
    implementation 'com.sun.mail:android-mail:1.6.4'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
}

AndroidManifest:

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

ng serve not detecting file changes automatically

In your project dist folder is own by root

Try to use sudo ng serve instead of ng serve.

Another solution

When there is having a large number of files watch not work in linux.There is a Limit at INotify Watches on Linux. So increasing the watches limit

//When live server not work in linux

sudo sysctl fs.inotify.max_user_watches=524288
sudo sysctl -p --system

ng serve //You can also do sudo **ng serve**

Android Studio Run/Debug configuration error: Module not specified

I had to select "Use classpath of module:" drop down option and choose my module.

intelliJ IDEA 13 error: please select Android SDK

  1. Go to Project structure (Ctrl + Alt + shift + S) -> Platforn settings -> SDKs -> press "Plus" icon
  2. Select "Android SDK" and input the SDKs path (for exanple: C:\Program Files (x86)\Android\android-sdk)
  3. Apply or OK button
  4. Be happy

How to detect a USB drive has been plugged in?

Here is a code that works for me, which is a part from the website above combined with my early trials: http://www.codeproject.com/KB/system/DriveDetector.aspx

This basically makes your form listen to windows messages, filters for usb drives and (cd-dvds), grabs the lparam structure of the message and extracts the drive letter.

protected override void WndProc(ref Message m)
    {

        if (m.Msg == WM_DEVICECHANGE)
        {
            DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
            if ((m.WParam.ToInt32() == DBT_DEVICEARRIVAL) &&  (vol.dbcv_devicetype == DBT_DEVTYPVOLUME) )
            {
                MessageBox.Show(DriveMaskToLetter(vol.dbcv_unitmask).ToString());
            }
            if ((m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
            {
                MessageBox.Show("usb out");
            }
        }
        base.WndProc(ref m);
    }

    [StructLayout(LayoutKind.Sequential)] //Same layout in mem
    public struct DEV_BROADCAST_VOLUME
    {
        public int dbcv_size;
        public int dbcv_devicetype;
        public int dbcv_reserved;
        public int dbcv_unitmask;
    }

    private static char DriveMaskToLetter(int mask)
    {
        char letter;
        string drives = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //1 = A, 2 = B, 3 = C
        int cnt = 0;
        int pom = mask / 2;
        while (pom != 0)    // while there is any bit set in the mask shift it right        
        {        
            pom = pom / 2;
            cnt++;
        }
        if (cnt < drives.Length)
            letter = drives[cnt];
        else
            letter = '?';
        return letter;
    }

Do not forget to add this:

using System.Runtime.InteropServices;

and the following constants:

    const int WM_DEVICECHANGE = 0x0219; //see msdn site
    const int DBT_DEVICEARRIVAL = 0x8000;
    const int DBT_DEVICEREMOVALCOMPLETE = 0x8004;
    const int DBT_DEVTYPVOLUME = 0x00000002;  

How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

For rails6, I was facing the same problem, as I was missing following files, once I added them, the issue resolved:

1. config/master.key
2. config/credentials.yml.enc

Make sure you have this files.!!!

Spring Boot Program cannot find main class

I know this is pretty late answer. But it might still help some new learners. The Following example is only for springboot with NETBEANS. I had to do the following steps:

Step 1. Follow @Mariuszs answer .

Step 2. Right click on project -> Properties -> RUN. Make sure the Main Class field is has the correct starter class else Click browse and select from the available classes .

Step 3. Click OK-> OK. Thant is all. Thank you.

How do I search for an object by its ObjectId in the mongo console?

Simply do:

db.getCollection('test').find('4ecbe7f9e8c1c9092c000027');

sqlplus how to find details of the currently connected database session

I know this is an old question but I did try all the above answers but didnt work in my case. What ultimately helped me out is

SHOW PARAMETER instance_name

Make cross-domain ajax JSONP request with jQuery

you need to parse your xml with jquery json parse...i.e

  var parsed_json = $.parseJSON(xml);

Difference between git pull and git pull --rebase

Suppose you have two commits in local branch:

      D---E master
     /
A---B---C---F origin/master

After "git pull", will be:

      D--------E  
     /          \
A---B---C---F----G   master, origin/master

After "git pull --rebase", there will be no merge point G. Note that D and E become different commits:

A---B---C---F---D'---E'   master, origin/master

Location of the android sdk has not been setup in the preferences in mac os?

Hope this helps:

Step 1.) Go to https://www.eclipse.org/downloads/index-developer.php?release=kepler and download appropriate Eclipse version.

Step 2.) Extract downloaded zip file in appropriate location. In this tutorial, I have downloaded and installed it under program files.

Step 3.) Right click on eclipse.exe file and send shortcut to desktop.

Step 4.) Double click on eclipse shortcut from desktop and select appropriate location to create your workspace.

Step 5.) Navigate to Window > Preferences. This should open Preferences window.

Step 6.) On the left hand side page expend “Java” and click on “Installed JREs”

Step 7.) Click Add. It will open “Add JRE” dialog. Select “Standard VM” and click Next.

Step 8.) For “JRE home” select “Direcotry…”. This will open “Browse for folder” dialog. Select the location where your JDK is installed. NOTE: MAKE SURE THAT ITS x64 AS WELL, AS WE ARE USING 64-BIT VERSION OF ECLIPSE.

Step 9.) If you have selected proper location, it will show JDK version in JRE name and it will display “JRE system libraries”.

Step 10.) Click finish. Now your JDK is properly pointed as “Installed JREs”.

Step 11.) Select checkbox unchecked before name of your JDK name.

Click ok and you’re done. You are now using JDK as “Installed JREs”

Read complete procedure at below location.

https://softwaretestingboard.com/qna/4/how-do-i-map-android-sdk-after-eclipse-plugin-is-installed#axzz4wM3UEZtq

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

Please take a look at my project on Sourceforge which has user types for standard SQL Date and Time types as well as JSR 310 and Joda Time. All of the types try to address the offsetting issue. See http://sourceforge.net/projects/usertype/

EDIT: In response to Derek Mahar's question attached to this comment:

"Chris, do your user types work with Hibernate 3 or greater? – Derek Mahar Nov 7 '10 at 12:30"

Yes these types support Hibernate 3.x versions including Hibernate 3.6.

How to get active user's UserDetails

Preamble: Since Spring-Security 3.2 there is a nice annotation @AuthenticationPrincipal described at the end of this answer. This is the best way to go when you use Spring-Security >= 3.2.

When you:

  • use an older version of Spring-Security,
  • need to load your custom User Object from the Database by some information (like the login or id) stored in the principal or
  • want to learn how a HandlerMethodArgumentResolver or WebArgumentResolver can solve this in an elegant way, or just want to an learn the background behind @AuthenticationPrincipal and AuthenticationPrincipalArgumentResolver (because it is based on a HandlerMethodArgumentResolver)

then keep on reading — else just use @AuthenticationPrincipal and thank to Rob Winch (Author of @AuthenticationPrincipal) and Lukas Schmelzeisen (for his answer).

(BTW: My answer is a bit older (January 2012), so it was Lukas Schmelzeisen that come up as the first one with the @AuthenticationPrincipal annotation solution base on Spring Security 3.2.)


Then you can use in your controller

public ModelAndView someRequestHandler(Principal principal) {
   User activeUser = (User) ((Authentication) principal).getPrincipal();
   ...
}

That is ok if you need it once. But if you need it several times its ugly because it pollutes your controller with infrastructure details, that normally should be hidden by the framework.

So what you may really want is to have a controller like this:

public ModelAndView someRequestHandler(@ActiveUser User activeUser) {
   ...
}

Therefore you only need to implement a WebArgumentResolver. It has a method

Object resolveArgument(MethodParameter methodParameter,
                   NativeWebRequest webRequest)
                   throws Exception

That gets the web request (second parameter) and must return the User if its feels responsible for the method argument (the first parameter).

Since Spring 3.1 there is a new concept called HandlerMethodArgumentResolver. If you use Spring 3.1+ then you should use it. (It is described in the next section of this answer))

public class CurrentUserWebArgumentResolver implements WebArgumentResolver{

   Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) {
        if(methodParameter is for type User && methodParameter is annotated with @ActiveUser) {
           Principal principal = webRequest.getUserPrincipal();
           return (User) ((Authentication) principal).getPrincipal();
        } else {
           return WebArgumentResolver.UNRESOLVED;
        }
   }
}

You need to define the Custom Annotation -- You can skip it if every instance of User should always be taken from the security context, but is never a command object.

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ActiveUser {}

In the configuration you only need to add this:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"
    id="applicationConversionService">
    <property name="customArgumentResolver">
        <bean class="CurrentUserWebArgumentResolver"/>
    </property>
</bean>

@See: Learn to customize Spring MVC @Controller method arguments

It should be noted that if you're using Spring 3.1, they recommend HandlerMethodArgumentResolver over WebArgumentResolver. - see comment by Jay


The same with HandlerMethodArgumentResolver for Spring 3.1+

public class CurrentUserHandlerMethodArgumentResolver
                               implements HandlerMethodArgumentResolver {

     @Override
     public boolean supportsParameter(MethodParameter methodParameter) {
          return
              methodParameter.getParameterAnnotation(ActiveUser.class) != null
              && methodParameter.getParameterType().equals(User.class);
     }

     @Override
     public Object resolveArgument(MethodParameter methodParameter,
                         ModelAndViewContainer mavContainer,
                         NativeWebRequest webRequest,
                         WebDataBinderFactory binderFactory) throws Exception {

          if (this.supportsParameter(methodParameter)) {
              Principal principal = webRequest.getUserPrincipal();
              return (User) ((Authentication) principal).getPrincipal();
          } else {
              return WebArgumentResolver.UNRESOLVED;
          }
     }
}

In the configuration, you need to add this

<mvc:annotation-driven>
      <mvc:argument-resolvers>
           <bean class="CurrentUserHandlerMethodArgumentResolver"/>         
      </mvc:argument-resolvers>
 </mvc:annotation-driven>

@See Leveraging the Spring MVC 3.1 HandlerMethodArgumentResolver interface


Spring-Security 3.2 Solution

Spring Security 3.2 (do not confuse with Spring 3.2) has own build in solution: @AuthenticationPrincipal (org.springframework.security.web.bind.annotation.AuthenticationPrincipal) . This is nicely described in Lukas Schmelzeisen`s answer

It is just writing

ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
    ...
 }

To get this working you need to register the AuthenticationPrincipalArgumentResolver (org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver) : either by "activating" @EnableWebMvcSecurity or by registering this bean within mvc:argument-resolvers - the same way I described it with may Spring 3.1 solution above.

@See Spring Security 3.2 Reference, Chapter 11.2. @AuthenticationPrincipal


Spring-Security 4.0 Solution

It works like the Spring 3.2 solution, but in Spring 4.0 the @AuthenticationPrincipal and AuthenticationPrincipalArgumentResolver was "moved" to an other package:

(But the old classes in its old packges still exists, so do not mix them!)

It is just writing

import org.springframework.security.core.annotation.AuthenticationPrincipal;
ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
    ...
}

To get this working you need to register the (org.springframework.security.web.method.annotation.) AuthenticationPrincipalArgumentResolver : either by "activating" @EnableWebMvcSecurity or by registering this bean within mvc:argument-resolvers - the same way I described it with may Spring 3.1 solution above.

<mvc:annotation-driven>
    <mvc:argument-resolvers>
        <bean class="org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver" />
    </mvc:argument-resolvers>
</mvc:annotation-driven>

@See Spring Security 5.0 Reference, Chapter 39.3 @AuthenticationPrincipal

How do I "decompile" Java class files?

JD-GUI is really good. You could just open a JAR file and browse through the code as if you are working on an IDE. Good stuff.

How to increase timeout for a single test case in mocha

If you are using in NodeJS then you can set timeout in package.json

"test": "mocha --timeout 10000"

then you can run using npm like:

npm test

Merge two array of objects based on a key

Non of these solutions worked for my case:

  • missing objects can exist in either array
  • runtime complexity of O(n)

notes:

  • I used lodash but it's easy to replace with something else
  • Also used Typescript (just remove/ignore the types)
import { keyBy, values } from 'lodash';

interface IStringTMap<T> {
  [key: string]: T;
}

type IIdentified = {
  id?: string | number;
};

export function mergeArrayById<T extends IIdentified>(
  array1: T[],
  array2: T[]
): T[] {
  const mergedObjectMap: IStringTMap<T> = keyBy(array1, 'id');

  const finalArray: T[] = [];

  for (const object of array2) {
    if (object.id && mergedObjectMap[object.id]) {
      mergedObjectMap[object.id] = {
        ...mergedObjectMap[object.id],
        ...object,
      };
    } else {
      finalArray.push(object);
    }
  }

  values(mergedObjectMap).forEach(object => {
    finalArray.push(object);
  });

  return finalArray;
}

How to get the day name from a selected date?

I use this Extension Method:

public static string GetDayName(this DateTime date)
{
    string _ret = string.Empty; //Only for .NET Framework 4++
    var culture = new System.Globalization.CultureInfo("es-419"); //<- 'es-419' = Spanish (Latin America), 'en-US' = English (United States)
    _ret = culture.DateTimeFormat.GetDayName(date.DayOfWeek); //<- Get the Name     
    _ret = culture.TextInfo.ToTitleCase(_ret.ToLower()); //<- Convert to Capital title
    return _ret;
}

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player); is passing a type as parameter. That's illegal, you need to pass an object.

For example, something like:

player p;
showInventory(p);  

I'm guessing you have something like this:

int main()
{
   player player;
   toDo();
}

which is awful. First, don't name the object the same as your type. Second, in order for the object to be visible inside the function, you'll need to pass it as parameter:

int main()
{
   player p;
   toDo(p);
}

and

std::string toDo(player& p) 
{
    //....
    showInventory(p);
    //....
}

How can I delete a query string parameter in JavaScript?

All of the responses on this thread have a flaw in that they do not preserve anchor/fragment parts of URLs.

So if your URL looks like:

http://dns-entry/path?parameter=value#fragment-text

and you replace 'parameter'

you will lose your fragment text.

The following is adaption of previous answers (bobince via LukePH) that addresses this problem:

function removeParameter(url, parameter)
{
  var fragment = url.split('#');
  var urlparts= fragment[0].split('?');

  if (urlparts.length>=2)
  {
    var urlBase=urlparts.shift(); //get first part, and remove from array
    var queryString=urlparts.join("?"); //join it back up

    var prefix = encodeURIComponent(parameter)+'=';
    var pars = queryString.split(/[&;]/g);
    for (var i= pars.length; i-->0;) {               //reverse iteration as may be destructive
      if (pars[i].lastIndexOf(prefix, 0)!==-1) {   //idiom for string.startsWith
        pars.splice(i, 1);
      }
    }
    url = urlBase + (pars.length > 0 ? '?' + pars.join('&') : '');
    if (fragment[1]) {
      url += "#" + fragment[1];
    }
  }
  return url;
}

MySQL - UPDATE query with LIMIT

UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 LIMIT 1001, 1000

This query is not correct (or at least i don't know a possible way to use limit in UPDATE queries), you should put a where condition on you primary key (this assumes you have an auto_increment column as your primary key, if not provide more details):

UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE primary_key BETWEEN 1001 AND 2000

For the second query you must use IS

UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE panel_id is null

EDIT - if your primary_key is a column named MAX+1 you query should be (with backticks as stated correctly in the comment):

UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE `MAX+1` BETWEEN 1001 AND 2000

To update the rows with MAX+1 from 1001 TO 2000 (including 1001 and 2000)

How do I configure Notepad++ to use spaces instead of tabs?

Go to the Preferences menu command under menu Settings, and select Language Menu/Tab Settings, depending on your version. Earlier versions use Tab Settings. Later versions use Language. Click the Replace with space check box. Set the size to 4.

Enter image description here

See documentation: http://docs.notepad-plus-plus.org/index.php/Built-in_Languages#Tab_settings

How can I check if a key exists in a dictionary?

if key in array:
  # do something

Associative arrays are called dictionaries in Python and you can learn more about them in the stdtypes documentation.

How to delete a whole folder and content?

The fastest and easiest way:

public static boolean deleteFolder(File removableFolder) {
        File[] files = removableFolder.listFiles();
        if (files != null && files.length > 0) {
            for (File file : files) {
                boolean success;
                if (file.isDirectory())
                    success = deleteFolder(file);
                else success = file.delete();
                if (!success) return false;
            }
        }
        return removableFolder.delete();
}

Given a filesystem path, is there a shorter way to extract the filename without its extension?

Try this:

string fileName = Path.GetFileNameWithoutExtension(@"C:\Program Files\hello.txt");

This will return "hello" for fileName.

How to order results with findBy() in Doctrine

$ens = $em->getRepository('AcmeBinBundle:Marks')
              ->findBy(
                 array(), 
                 array('id' => 'ASC')
               );

Python string.replace regular expression

re.sub is definitely what you are looking for. And so you know, you don't need the anchors and the wildcards.

re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line)

will do the same thing--matching the first substring that looks like "interfaceOpDataFile" and replacing it.

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

accessing a variable from another class

You could make the variables public fields:

  public int width;
  public int height;

  DrawFrame() {
    this.width = 400;
    this.height = 400;
  }

You could then access the variables like so:

DrawFrame frame = new DrawFrame();
int theWidth = frame.width;
int theHeight = frame.height;

A better solution, however, would be to make the variables private fields add two accessor methods to your class, keeping the data in the DrawFrame class encapsulated:

 private int width;
 private int height;

 DrawFrame() {
    this.width = 400;
    this.height = 400;
 }

  public int getWidth() {
     return this.width;
  }

  public int getHeight() {
     return this.height;
  }

Then you can get the width/height like so:

  DrawFrame frame = new DrawFrame();
  int theWidth = frame.getWidth();
  int theHeight = frame.getHeight();

I strongly suggest you use the latter method.

How do I use NSTimer?

Firstly I'd like to draw your attention to the Cocoa/CF documentation (which is always a great first port of call). The Apple docs have a section at the top of each reference article called "Companion Guides", which lists guides for the topic being documented (if any exist). For example, with NSTimer, the documentation lists two companion guides:

For your situation, the Timer Programming Topics article is likely to be the most useful, whilst threading topics are related but not the most directly related to the class being documented. If you take a look at the Timer Programming Topics article, it's divided into two parts:

  • Timers
  • Using Timers

For articles that take this format, there is often an overview of the class and what it's used for, and then some sample code on how to use it, in this case in the "Using Timers" section. There are sections on "Creating and Scheduling a Timer", "Stopping a Timer" and "Memory Management". From the article, creating a scheduled, non-repeating timer can be done something like this:

[NSTimer scheduledTimerWithTimeInterval:2.0
    target:self
    selector:@selector(targetMethod:)
    userInfo:nil
    repeats:NO];

This will create a timer that is fired after 2.0 seconds and calls targetMethod: on self with one argument, which is a pointer to the NSTimer instance.

If you then want to look in more detail at the method you can refer back to the docs for more information, but there is explanation around the code too.

If you want to stop a timer that is one which repeats, (or stop a non-repeating timer before it fires) then you need to keep a pointer to the NSTimer instance that was created; often this will need to be an instance variable so that you can refer to it in another method. You can then call invalidate on the NSTimer instance:

[myTimer invalidate];
myTimer = nil;

It's also good practice to nil out the instance variable (for example if your method that invalidates the timer is called more than once and the instance variable hasn't been set to nil and the NSTimer instance has been deallocated, it will throw an exception).

Note also the point on Memory Management at the bottom of the article:

Because the run loop maintains the timer, from the perspective of memory management there's typically no need to keep a reference to a timer after you’ve scheduled it. Since the timer is passed as an argument when you specify its method as a selector, you can invalidate a repeating timer when appropriate within that method. In many situations, however, you also want the option of invalidating the timer—perhaps even before it starts. In this case, you do need to keep a reference to the timer, so that you can send it an invalidate message whenever appropriate. If you create an unscheduled timer (see “Unscheduled Timers”), then you must maintain a strong reference to the timer (in a reference-counted environment, you retain it) so that it is not deallocated before you use it.

read file in classpath

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class readFile {
    /**
     * feel free to make any modification I have have been here so I feel you
     * 
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        File dir = new File(".");// read file from same directory as source //
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                // if you wanna read file name with txt files
                if (file.getName().contains("txt")) {
                    System.out.println(file.getName());
                }

                // if you want to open text file and read each line then
                if (file.getName().contains("txt")) {
                    try {
                        // FileReader reads text files in the default encoding.
                        FileReader fileReader = new FileReader(
                                file.getAbsolutePath());
                        // Always wrap FileReader in BufferedReader.
                        BufferedReader bufferedReader = new BufferedReader(
                                fileReader);
                        String line;
                        // get file details and get info you need.
                        while ((line = bufferedReader.readLine()) != null) {
                            System.out.println(line);
                            // here you can say...
                            // System.out.println(line.substring(0, 10)); this
                            // prints from 0 to 10 indext
                        }
                    } catch (FileNotFoundException ex) {
                        System.out.println("Unable to open file '"
                                + file.getName() + "'");
                    } catch (IOException ex) {
                        System.out.println("Error reading file '"
                                + file.getName() + "'");
                        // Or we could just do this:
                        ex.printStackTrace();
                    }
                }
            }
        }

    }`enter code here`

}

Removing highcharts.com credits link

Add this to your css.

.highcharts-credits {
display: none !important;
}

Why does "pip install" inside Python raise a SyntaxError?

If you are doing it from command line,

try -

python -m pip install selenium

or (for Python3 and above)

python3 -m pip install selenium

Practical uses of git reset --soft?

You can use git reset --soft to change the version you want to have as parent for the changes you have in your index and working tree. The cases where this is useful are rare. Sometimes you might decide that the changes you have in your working tree should belong onto a different branch. Or you can use this as a simple way to collapse several commits into one (similar to squash/fold).

See this answer by VonC for a practical example: Squash the first two commits in Git?

Is it possible to insert HTML content in XML document?

You can include HTML content. One possibility is encoding it in BASE64 as you have mentioned.

Another might be using CDATA tags.

Example using CDATA:

<xml>
    <title>Your HTML title</title>
    <htmlData><![CDATA[<html>
        <head>
            <script/>
        </head>
        <body>
        Your HTML's body
        </body>
        </html>
     ]]>
    </htmlData>
</xml>

Please note:

CDATA's opening character sequence: <![CDATA[

CDATA's closing character sequence: ]]>

How to switch text case in visual studio code

I've written a Visual Studio Code extension for changing case (not only upper case, many other options): https://github.com/wmaurer/vscode-change-case

To map the upper case command to a keybinding (e.g. Ctrl+T U), click File -> Preferences -> Keyboard shortcuts, and insert the following into the json config:

{
  "key": "ctrl+t u",
  "command": "extension.changeCase.upper",
  "when": "editorTextFocus"
}




EDIT:

With the November 2016 (release notes) update of VSCode, there is built-in support for converting to upper case and lower case via the commands editor.action.transformToUppercase and editor.action.transformToLowercase. These don't have default keybindings.

The change-case extension is still useful for other text transformations, e.g. camelCase, PascalCase, snake-case, etc.

How to load CSS Asynchronously

2020 Update


The simple answer (full browser support):

<link rel="stylesheet" href="style.css" media="print" onload="this.media='all'">

The documented answer (with optional preloading and script-disabled fallback):

 <!-- Optional, if we want the stylesheet to get preloaded. Note that this line causes stylesheet to get downloaded, but not applied to the page. Use strategically — while preloading will push this resource up the priority list, it may cause more important resources to be pushed down the priority list. This may not be the desired effect for non-critical CSS, depending on other resources your app needs. -->
 <link rel="preload" href="style.css" as="style">

 <!-- Media type (print) doesn't match the current environment, so browser decides it's not that important and loads the stylesheet asynchronously (without delaying page rendering). On load, we change media type so that the stylesheet gets applied to screens. -->
 <link rel="stylesheet" href="style.css" media="print" onload="this.media='all'">

 <!-- Fallback that only gets inserted when JavaScript is disabled, in which case we can't load CSS asynchronously. -->
 <noscript><link rel="stylesheet" href="style.css"></noscript>

Preloading and async combined:

If you need preloaded and async CSS, this solution simply combines two lines from the documented answer above, making it slightly cleaner. But this won't work in Firefox until they support the preload keyword. And again, as detailed in the documented answer above, preloading may not actually be beneficial.

<link href="style.css" rel="preload" as="style" onload="this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="style.css"></noscript>

Additional considerations:

Note that, in general, if you're going to load CSS asynchronously, it's generally recommended that you inline critical CSS, since CSS is a render-blocking resource for a reason.

Credit to filament group for their many async CSS solutions.

Best way to format if statement with multiple conditions

When condition is really complex I use the following style (PHP real life example):

if( $format_bool &&
    (
        ( isset( $column_info['native_type'] )
            && stripos( $column_info['native_type'], 'bool' ) !== false
        )
        || ( isset( $column_info['driver:decl_type'] )
            && stripos( $column_info['driver:decl_type'], 'bool' ) !== false
        )
        || ( isset( $column_info['pdo_type'] )
            && $column_info['pdo_type'] == PDO::PARAM_BOOL
        )
    )
)

I believe it's more nice and readable than nesting multiple levels of if(). And in some cases like this you simply can't break complex condition into pieces because otherwise you would have to repeat the same statements in if() {...} block many times.

I also believe that adding some "air" into code is always a good idea. It improves readability greatly.

ASP.NET MVC on IIS 7.5

Please note for Windows 8 users you need to add/remove windows components and remove the version of .net reboot then re-install in order to register it with IIS. I presume this happens if you get .net 4.5 from visual studio and install IIS afterwards.

How to print bytes in hexadecimal using System.out.println?

System.out.println(Integer.toHexString(test[0]));

OR (pretty print)

System.out.printf("0x%02X", test[0]);

OR (pretty print)

System.out.println(String.format("0x%02X", test[0]));

How to set String's font size, style in Java using the Font class?

Look here http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#deriveFont%28float%29

JComponent has a setFont() method. You will control the font there, not on the String.

Such as

JButton b = new JButton();
b.setFont(b.getFont().deriveFont(18.0f));

Create a directly-executable cross-platform GUI app using Python

For the GUI itself:

PyQT is pretty much the reference.

Another way to develop a rapid user interface is to write a web app, have it run locally and display the app in the browser.

Plus, if you go for the Tkinter option suggested by lubos hasko you may want to try portablepy to have your app run on Windows environment without Python.

What is the point of the diamond operator (<>) in Java 7?

This line causes the [unchecked] warning:

List<String> list = new LinkedList();

So, the question transforms: why [unchecked] warning is not suppressed automatically only for the case when new collection is created?

I think, it would be much more difficult task then adding <> feature.

UPD: I also think that there would be a mess if it were legally to use raw types 'just for a few things'.

Subtract a value from every number in a list in Python?

To clarify an already posted solution due to questions in the comments

import numpy

array = numpy.array([49, 51, 53, 56])
array = array - 13

will output:

array([36, 38, 40, 43])

How to get current timestamp in milliseconds since 1970 just the way Java gets

Since C++11 you can use std::chrono:

  • get current system time: std::chrono::system_clock::now()
  • get time since epoch: .time_since_epoch()
  • translate the underlying unit to milliseconds: duration_cast<milliseconds>(d)
  • translate std::chrono::milliseconds to integer (uint64_t to avoid overflow)
#include <chrono>
#include <cstdint>
#include <iostream>

uint64_t timeSinceEpochMillisec() {
  using namespace std::chrono;
  return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
}

int main() {
  std::cout << timeSinceEpochMillisec() << std::endl;
  return 0;
}

How can I center <ul> <li> into div

Here is the solution I could find:

#wrapper {
  float:right;
  position:relative;
  left:-50%;
  text-align:left;
}
#wrapper ul {
  list-style:none;
  position:relative;
  left:50%;
}

#wrapper li{
  float:left;
  position:relative;
}

compare two files in UNIX

Well, you can just sort the files first, and diff the sorted files.

sort file1 > file1.sorted
sort file2 > file2.sorted
diff file1.sorted file2.sorted

You can also filter the output to report lines in file2 which are absent from file1:

diff -u file1.sorted file2.sorted | grep "^+" 

As indicated in comments, you in fact do not need to sort the files. Instead, you can use a process substitution and say:

diff <(sort file1) <(sort file2)

Set opacity of background image without affecting child elements

I found a pretty good and simple tutorial about this issue. I think it works great (and though it supports IE, I just tell my clients to use other browsers):

CSS background transparency without affecting child elements, through RGBa and filters

From there you can add gradient support, etc.

Least common multiple for 3 or more numbers

If there's no time-constraint, this is fairly simple and straight-forward:

def lcm(a,b,c):
    for i in range(max(a,b,c), (a*b*c)+1, max(a,b,c)):
        if i%a == 0 and i%b == 0 and i%c == 0:
            return i

Sorting an Array of int using BubbleSort

public static void BubbleSort(int[] array){
        boolean swapped ;
        do {
            swapped = false;
            for (int i = 0; i < array.length - 1; i++) {
                if (array[i] > array[i + 1]) {
                    int temp = array[i];
                    array[i] = array[i + 1];
                    array[i + 1] = temp;
                    swapped = true;
                }
            }
        }while (swapped);
    }

Does Index of Array Exist

You can use LINQ to achieve that too:

var exists = array.ElementAtOrDefault(index) != null;

How to reshape data from long to wide format

much easier way!

devtools::install_github("yikeshu0611/onetree") #install onetree package

library(onetree)
widedata=reshape_toWide(data = dat1,id = "name",j = "numbers",value.var.prefix = "value")
widedata

        name     value1     value2     value3     value4
   firstName  0.3407997 -0.7033403 -0.3795377 -0.7460474
  secondName -0.8981073 -0.3347941 -0.5013782 -0.1745357

if you want to go back from wide to long, only change Wide to Long, and no changes in objects.

reshape_toLong(data = widedata,id = "name",j = "numbers",value.var.prefix = "value")

        name numbers      value
   firstName       1  0.3407997
  secondName       1 -0.8981073
   firstName       2 -0.7033403
  secondName       2 -0.3347941
   firstName       3 -0.3795377
  secondName       3 -0.5013782
   firstName       4 -0.7460474
  secondName       4 -0.1745357

How to get the mobile number of current sim card in real device?

I have to make an application which shows the Contact no of the SIM card that is being used in the cell. For that I need to use Telephony Manager class. Can i get details on its usage?

Yes, You have to use Telephony Manager;If at all you not found the contact no. of user; You can get Sim Serial Number of Sim Card and Imei No. of Android Device by using the same Telephony Manager Class...

Add permission:

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

Import:

import android.telephony.TelephonyManager;

Use the below code:

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

         // get IMEI
         imei = tm.getDeviceId();

         // get SimSerialNumber
         simSerialNumber = tm.getSimSerialNumber();

How do I connect C# with Postgres?

If you want an recent copy of npgsql, then go here

http://www.npgsql.org/

This can be installed via package manager console as

PM> Install-Package Npgsql

How to determine MIME type of file in android?

The above solution returned null in case of .rar file, using URLConnection.guessContentTypeFromName(url) worked in this case.

How to generate a QR Code for an Android application?

zxing does not (only) provide a web API; really, that is Google providing the API, from source code that was later open-sourced in the project.

As Rob says here you can use the Java source code for the QR code encoder to create a raw barcode and then render it as a Bitmap.

I can offer an easier way still. You can call Barcode Scanner by Intent to encode a barcode. You need just a few lines of code, and two classes from the project, under android-integration. The main one is IntentIntegrator. Just call shareText().

Express: How to pass app-instance to routes from a different file?

If you want to pass an app-instance to others in Node-Typescript :

Option 1: With the help of import (when importing)

//routes.ts
import { Application } from "express";
import { categoryRoute } from './routes/admin/category.route'
import { courseRoute } from './routes/admin/course.route';

const routing = (app: Application) => {
    app.use('/api/admin/category', categoryRoute)
    app.use('/api/admin/course', courseRoute)
}
export { routing }

Then import it and pass app:

import express, { Application } from 'express';

const app: Application = express();
import('./routes').then(m => m.routing(app))

Option 2: With the help of class

// index.ts
import express, { Application } from 'express';
import { Routes } from './routes';


const app: Application = express();
const rotues = new Routes(app)
...

Here we will access the app in the constructor of Routes Class

// routes.ts
import { Application } from 'express'
import { categoryRoute } from '../routes/admin/category.route'
import { courseRoute } from '../routes/admin/course.route';

class Routes {
    constructor(private app: Application) {
        this.apply();
    }

    private apply(): void {
       this.app.use('/api/admin/category', categoryRoute)
       this.app.use('/api/admin/course', courseRoute)
    }
}

export { Routes }

TypeError: not all arguments converted during string formatting python

In python 3.7 and above there is a new and easy way. here is the syntax:

name = "Eric"
age = 74
f"Hello, {name}. You are {age}."

OutPut:

Hello, Eric. You are 74.

Convert DataTable to IEnumerable<T>

Universal extension method for DataTable. May be somebody be interesting. Idea creating dynamic properties I take from another post: https://stackoverflow.com/a/15819760/8105226

    public static IEnumerable<dynamic> AsEnumerable(this DataTable dt)
    {
        List<dynamic> result = new List<dynamic>();
        Dictionary<string, object> d;
        foreach (DataRow dr in dt.Rows)
        {
            d = new Dictionary<string, object>();

            foreach (DataColumn dc in dt.Columns)
                d.Add(dc.ColumnName, dr[dc]);

            result.Add(GetDynamicObject(d));
        }
        return result.AsEnumerable<dynamic>();
    }

    public static dynamic GetDynamicObject(Dictionary<string, object> properties)
    {
        return new MyDynObject(properties);
    }

    public sealed class MyDynObject : DynamicObject
    {
        private readonly Dictionary<string, object> _properties;

        public MyDynObject(Dictionary<string, object> properties)
        {
            _properties = properties;
        }

        public override IEnumerable<string> GetDynamicMemberNames()
        {
            return _properties.Keys;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (_properties.ContainsKey(binder.Name))
            {
                result = _properties[binder.Name];
                return true;
            }
            else
            {
                result = null;
                return false;
            }
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (_properties.ContainsKey(binder.Name))
            {
                _properties[binder.Name] = value;
                return true;
            }
            else
            {
                return false;
            }
        }
    }

changing minDate option in JQuery DatePicker not working

Change the minDate dynamically

.datepicker("destroy")

For example

<script>
    $(function() {
      $( "#datepicker" ).datepicker("destroy");
      $( "#datepicker" ).datepicker();
    });
  </script>

  <p>Date: <input type="text" id="datepicker" /></p>

Python: How to create a unique file name?

This can be done using the unique function in ufp.path module.

import ufp.path
ufp.path.unique('./test.ext')

if current path exists 'test.ext' file. ufp.path.unique function return './test (d1).ext'.

How do I get cURL to not show the progress bar?

In curl version 7.22.0 on Ubuntu and 7.24.0 on OSX the solution to not show progress but to show errors is to use both -s (--silent) and -S (--show-error) like so:

curl -sS http://google.com > temp.html

This works for both redirected output > /some/file, piped output | less and outputting directly to the terminal for me.

Update: Since curl 7.67.0 there is a new option --no-progress-meter which does precisely this and nothing else, see clonejo's answer for more details.

Switch android x86 screen resolution

OK, maybe there are more like me that do not have any UVESA_MODE or S3 references in their menu.lst. First, do "VBoxManage setextradata "VM_NAME_HERE" "CustomVideoMode1" "320x480x32"" procedure through terminal. My custom videomode was "1920x1089x32"... (sorry, I use Linux, so procedure works on linux) for Windows, just add .exe to VBoxManage.. Look in the first entry as described before, this is the menu entry you would normally boot. I normally use nano as it works more easy for me. And nano happens to be present in Android >6 too. (other version not tried)

Procedure:

  • Boot VM, chose the "debug mode" option to boot. Pressing "enter" after a while will result in the prompt
  • Change directory to /mnt/grub "cd /mnt/grub"
  • list directory content with "ls" (not necessary but I like to see where I am)
  • copy menu.lst (make this standard procedure before changing anything) "cp menu.lst menu.lst.bak" (or whatever extension you like to use for backup)
  • open menu.lst, e.g.: "nano menu.lst".
  • look in first menu entry (normally there are 4, starting with the titles you see in the boot menu) the "kernel" entry, which ends with the word "quiet"
  • replace "quiet" with something like "vga=ask" if you would like to be asked every time at boot for the screen resolution, or "vga=(HEX value)" as seen in surlac's anwer.
  • exit and save, don't forget to actually save it! double check this. (ctrl+X, YES, Enter for nano)
  • reboot VM with "YOUR HOST KEY" + "R" (normally "right control" + "R")

Hope this helps anyone as it did solve my problem.

edit: I see that I did place this article in the wrong place, since the original question is about another Android version. Does anyone know how to move it to an appropriate location?

How to Sort a List<T> by a property in the object

Here is a generic LINQ extension method that does not create an extra copy of the list:

public static void Sort<T,U>(this List<T> list, Func<T, U> expression)
    where U : IComparable<U>
{
    list.Sort((x, y) => expression.Invoke(x).CompareTo(expression.Invoke(y)));
}

To use it:

myList.Sort(x=> x.myProperty);

I recently built this additional one which accepts an ICompare<U>, so that you can customize the comparison. This came in handy when I needed to do a Natural string sort:

public static void Sort<T, U>(this List<T> list, Func<T, U> expression, IComparer<U> comparer)
    where U : IComparable<U>
{    
    list.Sort((x, y) => comparer.Compare(expression.Invoke(x), expression.Invoke(y)));
}

Create Django model or update if exists

If you're looking for "update if exists else create" use case, please refer to @Zags excellent answer


Django already has a get_or_create, https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create

For you it could be :

id = 'some identifier'
person, created = Person.objects.get_or_create(identifier=id)

if created:
   # means you have created a new person
else:
   # person just refers to the existing one

`&mdash;` or `&#8212;` is there any difference in HTML output?

&mdash; :: &#8212; :: \u2014

When representing the m-dash in a JavaScript text string for output to HTML, note that it will be represented by its unicode value. There are cases when ampersand characters ('&') will not be resolved—notably certain contexts within JSX. In this case, neither &mdash; nor &#8212; will work. Instead you need to use the Unicode escape sequence: \u2014.

For example, when implementing a render() method to output text from a JavaScript variable:

render() {
   let text='JSX transcoders will preserve the & character&mdash;to ' 
            + 'protect from possible script hacking and cross-site hacks.'
   return (
     <div>{text}</div>
   )
}

This will output:

<div>JSX transcoders will preserve the & character&mdash;to protect from possible script hacking and cross-site hacks.</div>

Instead of the &– prefixed representation, you should use \u2014:

let text='JSX transcoders will preserve the & character\u2014to …'

OnItemClickListener using ArrayAdapter for ListView

i'm using arrayadpter ,using this follwed code i'm able to get items

String value = (String)adapter.getItemAtPosition(position);

listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
             String string=adapter.getItem(position);
             Log.d("**********", string);

        }
    });

Using Chrome's Element Inspector in Print Preview Mode?

As of Chrome 48+, you can access the print preview via the following steps:

  1. Open dev tools – Ctrl/Cmd + Shift + I or right click on the page and choose 'Inspect'.

  2. Hit Esc to open the additional drawer.

  3. If 'Rendering' isn't already being show, click the 3 dot kebab and choose 'rendering'.

  4. Check the 'Emulate print media' checkbox.

From there Chrome will show you a print version of your page and you can inspect element and troubleshoot like you would the browser version.

Image of Chrome 49+ Print Preview option in Dev Tools

Multiple HttpPost method in Web API controller

public class Journal : ApiController
{
    public MyResult Get(journal id)
    {
        return null;
    }
}

public class Journal : ApiController
{

    public MyResult Get(journal id, publication id)
    {
        return null;
    }
}

I am not sure whether overloading get/post method violates the concept of restfull api,but it workds. If anyone could've enlighten on this matter. What if I have a uri as

uri:/api/journal/journalid
uri:/api/journal/journalid/publicationid

so as you might seen my journal sort of aggregateroot, though i can define another controller for publication solely and pass id number of publication in my url however this gives much more sense. since my publication would not exist without journal itself.

Insert data into hive table

If table is without partition then code will be,

Insert into table table_name select col_a,col_b,col_c from another_table(source table)

--here any condition can be applied such as limit, group by, order by etc...

If table is with partitions then code will be,

set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;

insert into table table_name partition(partition_col1, paritition_col2) select col_a,col_b,col_c,partition_col1,partition_col2 from another_table(source table)

--here any condition can be applied such as limit, group by, order by etc...

Regex AND operator

Maybe you are looking for something like this. If you want to select the complete line when it contains both "foo" and "baz" at the same time, this RegEx will comply that:

.*(foo)+.*(baz)+|.*(baz)+.*(foo)+.*

Loop through each cell in a range of cells when given a Range object

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCell In rRng.Cells
        Debug.Print rCell.Address, rCell.Value
    Next rCell

End Sub

Processing Symbol Files in Xcode

It compares crash logs retrieved from the device to archived (symbolized to be correct) version of your applications to try to retrieved where on your code the crash occurred.

Look at xcode symbol file location for details

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

Another neat option is to use the Directive as an element and not as an attribute.

@Directive({
   selector: 'app-directive'
})
export class InformativeDirective implements AfterViewInit {

    @Input()
    public first: string;

    @Input()
    public second: string;

    ngAfterViewInit(): void {
       console.log(`Values: ${this.first}, ${this.second}`);
    }
}

And this directive can be used like that:

<app-someKindOfComponent>
    <app-directive [first]="'first 1'" [second]="'second 1'">A</app-directive>
    <app-directive [first]="'First 2'" [second]="'second 2'">B</app-directive>
    <app-directive [first]="'First 3'" [second]="'second 3'">C</app-directive>
</app-someKindOfComponent>`

Simple, neat and powerful.

Sort dataGridView columns in C# ? (Windows Form)

There's a method on the DataGridView called "Sort":

this.dataGridView1.Sort(this.dataGridView1.Columns["Name"], ListSortDirection.Ascending);

This will programmatically sort your datagridview.

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

The menu location seems to have changed to:

Query Designer --> Pane --> SQL

Reading JSON POST using PHP

you can put your json in a parameter and send it instead of put only your json in header:

$post_string= 'json_param=' . json_encode($data);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');  // Set the url path we want to call

//execute post
$result = curl_exec($curl);

//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);

on the service side you can get your json string as a parameter:

$json_string = $_POST['json_param'];
$obj = json_decode($json_string);

then you can use your converted data as object.

How to solve javax.net.ssl.SSLHandshakeException Error?

First, you need to obtain the public certificate from the server you're trying to connect to. That can be done in a variety of ways, such as contacting the server admin and asking for it, using OpenSSL to download it, or, since this appears to be an HTTP server, connecting to it with any browser, viewing the page's security info, and saving a copy of the certificate. (Google should be able to tell you exactly what to do for your specific browser.)

Now that you have the certificate saved in a file, you need to add it to your JVM's trust store. At $JAVA_HOME/jre/lib/security/ for JREs or $JAVA_HOME/lib/security for JDKs, there's a file named cacerts, which comes with Java and contains the public certificates of the well-known Certifying Authorities. To import the new cert, run keytool as a user who has permission to write to cacerts:

keytool -import -file <the cert file> -alias <some meaningful name> -keystore <path to cacerts file>

It will most likely ask you for a password. The default password as shipped with Java is changeit. Almost nobody changes it. After you complete these relatively simple steps, you'll be communicating securely and with the assurance that you're talking to the right server and only the right server (as long as they don't lose their private key).

Can we make unsigned byte in Java

I am trying to use this data as a parameter to a function of Java that accepts only a byte as parameter

This is not substantially different from a function accepting an integer to which you want to pass a value larger than 2^32-1.

That sounds like it depends on how the function is defined and documented; I can see three possibilities:

  1. It may explicitly document that the function treats the byte as an unsigned value, in which case the function probably should do what you expect but would seem to be implemented wrong. For the integer case, the function would probably declare the parameter as an unsigned integer, but that is not possible for the byte case.

  2. It may document that the value for this argument must be greater than (or perhaps equal to) zero, in which case you are misusing the function (passing an out-of-range parameter), expecting it to do more than it was designed to do. With some level of debugging support you might expect the function to throw an exception or fail an assertion.

  3. The documentation may say nothing, in which case a negative parameter is, well, a negative parameter and whether that has any meaning depends on what the function does. If this is meaningless then perhaps the function should really be defined/documented as (2). If this is meaningful in an nonobvious manner (e.g. non-negative values are used to index into an array, and negative values are used to index back from the end of the array so -1 means the last element) the documentation should say what it means and I would expect that it isn't what you want it to do anyway.

What is the difference between public, protected, package-private and private in Java?

Private: Limited access to class only

Default (no modifier): Limited access to class and package

Protected: Limited access to class, package and subclasses (both inside and outside package)

Public: Accessible to class, package (all), and subclasses... In short, everywhere.

How do I do top 1 in Oracle?

select * from (
    select FName from MyTbl
)
where rownum <= 1;

How do I add to the Windows PATH variable using setx? Having weird problems

Run cmd as administrator, then:

setx /M PATH "%PATH%;<your-new-path>"

The /M option sets the variable at SYSTEM scope. The default behaviour is to set it for the USER.

TL;DR

The truncation issue happens because when you echo %PATH% it will show the concatenation of SYSTEM and USER values. So when you add it in your second argument to setx, it will be fitting SYSTEM and USER values inside the USER var. When you echo again, things will be doubled.

Additionally, the /M option requires administrator privilege, so you need to open your terminal with "run as administrator", otherwise setx will complain with "access to registry path is denied".

Last thing to note: You won't see the new value when you echo %PATH% just after setting it this way, you need to close cmd and open again.

If you want to check the actual values stored in registry check this question.

Adding an item to an associative array

You can simply do this

$data += array($category => $question);

If your're running on php 5.4+

$data += [$category => $question];

How to change date format using jQuery?

You don't need any date-specific functions for this, it's just string manipulation:

var parts = fecha2.value.split('-');
var newdate = parts[1]+'-'+parts[2]+'-'+(parseInt(parts[0], 10)%100);

Resource files not found from JUnit test cases

The test Resource files(src/test/resources) are loaded to target/test-classes sub folder. So we can use the below code to load the test resource files.

String resource = "sample.txt";
File file = new File(getClass().getClassLoader().getResource(resource).getFile());

System.out.println(file.getAbsolutePath());

Note : Here the sample.txt file should be placed under src/test/resources folder.

For more details refer options_to_load_test_resources

Add a Progress Bar in WebView

You can try this code into your activity

    private void startWebView(WebView webView,String url) {
 webView.setWebViewClient(new WebViewClient() {
            ProgressDialog progressDialog;

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return false;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            public void onLoadResource (WebView view, String url) {

                    if (progressDialog == null) {
                        progressDialog = new ProgressDialog(SponceredDetailsActivity.this);
                        progressDialog.setMessage("Loading...");
                        progressDialog.show();
                    }

            }
            public void onPageFinished(WebView view, String url) {
                try{
                    if (progressDialog.isShowing()) {
                        progressDialog.dismiss();
                        progressDialog = null;
                    }

                }catch(Exception exception){
                    exception.printStackTrace();
                }
            }

        });

        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl(url);
    }

Call this method using this way:

startWebView(web_view,"Your Url");

Sometimes if URL is dead it will redirected and it will come to onLoadResource() before onPageFinished method. For this reason progress bar will not dismis. To solve this issue see my this Answer.

Thanks :)

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

In my case: Xcode 12

I set empty values on EXCLUDED_ARCHS and set ONLY_ACTIVE_ARCH Debug = YES Release = NO Project's Build Setting

and I included this in my Podfile:

post_install do |installer|
    installer.pods_project.targets.each do |target|
        target.build_configurations.each do |config|
            config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
        end
    end
end

It runs on my Simulator iPhone 8 (iOS 12) and iPhone 11 Pro Max (iOS 14) and on my device iPhone 7 Plus (iOS 13.4)

Action bar navigation modes are deprecated in Android L

I found these tutorials helpful while putting together an action bar (now the 'tool bar' - argh) that supports sliding tabs with Material Design:

https://www.youtube.com/watch?v=Fl0xMuo10yA

http://www.exoguru.com/android/material-design/navigation/android-sliding-tabs-with-material-design.html

You sort of have to synthesize these resources to match your particular situation. For example, you may not want to manually create the tabs in the same style that the exoguru.com tutorial did.

How to randomize Excel rows

Perhaps the whole column full of random numbers is not the best way to do it, but it seems like probably the most practical as @mariusnn mentioned.

On that note, this stomped me for a while with Office 2010, and while generally answers like the one in lifehacker work,I just wanted to share an extra step required for the numbers to be unique:

  1. Create a new column next to the list that you're going to randomize
  2. Type in =rand() in the first cell of the new column - this will generate a random number between 0 and 1
  3. Fill the column with that formula. The easiest way to do this may be to:

    • go down along the new column up until the last cell that you want to randomize
    • hold down Shift and click on the last cell
    • press Ctrl+D
  4. Now you should have a column of identical numbers, even though they are all generated randomly.

    Random numbers... that are the same...

    The trick here is to recalculate them! Go to the Formulas tab and then click on Calculate Now (or press F9).

    Actually random numbers!

    Now all the numbers in the column will be actually generated randomly.

  5. Go to the Home tab and click on Sort & Filter. Choose whichever order you want (Smallest to Largest or Largest to Smallest) - whichever one will give you a random order with respect to the original order. Then click OK when the Sort Warning prompts you to Expand the selection.

  6. Your list should be randomized now! You can get rid of the column of random numbers if you want.

Getting values from JSON using Python

There's a Py library that has a module that facilitates access to Json-like dictionary key-values as attributes: https://github.com/asuiu/pyxtension You can use it as:

j = Json('{"lat":444, "lon":555}')
j.lat + ' ' + j.lon

how to check if a datareader is null or empty

I also experiencing this kind of problem but mine, i'm using DbDataReader as my generic reader (for SQL, Oracle, OleDb, etc.). If using DataTable, DataTable has this method:

DataTable dt = new DataTable();
dt.Rows[0].Table.Columns.Contains("SampleColumn");

using this I can determine if that column is existing in the result set that my query has. I'm also looking if DbDataReader has this capability.

How to compare two double values in Java?

double a = 1.000001;
double b = 0.000001;

System.out.println( a.compareTo(b) );

Returns:

  • -1 : 'a' is numerically less than 'b'.

  • 0 : 'a' is equal to 'b'.

  • 1 : 'a' is greater than 'b'.

Select distinct rows from datatable in Linq

Like this: (Assuming a typed dataset)

someTable.Select(r => new { r.attribute1_name, r.attribute2_name }).Distinct();

Convert an array to string

My suggestion:

using System.Linq;

string myStringOutput = String.Join(",", myArray.Select(p => p.ToString()).ToArray());

reference: https://coderwall.com/p/oea7uq/convert-simple-int-array-to-string-c

How to find out what type of a Mat object is with Mat::type() in OpenCV

For debugging purposes in case you want to look up a raw Mat::type in a debugger:

+--------+----+----+----+----+------+------+------+------+
|        | C1 | C2 | C3 | C4 | C(5) | C(6) | C(7) | C(8) |
+--------+----+----+----+----+------+------+------+------+
| CV_8U  |  0 |  8 | 16 | 24 |   32 |   40 |   48 |   56 |
| CV_8S  |  1 |  9 | 17 | 25 |   33 |   41 |   49 |   57 |
| CV_16U |  2 | 10 | 18 | 26 |   34 |   42 |   50 |   58 |
| CV_16S |  3 | 11 | 19 | 27 |   35 |   43 |   51 |   59 |
| CV_32S |  4 | 12 | 20 | 28 |   36 |   44 |   52 |   60 |
| CV_32F |  5 | 13 | 21 | 29 |   37 |   45 |   53 |   61 |
| CV_64F |  6 | 14 | 22 | 30 |   38 |   46 |   54 |   62 |
+--------+----+----+----+----+------+------+------+------+

So for example, if type = 30 then OpenCV data type is CV_64FC4. If type = 50 then the OpenCV data type is CV_16UC(7).

Arithmetic overflow error converting numeric to data type numeric

If you want to reduce the size to decimal(7,2) from decimal(9,2) you will have to account for the existing data with values greater to fit into decimal(7,2). Either you will have to delete those numbers are truncate it down to fit into your new size. If there was no data for the field you are trying to update it will do it automatically without issues

How to open an Excel file in C#?

you should open like this

        Excel.Application xlApp ;
        Excel.Workbook xlWorkBook ;
        Excel.Worksheet xlWorkSheet ;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

source : http://csharp.net-informations.com/excel/csharp-open-excel.htm

ruden

XPath to get all child nodes (elements, comments, and text) without parent

Use this XPath expression:

/*/*/X/node()

This selects any node (element, text node, comment or processing instruction) that is a child of any X element that is a grand-child of the top element of the XML document.

To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>
 <xsl:template match="/">
  <xsl:copy-of select="/*/*/X/node()"/>
 </xsl:template>
</xsl:stylesheet>

and it produces exactly the wanted, correct result:

   First Text Node #1            
    <y> Y can Have Child Nodes #                
        <child> deep to it </child>
    </y>            Second Text Node #2 
    <z />

Explanation:

  1. As defined in the W3 XPath 1.0 Spec, "child::node() selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.

  2. node() is an abbreviation of child::node() (because child:: is the primary axis and is used when no axis is explicitly specified).

How do I create a ListView with rounded corners in Android?

Although that did work, it took out the entire background colour as well. I was looking for a way to do just the border and just replace that XML layout code with this one and I was good to go!

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="4dp" android:color="#FF00FF00" />
    <padding android:left="7dp" android:top="7dp"
            android:right="7dp" android:bottom="7dp" />
    <corners android:radius="4dp" />
</shape>