Programs & Examples On #Android sdcard

SD Card is a Secure Digital Card available with Android which acts as the External Storage Directory.

Android Open External Storage directory(sdcard) for storing file

yes, it may work in KITKAT.

above KITKAT+ it will go to internal storage:paths like(storage/emulated/0).

please think, how "Xender app" give permission to write in to external sd card.

So, Fortunately in Android 5.0 and later there is a new official way for apps to write to the external SD card. Apps must ask the user to grant write access to a folder on the SD card. They open a system folder chooser dialog. The user need to navigate into that specific folder and select it.

for more details, please refer https://metactrl.com/docs/sdcard-on-lollipop/

Solution to INSTALL_FAILED_INSUFFICIENT_STORAGE error on Android

Emulator solution

Open your .Android directory. Usually in your home directory. Then go to avd and then open the directory that has the name of the avd you would like to change.

Now edit the config.ini file and add the following line or modify the following line:

disk.dataPartition.size=1024

Where 1024 is the size you would like to use in MB. Save the file and then start your emulator with wipe user data checked. Your emulator should now have the new size.

How do I adb pull ALL files of a folder present in SD Card

Please try with just giving the path from where you want to pull the files I just got the files from sdcard like

adb pull sdcard/

do NOT give * like to broaden the search or to filter out. ex: adb pull sdcard/*.txt --> this is invalid.

just give adb pull sdcard/

How to get file name from file path in android

you can use the Common IO library which can get you the Base name of your file and the Extension.

 String fileUrl=":/storage/sdcard0/DCIM/Camera/1414240995236.jpg";
      String fileName=FilenameUtils.getBaseName(fileUrl);
           String    fileExtention=FilenameUtils.getExtension(fileUrl);
//this will return filename:1414240995236 and fileExtention:jpg

error opening trace file: No such file or directory (2)

You will not have access to your real sd card in emulator. You will have to follow the steps in this tutorial to direct your emulator to a directory on your development environment acting as your SD card.

Simple mediaplayer play mp3 from file path?

Here is the code to set up a MediaPlayer to play off of the SD card:

String PATH_TO_FILE = "/sdcard/music.mp3";    
mediaPlayer = new  MediaPlayer();
mediaPlayer.setDataSource(PATH_TO_FILE);
mediaPlayer.prepare();   
mediaPlayer.start()

You can see the full example here. Let me know if you have any problems.

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

How to delete a file from SD card?

Recursively delete all children of the file ...

public static void DeleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory()) {
        for (File child : fileOrDirectory.listFiles()) {
            DeleteRecursive(child);
        }
    }

    fileOrDirectory.delete();
}

Android: How to open a specific folder via Intent and show its content in a file browser?

You seem close.

I would try to set the URI like this :

String folderPath = Environment.getExternalStorageDirectory()+"/pathTo/folder";

Intent intent = new Intent();  
intent.setAction(Intent.ACTION_GET_CONTENT);
Uri myUri = Uri.parse(folderPath);
intent.setDataAndType(myUri , "file/*");   
startActivity(intent);

But it's not so different from what you have tried. Tell us if it changes anything ?

Also make sure the targeted folder exists, and have a look on the resulting Uri object before to send it to the intent, it may not be what we are expected.

How can I get the external SD card path for Android 4.0+?

refer to my code, hope helpful for you:

    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec("mount");
    InputStream is = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    String line;
    String mount = new String();
    BufferedReader br = new BufferedReader(isr);
    while ((line = br.readLine()) != null) {
        if (line.contains("secure")) continue;
        if (line.contains("asec")) continue;

        if (line.contains("fat")) {//TF card
            String columns[] = line.split(" ");
            if (columns != null && columns.length > 1) {
                mount = mount.concat("*" + columns[1] + "\n");
            }
        } else if (line.contains("fuse")) {//internal storage
            String columns[] = line.split(" ");
            if (columns != null && columns.length > 1) {
                mount = mount.concat(columns[1] + "\n");
            }
        }
    }
    txtView.setText(mount);

How do you write to a folder on an SD card in Android?

File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");

FileOutputStream f = new FileOutputStream(file);
...

How to access /storage/emulated/0/

if you are using Android device monitor and android emulator : I have accessed following way: Data/Media/0/ enter image description here

Android 6.0 Marshmallow. Cannot write to SD Card

Maybe you cannot use manifest class from generated code in your project. So, you can use manifest class from android sdk "android.Manifest.permission.WRITE_EXTERNAL_STORAGE". But in Marsmallow version have 2 permission must grant are WRITE and READ EXTERNAL STORAGE in storage category. See my program, my program will request permission until user choose yes and do something after permissions is granted.

            if (Build.VERSION.SDK_INT >= 23) {
                if (ContextCompat.checkSelfPermission(LoginActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(LoginActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(LoginActivity.this,
                            new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE},
                            1);
                } else {
                    //do something
                }
            } else {
                    //do something
            }

How can I read a text file from the SD card in Android?

You should have READ_EXTERNAL_STORAGE permission for reading sdcard. Add permission in manifest.xml

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

From android 6.0 or higher, your app must ask user to grant the dangerous permissions at runtime. Please refer this link Permissions overview

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
    }
}

How to install a Mac application using Terminal

To disable inputting password:

sudo visudo

Then add a new line like below and save then:

# The user can run installer as root without inputting password
yourusername ALL=(root) NOPASSWD: /usr/sbin/installer

Then you run installer without password:

sudo installer -pkg ...

Negate if condition in bash script

Since you're comparing numbers, you can use an arithmetic expression, which allows for simpler handling of parameters and comparison:

wget -q --tries=10 --timeout=20 --spider http://google.com
if (( $? != 0 )); then
    echo "Sorry you are Offline"
    exit 1
fi

Notice how instead of -ne, you can just use !=. In an arithmetic context, we don't even have to prepend $ to parameters, i.e.,

var_a=1
var_b=2
(( var_a < var_b )) && echo "a is smaller"

works perfectly fine. This doesn't appply to the $? special parameter, though.

Further, since (( ... )) evaluates non-zero values to true, i.e., has a return status of 0 for non-zero values and a return status of 1 otherwise, we could shorten to

if (( $? )); then

but this might confuse more people than the keystrokes saved are worth.

The (( ... )) construct is available in Bash, but not required by the POSIX shell specification (mentioned as possible extension, though).

This all being said, it's better to avoid $? altogether in my opinion, as in Cole's answer and Steven's answer.

How can I split a string into segments of n characters?

str.match(/.{3}/g); // => ['abc', 'def', 'ghi', 'jkl']

Visual Studio: How to show Overloads in IntelliSense?

Great question; I had the same issue. Turns out that there is indeed a keyboard shortcut to bring up this list: Ctrl+Shift+Space (a variation of the basic IntelliSense shortcut of Ctrl+Space).

Variables as commands in bash scripts

eval is not an acceptable practice if your directory names can be generated by untrusted sources. See BashFAQ #48 for more on why eval should not be used, and BashFAQ #50 for more on the root cause of this problem and its proper solutions, some of which are touched on below:

If you need to build up your commands over time, use arrays:

tar_cmd=( tar cv "$directory" )
split_cmd=( split -b 1024m - "$backup_file" )
encrypt_cmd=( openssl des3 -salt )
"${tar_cmd[@]}" | "${encrypt_cmd[@]}" | "${split_cmd[@]}"

Alternately, if this is just about defining your commands in one central place, use functions:

tar_cmd() { tar cv "$directory"; }
split_cmd() { split -b 1024m - "$backup_file"; }
encrypt_cmd() { openssl des3 -salt; }
tar_cmd | split_cmd | encrypt_cmd

Get the (last part of) current directory name in C#

var lastFolderName = Path.GetFileName(
    path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));

This works if the path happens to contain forward slash separators or backslash separators.

How to destroy a JavaScript object?

I was facing a problem like this, and had the idea of simply changing the innerHTML of the problematic object's children.

adiv.innerHTML = "<div...> the original html that js uses </div>";

Seems dirty, but it saved my life, as it works!

How do I change button size in Python?

Configuring a button (or any widget) in Tkinter is done by calling a configure method "config"

To change the size of a button called button1 you simple call

button1.config( height = WHATEVER, width = WHATEVER2 )

If you know what size you want at initialization these options can be added to the constructor.

button1 = Button(self, text = "Send", command = self.response1, height = 100, width = 100) 

Using "word-wrap: break-word" within a table

You can try this:

td p {word-break:break-all;}

This, however, makes it appear like this when there's enough space, unless you add a <br> tag:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

So, I would then suggest adding <br> tags where there are newlines, if possible.

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

http://jsfiddle.net/LLyH3/3/

Also, if this doesn't solve your problem, there's a similar thread here.

Using jQuery to compare two arrays of Javascript objects

I found this discussion because I needed a way to deep compare arrays and objects. Using the examples here, I came up with the following (broken up into 3 methods for clarity):

jQuery.extend({
    compare : function (a,b) {
        var obj_str = '[object Object]',
            arr_str = '[object Array]',
            a_type  = Object.prototype.toString.apply(a),
            b_type  = Object.prototype.toString.apply(b);

            if ( a_type !== b_type) { return false; }
            else if (a_type === obj_str) {
                return $.compareObject(a,b);
            }
            else if (a_type === arr_str) {
                return $.compareArray(a,b);
            }
            return (a === b);
        }
});

jQuery.extend({
    compareArray: function (arrayA, arrayB) {
        var a,b,i,a_type,b_type;
        // References to each other?
        if (arrayA === arrayB) { return true;}

        if (arrayA.length != arrayB.length) { return false; }
        // sort modifies original array
        // (which are passed by reference to our method!)
        // so clone the arrays before sorting
        a = jQuery.extend(true, [], arrayA);
        b = jQuery.extend(true, [], arrayB);
        a.sort(); 
        b.sort();
        for (i = 0, l = a.length; i < l; i+=1) {
            a_type = Object.prototype.toString.apply(a[i]);
            b_type = Object.prototype.toString.apply(b[i]);

            if (a_type !== b_type) {
                return false;
            }

            if ($.compare(a[i],b[i]) === false) {
                return false;
            }
        }
        return true;
    }
});

jQuery.extend({
    compareObject : function(objA,objB) {

        var i,a_type,b_type;

        // Compare if they are references to each other 
        if (objA === objB) { return true;}

        if (Object.keys(objA).length !== Object.keys(objB).length) { return false;}
        for (i in objA) {
            if (objA.hasOwnProperty(i)) {
                if (typeof objB[i] === 'undefined') {
                    return false;
                }
                else {
                    a_type = Object.prototype.toString.apply(objA[i]);
                    b_type = Object.prototype.toString.apply(objB[i]);

                    if (a_type !== b_type) {
                        return false; 
                    }
                }
            }
            if ($.compare(objA[i],objB[i]) === false){
                return false;
            }
        }
        return true;
    }
});

Testing

var a={a : {a : 1, b: 2}},
    b={a : {a : 1, b: 2}},
    c={a : {a : 1, b: 3}},
    d=[1,2,3],
    e=[2,1,3];

console.debug('a and b = ' + $.compare(a,b)); // a and b = true
console.debug('b and b = ' + $.compare(b,b)); // b and b = true
console.debug('b and c = ' + $.compare(b,c)); // b and c = false
console.debug('c and d = ' + $.compare(c,d)); // c and d = false
console.debug('d and e = ' + $.compare(d,e)); // d and e = true

How can I create directory tree in C++/Linux?

If you don't have C++17 yet and look for a platform agnostic solution, use ghc::filesystem. The header-ony code is compatible to C++17 (in fact a backport) and easy to migrate later on.

Automatic HTTPS connection/redirect with node.js/express

var express = require('express');
var app = express();

app.get('*',function (req, res) {
    res.redirect('https://<domain>' + req.url);
});

app.listen(80);

This is what we use and it works great!

Eclipse DDMS error "Can't bind to local 8600 for debugger"

The only fix that really worked for me was uninstalling Java 7 and installing Java 6 on my Windows 8 x64 based machine.

You can download Java 6 from here.

cc1plus: error: unrecognized command line option "-std=c++11" with g++

I also got same error, compiling with -D flag fixed it, Try this:

g++ -Dstd=c++11

how to show confirmation alert with three buttons 'Yes' 'No' and 'Cancel' as it shows in MS Word

This cannot be done with the native javascript dialog box, but a lot of javascript libraries include more flexible dialogs. You can use something like jQuery UI's dialog box for this.

See also these very similar questions:

Here's an example, as demonstrated in this jsFiddle:

<html><head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/normalize.css">
    <link rel="stylesheet" type="text/css" href="/css/result-light.css">
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css">
</head>
<body>
    <a class="checked" href="http://www.google.com">Click here</a>
    <script type="text/javascript">

        $(function() {
            $('.checked').click(function(e) {
                e.preventDefault();
                var dialog = $('<p>Are you sure?</p>').dialog({
                    buttons: {
                        "Yes": function() {alert('you chose yes');},
                        "No":  function() {alert('you chose no');},
                        "Cancel":  function() {
                            alert('you chose cancel');
                            dialog.dialog('close');
                        }
                    }
                });
            });
        });

    </script>
</body><html>

Get the client IP address using PHP

    $ipaddress = '';
    if ($_SERVER['HTTP_CLIENT_IP'] != '127.0.0.1')
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if ($_SERVER['HTTP_X_FORWARDED_FOR'] != '127.0.0.1')
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if ($_SERVER['HTTP_X_FORWARDED'] != '127.0.0.1')
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if ($_SERVER['HTTP_FORWARDED_FOR'] != '127.0.0.1')
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if ($_SERVER['HTTP_FORWARDED'] != '127.0.0.1')
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if ($_SERVER['REMOTE_ADDR'] != '127.0.0.1')
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';

Rotating a point about another point (2D)

This is the answer by Nils Pipenbrinck, but implemented in c# fiddle.

https://dotnetfiddle.net/btmjlG

using System;

public class Program
{
    public static void Main()
    {   
        var angle = 180 * Math.PI/180;
        Console.WriteLine(rotate_point(0,0,angle,new Point{X=10, Y=10}).Print());
    }

    static Point rotate_point(double cx, double cy, double angle, Point p)
    {
        double s = Math.Sin(angle);
        double c = Math.Cos(angle);
        // translate point back to origin:
        p.X -= cx;
        p.Y -= cy;
        // rotate point
        double Xnew = p.X * c - p.Y * s;
        double Ynew = p.X * s + p.Y * c;
        // translate point back:
        p.X = Xnew + cx;
        p.Y = Ynew + cy;
        return p;
    }

    class Point
    {
        public double X;
        public double Y;

        public string Print(){
            return $"{X},{Y}";
        }
    }
}

Ps: Apparently I can’t comment, so I’m obligated to post it as an answer ...

YouTube API to fetch all videos on a channel

You need to look at the YouTube Data API. You will find there documentation about how the API can be accessed. You can also find client libraries.

You could also make the requests yourself. Here is an example URL that retrieves the latest videos from a channel:

https://www.googleapis.com/youtube/v3/search?key={your_key_here}&channelId={channel_id_here}&part=snippet,id&order=date&maxResults=20

After that you will receive a JSON with video ids and details, and you can construct your video URL like this:

http://www.youtube.com/watch?v={video_id_here}

SOAP Action WSDL

the service have 4 operations: 1. GetServiceDetails 2. GetArrivalBoard 3. GetDepartureBoard 4. GetArrivalDepartureBoard

Implementation of web service

.NET NewtonSoft JSON deserialize map to a different property name

Adding to Jacks solution. I need to Deserialize using the JsonProperty and Serialize while ignoring the JsonProperty (or vice versa). ReflectionHelper and Attribute Helper are just helper classes that get a list of properties or attributes for a property. I can include if anyone actually cares. Using the example below you can serialize the viewmodel and get "Amount" even though the JsonProperty is "RecurringPrice".

    /// <summary>
    /// Ignore the Json Property attribute. This is usefule when you want to serialize or deserialize differently and not 
    /// let the JsonProperty control everything.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class IgnoreJsonPropertyResolver<T> : DefaultContractResolver
    {
        private Dictionary<string, string> PropertyMappings { get; set; }

        public IgnoreJsonPropertyResolver()
        {
            this.PropertyMappings = new Dictionary<string, string>();
            var properties = ReflectionHelper<T>.GetGetProperties(false)();
            foreach (var propertyInfo in properties)
            {
                var jsonProperty = AttributeHelper.GetAttribute<JsonPropertyAttribute>(propertyInfo);
                if (jsonProperty != null)
                {
                    PropertyMappings.Add(jsonProperty.PropertyName, propertyInfo.Name);
                }
            }
        }

        protected override string ResolvePropertyName(string propertyName)
        {
            string resolvedName = null;
            var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
            return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
        }
    }

Usage:

        var settings = new JsonSerializerSettings();
        settings.DateFormatString = "YYYY-MM-DD";
        settings.ContractResolver = new IgnoreJsonPropertyResolver<PlanViewModel>();
        var model = new PlanViewModel() {Amount = 100};
        var strModel = JsonConvert.SerializeObject(model,settings);

Model:

public class PlanViewModel
{

    /// <summary>
    ///     The customer is charged an amount over an interval for the subscription.
    /// </summary>
    [JsonProperty(PropertyName = "RecurringPrice")]
    public double Amount { get; set; }

    /// <summary>
    ///     Indicates the number of intervals between each billing. If interval=2, the customer would be billed every two
    ///     months or years depending on the value for interval_unit.
    /// </summary>
    public int Interval { get; set; } = 1;

    /// <summary>
    ///     Number of free trial days that can be granted when a customer is subscribed to this plan.
    /// </summary>
    public int TrialPeriod { get; set; } = 30;

    /// <summary>
    /// This indicates a one-time fee charged upfront while creating a subscription for this plan.
    /// </summary>
    [JsonProperty(PropertyName = "SetupFee")]
    public double SetupAmount { get; set; } = 0;


    /// <summary>
    /// String representing the type id, usually a lookup value, for the record.
    /// </summary>
    [JsonProperty(PropertyName = "TypeId")]
    public string Type { get; set; }

    /// <summary>
    /// Billing Frequency
    /// </summary>
    [JsonProperty(PropertyName = "BillingFrequency")]
    public string Period { get; set; }


    /// <summary>
    /// String representing the type id, usually a lookup value, for the record.
    /// </summary>
    [JsonProperty(PropertyName = "PlanUseType")]
    public string Purpose { get; set; }
}

Remove all unused resources from an android project

You can easily search for unused resources from Android Studio. Just press CtrlAltShifti and type "unused resources" (without quotes). That will execute lint. Super easy way to run lint commands (and other stuff from IDE).

OR

In Android Studio Menu > Refactor > Remove Unused Resources...

Select the resources you want to remove. You can exclude resources you want to keep by right-clicking on the resource item.

Use Do Refactor to remove all Resources at once.

Update: use ?OptionShifti for mac

Apache - MySQL Service detected with wrong path. / Ports already in use

hello i have had same problem an i did the steps with tommer and the problem solved thank you

note :

you don't have to go to that like just do this ;

1)-- Edit your “my.ini” file in c:\xampp\mysql\bin\ Change all default 3306 port entries to a new value 3308

2)--edit your “php.ini” in c:\xampp\php and replace 3306 by 3308

3)--Create the service entry - in Windows command line type

sc.exe create "mysqlweb" binPath= "C:\xampp\mysql\bin\mysqld.exe --defaults-file=c:\xampp\mysql\bin\my.ini mysqlweb"

4)--Open Windows Services and set Startup Type: Automatic, Start the service

Android fastboot waiting for devices

In my case (on windows 10), it would connect fine to adb and I could type any adb commands. But as soon as it got to the bootloader using adb reboot bootloader I wasn't able to perform any fastboot commands.

What I did notice that in the device manager that it refreshed when I connected to device. Next thing to do was to check what changed when connecting. Apparently the fastboot device was inside the Kedacom USB Device. Not really sure what that was, but I updated the device to use a different driver, in my case the Fastboot interface (Google USB ID), and that fixed my waiting for device issue

How to load images dynamically (or lazily) when users scrolls them into view

The Swiss Army knife of image lazy loading is YUI's ImageLoader.

Because there is more to this problem than simply watching the scroll position.

How is TeamViewer so fast?

My random guess is: TV uses x264 codec which has a commercial license (otherwise TeamViewer would have to release their source code). At some point (more than 5 years ago), I recall main developer of x264 wrote an article about improvements he made for low delay encoding (if you delay by a few frames encoders can compress better), plus he mentioned some other improvements that were relevant for TeamViewer-like use. In that post he mentioned playing quake over video stream with no noticeable issues. Back then I was kind of sure who was the sponsor of these improvements, as TeamViewer was pretty much the only option at that time. x264 is an open source implementation of H264 video codec, and it's insanely good implementation, it's the best one. At the same time it's extremely well optimized. Most likely due to extremely good implementation of x264 you get much better results with TV at lower CPU load. AnyDesk and Chrome Remote Desk use libvpx, which isn't as good as x264 (optimization and video quality wise).

However, I don't think TeamView can beat microsoft's RDP. To me it's the best, however it works between windows PCs or from Mac to Windows only. TV works even from mobiles.

Update: article was written in January 2010, so that work was done roughly 10 years ago. Also, I made a mistake: he played call of duty, not quake. When you posted your question, if my guess is correct, TeamViewer had been using that work for 3 years. Read that blog post from web archive: x264: the best low-latency video streaming platform in the world. When I read the article back in 2010, I was sure that the "startup–which has requested not to be named" that the author mentions was TeamViewer.

How to detect if CMD is running as Administrator/has elevated privileges?

Here's a simple method I've used on Windows 7 through Windows 10. Basically, I simply use the "IF EXIST" command to check for the Windows\System32\WDI\LogFiles folder. The WDI folder exists on every install of Windows from at least 7 onward, and it requires admin privileges to access. The WDI folder always has a LogFiles folder inside it. So, running "IF EXIST" on the WDI\LogFiles folder will return true if run as admin, and false if not run as admin. This can be used in a batch file to check privilege level, and branch to whichever commands you desire based on that result.

Here's a brief snippet of example code:

IF EXIST %SYSTEMROOT%\SYSTEM32\WDI\LOGFILES GOTO GOTADMIN
(Commands for running with normal privileges)

:GOTADMIN
(Commands for running with admin privileges)

Keep in mind that this method assumes the default security permissions have not been modified on the WDI folder (which is unlikely to happen in most situations, but please see caveat #2 below). Even in that case, it's simply a matter of modifying the code to check for a different common file/folder that requires admin access (System32\config\SAM may be a good alternate candidate), or you could even create your own specifically for that purpose.

There are two caveats about this method though:

  1. Disabling UAC will likely break it through the simple fact that everything would be run as admin anyway.

  2. Attempting to open the WDI folder in Windows Explorer and then clicking "Continue" when prompted will add permanent access rights for that user account, thus breaking my method. If this happens, it can be fixed by removing the user account from the WDI folder security permissions. If for any reason the user MUST be able to access the WDI folder with Windows Explorer, then you'd have to modify the code to check a different folder (as mentioned above, creating your own specifically for this purpose may be a good choice).

So, admittedly my method isn't perfect since it can be broken, but it's a relatively quick method that's easy to implement, is equally compatible with all versions of Windows 7, 8 and 10, and provided I stay mindful of the mentioned caveats has been 100% effective for me.

What is the best way to initialize a JavaScript Date to midnight?

If calculating with dates summertime will cause often 1 uur more or one hour less than midnight (CEST). This causes 1 day difference when dates return. So the dates have to round to the nearest midnight. So the code will be (ths to jamisOn):

    var d = new Date();
    if(d.getHours() < 12) {
    d.setHours(0,0,0,0); // previous midnight day
    } else {
    d.setHours(24,0,0,0); // next midnight day
    }

How to create a floating action button (FAB) in android, using AppCompat v21?

@Justin Pollard xml code works really good. As a side note you can add a ripple effect with the following xml lines.

    <item>
    <ripple
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="?android:colorControlHighlight" >
        <item android:id="@android:id/mask">
            <shape android:shape="oval" >
                <solid android:color="#FFBB00" />
            </shape>
        </item>
        <item>
            <shape android:shape="oval" >
                <solid android:color="@color/ColorPrimary" />
            </shape>
        </item>
    </ripple>
</item>

jQuery slide left and show

And if you want to vary the speed and include callbacks simply add them like this :

        jQuery.fn.extend({
            slideRightShow: function(speed,callback) {
                return this.each(function() {
                    $(this).show('slide', {direction: 'right'}, speed, callback);
                });
            },
            slideLeftHide: function(speed,callback) {
                return this.each(function() {
                    $(this).hide('slide', {direction: 'left'}, speed, callback);
                });
            },
            slideRightHide: function(speed,callback) {
                return this.each(function() {  
                    $(this).hide('slide', {direction: 'right'}, speed, callback);
                });
            },
            slideLeftShow: function(speed,callback) {
                return this.each(function() {
                    $(this).show('slide', {direction: 'left'}, speed, callback);
                });
            }
        });

Root password inside a Docker container

I'd suggest a better solution is to give the --add-host NAME:IP argument to docker run when starting the container. That will update the /etc/hosts/ file without any need to become root.

Otherwise, you can override the the USER setting by giving the -u USER flag to docker run. I would advise against this however, as you shouldn't really be changing things in a running container. Instead, make your changes in a Dockerfile and build a new image.

How to redirect the output of the time command to a file in Linux?

If you want just the time in a shell variable then this works:

var=`{ time <command> ; } 2>&1 1>/dev/null`

What's the idiomatic syntax for prepending to a short python list?

What's the idiomatic syntax for prepending to a short python list?

You don't usually want to repetitively prepend to a list in Python.

If it's short, and you're not doing it a lot... then ok.

list.insert

The list.insert can be used this way.

list.insert(0, x)

But this is inefficient, because in Python, a list is an array of pointers, and Python must now take every pointer in the list and move it down by one to insert the pointer to your object in the first slot, so this is really only efficient for rather short lists, as you ask.

Here's a snippet from the CPython source where this is implemented - and as you can see, we start at the end of the array and move everything down by one for every insertion:

for (i = n; --i >= where; )
    items[i+1] = items[i];

If you want a container/list that's efficient at prepending elements, you want a linked list. Python has a doubly linked list, which can insert at the beginning and end quickly - it's called a deque.

deque.appendleft

A collections.deque has many of the methods of a list. list.sort is an exception, making deque definitively not entirely Liskov substitutable for list.

>>> set(dir(list)) - set(dir(deque))
{'sort'}

The deque also has an appendleft method (as well as popleft). The deque is a double-ended queue and a doubly-linked list - no matter the length, it always takes the same amount of time to preprend something. In big O notation, O(1) versus the O(n) time for lists. Here's the usage:

>>> import collections
>>> d = collections.deque('1234')
>>> d
deque(['1', '2', '3', '4'])
>>> d.appendleft('0')
>>> d
deque(['0', '1', '2', '3', '4'])

deque.extendleft

Also relevant is the deque's extendleft method, which iteratively prepends:

>>> from collections import deque
>>> d2 = deque('def')
>>> d2.extendleft('cba')
>>> d2
deque(['a', 'b', 'c', 'd', 'e', 'f'])

Note that each element will be prepended one at a time, thus effectively reversing their order.

Performance of list versus deque

First we setup with some iterative prepending:

import timeit
from collections import deque

def list_insert_0():
    l = []
    for i in range(20):
        l.insert(0, i)

def list_slice_insert():
    l = []
    for i in range(20):
        l[:0] = [i]      # semantically same as list.insert(0, i)

def list_add():
    l = []
    for i in range(20):
        l = [i] + l      # caveat: new list each time

def deque_appendleft():
    d = deque()
    for i in range(20):
        d.appendleft(i)  # semantically same as list.insert(0, i)

def deque_extendleft():
    d = deque()
    d.extendleft(range(20)) # semantically same as deque_appendleft above

and performance:

>>> min(timeit.repeat(list_insert_0))
2.8267281929729506
>>> min(timeit.repeat(list_slice_insert))
2.5210217320127413
>>> min(timeit.repeat(list_add))
2.0641671380144544
>>> min(timeit.repeat(deque_appendleft))
1.5863927800091915
>>> min(timeit.repeat(deque_extendleft))
0.5352169770048931

The deque is much faster. As the lists get longer, I would expect a deque to perform even better. If you can use deque's extendleft you'll probably get the best performance that way.

How to create JSON object using jQuery

A "JSON object" doesn't make sense : JSON is an exchange format based on the structure of Javascript object declaration.

If you want to convert your javascript object to a json string, use JSON.stringify(yourObject);

If you want to create a javascript object, simply do it like this :

var yourObject = {
          test:'test 1',
          testData: [ 
                {testName: 'do',testId:''}
          ],
          testRcd:'value'   
};

Set keyboard caret position in html textbox

Excerpted from Josh Stodola's Setting keyboard caret Position in a Textbox or TextArea with Javascript

A generic function that will allow you to insert the caret at any position of a textbox or textarea that you wish:

function setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

The first expected parameter is the ID of the element you wish to insert the keyboard caret on. If the element is unable to be found, nothing will happen (obviously). The second parameter is the caret positon index. Zero will put the keyboard caret at the beginning. If you pass a number larger than the number of characters in the elements value, it will put the keyboard caret at the end.

Tested on IE6 and up, Firefox 2, Opera 8, Netscape 9, SeaMonkey, and Safari. Unfortunately on Safari it does not work in combination with the onfocus event).

An example of using the above function to force the keyboard caret to jump to the end of all textareas on the page when they receive focus:

function addLoadEvent(func) {
    if(typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        if(func) {
            var oldLoad = window.onload;

            window.onload = function() {
                if(oldLoad)
                        oldLoad();

                func();
            }
        }
    }
}

// The setCaretPosition function belongs right here!

function setTextAreasOnFocus() {
/***
 * This function will force the keyboard caret to be positioned
 * at the end of all textareas when they receive focus.
 */
    var textAreas = document.getElementsByTagName('textarea');

    for(var i = 0; i < textAreas.length; i++) {
        textAreas[i].onfocus = function() {
            setCaretPosition(this.id, this.value.length);
        }
    }

    textAreas = null;
}

addLoadEvent(setTextAreasOnFocus);

Python regex findall

Your question is not 100% clear, but I'm assuming you want to find every piece of text inside [P][/P] tags:

>>> import re
>>> line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bill Gates [/P], yesterday."
>>> re.findall('\[P\]\s?(.+?)\s?\[\/P\]', line)
['Barack Obama', 'Bill Gates']

How to insert image in mysql database(table)?

I have three answers to this question:

  1. It is against user experience UX best practice to use BLOB and CLOB data types in string and retrieving binary data from an SQL database thus it is advised that you use the technique that involves storing the URL for the image( or any Binary file in the database). This URL will help the user application to retrieve and use this binary file.

  2. Second the BLOB and CLOB data types are only available to a number of SQL versions thus functions such as LOAD_FILE or the datatypes themselves could miss in some versions.

  3. Third DON'T USE BLOB OR CLOB. Store the URL; let the user application access the binary file from a folder in the project directory.

Copy a git repo without history

#!/bin/bash
set -e

# Settings
user=xxx
pass=xxx
dir=xxx
repo_src=xxx
repo_trg=xxx
src_branch=xxx

repo_base_url=https://$user:[email protected]/$user
repo_src_url=$repo_base_url/$repo_src.git
repo_trg_url=$repo_base_url/$repo_trg.git

echo "Clone Source..."
git clone --depth 1 -b $src_branch $repo_src_url $dir

echo "CD"
cd ./$dir

echo "Remove GIT"
rm -rf .git

echo "Init GIT"
git init
git add .
git commit -m "Initial Commit"
git remote add origin $repo_trg_url

echo "Push..."
git push -u origin master

How to iterate over a column vector in Matlab?

with many functions in matlab, you don't need to iterate at all.

for example, to multiply by it's position in the list:

m = [1:numel(list)]';
elm = list.*m;

vectorized algorithms in matlab are in general much faster.

Python/BeautifulSoup - how to remove all tags from an element?

Here is the source code: you can get the text which is exactly in the URL

URL = ''
page = requests.get(URL)
soup = bs4.BeautifulSoup(page.content,'html.parser').get_text()
print(soup)

Syntax for a for loop in ruby

Ruby's enumeration loop syntax is different:

collection.each do |item|
...
end

This reads as "a call to the 'each' method of the array object instance 'collection' that takes block with 'blockargument' as argument". The block syntax in Ruby is 'do ... end' or '{ ... }' for single line statements.

The block argument '|item|' is optional but if provided, the first argument automatically represents the looped enumerated item.

New to unit testing, how to write great tests?

Try writing a Unit Test before writing the method it is going to test.

That will definitely force you to think a little differently about how things are being done. You'll have no idea how the method is going to work, just what it is supposed to do.

You should always be testing the results of the method, not how the method gets those results.

Conversion of a datetime2 data type to a datetime data type results out-of-range value

I'm aware of this problem and you all should be too:

https://en.wikipedia.org/wiki/Year_2038_problem

In SQL a new field type was created to avoid this problem (datetime2).

This 'Date' field type has the same range values as a DateTime .Net class. It will solve all your problems, so I think the best way of solving it is changing your database column type (it won't affect your table data).

Intel's HAXM equivalent for AMD on Windows OS

hello to run the avd manager on AMD processor you need update your SDK MANAGER in Android Studio: https://android-developers.googleblog.com/2018/07/android-emulator-amd-processor-hyper-v.html

You go to tools->SDK MANAGER->SDK Tools

then look for Android Emulator and Android Emulator Hypervisor Driver for AMD Processors

check the boxes and click apply or OK

What does 'synchronized' mean?

To my understanding synchronized basically means that the compiler write a monitor.enter and monitor.exit around your method. As such it may be thread safe depending on how it is used (what I mean is you can write an object with synchronized methods that isn't threadsafe depending on what your class does).

Send Post Request with params using Retrofit

This is a simple solution where we do not need to use JSON

public interface RegisterAPI {
@FormUrlEncoded
@POST("/RetrofitExample/insert.php")
public void insertUser(
        @Field("name") String name,
        @Field("username") String username,
        @Field("password") String password,
        @Field("email") String email,
        Callback<Response> callback);
}

method to send data

private void insertUser(){
    //Here we will handle the http request to insert user to mysql db
    //Creating a RestAdapter
    RestAdapter adapter = new RestAdapter.Builder()
            .setEndpoint(ROOT_URL) //Setting the Root URL
            .build(); //Finally building the adapter

    //Creating object for our interface
    RegisterAPI api = adapter.create(RegisterAPI.class);

    //Defining the method insertuser of our interface
    api.insertUser(

            //Passing the values by getting it from editTexts
            editTextName.getText().toString(),
            editTextUsername.getText().toString(),
            editTextPassword.getText().toString(),
            editTextEmail.getText().toString(),

            //Creating an anonymous callback
            new Callback<Response>() {
                @Override
                public void success(Response result, Response response) {
                    //On success we will read the server's output using bufferedreader
                    //Creating a bufferedreader object
                    BufferedReader reader = null;

                    //An string to store output from the server
                    String output = "";

                    try {
                        //Initializing buffered reader
                        reader = new BufferedReader(new InputStreamReader(result.getBody().in()));

                        //Reading the output in the string
                        output = reader.readLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    //Displaying the output as a toast
                    Toast.makeText(MainActivity.this, output, Toast.LENGTH_LONG).show();
                }

                @Override
                public void failure(RetrofitError error) {
                    //If any error occured displaying the error as toast
                    Toast.makeText(MainActivity.this, error.toString(),Toast.LENGTH_LONG).show();
                }
            }
    );
}

Now we can get the post request using php aur any other server side scripting.

Source Android Retrofit Tutorial

Java 8 Lambda function that throws exception?

I'm the author of a tiny lib with some generic magic to throw any Java Exception anywhere without the need of catching them nor wrapping them into RuntimeException.

Usage: unchecked(() -> methodThrowingCheckedException())

public class UncheckedExceptions {

    /**
     * throws {@code exception} as unchecked exception, without wrapping exception.
     *
     * @return will never return anything, return type is set to {@code exception} only to be able to write <code>throw unchecked(exception)</code>
     * @throws T {@code exception} as unchecked exception
     */
    @SuppressWarnings("unchecked")
    public static <T extends Throwable> T unchecked(Exception exception) throws T {
        throw (T) exception;
    }


    @FunctionalInterface
    public interface UncheckedFunction<R> {
        R call() throws Exception;
    }

    /**
     * Executes given function,
     * catches and rethrows checked exceptions as unchecked exceptions, without wrapping exception.
     *
     * @return result of function
     * @see #unchecked(Exception)
     */
    public static <R> R unchecked(UncheckedFunction<R> function) {
        try {
            return function.call();
        } catch (Exception e) {
            throw unchecked(e);
        }
    }


    @FunctionalInterface
    public interface UncheckedMethod {
        void call() throws Exception;
    }

    /**
     * Executes given method,
     * catches and rethrows checked exceptions as unchecked exceptions, without wrapping exception.
     *
     * @see #unchecked(Exception)
     */
    public static void unchecked(UncheckedMethod method) {
        try {
            method.call();
        } catch (Exception e) {
            throw unchecked(e);
        }
    }
}

source: https://github.com/qoomon/unchecked-exceptions-java

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

Including more than one reference to Jquery library is the reason for the error Only Include one reference to the Jquery library and that will resolve the issue

IF EXISTS before INSERT, UPDATE, DELETE for optimization

IF EXISTS....UPDATE

Don't do it. It forces two scans/seeks instead of one.

If update doesn't find a match on the WHERE clause, the cost of the update statement is just a seek/scan.

If it does find a match, and if you preface it w/ IF EXISTS, it has to find the same match twice. And in a concurrent environment, what was true for the EXISTS may not be true any longer for the UPDATE.

This is precisely why UPDATE/DELETE/INSERT statements allow a WHERE clause. Use it!

How to get ERD diagram for an existing database?

postgresql_autodoc is a cli for doing this. Doesnt do cardinality, but none of the above mentioned GUI tools do as well.

Looping through a DataTable

foreach (DataColumn col in rightsTable.Columns)
{
     foreach (DataRow row in rightsTable.Rows)
     {
          Console.WriteLine(row[col.ColumnName].ToString());           
     }
} 

Can't connect Nexus 4 to adb: unauthorized

For my Samsung S3, I had to go into Developer Options on the phone, untick the "USB debugging" checkbox, then re-tick it.

Then the dialog will appear, asking if you want to allow USB Debugging.

Once I'd done this, the "adb devices" command no longer showed "unauthorized" as my device name.

(Several months later..)

Actually, the same was true for connecting my Galaxy Tab S device, and the menu options were in slightly different places with Android 4.4.2:

enter image description here

How to get the range of occupied cells in excel sheet

You should not delete the data in box by pressing "delete", i think thats the problem , because excel will still detected the box as "" <- still have value, u should delete by right click the box and click delete.

Role/Purpose of ContextLoaderListener in Spring?

When you want to put your Servlet file in your custom location or with custom name, rather than the default naming convention [servletname]-servlet.xml and path under Web-INF/ ,then you can use ContextLoaderListener.

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

The $.browser method has been removed as of jQuery 1.9.

jQuery.browser() removed

The jQuery.browser() method has been deprecated since jQuery 1.3 and is removed in 1.9. If needed, it is available as part of the jQuery Migrate plugin. We recommend using feature detection with a library such as Modernizr.

jQuery Core 1.9 Upgrade Guide.

As stated in the Upgrade Guide you can try using the jQuery Migrate plugin to restore this functionality and let jQuery Tools work.

How to perform a for loop on each character in a string in Bash?

You can use a C-style for loop:

foo=string
for (( i=0; i<${#foo}; i++ )); do
  echo "${foo:$i:1}"
done

${#foo} expands to the length of foo. ${foo:$i:1} expands to the substring starting at position $i of length 1.

Load CSV data into MySQL in Python

I think you have to do mydb.commit() all the insert into.

Something like this

import csv
import MySQLdb

mydb = MySQLdb.connect(host='localhost',
    user='root',
    passwd='',
    db='mydb')
cursor = mydb.cursor()

csv_data = csv.reader(file('students.csv'))
for row in csv_data:

    cursor.execute('INSERT INTO testcsv(names, \
          classes, mark )' \
          'VALUES("%s", "%s", "%s")', 
          row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"

How to always show the vertical scrollbar in a browser?

Add the class to the div you want to be scrollable.

overflow-x: hidden; hides the horizantal scrollbar. While overflow-y: scroll; allows you to scroll vertically.

<!DOCTYPE html>
<html>
<head>
<style>
.scroll {
    width: 500px;
    height: 300px;
    overflow-x: hidden; 
    overflow-y: scroll;
}


</style>
</head>
<body>

<div class="scroll"><h1> DATA </h1></div>

Go install fails with error: no install location for directory xxx outside GOPATH

In my case (OS X) it was because I have set GOPATH to /home/username/go (as per the book) instead of /Users/username/go

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

Adding sheets to end of workbook in Excel (normal method not working?)

A common mistake is

mainWB.Sheets.Add(After:=Sheets.Count)

which leads to Error 1004. Although it is not clear at all from the official documentation, it turns out that the 'After' parameter cannot be an integer, it must be a reference to a sheet in the same workbook.

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

You need to import FormsModule in your @NgModule Decorator, @NgModule is present in your moduleName.module.ts file.

import { FormsModule } from '@angular/forms';
@NgModule({
   imports: [
      BrowserModule,
      FormsModule
   ],
   declarations: [ AppComponent ],
   bootstrap: [ AppComponent ]
 })

Android: adb: Permission Denied

According to adb help:

adb root                     - restarts the adbd daemon with root permissions

Which indeed resolved the issue for me.

FFmpeg: How to split video efficiently?

Here is a simple Windows bat file to split incoming file into 50 parts. Each part has length 1 minute. Sorry for such dumb script. I hope it is better to have a dumb windows script instead of do not have it at all. Perhaps it help someone. (Based on "bat file for loop" from this site.)

set var=0
@echo off
:start
set lz=
if %var% EQU 50 goto end
if %var% LEQ 9 set lz=0
echo part %lz%%var%
ffmpeg -ss 00:%lz%%var%:00 -t 00:01:00 -i %1 -acodec copy -vcodec copy %2_%lz%%var%.mp4
set /a var+=1
goto start

:end
echo var has reached %var%.
exit

Check if a temporary table exists and delete if it exists before creating a temporary table

Instead of dropping and re-creating the temp table you can truncate and reuse it

IF OBJECT_ID('tempdb..#Results') IS NOT NULL
    Truncate TABLE #Results
else
    CREATE TABLE #Results
    (
        Company             CHAR(3),
        StepId              TINYINT,
        FieldId             TINYINT,
    )

If you are using Sql Server 2016 or Azure Sql Database then use the below syntax to drop the temp table and recreate it. More info here MSDN

Syntax

DROP TABLE [ IF EXISTS ] [ database_name . [ schema_name ] . | schema_name . ] table_name [ ,...n ]

Query:

DROP TABLE IF EXISTS tempdb.dbo.#Results
CREATE TABLE #Results
  (
   Company             CHAR(3),
   StepId              TINYINT,
   FieldId             TINYINT,
  )

Can't access RabbitMQ web management interface after fresh install

If on Windows and installed using chocolatey make sure firewall is allowing the default ports for it:

netsh advfirewall firewall add rule name="RabbitMQ Management" dir=in action=allow protocol=TCP localport=15672
netsh advfirewall firewall add rule name="RabbitMQ" dir=in action=allow protocol=TCP localport=5672

for the remote access.

jQuery get value of select onChange

Try this-

_x000D_
_x000D_
$('select').on('change', function() {_x000D_
  alert( this.value );_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<select>_x000D_
    <option value="1">One</option>_x000D_
    <option value="2">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

You can also reference with onchange event-

_x000D_
_x000D_
function getval(sel)_x000D_
{_x000D_
    alert(sel.value);_x000D_
}
_x000D_
<select onchange="getval(this);">_x000D_
    <option value="1">One</option>_x000D_
    <option value="2">Two</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Send email using java

It has been quite a while since this has been posted. But as of Nov 13, 2012 I can verify that port 465 still works.

Refer to GaryM's answer on this forum. I hope this helps few more people.

/*
* Created on Feb 21, 2005
*
*/

import java.security.Security;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GoogleTest {

    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final String SMTP_PORT = "465";
    private static final String emailMsgTxt = "Test Message Contents";
    private static final String emailSubjectTxt = "A test from gmail";
    private static final String emailFromAddress = "";
    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    private static final String[] sendTo = { "" };


    public static void main(String args[]) throws Exception {

        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

        new GoogleTest().sendSSLMessage(sendTo, emailSubjectTxt,
            emailMsgTxt, emailFromAddress);
        System.out.println("Sucessfully mail to All Users");
    }

    public void sendSSLMessage(String recipients[], String subject,
                               String message, String from) throws MessagingException {
        boolean debug = true;

        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");

        Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("xxxxxx", "xxxxxx");
            }
        });

        session.setDebug(debug);

        Message msg = new MimeMessage(session);
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);
    }
}

How do I remove an object from an array with JavaScript?

Well splice works:

var arr = [{id:1,name:'serdar'}];
arr.splice(0,1);
// []

Do NOT use the delete operator on Arrays. delete will not remove an entry from an Array, it will simply replace it with undefined.

var arr = [0,1,2];
delete arr[1];
// [0, undefined, 2]

But maybe you want something like this?

var removeByAttr = function(arr, attr, value){
    var i = arr.length;
    while(i--){
       if( arr[i] 
           && arr[i].hasOwnProperty(attr) 
           && (arguments.length > 2 && arr[i][attr] === value ) ){ 

           arr.splice(i,1);

       }
    }
    return arr;
}

Just an example below.

var arr = [{id:1,name:'serdar'}, {id:2,name:'alfalfa'},{id:3,name:'joe'}];
removeByAttr(arr, 'id', 1);   
// [{id:2,name:'alfalfa'}, {id:3,name:'joe'}]

removeByAttr(arr, 'name', 'joe');
// [{id:2,name:'alfalfa'}]

How to replace specific values in a oracle database column?

I'm using Version 4.0.2.15 with Build 15.21

For me I needed this:

UPDATE table_name SET column_name = REPLACE(column_name,"search str","replace str");

Putting t.column_name in the first argument of replace did not work.

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

For the scroll : 'html' or 'body' for setter (depend on browser)... 'window' for getter...

A jsFiddle for testing is here : http://jsfiddle.net/molokoloco/uCrLa/

var $window = $(window), // Set in cache, intensive use !
    $document = $(document),
    $body = $('body'),
    scrollElement = 'html, body',
    $scrollElement = $();

var isAnimated = false;

// Find scrollElement
// Inspired by http://www.zachstronaut.com/posts/2009/01/18/jquery-smooth-scroll-bugs.html
$(scrollElement).each(function(i) {
    // 'html, body' for setter... window for getter... 
    var initScrollTop = parseInt($(this).scrollTop(), 10);
    $(this).scrollTop(initScrollTop + 1);
    if ($window.scrollTop() == initScrollTop + 1) {
        scrollElement = this.nodeName.toLowerCase(); // html OR body
        return false; // Break
    }
});
$scrollElement = $(scrollElement);

// UTILITIES...
var getHash = function() {
        return window.location.hash || '';
    },
    setHash = function(hash) {
        if (hash && getHash() != hash) window.location.hash = hash;
    },
    getWinWidth = function() {
        return $window.width();
    },
    // iphone ? ((window.innerWidth && window.innerWidth > 0) ? window.innerWidth : $window.width());
    getWinHeight = function() {
        return $window.height();
    },
    // iphone ? ((window.innerHeight && window.innerHeight > 0) ? window.innerHeight : $window.height());
    getPageWidth = function() {
        return $document.width();
    },
    getPageHeight = function() {
        return $document.height();
    },
    getScrollTop = function() {
        return parseInt($scrollElement.scrollTop() || $window.scrollTop(), 10);
    },
    setScrollTop = function(y) {
        $scrollElement.stop(true, false).scrollTop(y);
    },
    myScrollTo = function(y, newAnchror) { // Call page scrolling to a value (like native window.scrollBy(x, y)) // Can be flooded
        isAnimated = true; // kill waypoint AUTO hash
        var duration = 360 + (Math.abs(y - getScrollTop()) * 0.42); // Duration depend on distance...
        if (duration > 2222) duration = 0; // Instant go !! ^^
        $scrollElement.stop(true, false).animate({
            scrollTop: y
        }, {
            duration: duration,
            complete: function() { // Listenner of scroll finish...
                if (newAnchror) setHash(newAnchror); // If new anchor
                isAnimated = false;
            }
        });
    },
    goToScreen = function(dir) { // Scroll viewport page by paginette // 1, -1 or factor
        var winH = parseInt((getWinHeight() * 0.75) * dir); // 75% de la hauteur visible comme unite
        myScrollTo(getScrollTop() + winH);
    };


myScrollTo((getPageHeight() / 2), 'iamAMiddleAnchor');

Add onClick event to document.createElement("th")

var newTH = document.createElement('th');
newTH.setAttribute("onclick", "removeColumn(#)");
newTH.setAttribute("id", "#");

function removeColumn(#){
// remove column #
}

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

Laravel Eloquent "WHERE NOT IN"

The dynamic way of implement whereNotIn:

 $users = User::where('status',0)->get();
    foreach ($users as $user) {
                $data[] = $user->id;
            }
    $available = User::orderBy('name', 'DEC')->whereNotIn('id', $data)->get();

FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

Change control panel Java's option about proxy to "direct", change window's internet option to not use proxy and reboot. It worked for me.

Move UIView up when the keyboard appears in iOS

Based on Daniel Krom's solution. This is version in swift 3.0. Works great with AutoLayout, and moves whole view when keyboard appears.

extension UIView {

    func bindToKeyboard(){
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    func unbindFromKeyboard(){
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    @objc
    func keyboardWillChange(notification: NSNotification) {

        guard let userInfo = notification.userInfo else { return }

        let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let curFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let targetFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let deltaY = targetFrame.origin.y - curFrame.origin.y

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
            self.frame.origin.y += deltaY
        })
    }  
}

How to use it: Add bindToKeyboard function in viewDidLoad like:

override func viewDidLoad() {
    super.viewDidLoad()

    view.bindToKeyboard()
}

And add unbindFromKeyboard function in deinit:

deinit {
    view.unbindFromKeyboard()
}

How to iterate over a string in C?

The last index of a C-String is always the integer value 0, hence the phrase "null terminated string". Since integer 0 is the same as the Boolean value false in C, you can use that to make a simple while clause for your for loop. When it hits the last index, it will find a zero and equate that to false, ending the for loop.

for(int i = 0; string[i]; i++) { printf("Char at position %d is %c\n", i, string[i]); }

How to find length of digits in an integer?

Without conversion to string

import math
digits = int(math.log10(n))+1

To also handle zero and negative numbers

import math
if n > 0:
    digits = int(math.log10(n))+1
elif n == 0:
    digits = 1
else:
    digits = int(math.log10(-n))+2 # +1 if you don't count the '-' 

You'd probably want to put that in a function :)

Here are some benchmarks. The len(str()) is already behind for even quite small numbers

timeit math.log10(2**8)
1000000 loops, best of 3: 746 ns per loop
timeit len(str(2**8))
1000000 loops, best of 3: 1.1 µs per loop

timeit math.log10(2**100)
1000000 loops, best of 3: 775 ns per loop
 timeit len(str(2**100))
100000 loops, best of 3: 3.2 µs per loop

timeit math.log10(2**10000)
1000000 loops, best of 3: 844 ns per loop
timeit len(str(2**10000))
100 loops, best of 3: 10.3 ms per loop

How to fix Git error: object file is empty?

if you have an OLD backup and is in a hurry:

make a NEW BACKUP of your current, git-broken, project path.

  1. move your .git to trash (never delete)
  2. copy .git from the OLD backup
  3. git pull (will create merge conflicts)
  4. move all your sources (everything you put in git) to trash: ./src (never delete)
  5. .copy all your sources (everything you put in git) from the NEW BACKUP
  6. accept all "merges" at git gui, push and... clap your hands!

How to pass arguments to entrypoint in docker-compose.yml

The command clause does work as @Karthik says above.

As a simple example, the following service will have a -inMemory added to its ENTRYPOINT when docker-compose up is run.

version: '2'
services:
  local-dynamo:
    build: local-dynamo
    image: spud/dynamo
    command: -inMemory

Cannot resolve symbol 'AppCompatActivity'

Remember to press Alt+Enter or add the import.

import android.support.v7.app.AppCompatActivity; 

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

Create an empty object in JavaScript with {} or new Object()?

Yes, There is a difference, they're not the same. It's true that you'll get the same results but the engine works in a different way for both of them. One of them is an object literal, and the other one is a constructor, two different ways of creating an object in javascript.

var objectA = {} //This is an object literal

var objectB = new Object() //This is the object constructor

In JS everything is an object, but you should be aware about the following thing with new Object(): It can receive a parameter, and depending on that parameter, it will create a string, a number, or just an empty object.

For example: new Object(1), will return a Number. new Object("hello") will return a string, it means that the object constructor can delegate -depending on the parameter- the object creation to other constructors like string, number, etc... It's highly important to keep this in mind when you're managing dynamic data to create objects..

Many authors recommend not to use the object constructor when you can use a certain literal notation instead, where you will be sure that what you're creating is what you're expecting to have in your code.

I suggest you to do a further reading on the differences between literal notation and constructors on javascript to find more details.

How to convert string into float in JavaScript?

If someone is looking for a way to parse float from an arbitrary string,

it can be done like that:

function extractFloat(text) {
  const match = text.match(/\d+((\.|,)\d+)?/)
  return match && match[0]
}

extractFloat('some text with float 5.25') // 5.25

Posting form to different MVC post action depending on the clicked submit button

This sounds to me like what you have is one command with 2 outputs, I would opt for making the change in both client and server for this.

At the client, use JS to build up the URL you want to post to (use JQuery for simplicity) i.e.

<script type="text/javascript">
    $(function() {
        // this code detects a button click and sets an `option` attribute
        // in the form to be the `name` attribute of whichever button was clicked
        $('form input[type=submit]').click(function() {
            var $form = $('form');
            form.removeAttr('option');
            form.attr('option', $(this).attr('name'));
        });
        // this code updates the URL before the form is submitted
        $("form").submit(function(e) { 
            var option = $(this).attr("option");
            if (option) {
                e.preventDefault();
                var currentUrl = $(this).attr("action");
                $(this).attr('action', currentUrl + "/" + option).submit();     
            }
        });
    });
</script>
...
<input type="submit" ... />
<input type="submit" name="excel" ... />

Now at the server side we can add a new route to handle the excel request

routes.MapRoute(
    name: "ExcelExport",
    url: "SearchDisplay/Submit/excel",
    defaults: new
    {
        controller = "SearchDisplay",
        action = "SubmitExcel",
    });

You can setup 2 distinct actions

public ActionResult SubmitExcel(SearchCostPage model)
{
   ...
}

public ActionResult Submit(SearchCostPage model)
{
   ...
}

Or you can use the ActionName attribute as an alias

public ActionResult Submit(SearchCostPage model)
{
   ...
}

[ActionName("SubmitExcel")]
public ActionResult Submit(SearchCostPage model)
{
   ...
}

Set database timeout in Entity Framework

Same as other answers, but as an extension method:

static class Extensions
{
    public static void SetCommandTimeout(this IObjectContextAdapter db, TimeSpan? timeout)
    {
        db.ObjectContext.CommandTimeout = timeout.HasValue ? (int?) timeout.Value.TotalSeconds : null;
    }
}

Is it possible to center text in select box?

Alternative "fake" solution if you have a list with options similar in text length (page select for example):

padding-left: calc(50% - 1em);

This works in Chrome, Firefox and Edge. The trick is here to push the text from the left to the center, then substract the half of length in px, em or whatever of the option text.

enter image description here

Best solution IMO (in 2017) is still replacing the select via JS and build your own fake select-box with divs or whatever and bind click events on it for cross-browser support.

Removing element from array in component state

Here is a way to remove the element from the array in the state using ES6 spread syntax.

onRemovePerson: (index) => {
  const data = this.state.data;
  this.setState({ 
    data: [...data.slice(0,index), ...data.slice(index+1)]
  });
}

Check if character is number?

Use combination of isNaN and parseInt functions:

var character = ... ; // your character
var isDigit = ! isNaN( parseInt(character) );

Another notable way - multiplication by one (like character * 1 instead of parseInt(character)) - makes a number not only from any numeric string, but also a 0 from empty string and a string containing only spaces so it is not suitable here.

Python: Checking if a 'Dictionary' is empty doesn't seem to work

Simple ways to check an empty dict are below:

        a= {}

    1. if a == {}:
           print ('empty dict')
    2. if not a:
           print ('empty dict')

Although method 1st is more strict as when a = None, method 1 will provide correct result but method 2 will give an incorrect result.

Ruby: How to iterate over a range, but in set increments?

See http://ruby-doc.org/core/classes/Range.html#M000695 for the full API.

Basically you use the step() method. For example:

(10..100).step(10) do |n|
    # n = 10
    # n = 20
    # n = 30
    # ...
end

Hide Signs that Meteor.js was Used

A Meteor app does not, by default, add any X-Powered-By headers to HTTP responses, as you might find in various PHP apps. The headers look like:

$ curl -I https://atmosphere.meteor.com  HTTP/1.1 200 OK content-type: text/html; charset=utf-8 date: Tue, 31 Dec 2013 23:12:25 GMT connection: keep-alive 

However, this doesn't mask that Meteor was used. Viewing the source of a Meteor app will look very distinctive.

<script type="text/javascript"> __meteor_runtime_config__ = {"meteorRelease":"0.6.3.1","ROOT_URL":"http://atmosphere.meteor.com","serverId":"62a4cf6a-3b28-f7b1-418f-3ddf038f84af","DDP_DEFAULT_CONNECTION_URL":"ddp+sockjs://ddp--****-atmosphere.meteor.com/sockjs"}; </script> 

If you're trying to avoid people being able to tell you are using Meteor even by viewing source, I don't think that's possible.

Unix epoch time to Java Date object

java.time

Using the java.time framework built into Java 8 and later.

import java.time.LocalDateTime;
import java.time.Instant;
import java.time.ZoneId;

long epoch = Long.parseLong("1081157732");
Instant instant = Instant.ofEpochSecond(epoch);
ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); # ZonedDateTime = 2004-04-05T09:35:32Z[UTC]

In this case you should better use ZonedDateTime to mark it as date in UTC time zone because Epoch is defined in UTC in Unix time used by Java.

ZoneOffset contains a handy constant for the UTC time zone, as seen in last line above. Its superclass, ZoneId can be used to adjust into other time zones.

ZoneId zoneId = ZoneId.of( "America/Montreal" );

Is there a way to run Python on Android?

Scripting Layer for Android

SL4A does what you want. You can easily install it directly onto your device from their site, and do not need root.

It supports a range of languages. Python is the most mature. By default, it uses Python 2.6, but there is a 3.2 port you can use instead. I have used that port for all kinds of things on a Galaxy S2 and it worked fine.

API

SL4A provides a port of their android library for each supported language. The library provides an interface to the underlying Android API through a single Android object.

from android import Android

droid = Android()
droid.ttsSpeak('hello world') # example using the text to speech facade

Each language has pretty much the same API. You can even use the JavaScript API inside webviews.

let droid = new Android();
droid.ttsSpeak("hello from js");

User Interfaces

For user interfaces, you have three options:

  • You can easily use the generic, native dialogues and menus through the API. This is good for confirmation dialogues and other basic user inputs.
  • You can also open a webview from inside a Python script, then use HTML5 for the user interface. When you use webviews from Python, you can pass messages back and forth, between the webview and the Python process that spawned it. The UI will not be native, but it is still a good option to have.
  • There is some support for native Android user interfaces, but I am not sure how well it works; I just haven't ever used it.

You can mix options, so you can have a webview for the main interface, and still use native dialogues.

QPython

There is a third party project named QPython. It builds on SL4A, and throws in some other useful stuff.

QPython gives you a nicer UI to manage your installation, and includes a little, touchscreen code editor, a Python shell, and a PIP shell for package management. They also have a Python 3 port. Both versions are available from the Play Store, free of charge. QPython also bundles libraries from a bunch of Python on Android projects, including Kivy, so it is not just SL4A.

Note that QPython still develop their fork of SL4A (though, not much to be honest). The main SL4A project itself is pretty much dead.

Useful Links

What is a word boundary in regex, does \b match hyphen '-'?

Check out the documentation on boundary conditions:

http://java.sun.com/docs/books/tutorial/essential/regex/bounds.html

Check out this sample:

public static void main(final String[] args)
    {
        String x = "I found the value -12 in my string.";
        System.err.println(Arrays.toString(x.split("\\b-?\\d+\\b")));
    }

When you print it out, notice that the output is this:

[I found the value -, in my string.]

This means that the "-" character is not being picked up as being on the boundary of a word because it's not considered a word character. Looks like @brianary kinda beat me to the punch, so he gets an up-vote.

Adding Python Path on Windows 7

  1. Hold Win and press Pause.
  2. Click Advanced System Settings.
  3. Click Environment Variables.
  4. Append ;C:\python27 to the Path variable.
  5. Restart Command Prompt.

How do you subtract Dates in Java?

Here's the basic approach,

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

Date beginDate = dateFormat.parse("2013-11-29");
Date endDate = dateFormat.parse("2013-12-4");

Calendar beginCalendar = Calendar.getInstance();
beginCalendar.setTime(beginDate);

Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);

There is simple way to implement it. We can use Calendar.add method with loop. The minus days between beginDate and endDate, and the implemented code as below,

int minusDays = 0;
while (true) {
  minusDays++;

  // Day increasing by 1
  beginCalendar.add(Calendar.DAY_OF_MONTH, 1);

  if (dateFormat.format(beginCalendar.getTime()).
            equals(dateFormat.format(endCalendar).getTime())) {
    break;
  }
}
System.out.println("The subtraction between two days is " + (minusDays + 1));**

IIS error, Unable to start debugging on the webserver

I didn't see this answer on this thread or the (possible duplicated) question here.

I fixed the issue by:

  • Opening the Task Manager (ctrl+alt+del)
  • Under the Processes tab, End the task of IIS Worker Process (This may now be listed as Microsoft.IIS.Worker.Process or something similar) (You may have to click More details at the bottom if you don't see all of the processes)
  • Then going to the Services tab, Stop the IISADMIN service and the start it up again.

Run the program and that should hopefully fix it! Happy Coding and Debugging! :)

CSS: Creating textured backgrounds

with latest CSS3 technology, it is possible to create textured background. Check this out: http://lea.verou.me/css3patterns/#

but it still limited on so many aspect. And browser support is also not so ready.

your best bet is using small texture image and make repeat to that background. you could get some nice ready to use texture image here:

http://subtlepatterns.com

How to get current user in asp.net core

If you are using the scafolded Identity and using Asp.net Core 2.2+ you can access the current user from a view like this:

@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager

 @if (SignInManager.IsSignedIn(User))
    {
        <p>Hello @User.Identity.Name!</p>
    }
    else
    {
        <p>You're not signed in!</p>
    }

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-2.2&tabs=visual-studio

How to determine previous page URL in Angular?

FOR ANGULAR 7+

Actually since Angular 7.2 there is not need to use a service for saving the previous url. You could just use the state object to set the last url before linking to the login page. Here is an example for a login scenario.

@Component({ ... })
class SomePageComponent {
  constructor(private router: Router) {}

  checkLogin() {
    if (!this.auth.loggedIn()) {
      this.router.navigate(['login'], { state: { redirect: this.router.url } });
    }
  }
}
@Component({...})
class LoginComponent {
  constructor(private router: Router) {}

  backToPreviousPage() {
    const { redirect } = window.history.state;

    this.router.navigateByUrl(redirect || '/homepage');
  }
}
----------------

Additionally you could also pass the data in the template:

@Component({
  template: '<a routerLink="/some-route" [state]="{ redirect: router.url}">Go to some route</a>'
})
class SomePageComponent {
  constructor(public router: Router) {}
}

Jquery Ajax Loading image

Description

You should do this using jQuery.ajaxStart and jQuery.ajaxStop.

  1. Create a div with your image
  2. Make it visible in jQuery.ajaxStart
  3. Hide it in jQuery.ajaxStop

Sample

<div id="loading" style="display:none">Your Image</div>

<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script>
    $(function () {
        var loading = $("#loading");
        $(document).ajaxStart(function () {
            loading.show();
        });

        $(document).ajaxStop(function () {
            loading.hide();
        });

        $("#startAjaxRequest").click(function () {
            $.ajax({
                url: "http://www.google.com",
                // ... 
            });
        });
    });
</script>

<button id="startAjaxRequest">Start</button>

More Information

C: What is the difference between ++i and i++?

Pre-crement means increment on the same line. Post-increment means increment after the line executes.

int j=0;
System.out.println(j); //0
System.out.println(j++); //0. post-increment. It means after this line executes j increments.

int k=0;
System.out.println(k); //0
System.out.println(++k); //1. pre increment. It means it increments first and then the line executes

When it comes with OR, AND operators, it becomes more interesting.

int m=0;
if((m == 0 || m++ == 0) && (m++ == 1)) { //false
/* in OR condition if first line is already true then compiler doesn't check the rest. It is technique of compiler optimization */
System.out.println("post-increment "+m);
}

int n=0;
if((n == 0 || n++ == 0) && (++n == 1)) { //true
System.out.println("pre-increment "+n); //1
}

In Array

System.out.println("In Array");
int[] a = { 55, 11, 15, 20, 25 } ;
int ii, jj, kk = 1, mm;
ii = ++a[1]; // ii = 12. a[1] = a[1] + 1
System.out.println(a[1]); //12

jj = a[1]++; //12
System.out.println(a[1]); //a[1] = 13

mm = a[1];//13
System.out.printf ( "\n%d %d %d\n", ii, jj, mm ) ; //12, 12, 13

for (int val: a) {
     System.out.print(" " +val); //55, 13, 15, 20, 25
}

In C++ post/pre-increment of pointer variable

#include <iostream>
using namespace std;

int main() {

    int x=10;
    int* p = &x;

    std::cout<<"address = "<<p<<"\n"; //prints address of x
    std::cout<<"address = "<<p<<"\n"; //prints (address of x) + sizeof(int)
    std::cout<<"address = "<<&x<<"\n"; //prints address of x

    std::cout<<"address = "<<++&x<<"\n"; //error. reference can't re-assign because it is fixed (immutable)
}

Declaring and using MySQL varchar variables

If you are using phpmyadmin to add new routine then don't forget to wrap your code between BEGIN and ENDenter image description here

NameError: global name is not defined

You need to do:

import sqlitedbx

def main():
    db = sqlitedbx.SqliteDBzz()
    db.connect()

if __name__ == "__main__":
    main()

Convert integer value to matching Java Enum

As @MeBigFatGuy says, except you can make your static {...} block use a loop over the values() collection:

static {
    for (PcapLinkType type : PcapLinkType.values()) {
        intToTypeMap.put(type.getValue(), type);
    }
}

How do I change Bootstrap 3 column order on mobile layout?

October 2017

I would like to add another Bootstrap 4 solution. One that worked for me.

The CSS "Order" property, combined with a media query, can be used to re-order columns when they get stacked in smaller screens.

Something like this:

@media only screen and (max-width: 768px) {
    #first {
        order: 2;
    }
    #second {
        order: 4;
    }
    #third {
        order: 1;
    }
    #fourth {
        order: 3;
    }
}

CodePen Link: https://codepen.io/preston206/pen/EwrXqm

Adjust the screen size and you'll see the columns get stacked in a different order.

I'll tie this in with the original poster's question. With CSS, the navbar, sidebar, and content can be targeted and then order properties applied within a media query.

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable

For people using Tomee or Tomcat and can't get it working, try to create context.xml in META-INF and add allowCasualMultipartParsing="true"

<?xml version="1.0" encoding="UTF-8"?>
<Context allowCasualMultipartParsing="true">
  <!-- empty or not depending your project -->
</Context>

.htaccess File Options -Indexes on Subdirectories

The correct answer is

Options -Indexes

You must have been thinking of

AllowOverride All

https://httpd.apache.org/docs/2.2/howto/htaccess.html

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

Resource leak: 'in' is never closed

You should close your Scanner when you're done with it:

in.close();

What is the difference between %g and %f in C?

As Unwind points out f and g provide different default outputs.

Roughly speaking if you care more about the details of what comes after the decimal point I would do with f and if you want to scale for large numbers go with g. From some dusty memories f is very nice with small values if your printing tables of numbers as everything stays lined up but something like g is needed if you stand a change of your numbers getting large and your layout matters. e is more useful when your numbers tend to be very small or very large but never near ten.

An alternative is to specify the output format so that you get the same number of characters representing your number every time.

Sorry for the woolly answer but it is a subjective out put thing that only gets hard answers if the number of characters generated is important or the precision of the represented value.

How to get all keys with their values in redis

There is no native way of doing this.

The Redis command documentation contains no native commands for getting the key and value of multiple keys.

The most native way of doing this would be to load a lua script into your redis using the SCRIPT LOAD command or the EVAL command.

Bash Haxx solution

A workaround would be to use some bash magic, like this:

echo 'keys YOURKEY*' | redis-cli | sed 's/^/get /' | redis-cli 

This will output the data from all the keys which begin with YOURKEY

Note that the keys command is a blocking operation and should be used with care.

array filter in python?

Yes, the filter function:

filter(lambda x: x not in subset_of_A, A)

Count multiple columns with group by in one query

One solution is to wrap it in a subquery

SELECT *
FROM
(
    SELECT COUNT(column1),column1 FROM table GROUP BY column1
    UNION ALL
    SELECT COUNT(column2),column2 FROM table GROUP BY column2
    UNION ALL
    SELECT COUNT(column3),column3 FROM table GROUP BY column3
) s

Learning Ruby on Rails

Fantastic decision! It is extremely useful to get a grounding in Ruby before going to Rails so here is my take on the best path to Rails:

Aside from books the most important thing is to get feedback on what you are doing. To do this I recommend spending time in irc.freenode.net #ruby and #rubyonrails. It is also extremely helpful to post things you are working on or having trouble with here on stackoverflow as the comments, explanations and different way of thinking about things that people provide are invaluable.

You should also definitely check out the Ruby Rogues podcast, they provide invaluable information and the commentators are all extremely respected people in the Ruby community. And for your viewing and reading pleasure (in that order,) head over to Ryan Bates's Railscasts and then Eifion Bedford's Asciicasts.

Finally, I recommend looking into different gems on github, reading the code and then contributing to them. You don't have to get overly ambitious and do massive recodes, especially at first. Just start with small things like editing and making the README files a little easier to read.

I don't use an IDE but at Railsconf I saw a demo of Rubymine from Jetbrains and it seemed pretty amazing.

Controller 'ngModel', required by directive '...', can't be found

I faced the same error, in my case I miss-spelled ng-model directive something like "ng-moel"

Wrong one: ng-moel="user.name" Right one: ng-model="user.name"

enter image description here

How do I call a non-static method from a static method in C#?

Assuming that both data1() and data2() are in the same class, then another alternative is to make data1() static.

private static void data1()
{
}
private static void data2()
{
   data1();
}

.prop('checked',false) or .removeAttr('checked')?

I recommend to use both, prop and attr because I had problems with Chrome and I solved it using both functions.

if ($(':checkbox').is(':checked')){
    $(':checkbox').prop('checked', true).attr('checked', 'checked');
}
else {
    $(':checkbox').prop('checked', false).removeAttr('checked');
}

How to get all files under a specific directory in MATLAB?

This is a handy function for getting filenames, with the specified format (usually .mat) in a root folder!

    function filenames = getFilenames(rootDir, format)
        % Get filenames with specified `format` in given `foler` 
        %
        % Parameters
        % ----------
        % - rootDir: char vector
        %   Target folder
        % - format: char vector = 'mat'
        %   File foramt

        % default values
        if ~exist('format', 'var')
            format = 'mat';
        end

        format = ['*.', format];
        filenames = dir(fullfile(rootDir, format));
        filenames = arrayfun(...
            @(x) fullfile(x.folder, x.name), ...
            filenames, ...
            'UniformOutput', false ...
        );
    end

In your case, you can use the following snippet :)

filenames = getFilenames('D:/dic/**');
for i = 1:numel(filenames)
    filename = filenames{i};
    % do your job!
end

Image resizing in React Native

Use Resizemode with 'cover' or 'contain' and set the height and with of the Image.

Circular dependency in Spring

Constructor Injection fails when there is Circular Dependency between spring beans. So in this case we Setter injection helps to resolve the issue.

Basically, Constructor Injection is useful for Mandatory dependencies, for optional dependencies better to use Setter injection because we can do re-injection.

How can I disable the UITableView selection?

cell.selectionStyle = UITableViewCellSelectionStyleNone;

How to set the From email address for mailx command?

Just ran into this syntax problem on a CentOS 7 machine.

On a very old Ubuntu machine running mail, the syntax for a nicely composed email is

echo -e "$body" | mail -s "$subject" -a "From: Sender Name <$sender>" "$recipient"

However on a CentOS 7 box which came with mailx installed, it's quite different:

echo -e "$body" | mail -s "$subject" -S "from=Sender Name <$sender>" "$recipient"

Consulting man mail indicates that -r is deprecated and the 'From' sender address should now be set directly using -S "variable=value".

In these and subsequent examples, I'm defining $sender as "Sender Name <[email protected]>" and $recipients as "[email protected]" as I do in my bash script.

You may then find, as I did, that when you try to generate the email's body content in your script at the point of sending the email, you encounter a strange behaviour where the email body is instead attached as a binary file ("ATT00001.bin", "application/octet-stream" or "noname", depending on client).

This behaviour is how Heirloom mailx handles unrecognised / control characters in text input. (More info: https://access.redhat.com/solutions/1136493, which itself references the mailx man page for the solution.)

To get around this, I used a method which pipes the generated output through tr before passing to mail, and also specifies the charset of the email:

echo -e "$body" | tr -d \\r | mail -s "$subject" -S "from=$sender" -S "sendcharsets=utf-8,iso-8859-1" "$recipients"

In my script, I'm also explicitly delaring the locale beforehand as it's run as a cronjob (and cron doesn't inherit environmental variables):

LANG="en_GB.UTF8" ; export LANG ;

(An alternate method of setting locales for cronjobs is discussed here)

More info on these workarounds via https://stackoverflow.com/a/29826988/253139 and https://stackoverflow.com/a/3120227/253139.

iPhone - Get Position of UIView within entire UIWindow

In Swift:

let globalPoint = aView.superview?.convertPoint(aView.frame.origin, toView: nil)

SSL handshake alert: unrecognized_name error since upgrade to Java 1.7.0

If you are building a client with Resttemplate, you can only set the endpoint like this: https://IP/path_to_service and set the requestFactory.
With this solution you don't need to RESTART your TOMCAT or Apache:

public static HttpComponentsClientHttpRequestFactory requestFactory(CloseableHttpClient httpClient) {
    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    };

    SSLContext sslContext = null;
    try {
        sslContext = org.apache.http.ssl.SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy)
                .build();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }   

    HostnameVerifier hostnameVerifier = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    final SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext,hostnameVerifier);

    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new PlainConnectionSocketFactory())
            .register("https", csf)
            .build();

    final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setMaxTotal(100);
    httpClient = HttpClients.custom()
            .setSSLSocketFactory(csf)
            .setConnectionManager(cm)
            .build();

    HttpComponentsClientHttpRequestFactory requestFactory =
            new HttpComponentsClientHttpRequestFactory();

    requestFactory.setHttpClient(httpClient);

    return requestFactory;
}

C++ equivalent of java's instanceof

Try using:

if(NewType* v = dynamic_cast<NewType*>(old)) {
   // old was safely casted to NewType
   v->doSomething();
}

This requires your compiler to have rtti support enabled.

EDIT: I've had some good comments on this answer!

Every time you need to use a dynamic_cast (or instanceof) you'd better ask yourself whether it's a necessary thing. It's generally a sign of poor design.

Typical workarounds is putting the special behaviour for the class you are checking for into a virtual function on the base class or perhaps introducing something like a visitor where you can introduce specific behaviour for subclasses without changing the interface (except for adding the visitor acceptance interface of course).

As pointed out dynamic_cast doesn't come for free. A simple and consistently performing hack that handles most (but not all cases) is basically adding an enum representing all the possible types your class can have and check whether you got the right one.

if(old->getType() == BOX) {
   Box* box = static_cast<Box*>(old);
   // Do something box specific
}

This is not good oo design, but it can be a workaround and its cost is more or less only a virtual function call. It also works regardless of RTTI is enabled or not.

Note that this approach doesn't support multiple levels of inheritance so if you're not careful you might end with code looking like this:

// Here we have a SpecialBox class that inherits Box, since it has its own type
// we must check for both BOX or SPECIAL_BOX
if(old->getType() == BOX || old->getType() == SPECIAL_BOX) {
   Box* box = static_cast<Box*>(old);
   // Do something box specific
}

Adding form action in html in laravel

You need to set a name to your Routes. Like this:


    Route::get('/','WelcomeController@home')->name('welcome.home');
    Route::post('/', array('as' => 'log_in', 'uses' => 'WelcomeController@log_in'))->name('welcome.log_in');
    Route::get('home', 'HomeController@index')->name('home.index');

I just put name on Routes that need this. In my case, to call from tag form at blade template. Like this:

<form action="{{ route('home.index') }}" >

Or, You can do this:

<form action="/" >

How can I write to the console in PHP?

I was looking for a way to debug code in a WordPress plugin that I was developing and came across this post.

I took the bits of code that are most applicable to me from other responses and combined these into a function that I can use for debugging WordPress. The function is:

function debug_log($object=null, $label=null, $priority=1) {
    $priority = $priority<1? 1: $priority;
    $message = json_encode($object, JSON_PRETTY_PRINT);
    $label = "Debug" . ($label ? " ($label): " : ': ');
    echo "<script>console.log('" . str_repeat("-", $priority-1) . $label . "', " . $message . ");</script>";
}

Usage is as follows:

$txt = 'This is a test string';
$sample_array = array('cat', 'dog', 'pig', 'ant', 'fly');
debug_log($txt, '', 7);
debug_log($sample_array);

If this function is used with WordPress development, the function should be placed in the functions.php file of the child theme and can then be called anywhere in the code.

How do I pick randomly from an array?

myArray.sample

will return 1 random value.

myArray.shuffle.first

will also return 1 random value.

Copy directory to another directory using ADD command

ADD go /usr/local/

will copy the contents of your local go directory in the /usr/local/ directory of your docker image.

To copy the go directory itself in /usr/local/ use:

ADD go /usr/local/go

or

COPY go /usr/local/go

Is it possible to create a temporary table in a View and drop it after select?

You can achieve what you are trying to do, using a Stored Procedure which returns a query result. Views are not suitable / developed for operations like this one.

Why does Eclipse Java Package Explorer show question mark on some classes?

With some version-control plug-ins, it means that the local file has not yet been shared with the version-control repository. (In my install, this includes plug-ins for CVS and git, but not Perforce.)

You can sometimes see a list of these decorations in the plug-in's preferences under Team/X/Label Decorations, where X describes the version-control system.

For example, for CVS, the list looks like this:

enter image description here

These adornments are added to the object icons provided by Eclipse. For example, here's a table of icons for the Java development environment.

Font is not available to the JVM with Jasper Reports

There are three method to avoid such a problem.

Method 1 : by setting ignore missing font property.

JRProperties.setProperty("net.sf.jasperreports.awt.ignore.missing.font", "true");

or you can set this property by entering following line into .jrxml file.

<property name="net.sf.jasperreports.awt.ignore.missing.font" value="true"/>

Method 2 : by setting default font property.

JRProperties.setProperty("net.sf.jasperreports.default.font.name", "Sans Serif");

or you can set this property by entering following line into .jrxml file.

<property name="net.sf.jasperreports.default.font.name" value="Sans Serif"/>

Method 3 : by adding missing font property.

Firstly install missing fonts in IReport by selecting " Tools >> Options >> Fonts >> Install Font " then select the all font and Export this By clicking on "Export as Extension" with .jar Extension.

You can use this jar for Jasperreports-font.X.X.X.jar which will be present in your project library or classpath.

WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property

You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.

Source: http://www.albeesonline.com/blog/2008/11/29/warning-setpropertiesruleserverserviceenginehostcontext-setting-property/

Javascript: Fetch DELETE and PUT requests

Some examples:

async function loadItems() { try { let response = await fetch(https://url/${AppID}); let result = await response.json(); return result; } catch (err) { } }

async function addItem(item) {
    try {
        let response = await fetch("https://url", {
            method: "POST",
            body: JSON.stringify({
                AppId: appId,
                Key: item,
                Value: item,
                someBoolean: false,
            }),
            headers: {
                "Content-Type": "application/json",
            },
        });
        let result = await response.json();
        return result;
    } catch (err) {
    }
}

async function removeItem(id) {
    try {
        let response = await fetch(`https://url/${id}`, {
            method: "DELETE",
        });
    } catch (err) {
    }
}

async function updateItem(item) {
    try {
        let response = await fetch(`https://url/${item.id}`, {
            method: "PUT",
            body: JSON.stringify(todo),
            headers: {
                "Content-Type": "application/json",
            },
        });
    } catch (err) {
    }
}

Jackson Vs. Gson

I did this research the last week and I ended up with the same 2 libraries. As I'm using Spring 3 (that adopts Jackson in its default Json view 'JacksonJsonView') it was more natural for me to do the same. The 2 lib are pretty much the same... at the end they simply map to a json file! :)

Anyway as you said Jackson has a + in performance and that's very important for me. The project is also quite active as you can see from their web page and that's a very good sign as well.

How to Copy Text to Clip Board in Android?

Just write this code:

clipboard.setText(getstring);

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

You need to set utf8mb4 in meta html and also in your server alter tabel and set collation to utf8mb4

How to view/delete local storage in Firefox?

As 'localStorage' is just another object, you can: create, view, and edit it in the 'Console'. Simply enter 'localStorage' as a command and press enter, it'll display a string containing the key-value pairs of localStorage (Tip: Click on that string for formatted output, i.e. to display each key-value pair in each line).

Node.js: printing to console without a trailing newline?

Also, if you want to overwrite messages in the same line, for instance in a countdown, you could add '\r' at the end of the string.

process.stdout.write("Downloading " + data.length + " bytes\r");

how to change class name of an element by jquery

$('.IsBestAnswer').addClass('bestanswer').removeClass('IsBestAnswer');

Case in method names is important, so no addclass.

jQuery addClass()
jQuery removeClass()

How can you integrate a custom file browser/uploader with CKEditor?

For people wondering about a Servlet/JSP implementation here's how you go about doing it... I will be explaining uploadimage below also.

1) First make sure you have added the filebrowser and uploadimage variable to your config.js file. Make you also have the uploadimage and filebrowser folder inside the plugins folder too.

2) This part is where it tripped me up:

The Ckeditor website documentation says you need to use these two methods:

function getUrlParam( paramName ) {
    var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
    var match = window.location.search.match( reParam );
    return ( match && match.length > 1 ) ? match[1] : null;
}
function returnFileUrl() {
    var funcNum = getUrlParam( 'CKEditorFuncNum' );
    var fileUrl = 'https://patiliyo.com/wp-content/uploads/2017/07/ruyada-kedi-gormek.jpg';
    window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl );
    window.close();
}

What they don't mention is that these methods have to be on a different page and not the page where you are clicking the browse server button from.

So if you have ckeditor initialized in page editor.jsp then you need to create a file browser (with basic html/css/javascript) in page filebrowser.jsp.

editor.jsp (all you need is this in your script tag) This page will open filebrowser.jsp in a mini window when you click on the browse server button.

CKEDITOR.replace( 'editor', {
    filebrowserBrowseUrl: '../filebrowser.jsp', //jsp page with jquery to call servlet and get image files to view
    filebrowserUploadUrl: '../UploadImage', //servlet

});

filebrowser.jsp (is the custom file browser you built which will contain the methods mentioned above)

<head>
<script src="../../ckeditor/ckeditor.js"></script>
</head>
<body>
<script>


function getUrlParam( paramName ) {
    var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
    var match = window.location.search.match( reParam );
    return ( match && match.length > 1 ) ? match[1] : null;
}

function returnFileUrl() {
    var funcNum = getUrlParam( 'CKEditorFuncNum' );
var fileUrl = 'https://patiliyo.com/wp-content/uploads/2017/07/ruyada-kedi-gormek.jpg';
    window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl );
    window.close();
}


//when this window opens it will load all the images which you send from the FileBrowser Servlet. 
getImages();
function getImages(){
    $.get("../FileBrowser", function(responseJson) {    
        //do something with responseJson (like create <img> tags and update the src attributes) 
    });
}

   //you call this function and pass 'fileUrl' when user clicks on an image that you loaded into this window from a servlet
returnFileUrl();
</script>
</body>

3) The FileBrowser Servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Images i = new Images();
    List<ImageObject> images = i.getImages(); //get images from your database or some cloud service or whatever (easier if they are in a url ready format)
    String json = new Gson().toJson(images);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

4) UploadImage Servlet

Go back to your config.js file for ckeditor and add the following line:

//https://docs.ckeditor.com/ckeditor4/latest/guide/dev_file_upload.html
config.uploadUrl = '/UploadImage';

Then you can drag and drop files also:

   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


                Images i = new Images();

   //do whatever you usually do to upload your image to your server (in my case i uploaded to google cloud storage and saved the url in a database. 

   //Now this part is important. You need to return the response in json format. And it has to look like this:

//      https://docs.ckeditor.com/ckeditor4/latest/guide/dev_file_upload.html
//      response must be in this format:
//      {
//          "uploaded": 1,
//          "fileName": "example.png",
//          "url": "https://www.cats.com/example.png"
//      }

                    String image = "https://www.cats.com/example.png";
                        ImageObject objResponse = i.getCkEditorObjectResponse(image);
                        String json = new Gson().toJson(objResponse);
                        response.setContentType("application/json");
                        response.setCharacterEncoding("UTF-8");
                        response.getWriter().write(json);
                    }
                }

And that's all folks. Hope it helps someone.

Program to find largest and second largest number in array

The problem with your code is a logic problem (which is what most coding is about). If the largest number is first then it gets the second largest number wrong ... why?

Well, look at your logic for deciding on the second largest number. You first set it to be equal to the first element in the array and then you go through the array and change the index if the element is greater than the current second largest number (which will never be true because we already set it to be the largest number!).

To solve it you can special case this: check if the largest number was the first and if so then set it to the second element (and then special case the issue of someone asking to find the highest two elements in a one element array, without reading past the end of an array.)

I think the method given in chqrlie's answer to do this all in one pass is best. And logical too: write a program to find the largest number. Second largest number, well that's just the one which was previously the largest!

How can I check what version/edition of Visual Studio is installed programmatically?

if somebody needs C# example then:

var registry = Registry.ClassesRoot;
var subKeyNames = registry.GetSubKeyNames();
var regex = new Regex(@"^VisualStudio\.edmx\.(\d+)\.(\d+)$");
foreach (var subKeyName in subKeyNames)
{
    var match = regex.Match(subKeyName);
    if (match.Success)
        Console.WriteLine("V" + match.Groups[1].Value + "." + match.Groups[2].Value);
}

Basic authentication for REST API using spring restTemplate

There are multiple ways to add the basic HTTP authentication to the RestTemplate.

1. For a single request

try {
    // request url
    String url = "https://jsonplaceholder.typicode.com/posts";

    // create auth credentials
    String authStr = "username:password";
    String base64Creds = Base64.getEncoder().encodeToString(authStr.getBytes());

    // create headers
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);

    // create request
    HttpEntity request = new HttpEntity(headers);

    // make a request
    ResponseEntity<String> response = new RestTemplate().exchange(url, HttpMethod.GET, request, String.class);

    // get JSON response
    String json = response.getBody();

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

If you are using Spring 5.1 or higher, it is no longer required to manually set the authorization header. Use headers.setBasicAuth() method instead:

// create headers
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("username", "password");

2. For a group of requests

@Service
public class RestService {

    private final RestTemplate restTemplate;

    public RestService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder
                .basicAuthentication("username", "password")
                .build();
    }

   // use `restTemplate` instance here
}

3. For each and every request

@Bean
RestOperations restTemplateBuilder(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.basicAuthentication("username", "password").build();
}

I hope it helps!

Unable to get spring boot to automatically create database schema

Just add createDatabaseIfNotExist=true parameter in spring datasource url

Example: spring.datasource.url= jdbc:mysql://localhost:3306/test?createDatabaseIfNotExist=true

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

how to overwrite css style

Using !important is not recommended but in this situation I think you should -

Write this in your internal CSS -

.flex-control-thumbs li {
  width: auto !important;
  float: none !important;
}

Java 256-bit AES Password-Based Encryption

Use this class for encryption. It works.

public class ObjectCrypter {


    public static byte[] encrypt(byte[] ivBytes, byte[] keyBytes, byte[] mes) 
            throws NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            InvalidAlgorithmParameterException,
            IllegalBlockSizeException,
            BadPaddingException, IOException {

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = null;
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
        return  cipher.doFinal(mes);

    }

    public static byte[] decrypt(byte[] ivBytes, byte[] keyBytes, byte[] bytes) 
            throws NoSuchAlgorithmException,
            NoSuchPaddingException,
            InvalidKeyException,
            InvalidAlgorithmParameterException,
            IllegalBlockSizeException,
            BadPaddingException, IOException, ClassNotFoundException {

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
        return  cipher.doFinal(bytes);

    }
}

And these are ivBytes and a random key;

String key = "e8ffc7e56311679f12b6fc91aa77a5eb";

byte[] ivBytes = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
keyBytes = key.getBytes("UTF-8");

How to implement "select all" check box in HTML?

Using jQuery and knockout:

With this binding main checkbox stays in sync with underliying checkboxes, it will be unchecked unless all checkboxes checked.

ko.bindingHandlers.allChecked = {
  init: function (element, valueAccessor) {
    var selector = valueAccessor();

    function getChecked () {
      element.checked = $(selector).toArray().every(function (checkbox) {
        return checkbox.checked;
      });
    }

    function setChecked (value) {
      $(selector).toArray().forEach(function (checkbox) {
        if (checkbox.checked !== value) {
          checkbox.click();
        }
      });
    }

    ko.utils.registerEventHandler(element, 'click', function (event) {
      setChecked(event.target.checked);
    });

    $(window.document).on('change', selector, getChecked);

    ko.utils.domNodeDisposal.addDisposeCallback(element, () => {
      $(window.document).off('change', selector, getChecked);
    });

    getChecked();
  }
};

in html:

<input id="check-all-values" type="checkbox" data-bind="allChecked: '.checkValue'"/>
<input id="check-1" type="checkbox" class="checkValue"/>
<input id="check-2" type="checkbox" class="checkValue"/>

How to format string to money

decimal value = 0.00M;
value = Convert.ToDecimal(12345.12345);
Console.WriteLine(value.ToString("C"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C1"));
//OutPut : $12345.1
Console.WriteLine(value.ToString("C2"));
//OutPut : $12345.12
Console.WriteLine(value.ToString("C3"));
//OutPut : $12345.123
Console.WriteLine(value.ToString("C4"));
//OutPut : $12345.1234
Console.WriteLine(value.ToString("C5"));
//OutPut : $12345.12345
Console.WriteLine(value.ToString("C6"));
//OutPut : $12345.123450

Console output:

What is the difference between DAO and Repository patterns?

The key difference is that a repository handles the access to the aggregate roots in a an aggregate, while DAO handles the access to entities. Therefore, it's common that a repository delegates the actual persistence of the aggregate roots to a DAO. Additionally, as the aggregate root must handle the access of the other entities, then it may need to delegate this access to other DAOs.

How to change credentials for SVN repository in Eclipse?

Very simple step to follow: Eclipse: Window ----> Preferences -----> SVN -----> SVN Interface ----->Select SVNKit (pure Java)

Iterate through a C array

I think you should store the size somewhere.

The null-terminated-string kind of model for determining array length is a bad idea. For instance, getting the size of the array will be O(N) when it could very easily have been O(1) otherwise.

Having that said, a good solution might be glib's Arrays, they have the added advantage of expanding automatically if you need to add more items.

P.S. to be completely honest, I haven't used much of glib, but I think it's a (very) reputable library.

Errno 13 Permission denied Python

Your user don't have the right permissions to read the file, since you used open() without specifying a mode.

Since you're using Windows, you should read a little more about File and Folder Permissions.

Also, if you want to play with your file permissions, you should right-click it, choose Properties and select Security tab.

Or if you want to be a little more hardcore, you can run your script as admin.

SO Related Questions:

Excel Validation Drop Down list using VBA

You are defining your array as xlValidateList(), so when you try to assign the type, it gets confused as to what you are trying to assign to the type.

Instead, try this:

Dim MyList(5) As String
MyList(0) = 1
MyList(1) = 2
MyList(2) = 3
MyList(3) = 4
MyList(4) = 5
MyList(5) = 6

With Range("A1").Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
         Operator:=xlBetween, Formula1:=Join(MyList, ",")
End With

JRE installation directory in Windows

Not as a command, but this information is in the registry:

  • Open the key HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  • Read the CurrentVersion REG_SZ
  • Open the subkey under Java Runtime Environment named with the CurrentVersion value
  • Read the JavaHome REG_SZ to get the path

For example on my workstation i have

HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  CurrentVersion = "1.6"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5
  JavaHome = "C:\Program Files\Java\jre1.5.0_20"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6
  JavaHome = "C:\Program Files\Java\jre6"

So my current JRE is in C:\Program Files\Java\jre6

How to merge two PDF files into one in Java?

This is a ready to use code, merging four pdf files with itext.jar from http://central.maven.org/maven2/com/itextpdf/itextpdf/5.5.0/itextpdf-5.5.0.jar, more on http://tutorialspointexamples.com/

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * This class is used to merge two or more 
 * existing pdf file using iText jar.
 */
public class PDFMerger {

static void mergePdfFiles(List<InputStream> inputPdfList,
        OutputStream outputStream) throws Exception{
    //Create document and pdfReader objects.
    Document document = new Document();
    List<PdfReader> readers = 
            new ArrayList<PdfReader>();
    int totalPages = 0;

    //Create pdf Iterator object using inputPdfList.
    Iterator<InputStream> pdfIterator = 
            inputPdfList.iterator();

    // Create reader list for the input pdf files.
    while (pdfIterator.hasNext()) {
            InputStream pdf = pdfIterator.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages = totalPages + pdfReader.getNumberOfPages();
    }

    // Create writer for the outputStream
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);

    //Open document.
    document.open();

    //Contain the pdf data.
    PdfContentByte pageContentByte = writer.getDirectContent();

    PdfImportedPage pdfImportedPage;
    int currentPdfReaderPage = 1;
    Iterator<PdfReader> iteratorPDFReader = readers.iterator();

    // Iterate and process the reader list.
    while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();
            //Create page and add content.
            while (currentPdfReaderPage <= pdfReader.getNumberOfPages()) {
                  document.newPage();
                  pdfImportedPage = writer.getImportedPage(
                          pdfReader,currentPdfReaderPage);
                  pageContentByte.addTemplate(pdfImportedPage, 0, 0);
                  currentPdfReaderPage++;
            }
            currentPdfReaderPage = 1;
    }

    //Close document and outputStream.
    outputStream.flush();
    document.close();
    outputStream.close();

    System.out.println("Pdf files merged successfully.");
}

public static void main(String args[]){
    try {
        //Prepare input pdf file list as list of input stream.
        List<InputStream> inputPdfList = new ArrayList<InputStream>();
        inputPdfList.add(new FileInputStream("..\\pdf\\pdf_1.pdf"));
        inputPdfList.add(new FileInputStream("..\\pdf\\pdf_2.pdf"));
        inputPdfList.add(new FileInputStream("..\\pdf\\pdf_3.pdf"));
        inputPdfList.add(new FileInputStream("..\\pdf\\pdf_4.pdf"));


        //Prepare output stream for merged pdf file.
        OutputStream outputStream = 
                new FileOutputStream("..\\pdf\\MergeFile_1234.pdf");

        //call method to merge pdf files.
        mergePdfFiles(inputPdfList, outputStream);     
    } catch (Exception e) {
        e.printStackTrace();
    }
    }
}

RecyclerView vs. ListView

Simple answer: You should use RecyclerView in a situation where you want to show a lot of items, and the number of them is dynamic. ListView should only be used when the number of items is always the same and is limited to the screen size.

You find it harder because you are thinking just with the Android library in mind.

Today there exists a lot of options that help you build your own adapters, making it easy to build lists and grids of dynamic items that you can pick, reorder, use animation, dividers, add footers, headers, etc, etc.

Don't get scared and give a try to RecyclerView, you can starting to love it making a list of 100 items downloaded from the web (like facebook news) in a ListView and a RecyclerView, you will see the difference in the UX (user experience) when you try to scroll, probably the test app will stop before you can even do it.

I recommend you to check this two libraries for making easy adapters:

FastAdapter by mikepenz

FlexibleAdapter by davideas

How to center an iframe horizontally?

best way and more simple to center an iframe on your webpage is :

<p align="center"><iframe src="http://www.google.com/" width=500 height="500"></iframe></p>

where width and height will be the size of your iframe in your html page.

2D cross-platform game engine for Android and iOS?

Here is just a reply from Richard Pickup on LinkedIn to a similar question of mine:

I've used cocos 2dx marmalade and unity on both iOS and android. For 2d games cocos2dx is the way to go every time. Unity is just too much overkill for 2d games and as already stated marmalade is just a thin abstraction layer not really a game engine. You can even run cocos2d on top of marmalade. My approach would be to use cocos2dx on iOS and android then in future run cocosd2dx code on top of marmalade as an easy way to port to bb10 and win phone 7

How to execute .sql script file using JDBC

I had the same problem trying to execute an SQL script that creates an SQL database. Googling here and there I found a Java class initially written by Clinton Begin which supports comments (see http://pastebin.com/P14HsYAG). I modified slightly the file to cater for triggers where one has to change the default DELIMITER to something different. I've used that version ScriptRunner (see http://pastebin.com/sb4bMbVv). Since an (open source and free) SQLScriptRunner class is an absolutely necessary utility, it would be good to have some more input from developers and hopefully we'll have soon a more stable version of it.

Last non-empty cell in a column

I think the response from W5ALIVE is closest to what I use to find the last row of data in a column. Assuming I am looking for the last row with data in Column A, though, I would use the following for the more generic lookup:

=MAX(IFERROR(MATCH("*",A:A,-1),0),IFERROR(MATCH(9.99999999999999E+307,A:A,1),0))

The first MATCH will find the last text cell and the second MATCH finds the last numeric cell. The IFERROR function returns zero if the first MATCH finds all numeric cells or if the second match finds all text cells.

Basically this is a slight variation of W5ALIVE's mixed text and number solution.

In testing the timing, this was significantly quicker than the equivalent LOOKUP variations.

To return the actual value of that last cell, I prefer to use indirect cell referencing like this:

=INDIRECT("A"&MAX(IFERROR(MATCH("*",A:A,-1),0),IFERROR(MATCH(9.99999999999999E+307,A:A,1),0)))

The method offered by sancho.s is perhaps a cleaner option, but I would modify the portion that finds the row number to this:

=INDEX(MAX((A:A<>"")*(ROW(A:A))),1)

the only difference being that the ",1" returns the first value while the ",0" returns the entire array of values (all but one of which are not needed). I still tend to prefer addressing the cell to the index function there, in other words, returning the cell value with:

=INDIRECT("A"&INDEX(MAX((A:A<>"")*(ROW(A:A))),1))

Great thread!

Java 8 Iterable.forEach() vs foreach loop

forEach() can be implemented to be faster than for-each loop, because the iterable knows the best way to iterate its elements, as opposed to the standard iterator way. So the difference is loop internally or loop externally.

For example ArrayList.forEach(action) may be simply implemented as

for(int i=0; i<size; i++)
    action.accept(elements[i])

as opposed to the for-each loop which requires a lot of scaffolding

Iterator iter = list.iterator();
while(iter.hasNext())
    Object next = iter.next();
    do something with `next`

However, we also need to account for two overhead costs by using forEach(), one is making the lambda object, the other is invoking the lambda method. They are probably not significant.

see also http://journal.stuffwithstuff.com/2013/01/13/iteration-inside-and-out/ for comparing internal/external iterations for different use cases.

How can I subset rows in a data frame in R based on a vector of values?

Really human comprehensible example (as this is the first time I am using %in%), how to compare two data frames and keep only rows containing the equal values in specific column:

# Set seed for reproducibility.
set.seed(1)

# Create two sample data frames.
data_A <- data.frame(id=c(1,2,3), value=c(1,2,3))
data_B <- data.frame(id=c(1,2,3,4), value=c(5,6,7,8))

# compare data frames by specific columns and keep only 
# the rows with equal values 
data_A[data_A$id %in% data_B$id,]   # will keep data in data_A
data_B[data_B$id %in% data_A$id,]   # will keep data in data_b

Results:

> data_A[data_A$id %in% data_B$id,]
  id value
1  1     1
2  2     2
3  3     3

> data_B[data_B$id %in% data_A$id,]
  id value
1  1     5
2  2     6
3  3     7

Uninstall all installed gems, in OSX?

You could also build out a new Gemfile and run bundle clean --force. This will remove all other gems that aren't included in the new Gemfile.

What is the purpose of global.asax in asp.net

Global asax events explained

Application_Init: Fired when an application initializes or is first called. It's invoked for all HttpApplication object instances.

Application_Disposed: Fired just before an application is destroyed. This is the ideal location for cleaning up previously used resources.

Application_Error: Fired when an unhandled exception is encountered within the application.

Application_Start: Fired when the first instance of the HttpApplication class is created. It allows you to create objects that are accessible by all HttpApplication instances.

Application_End: Fired when the last instance of an HttpApplication class is destroyed. It's fired only once during an application's lifetime.

Application_BeginRequest: Fired when an application request is received. It's the first event fired for a request, which is often a page request (URL) that a user enters.

Application_EndRequest: The last event fired for an application request.

Application_PreRequestHandlerExecute: Fired before the ASP.NET page framework begins executing an event handler like a page or Web service.

Application_PostRequestHandlerExecute: Fired when the ASP.NET page framework is finished executing an event handler.

Applcation_PreSendRequestHeaders: Fired before the ASP.NET page framework sends HTTP headers to a requesting client (browser).

Application_PreSendContent: Fired before the ASP.NET page framework sends content to a requesting client (browser).

Application_AcquireRequestState: Fired when the ASP.NET page framework gets the current state (Session state) related to the current request.

Application_ReleaseRequestState: Fired when the ASP.NET page framework completes execution of all event handlers. This results in all state modules to save their current state data.

Application_ResolveRequestCache: Fired when the ASP.NET page framework completes an authorization request. It allows caching modules to serve the request from the cache, thus bypassing handler execution.

Application_UpdateRequestCache: Fired when the ASP.NET page framework completes handler execution to allow caching modules to store responses to be used to handle subsequent requests.

Application_AuthenticateRequest: Fired when the security module has established the current user's identity as valid. At this point, the user's credentials have been validated.

Application_AuthorizeRequest: Fired when the security module has verified that a user can access resources.

Session_Start: Fired when a new user visits the application Web site.

Session_End: Fired when a user's session times out, ends, or they leave the application Web site.

Video auto play is not working in Safari and Chrome desktop browser

I got mine to autoplay by making it muted. I think Google rules won't let chrome auto-play unless it's muted.

<video id="video" controls autoplay muted
        border:0px solid black;"
        width="300"
        height="300">
    <source src="~/Videos/Lumen5_CTAS_Home2.mp4"
            type="video/mp4" />
    Your browser does not support the video tag.
    Please download the mp4 plugin to see the CTAS Intro.
</video>

What is the difference between int, Int16, Int32 and Int64?

Int=Int32 --> Original long type

Int16 --> Original int

Int64 --> New data type become available after 64 bit systems

"int" is only available for backward compatibility. We should be really using new int types to make our programs more precise.

---------------

One more thing I noticed along the way is there is no class named Int similar to Int16, Int32 and Int64. All the helpful functions like TryParse for integer come from Int32.TryParse.

jQuery ajax error function

From jquery.com:

The jqXHR.success(), jqXHR.error(), and jqXHR.complete()
callback methods introduced injQuery 1.5 are deprecated
as of jQuery 1.8. To prepare your code for their eventual 
removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

If you want global handlers you can use:

.ajaxStart(), .ajaxStop(),
.ajaxComplete(), .ajaxError(),
.ajaxSuccess(), .ajaxSend()

How to Lock/Unlock screen programmatically?

Use Activity.getWindow() to get the window of your activity; use Window.addFlags() to add whichever of the following flags in WindowManager.LayoutParams that you desire:

How to check if a String is numeric in Java

Why is everyone pushing for exception/regex solutions?

While I can understand most people are fine with using try/catch, if you want to do it frequently... it can be extremely taxing.

What I did here was take the regex, the parseNumber() methods, and the array searching method to see which was the most efficient. This time, I only looked at integer numbers.

public static boolean isNumericRegex(String str) {
    if (str == null)
        return false;
    return str.matches("-?\\d+");
}

public static boolean isNumericArray(String str) {
    if (str == null)
        return false;
    char[] data = str.toCharArray();
    if (data.length <= 0)
        return false;
    int index = 0;
    if (data[0] == '-' && data.length > 1)
        index = 1;
    for (; index < data.length; index++) {
        if (data[index] < '0' || data[index] > '9') // Character.isDigit() can go here too.
            return false;
    }
    return true;
}

public static boolean isNumericException(String str) {
    if (str == null)
        return false;
    try {  
        /* int i = */ Integer.parseInt(str);
    } catch (NumberFormatException nfe) {  
        return false;  
    }
    return true;
}

The results in speed I got were:

Done with: for (int i = 0; i < 10000000; i++)...

With only valid numbers ("59815833" and "-59815833"):
    Array numeric took 395.808192 ms [39.5808192 ns each]
    Regex took 2609.262595 ms [260.9262595 ns each]
    Exception numeric took 428.050207 ms [42.8050207 ns each]
    // Negative sign
    Array numeric took 355.788273 ms [35.5788273 ns each]
    Regex took 2746.278466 ms [274.6278466 ns each]
    Exception numeric took 518.989902 ms [51.8989902 ns each]
    // Single value ("1")
    Array numeric took 317.861267 ms [31.7861267 ns each]
    Regex took 2505.313201 ms [250.5313201 ns each]
    Exception numeric took 239.956955 ms [23.9956955 ns each]
    // With Character.isDigit()
    Array numeric took 400.734616 ms [40.0734616 ns each]
    Regex took 2663.052417 ms [266.3052417 ns each]
    Exception numeric took 401.235906 ms [40.1235906 ns each]

With invalid characters ("5981a5833" and "a"):
    Array numeric took 343.205793 ms [34.3205793 ns each]
    Regex took 2608.739933 ms [260.8739933 ns each]
    Exception numeric took 7317.201775 ms [731.7201775 ns each]
    // With a single character ("a")
    Array numeric took 291.695519 ms [29.1695519 ns each]
    Regex took 2287.25378 ms [228.725378 ns each]
    Exception numeric took 7095.969481 ms [709.5969481 ns each]

With null:
    Array numeric took 214.663834 ms [21.4663834 ns each]
    Regex took 201.395992 ms [20.1395992 ns each]
    Exception numeric took 233.049327 ms [23.3049327 ns each]
    Exception numeric took 6603.669427 ms [660.3669427 ns each] if there is no if/null check

Disclaimer: I'm not claiming these methods are 100% optimized, they're just for demonstration of the data

Exceptions won if and only if the number is 4 characters or less, and every string is always a number... in which case, why even have a check?

In short, it is extremely painful if you run into invalid numbers frequently with the try/catch, which makes sense. An important rule I always follow is NEVER use try/catch for program flow. This is an example why.

Interestingly, the simple if char <0 || >9 was extremely simple to write, easy to remember (and should work in multiple languages) and wins almost all the test scenarios.

The only downside is that I'm guessing Integer.parseInt() might handle non ASCII numbers, whereas the array searching method does not.


For those wondering why I said it's easy to remember the character array one, if you know there's no negative signs, you can easily get away with something condensed as this:

public static boolean isNumericArray(String str) {
    if (str == null)
        return false;
    for (char c : str.toCharArray())
        if (c < '0' || c > '9')
            return false;
    return true;

Lastly as a final note, I was curious about the assigment operator in the accepted example with all the votes up. Adding in the assignment of

double d = Double.parseDouble(...)

is not only useless since you don't even use the value, but it wastes processing time and increased the runtime by a few nanoseconds (which led to a 100-200 ms increase in the tests). I can't see why anyone would do that since it actually is extra work to reduce performance.

You'd think that would be optimized out... though maybe I should check the bytecode and see what the compiler is doing. That doesn't explain why it always showed up as lengthier for me though if it somehow is optimized out... therefore I wonder what's going on. As a note: By lengthier, I mean running the test for 10000000 iterations, and running that program multiple times (10x+) always showed it to be slower.

EDIT: Updated a test for Character.isDigit()

How do I get the file extension of a file in Java?

How about (using Java 1.5 RegEx):

    String[] split = fullFileName.split("\\.");
    String ext = split[split.length - 1];

Can I have an IF block in DOS batch file?

Logically, Cody's answer should work. However I don't think the command prompt handles a code block logically. For the life of me I can't get that to work properly with any more than a single command within the block. In my case, extensive testing revealed that all of the commands within the block are being cached, and executed simultaneously at the end of the block. This of course doesn't yield the expected results. Here is an oversimplified example:

if %ERRORLEVEL%==0 (
set var1=blue
set var2=cheese
set var3=%var1%_%var2%
)

This should provide var3 with the following value:

blue_cheese

but instead yields:

_

because all 3 commands are cached and executed simultaneously upon exiting the code block.

I was able to overcome this problem by re-writing the if block to only execute one command - goto - and adding a few labels. Its clunky, and I don't much like it, but at least it works.

if %ERRORLEVEL%==0 goto :error0
goto :endif

:error0
set var1=blue
set var2=cheese
set var3=%var1%_%var2%

:endif

How do I set a JLabel's background color?

You must set the setOpaque(true) to true other wise the background will not be painted to the form. I think from reading that if it is not set to true that it will paint some or not any of its pixels to the form. The background is transparent by default which seems odd to me at least but in the way of programming you have to set it to true as shown below.

      JLabel lb = new JLabel("Test");
      lb.setBackground(Color.red);
      lb.setOpaque(true); <--This line of code must be set to true or otherwise the 

From the JavaDocs

setOpaque

public void setOpaque(boolean isOpaque)
  If true the component paints every pixel within its bounds. Otherwise, 
  the component may not paint some or all of its pixels, allowing the underlying 
  pixels to show through.
  The default value of this property is false for JComponent. However, 
  the default value for this property on most standard JComponent subclasses 
   (such as JButton and JTree) is look-and-feel dependent.

Parameters:
isOpaque - true if this component should be opaque
See Also:
isOpaque()

How to import js-modules into TypeScript file?

I tested 3 methods to do that...

Method1:

      const FriendCard:any = require('./../pages/FriendCard')

Method2:

      import * as FriendCard from './../pages/FriendCard';

Method3:

if you can find something like this in tsconfig.json:

      { "compilerOptions": { ..., "allowJs": true }

then you can write: import FriendCard from './../pages/FriendCard';

What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

Okay, the .NET 2.0 answers:

If you don't need to clone the values, you can use the constructor overload to Dictionary which takes an existing IDictionary. (You can specify the comparer as the existing dictionary's comparer, too.)

If you do need to clone the values, you can use something like this:

public static Dictionary<TKey, TValue> CloneDictionaryCloningValues<TKey, TValue>
   (Dictionary<TKey, TValue> original) where TValue : ICloneable
{
    Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count,
                                                            original.Comparer);
    foreach (KeyValuePair<TKey, TValue> entry in original)
    {
        ret.Add(entry.Key, (TValue) entry.Value.Clone());
    }
    return ret;
}

That relies on TValue.Clone() being a suitably deep clone as well, of course.

Using ffmpeg to change framerate

With re-encoding:

ffmpeg -y -i seeing_noaudio.mp4 -vf "setpts=1.25*PTS" -r 24 seeing.mp4

Without re-encoding:

First step - extract video to raw bitstream

ffmpeg -y -i seeing_noaudio.mp4 -c copy -f h264 seeing_noaudio.h264

Remux with new framerate

ffmpeg -y -r 24 -i seeing_noaudio.h264 -c copy seeing.mp4

MySQL Select last 7 days

Since you are using an INNER JOIN you can just put the conditions in the WHERE clause, like this:

SELECT 
    p1.kArtikel, 
    p1.cName, 
    p1.cKurzBeschreibung, 
    p1.dLetzteAktualisierung, 
    p1.dErstellt, 
    p1.cSeo,
    p2.kartikelpict,
    p2.nNr,
    p2.cPfad  
FROM 
    tartikel AS p1 INNER JOIN tartikelpict AS p2 
    ON p1.kArtikel = p2.kArtikel
WHERE
  DATE(dErstellt) > (NOW() - INTERVAL 7 DAY)
  AND p2.nNr = 1
ORDER BY 
  p1.kArtikel DESC
LIMIT
    100;

how to run python files in windows command prompt?

First go to the directory where your python script is present by using-

cd path/to/directory

then simply do:

python file_name.py

How do I find the PublicKeyToken for a particular dll?

As @CRice said you can use the below method to get a list of dependent assembly with publicKeyToken

public static int DependencyInfo(string args) 
{
    Console.WriteLine(Assembly.LoadFile(args).FullName);
    Console.WriteLine(Assembly.LoadFile(args).GetCustomAttributes(typeof(System.Runtime.Versioning.TargetFrameworkAttribute), false).SingleOrDefault());
    try {
        var assemblies = Assembly.LoadFile(args).GetReferencedAssemblies(); 

        if (assemblies.GetLength(0) > 0)
        {
            foreach (var assembly in assemblies)
            {
                Console.WriteLine(" - " + assembly.FullName + ", ProcessorArchitecture=" + assembly.ProcessorArchitecture);             
            }
            return 0;
        }
    }
    catch(Exception e) {
        Console.WriteLine("An exception occurred: {0}", e.Message);
        return 1;
    } 
    finally{}

    return 1;
}

i generally use it as a LinqPad script you can call it as

DependencyInfo("@c:\MyAssembly.dll"); from the code

How can I set focus on an element in an HTML form using JavaScript?

For what it's worth, you can use the autofocus attribute on HTML5 compatible browsers. Works even on IE as of version 10.

<input name="myinput" value="whatever" autofocus />

Parenthesis/Brackets Matching using Stack algorithm

import java.util.*;

public class Parenthesis

 {

    public static void main(String...okok)

    {
        Scanner sc= new Scanner(System.in);
        String str=sc.next();
        System.out.println(isValid(str));

    }
    public static int isValid(String a) {
        if(a.length()%2!=0)
        {

            return 0;
        }
        else if(a.length()==0)
        {

            return 1;
        }
        else
        {

            char c[]=a.toCharArray();
            Stack<Character> stk =  new Stack<Character>();
            for(int i=0;i<c.length;i++)
            {
                if(c[i]=='(' || c[i]=='[' || c[i]=='{')
                {
                    stk.push(c[i]);
                }
                else
                {
                    if(stk.isEmpty())
                    {
                        return 0;
                        //break;
                    }
                    else
                    {

                        char cc=c[i];
                        if(cc==')' && stk.peek()=='(' )
                        {
                            stk.pop();
                        }
                        else if(cc==']' && stk.peek()=='[' )
                        {

                            stk.pop();
                        }
                        else if(cc=='}' && stk.peek()=='{' )
                        {

                            stk.pop();
                        }
                    }
                }

            }
            if(stk.isEmpty())
            {
                return 1;
            }else
            {
                return 0;
            }
        }



    }

}

Restoring Nuget References?

This script will reinstall all packages of a project without messing up dependencies or installing dependencies that may have been intentianlyz removed. (More for their part package developers.)

Update-Package -Reinstall -ProjectName Proteus.Package.LinkedContent -IgnoreDependencies

Generate a Hash from string in Javascript

Thanks to the example by mar10, I found a way to get the same results in C# AND Javascript for an FNV-1a. If unicode chars are present, the upper portion is discarded for the sake of performance. Don't know why it would be helpful to maintain those when hashing, as am only hashing url paths for now.

C# Version

private static readonly UInt32 FNV_OFFSET_32 = 0x811c9dc5;   // 2166136261
private static readonly UInt32 FNV_PRIME_32 = 0x1000193;     // 16777619

// Unsigned 32bit integer FNV-1a
public static UInt32 HashFnv32u(this string s)
{
    // byte[] arr = Encoding.UTF8.GetBytes(s);      // 8 bit expanded unicode array
    char[] arr = s.ToCharArray();                   // 16 bit unicode is native .net 

    UInt32 hash = FNV_OFFSET_32;
    for (var i = 0; i < s.Length; i++)
    {
        // Strips unicode bits, only the lower 8 bits of the values are used
        hash = hash ^ unchecked((byte)(arr[i] & 0xFF));
        hash = hash * FNV_PRIME_32;
    }
    return hash;
}

// Signed hash for storing in SQL Server
public static Int32 HashFnv32s(this string s)
{
    return unchecked((int)s.HashFnv32u());
}

JavaScript Version

var utils = utils || {};

utils.FNV_OFFSET_32 = 0x811c9dc5;

utils.hashFnv32a = function (input) {
    var hval = utils.FNV_OFFSET_32;

    // Strips unicode bits, only the lower 8 bits of the values are used
    for (var i = 0; i < input.length; i++) {
        hval = hval ^ (input.charCodeAt(i) & 0xFF);
        hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
    }

    return hval >>> 0;
}

utils.toHex = function (val) {
    return ("0000000" + (val >>> 0).toString(16)).substr(-8);
}

Using both Python 2.x and Python 3.x in IPython Notebook

A solution is available that allows me to keep my MacPorts installation by configuring the Ipython kernelspec.

Requirements:

  • MacPorts is installed in the usual /opt directory
  • python 2.7 is installed through macports
  • python 3.4 is installed through macports
  • Ipython is installed for python 2.7
  • Ipython is installed for python 3.4

For python 2.x:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin
$ sudo ./ipython kernelspec install-self

For python 3.x:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin
$ sudo ./ipython kernelspec install-self

Now you can open an Ipython notebook and then choose a python 2.x or a python 3.x notebook.

Choose your python!

SQL query to make all data in a column UPPER CASE?

Permanent:

UPDATE
  MyTable
SET
  MyColumn = UPPER(MyColumn)

Temporary:

SELECT
  UPPER(MyColumn) AS MyColumn
FROM
  MyTable

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

Prior to standardization there was ioctl(...FIONBIO...) and fcntl(...O_NDELAY...), but these behaved inconsistently between systems, and even within the same system. For example, it was common for FIONBIO to work on sockets and O_NDELAY to work on ttys, with a lot of inconsistency for things like pipes, fifos, and devices. And if you didn't know what kind of file descriptor you had, you'd have to set both to be sure. But in addition, a non-blocking read with no data available was also indicated inconsistently; depending on the OS and the type of file descriptor the read may return 0, or -1 with errno EAGAIN, or -1 with errno EWOULDBLOCK. Even today, setting FIONBIO or O_NDELAY on Solaris causes a read with no data to return 0 on a tty or pipe, or -1 with errno EAGAIN on a socket. However 0 is ambiguous since it is also returned for EOF.

POSIX addressed this with the introduction of O_NONBLOCK, which has standardized behavior across different systems and file descriptor types. Because existing systems usually want to avoid any changes to behavior which might break backward compatibility, POSIX defined a new flag rather than mandating specific behavior for one of the others. Some systems like Linux treat all 3 the same, and also define EAGAIN and EWOULDBLOCK to the same value, but systems wishing to maintain some other legacy behavior for backward compatibility can do so when the older mechanisms are used.

New programs should use fcntl(...O_NONBLOCK...), as standardized by POSIX.

Error in Python script "Expected 2D array, got 1D array instead:"?

I use the below approach.

reg = linear_model.LinearRegression()
reg.fit(df[['year']],df.income)

reg.predict([[2136]])

Java ArrayList for integers

Here there are two different concepts that are merged togather in your question.

First : Add Integer array into List. Code is as follows.

List<Integer[]> list = new ArrayList<>();
Integer[] intArray1 = new Integer[] {2, 4};
Integer[] intArray2 = new Integer[] {2, 5};
Integer[] intArray3 = new Integer[] {3, 3};
Collections.addAll(list, intArray1, intArray2, intArray3);

Second : Add integer value in list.

List<Integer> list = new ArrayList<>();
int x = 5
list.add(x);

PHP Parse HTML code

Use PHP Document Object Model:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;
   $DOM->loadHTML($str);

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";
?>

This outputs as:

 T1
 T2
 T3

[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

How to determine if a String has non-alphanumeric characters?

string.matches("^\\W*$"); should do what you want, but it does not include whitespace. string.matches("^(?:\\W|\\s)*$"); does match whitespace as well.

How to use absolute path in twig functions

For Symfony 2.7 and newer

See this answer here.

1st working option

{{ app.request.scheme ~'://' ~ app.request.httpHost ~ asset('bundles/acmedemo/images/search.png') }}

2nd working option - preferred

Just made a quick test with a clean new Symfony copy. There is also another option which combines scheme and httpHost:

{{ app.request.getSchemeAndHttpHost() ~ asset('bundles/acmedemo/images/search.png') }}
{# outputs #}
{# http://localhost/Symfony/web/bundles/acmedemo/css/demo.css  #}

Can an interface extend multiple interfaces in Java?

You can extend multiple Interfaces but you cannot extend multiple classes.

The reason that it is not possible in Java to extending multiple classes, is the bad experience from C++ where this is possible.

The alternative for multipe inheritance is that a class can implement multiple interfaces (or an Interface can extend multiple Interfaces)

How to check if a char is equal to an empty space?

You can try:

if(Character.isSpaceChar(ch))
{
    // Do something...
}

Or:

if((int) ch) == 32)
{
    // Do something...
}

How to execute the start script with Nodemon

I know it's 5 years late, if you want to use nodemon.json you may try this,

{
  "verbose": true,
  "ignore": ["*.test.js", "fixtures/*"],
  "execMap": {
    "js": "electron ." // 'js' is for the extension, and 'electron .' is command that I want to execute
  }
}

The execMap will execute like a script in package.json, then you can run nodemon js

How to check encoding of a CSV file

In Linux systems, you can use file command. It will give the correct encoding

Sample:

file blah.csv

Output:

blah.csv: ISO-8859 text, with very long lines

NSRange from Swift Range?

For me this works perfectly:

let font = UIFont.systemFont(ofSize: 12, weight: .medium)
let text = "text"
let attString = NSMutableAttributedString(string: "exemple text :)")

attString.addAttributes([.font: font], range:(attString.string as NSString).range(of: text))

label.attributedText = attString

Table is marked as crashed and should be repaired

When I got this error:

#145 - Table '.\engine\phpbb3_posts' is marked as crashed and should be repaired

I ran this command in PhpMyAdmin to fix it:

REPAIR TABLE phpbb3_posts;