Programs & Examples On #Code complete

Code Complete is a software development book, written by Steve McConnell and published in 1993 by Microsoft Press.

What's the difference between an argument and a parameter?

Generally speaking, the terms parameter and argument are used interchangeably to mean information that is passed into a function.

Yet, from a function's perspective:

  • A parameter is the variable listed inside the parentheses in the function definition.
  • An argument is the value that is sent to the function when it is called.

Enabling/Disabling Microsoft Virtual WiFi Miniport

I have the same issue after I disabled the adapter in the Network setting. But when I go to the System->Device Manager and find it from the "Network adapters" and re-enable it. Then everything works again.

Using Pandas to pd.read_excel() for multiple worksheets of the same workbook

Yes unfortunately it will always load the full file. If you're doing this repeatedly probably best to extract the sheets to separate CSVs and then load separately. You can automate that process with d6tstack which also adds additional features like checking if all the columns are equal across all sheets or multiple Excel files.

import d6tstack
c = d6tstack.convert_xls.XLStoCSVMultiSheet('multisheet.xlsx')
c.convert_all() # ['multisheet-Sheet1.csv','multisheet-Sheet2.csv']

See d6tstack Excel examples

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

From milliseconds to hour, minutes, seconds and milliseconds

Maybe can be shorter an more elegant. But I did it.

public String getHumanTimeFormatFromMilliseconds(String millisecondS){
    String message = "";
    long milliseconds = Long.valueOf(millisecondS);
    if (milliseconds >= 1000){
        int seconds = (int) (milliseconds / 1000) % 60;
        int minutes = (int) ((milliseconds / (1000 * 60)) % 60);
        int hours = (int) ((milliseconds / (1000 * 60 * 60)) % 24);
        int days = (int) (milliseconds / (1000 * 60 * 60 * 24));
        if((days == 0) && (hours != 0)){
            message = String.format("%d hours %d minutes %d seconds ago", hours, minutes, seconds);
        }else if((hours == 0) && (minutes != 0)){
            message = String.format("%d minutes %d seconds ago", minutes, seconds);
        }else if((days == 0) && (hours == 0) && (minutes == 0)){
            message = String.format("%d seconds ago", seconds);
        }else{
            message = String.format("%d days %d hours %d minutes %d seconds ago", days, hours, minutes, seconds);
        }
    } else{
        message = "Less than a second ago.";
    }
    return message;
}

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

Most answers are pertaining to doing it on code. But I'll give you one that works on Storyboard. Yes! You read it right.

  • Click on main UINavigationController and navigate to it's Identity Inspector tab.

  • Under User Defined Runtime Attributes, set a single runtime property called interactivePopGestureRecognizer.enabled to true. Or graphically, you'd have to enable the checkbox as shown in the image below.

That's it. You're good to go. Your back gesture will work as if it was there all along.

Image displaying the property that out to be set

Remove all occurrences of a value from a list?

for i in range(a.count(' ')):
    a.remove(' ')

Much simpler I believe.

Circle line-segment collision detection algorithm?

If the line's coordinates are A.x, A.y and B.x, B.y and the circles center is C.x, C.y then the lines formulae are:

x = A.x * t + B.x * (1 - t)

y = A.y * t + B.y * (1 - t)

where 0<=t<=1

and the circle is

(C.x - x)^2 + (C.y - y)^2 = R^2

if you substitute x and y formulae of the line into the circles formula you get a second order equation of t and its solutions are the intersection points (if there are any). If you get a t which is smaller than 0 or greater than 1 then its not a solution but it shows that the line is 'pointing' to the direction of the circle.

How do I check if a file exists in Java?

I know I'm a bit late in this thread. However, here is my answer, valid since Java 7 and up.

The following snippet

if(Files.isRegularFile(Paths.get(pathToFile))) {
    // do something
}

is perfectly satifactory, because method isRegularFile returns false if file does not exist. Therefore, no need to check if Files.exists(...).

Note that other parameters are options indicating how links should be handled. By default, symbolic links are followed.

From Java Oracle documentation

How can I make a checkbox readonly? not disabled?

Through CSS:

<label for="">
  <input type="checkbox" style="pointer-events: none; tabindex: -1;" checked> Label
</label>

pointer-events not supported in IE<10

https://jsfiddle.net/fl4sh/3r0v8pug/2/

AlertDialog styling - how to change style (color) of title, message, etc

Use this in your Style in your values-v21/style.xml

_x000D_
_x000D_
<style name="AlertDialogCustom" parent="@android:style/Theme.Material.Dialog.NoActionBar">_x000D_
        <item name="android:windowBackground">@android:color/white</item>_x000D_
        <item name="android:windowActionBar">false</item>_x000D_
        <item name="android:colorAccent">@color/cbt_ui_primary_dark</item>_x000D_
        <item name="android:windowTitleStyle">@style/DialogWindowTitle.Sphinx</item>_x000D_
        <item name="android:textColorPrimary">@color/cbt_hints_color</item>_x000D_
        <item name="android:backgroundDimEnabled">true</item>_x000D_
        <item name="android:windowMinWidthMajor">@android:dimen/dialog_min_width_major</item>_x000D_
        <item name="android:windowMinWidthMinor">@android:dimen/dialog_min_width_minor</item>_x000D_
</style>
_x000D_
_x000D_
_x000D_

And for pre lollipop devices put it in values/style.xml

_x000D_
_x000D_
<style name="AlertDialogCustom" parent="@android:style/Theme.Material.Dialog.NoActionBar">_x000D_
        <item name="android:windowBackground">@android:color/white</item>_x000D_
        <item name="android:windowActionBar">false</item>_x000D_
        <item name="android:colorAccent">@color/cbt_ui_primary_dark</item>_x000D_
        <item name="android:windowTitleStyle">@style/DialogWindowTitle.Sphinx</item>_x000D_
        <item name="android:textColorPrimary">@color/cbt_hints_color</item>_x000D_
        <item name="android:backgroundDimEnabled">true</item>_x000D_
        <item name="android:windowMinWidthMajor">@android:dimen/dialog_min_width_major</item>_x000D_
        <item name="android:windowMinWidthMinor">@android:dimen/dialog_min_width_minor</item>_x000D_
</style>_x000D_
_x000D_
<style name="DialogWindowTitle.Sphinx" parent="@style/DialogWindowTitle_Holo">_x000D_
       <item name="android:textAppearance">@style/TextAppearance.Sphinx.DialogWindowTitle</item>_x000D_
</style>_x000D_
_x000D_
<style name="TextAppearance.Sphinx.DialogWindowTitle" parent="@android:style/TextAppearance.Holo.DialogWindowTitle">_x000D_
        <item name="android:textColor">@color/dark</item>_x000D_
        <!--<item name="android:fontFamily">sans-serif-condensed</item>-->_x000D_
        <item name="android:textStyle">bold</item>_x000D_
</style>
_x000D_
_x000D_
_x000D_

How to add a form load event (currently not working)

You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:

 public class ProgramViwer : Form{
  public ProgramViwer()
  {
       InitializeComponent();
       Load += new EventHandler(ProgramViwer_Load);
  }
  private void ProgramViwer_Load(object sender, System.EventArgs e)
  {
       formPanel.Controls.Clear();
       formPanel.Controls.Add(wel);
  }
}

JavaScript adding decimal numbers issue

Use toFixed to convert it to a string with some decimal places shaved off, and then convert it back to a number.

+(0.1 + 0.2).toFixed(12) // 0.3

It looks like IE's toFixed has some weird behavior, so if you need to support IE something like this might be better:

Math.round((0.1 + 0.2) * 1e12) / 1e12

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

This might help some who come across this error. If you are working across a VPN and it becomes disconnected, you can also get this error. The simple fix is to reconnect your VPN.

Daemon not running. Starting it now on port 5037

This worked for me: Open task manager (of your OS) and kill adb.exe process. Now start adb again, now adb should start normally.

Finding common rows (intersection) in two Pandas dataframes

My understanding is that this question is better answered over in this post.

But briefly, the answer to the OP with this method is simply:

s1 = pd.merge(df1, df2, how='inner', on=['user_id'])

Which gives s1 with 5 columns: user_id and the other two columns from each of df1 and df2.

How to write super-fast file-streaming code in C#?

The first thing I would recommend is to take measurements. Where are you losing your time? Is it in the read, or the write?

Over 100,000 accesses (sum the times): How much time is spent allocating the buffer array? How much time is spent opening the file for read (is it the same file every time?) How much time is spent in read and write operations?

If you aren't doing any type of transformation on the file, do you need a BinaryWriter, or can you use a filestream for writes? (try it, do you get identical output? does it save time?)

How to uninstall Ruby from /usr/local?

It's not a good idea to uninstall 1.8.6 if it's in /usr/bin. That is owned by the OS and is expected to be there.

If you put /usr/local/bin in your PATH before /usr/bin then things you have installed in /usr/local/bin will be found before any with the same name in /usr/bin, effectively overwriting or updating them, without actually doing so. You can still reach them by explicitly using /usr/bin in your #! interpreter invocation line at the top of your code.

@Anurag recommended using RVM, which I'll second. I use it to manage 1.8.7 and 1.9.1 in addition to the OS's 1.8.6.

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

How do I measure separate CPU core usage for a process?

I thought perf stat is what you need.

It shows a specific usage of a process when you specify a --cpu=list option. Here is an example of monitoring cpu usage of building a project using perf stat --cpu=0-7 --no-aggr -- make all -j command. The output is:

CPU0         119254.719293 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU1         119254.724776 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU2         119254.724179 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU3         119254.720833 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU4         119254.714109 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU5         119254.727721 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU6         119254.723447 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU7         119254.722418 task-clock (msec)         #    1.000 CPUs utilized            (100.00%)
CPU0                 8,108 context-switches          #    0.068 K/sec                    (100.00%)
CPU1                26,494 context-switches                                              (100.00%)
CPU2                10,193 context-switches                                              (100.00%)
CPU3                12,298 context-switches                                              (100.00%)
CPU4                16,179 context-switches                                              (100.00%)
CPU5                57,389 context-switches                                              (100.00%)
CPU6                 8,485 context-switches                                              (100.00%)
CPU7                10,845 context-switches                                              (100.00%)
CPU0                   167 cpu-migrations            #    0.001 K/sec                    (100.00%)
CPU1                    80 cpu-migrations                                                (100.00%)
CPU2                   165 cpu-migrations                                                (100.00%)
CPU3                   139 cpu-migrations                                                (100.00%)
CPU4                   136 cpu-migrations                                                (100.00%)
CPU5                   175 cpu-migrations                                                (100.00%)
CPU6                   256 cpu-migrations                                                (100.00%)
CPU7                   195 cpu-migrations                                                (100.00%)

The left column is the specific CPU index and the right most column is the usage of the CPU. If you don't specify the --no-aggr option, the result will aggregated together. The --pid=pid option will help if you want to monitor a running process.

Try -a --per-core or -a perf-socket too, which will present more classified information.

More about usage of perf stat can be seen in this tutorial: perf cpu statistic, also perf help stat will help on the meaning of the options.

Set color of TextView span in Android

Here is a little help function. Great for when you have multiple languages!

private void setColor(TextView view, String fulltext, String subtext, int color) {
    view.setText(fulltext, TextView.BufferType.SPANNABLE);
    Spannable str = (Spannable) view.getText();
    int i = fulltext.indexOf(subtext);
    str.setSpan(new ForegroundColorSpan(color), i, i + subtext.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}

Django: TemplateSyntaxError: Could not parse the remainder

Template Syntax Error: is due to many reasons one of them is {{ post.date_posted|date: "F d, Y" }} is the space between colon(:) and quote (") if u remove the space then it work like this ..... {{ post.date_posted|date:"F d, Y" }}

Cast object to interface in TypeScript

If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:

Didn't pass linting

const x = new Obj(a as b);

The linter was complaining that a was missing properties that existed on b. In other words, a had some properties and methods of b, but not all. To work around this, I followed VS Code's suggestion:

Passed linting and testing

const x = new Obj(a as unknown as b);

Note that if your code attempts to call one of the properties that exists on type b that is not implemented on type a, you should realize a runtime fault.

How can I select from list of values in SQL Server

Another way that you can use is a query like this:

SELECT DISTINCT
    LTRIM(m.n.value('.[1]','varchar(8000)')) as columnName
FROM 
    (SELECT CAST('<XMLRoot><RowData>' + REPLACE(t.val,',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
     FROM (SELECT '1, 1, 1, 2, 5, 1, 6') AS t(val)
    ) dt
  CROSS APPLY 
    x.nodes('/XMLRoot/RowData') m(n);

Programmatically set left drawable in a TextView

there are two ways of doing it either you can use XML or Java for it. If it's static and requires no changes then you can initialize in XML.

  android:drawableLeft="@drawable/cloud_up"
    android:drawablePadding="5sp"

Now if you need to change the icons dynamically then you can do it by calling the icons based on the events

       textViewContext.setText("File Uploaded");
textViewContext.setCompoundDrawablesWithIntrinsicBounds(R.drawable.uploaded, 0, 0, 0);

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

The accepted answer is correct regarding the Invoke-Command cmdlet, but more broadly speaking, cmdlets can have parameter sets where groups of input parameters are defined, such that you can't use two parameters that aren't members of the same parameter set.

If you're running into this error with any other cmdlet, look up its Microsoft documentation, and see if the the top of the page has distinct sets of parameters listed. For example, the documentation for Set-AzureDeployment defines three sets at the top of the page.

initialize a const array in a class initializer in C++

Where I've a constant array, it's always been done as static. If you can accept that, this code should compile and run.

#include <stdio.h>
#include <stdlib.h>

class a {
        static const int b[2];
public:
        a(void) {
                for(int i = 0; i < 2; i++) {
                        printf("b[%d] = [%d]\n", i, b[i]);
                }
        }
};

const int a::b[2] = { 4, 2 };

int main(int argc, char **argv)
{
        a foo;
        return 0;
}

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

Instead of manually adding the package name on the build.gradle, you can do it this way:

first add this line at the beggining

import java.util.regex.Pattern

Then add this on the defaultConfig

android {
    ...
    defaultConfig {
        ...
        applicationId = doExtractStringFromManifest("package")
        ...
    }
    ...
}

And finally add the doExtractStringFromManifest method

def doExtractStringFromManifest(name) {
     def manifestFile = file(android.sourceSets.main.manifest.srcFile)
     def pattern = Pattern.compile(name + "=\"(\\S+)\"")
     def matcher = pattern.matcher(manifestFile.getText())
     matcher.find()
     return matcher.group(1)
}

As there are a lot of Cordova comments on the answer, if you are working with Cordova, you shouldn't really edit the build.gradle yourself, it has a comment at the beggining that say

// GENERATED FILE! DO NOT EDIT!

So, if you are using a Cordova, the best thing you can do is to update to cordova-android 5.1.0 or greater where this changes are already present.

Visual studio code terminal, how to run a command with administrator rights?

Running as admin didn't help me. (also got errors with syscall: rename)

Turns out this error can also occur if files are locked by Windows.

This can occur if :

  • You are actually running the project
  • You have files open in both Visual Studio and VSCode.

Running as admin doesn't get around windows file locking.

I created a new project in VS2017 and then switched to VSCode to try to add more packages. After stopping the project from running and closing VS2017 it was able to complete without error

Disclaimer: I'm not exactly sure if this means running as admin isn't necessary, but try to avoid it if possible to avoid the possibility of some rogue package doing stuff it isn't meant to.

OpenCV - Saving images to a particular folder of choice

Answer given by Jeru Luke is working only on Windows systems, if we try on another operating system (Ubuntu) then it runs without error but the image is saved on target location or path.

Not working in Ubuntu and working in Windows

  import cv2
  img = cv2.imread('1.jpg', 1)
  path = '/tmp'
  cv2.imwrite(str(path) + 'waka.jpg',img)
  cv2.waitKey(0)

I run above code but the image does not save the image on target path. Then I found that the way of adding path is wrong for the general purpose we using OS module to add the path.

Example:

 import os
 final_path = os.path.join(path_1,path_2,path_3......)

working in Ubuntu and Windows

 import cv2
 import os
 img = cv2.imread('1.jpg', 1)
 path = 'D:/OpenCV/Scripts/Images'
 cv2.imwrite(os.path.join(path , 'waka.jpg'),img)
 cv2.waitKey(0)

that code works fine on both Windows and Ubuntu :)

How to set an environment variable in a running docker container

To:

  1. set up many env. vars in one step,
  2. prevent exposing them in 'sh' history, like with '-e' option (passing credentials/api tokens!),

you can use

--env-file key_value_file.txt

option:

docker run --env-file key_value_file.txt $INSTANCE_ID

Paging UICollectionView by cells, not screen

Also you can create fake scroll view to handle scrolling.

Horizontal or Vertical

// === Defaults ===
let bannerSize = CGSize(width: 280, height: 170)
let pageWidth: CGFloat = 290 // ^ + paging
let insetLeft: CGFloat = 20
let insetRight: CGFloat = 20
// ================

var pageScrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Create fake scrollview to properly handle paging
    pageScrollView = UIScrollView(frame: CGRect(origin: .zero, size: CGSize(width: pageWidth, height: 100)))
    pageScrollView.isPagingEnabled = true
    pageScrollView.alwaysBounceHorizontal = true
    pageScrollView.showsVerticalScrollIndicator = false
    pageScrollView.showsHorizontalScrollIndicator = false
    pageScrollView.delegate = self
    pageScrollView.isHidden = true
    view.insertSubview(pageScrollView, belowSubview: collectionView)

    // Set desired gesture recognizers to the collection view
    for gr in pageScrollView.gestureRecognizers! {
        collectionView.addGestureRecognizer(gr)
    }
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView == pageScrollView {
        // Return scrolling back to the collection view
        collectionView.contentOffset.x = pageScrollView.contentOffset.x
    }
}

func refreshData() {
    ...

    refreshScroll()
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    refreshScroll()
}

/// Refresh fake scrolling view content size if content changes
func refreshScroll() {
    let w = collectionView.width - bannerSize.width - insetLeft - insetRight
    pageScrollView.contentSize = CGSize(width: pageWidth * CGFloat(banners.count) - w, height: 100)
}

Adb over wireless without usb cable at all for not rooted phones

Connect android phone without using USB cable except XIAOMI PHONES
== MAKE SURE THAT YOUR PHONE HAS USB DEBUGGING ENABLED ==
== IP Address series should NOT be '0' like 192.168.0.10
1. Connect your PC (Laptop) and Android phone to same wifi network.
2. Go to the Android SDK folder > platform-tools and open command prompt by holding the shift key and right clicking on the folder.
3. Type the command "adb tcpip 5555", and hit Enter, sometimes it gives an error but ignore it and go ahead.
4. Type "adb connect [YOUR PHONE IP]". example: "adb connect 192.168.1.34" and hit enter, your phone will be connected to PC.

The maximum recursion 100 has been exhausted before statement completion

Specify the maxrecursion option at the end of the query:

...
from EmployeeTree
option (maxrecursion 0)

That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.

eloquent laravel: How to get a row count from a ->get()

Answer has been updated

count is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array:

$wordCount = count($wordlist);

If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count method. Example:

$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get();
$wordCount = $wordlist->count();

There is/was a discussion on having the query builder return a collection here: https://github.com/laravel/framework/issues/10478

However as of now, the query builder always returns an array.

Edit: As linked above, the query builder now returns a collection (not an array). As a result, what JP Foster was trying to do initially will work:

$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->get();
$wordCount = $wordlist->count();

However, as indicated by Leon in the comments, if all you want is the count, then querying for it directly is much faster than fetching an entire collection and then getting the count. In other words, you can do this:

// Query builder
$wordCount = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->count();

// Eloquent
$wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count();

How to check if a service is running on Android?

I had the same problem not long ago. Since my service was local, I ended up simply using a static field in the service class to toggle state, as described by hackbod here

EDIT (for the record):

Here is the solution proposed by hackbod:

If your client and server code is part of the same .apk and you are binding to the service with a concrete Intent (one that specifies the exact service class), then you can simply have your service set a global variable when it is running that your client can check.

We deliberately don't have an API to check whether a service is running because, nearly without fail, when you want to do something like that you end up with race conditions in your code.

PowerShell script to check the status of a URL

Below is the PowerShell code that I use for basic web URL testing. It includes the ability to accept invalid certs and get detailed information about the results of checking the certificate.

$CertificateValidatorClass = @'
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace CertificateValidation
{
    public class CertificateValidationResult
    {
        public string Subject { get; internal set; }
        public string Thumbprint { get; internal set; }
        public DateTime Expiration { get; internal set; }
        public DateTime ValidationTime { get; internal set; }
        public bool IsValid { get; internal set; }
        public bool Accepted { get; internal set; }
        public string Message { get; internal set; }

        public CertificateValidationResult()
        {
            ValidationTime = DateTime.UtcNow;
        }
    }

    public static class CertificateValidator
    {
        private static ConcurrentStack<CertificateValidationResult> certificateValidationResults = new ConcurrentStack<CertificateValidationResult>();

        public static CertificateValidationResult[] CertificateValidationResults
        {
            get
            {
                return certificateValidationResults.ToArray();
            }
        }

        public static CertificateValidationResult LastCertificateValidationResult
        {
            get
            {
                CertificateValidationResult lastCertificateValidationResult = null;
                certificateValidationResults.TryPeek(out lastCertificateValidationResult);

                return lastCertificateValidationResult;
            }
        }

        public static bool ServicePointManager_ServerCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            StringBuilder certificateValidationMessage = new StringBuilder();
            bool allowCertificate = true;

            if (sslPolicyErrors != System.Net.Security.SslPolicyErrors.None)
            {
                if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) == System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch)
                {
                    certificateValidationMessage.AppendFormat("The remote certificate name does not match.\r\n", certificate.Subject);
                }

                if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) == System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors)
                {
                    certificateValidationMessage.AppendLine("The certificate chain has the following errors:");
                    foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus chainStatus in chain.ChainStatus)
                    {
                        certificateValidationMessage.AppendFormat("\t{0}", chainStatus.StatusInformation);

                        if (chainStatus.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.Revoked)
                        {
                            allowCertificate = false;
                        }
                    }
                }

                if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable) == System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable)
                {
                    certificateValidationMessage.AppendLine("The remote certificate was not available.");
                    allowCertificate = false;
                }

                System.Console.WriteLine();
            }
            else
            {
                certificateValidationMessage.AppendLine("The remote certificate is valid.");
            }

            CertificateValidationResult certificateValidationResult = new CertificateValidationResult
                {
                    Subject = certificate.Subject,
                    Thumbprint = certificate.GetCertHashString(),
                    Expiration = DateTime.Parse(certificate.GetExpirationDateString()),
                    IsValid = (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None),
                    Accepted = allowCertificate,
                    Message = certificateValidationMessage.ToString()
                };

            certificateValidationResults.Push(certificateValidationResult);
            return allowCertificate;
        }

        public static void SetDebugCertificateValidation()
        {
            ServicePointManager.ServerCertificateValidationCallback = ServicePointManager_ServerCertificateValidationCallback;
        }

        public static void SetDefaultCertificateValidation()
        {
            ServicePointManager.ServerCertificateValidationCallback = null;
        }

        public static void ClearCertificateValidationResults()
        {
            certificateValidationResults.Clear();
        }
    }
}
'@

function Set-CertificateValidationMode
{
    <#
    .SYNOPSIS
    Sets the certificate validation mode.
    .DESCRIPTION
    Set the certificate validation mode to one of three modes with the following behaviors:
        Default -- Performs the .NET default validation of certificates. Certificates are not checked for revocation and will be rejected if invalid.
        CheckRevocationList -- Cerftificate Revocation Lists are checked and certificate will be rejected if revoked or invalid.
        Debug -- Certificate Revocation Lists are checked and revocation will result in rejection. Invalid certificates will be accepted. Certificate validation
                 information is logged and can be retrieved from the certificate handler.
    .EXAMPLE
    Set-CertificateValidationMode Debug
    .PARAMETER Mode
    The mode for certificate validation.
    #>
    [CmdletBinding(SupportsShouldProcess = $false)]
    param
    (
        [Parameter()]
        [ValidateSet('Default', 'CheckRevocationList', 'Debug')]
        [string] $Mode
    )

    begin
    {
        $isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null

        if ($isValidatorClassLoaded -eq $false)
        {
            Add-Type -TypeDefinition $CertificateValidatorClass
        }
    }

    process
    {
        switch ($Mode)
        {
            'Debug'
            {
                [System.Net.ServicePointManager]::CheckCertificateRevocationList = $true
                [CertificateValidation.CertificateValidator]::SetDebugCertificateValidation()
            }
            'CheckRevocationList'
            {
                [System.Net.ServicePointManager]::CheckCertificateRevocationList = $true
                [CertificateValidation.CertificateValidator]::SetDefaultCertificateValidation()
            }
            'Default'
            {
                [System.Net.ServicePointManager]::CheckCertificateRevocationList = $false
                [CertificateValidation.CertificateValidator]::SetDefaultCertificateValidation()
            }
        }
    }
}

function Clear-CertificateValidationResults
{
    <#
    .SYNOPSIS
    Clears the collection of certificate validation results.
    .DESCRIPTION
    Clears the collection of certificate validation results.
    .EXAMPLE
    Get-CertificateValidationResults
    #>
    [CmdletBinding(SupportsShouldProcess = $false)]
    param()

    begin
    {
        $isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null

        if ($isValidatorClassLoaded -eq $false)
        {
            Add-Type -TypeDefinition $CertificateValidatorClass
        }
    }

    process
    {
        [CertificateValidation.CertificateValidator]::ClearCertificateValidationResults()
        Sleep -Milliseconds 20
    }
}

function Get-CertificateValidationResults
{
    <#
    .SYNOPSIS
    Gets the certificate validation results for all operations performed in the PowerShell session since the Debug cerificate validation mode was enabled.
    .DESCRIPTION
    Gets the certificate validation results for all operations performed in the PowerShell session since the Debug certificate validation mode was enabled in reverse chronological order.
    .EXAMPLE
    Get-CertificateValidationResults
    #>
    [CmdletBinding(SupportsShouldProcess = $false)]
    param()

    begin
    {
        $isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null

        if ($isValidatorClassLoaded -eq $false)
        {
            Add-Type -TypeDefinition $CertificateValidatorClass
        }
    }

    process
    {
        return [CertificateValidation.CertificateValidator]::CertificateValidationResults
    }
}

function Test-WebUrl
{
    <#
    .SYNOPSIS
    Tests and reports information about the provided web URL.
    .DESCRIPTION
    Tests a web URL and reports the time taken to get and process the request and response, the HTTP status, and the error message if an error occurred.
    .EXAMPLE
    Test-WebUrl 'http://websitetotest.com/'
    .EXAMPLE
    'https://websitetotest.com/' | Test-WebUrl
    .PARAMETER HostName
    The Hostname to add to the back connection hostnames list.
    .PARAMETER UseDefaultCredentials
    If present the default Windows credential will be used to attempt to authenticate to the URL; otherwise, no credentials will be presented.
    #>
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [Uri] $Url,
        [Parameter()]
        [Microsoft.PowerShell.Commands.WebRequestMethod] $Method = 'Get',
        [Parameter()]
        [switch] $UseDefaultCredentials
    )

    process
    {
        [bool] $succeeded = $false
        [string] $statusCode = $null
        [string] $statusDescription = $null
        [string] $message = $null
        [int] $bytesReceived = 0
        [Timespan] $timeTaken = [Timespan]::Zero 

        $timeTaken = Measure-Command `
            {
                try
                {
                    [Microsoft.PowerShell.Commands.HtmlWebResponseObject] $response = Invoke-WebRequest -UseDefaultCredentials:$UseDefaultCredentials -Method $Method -Uri $Url
                    $succeeded = $true
                    $statusCode = $response.StatusCode.ToString('D')
                    $statusDescription = $response.StatusDescription
                    $bytesReceived = $response.RawContent.Length

                    Write-Verbose "$($Url.ToString()): $($statusCode) $($statusDescription) $($message)"
                }
                catch [System.Net.WebException]
                {
                    $message = $Error[0].Exception.Message
                    [System.Net.HttpWebResponse] $exceptionResponse = $Error[0].Exception.GetBaseException().Response

                    if ($exceptionResponse -ne $null)
                    {
                        $statusCode = $exceptionResponse.StatusCode.ToString('D')
                        $statusDescription = $exceptionResponse.StatusDescription
                        $bytesReceived = $exceptionResponse.ContentLength

                        if ($statusCode -in '401', '403', '404')
                        {
                            $succeeded = $true
                        }
                    }
                    else
                    {
                        Write-Warning "$($Url.ToString()): $($message)"
                    }
                }
            }

        return [PSCustomObject] @{ Url = $Url; Succeeded = $succeeded; BytesReceived = $bytesReceived; TimeTaken = $timeTaken.TotalMilliseconds; StatusCode = $statusCode; StatusDescription = $statusDescription; Message = $message; }
    }
}

Set-CertificateValidationMode Debug
Clear-CertificateValidationResults

Write-Host 'Testing web sites:'
'https://expired.badssl.com/', 'https://wrong.host.badssl.com/', 'https://self-signed.badssl.com/', 'https://untrusted-root.badssl.com/', 'https://revoked.badssl.com/', 'https://pinning-test.badssl.com/', 'https://sha1-intermediate.badssl.com/' | Test-WebUrl | ft -AutoSize

Write-Host 'Certificate validation results (most recent first):'
Get-CertificateValidationResults | ft -AutoSize

Push local Git repo to new remote including all branches and tags

Here is another take on the same thing which worked better for the situation I was in. It solves the problem where you have more than one remote, would like to clone all branches in remote source to remote destination but without having to check them all out beforehand.

(The problem I had with Daniel's solution was that it would refuse to checkout a tracking branch from the source remote if I had previously checked it out already, ie, it would not update my local branch before the push)

git push destination +refs/remotes/source/*:refs/heads/*

Note: If you are not using direct CLI, you must escape the asterisks:

git push destination +refs/remotes/source/\*:refs/heads/\*

this will push all branches in remote source to a head branch in destination, possibly doing a non-fast-forward push. You still have to push tags separately.

Is a new line = \n OR \r\n?

\n is used for Unix systems (including Linux, and OSX).

\r\n is mainly used on Windows.

\r is used on really old Macs.

PHP_EOL constant is used instead of these characters for portability between platforms.

How to use "/" (directory separator) in both Linux and Windows in Python?

Don't build directory and file names your self, use python's included libraries.

In this case the relevant one is os.path. Especially join which creates a new pathname from a directory and a file name or directory and split that gets the filename from a full path.

Your example would be

pathfile=os.path.dirname(templateFile)
p = os.path.join(pathfile, 'output')
p = os.path.join( p, 'log.txt')
rootTree.write(p)

How to run test methods in specific order in JUnit4?

JUnit 5 update (and my opinion)

I think it's quite important feature for JUnit, if author of JUnit doesn't want the order feature, why?

By default, unit testing libraries don't try to execute tests in the order that occurs in the source file.
JUnit 5 as JUnit 4 work in that way. Why ? Because if the order matters it means that some tests are coupled between them and that is undesirable for unit tests.
So the @Nested feature introduced by JUnit 5 follows the same default approach.

But for integration tests, the order of the test method may matter since a test method may change the state of the application in a way expected by another test method. For example when you write an integration test for a e-shop checkout processing, the first test method to be executed is registering a client, the second is adding items in the basket and the last one is doing the checkout. If the test runner doesn't respect that order, the test scenario is flawed and will fail.
So in JUnit 5 (from the 5.4 version) you have all the same the possibility to set the execution order by annotating the test class with @TestMethodOrder(OrderAnnotation.class) and by specifying the order with @Order(numericOrderValue) for the methods which the order matters.

For example :

@TestMethodOrder(OrderAnnotation.class) 
class FooTest {

    @Order(3)
    @Test
    void checkoutOrder() {
        System.out.println("checkoutOrder");
    }

    @Order(2)
    @Test
    void addItemsInBasket() {
        System.out.println("addItemsInBasket");
    }

    @Order(1)
    @Test
    void createUserAndLogin() {
        System.out.println("createUserAndLogin");
    }
}

Output :

createUserAndLogin

addItemsInBasket

checkoutOrder

By the way, specifying @TestMethodOrder(OrderAnnotation.class) looks like not needed (at least in the 5.4.0 version I tested).

Side note
About the question : is JUnit 5 the best choice to write integration tests ? I don't think that it should be the first tool to consider (Cucumber and co may often bring more specific value and features for integration tests) but in some integration test cases, the JUnit framework is enough. So that is a good news that the feature exists.

.htaccess mod_rewrite - how to exclude directory from rewrite rule

add a condition to check for the admin directory, something like:

RewriteCond %{REQUEST_URI} !^/?(admin|user)/
RewriteRule ^([^/] )/([^/] )\.html$ index.php?lang=$1&mod=$2 [L]

RewriteCond %{REQUEST_URI} !^/?(admin|user)/
RewriteRule ^([^/] )/$ index.php?lang=$1&mod=home [L]

How to create an empty file at the command line in Windows?

call>file.txt

this is the cleanest way I know.

How do I tell if .NET 3.5 SP1 is installed?

Look at HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5\. One of these must be true:

  • The Version value in that key should be 3.5.30729.01
  • Or the SP value in the same key should be 1

In C# (taken from the first comment), you could do something along these lines:

const string name = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5";
RegistryKey subKey = Registry.LocalMachine.OpenSubKey(name);
var version = subKey.GetValue("Version").ToString();
var servicePack = subKey.GetValue("SP").ToString();

executing a function in sql plus

declare
  x number;
begin
  x := myfunc(myargs);
end;

Alternatively:

select myfunc(myargs) from dual;

What does hash do in python?

You can use the Dictionary data type in python. It's very very similar to the hash—and it also supports nesting, similar to the to nested hash.

Example:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School" # Add new entry

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

For more information, please reference this tutorial on the dictionary data type.

How to find EOF through fscanf?

fscanf - "On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure. In the case of an input failure before any data could be successfully read, EOF is returned."

So, instead of doing nothing with the return value like you are right now, you can check to see if it is == EOF.

You should check for EOF when you call fscanf, not check the array slot for EOF.

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

values_of_objArray = [
  { id: 3432, name: "Recent" },
  { id: 3442, name: "Most Popular" },
  { id: 3352, name: "Rating" }
];

private ValueId : number = 0 // this will be used for multi access like 
                             // update, deleting the obj with id.
private selectedObj : any;

private selectedValueObj(id: any) {
  this.ValueId = (id.srcElement || id.target).value;
  for (let i = 0; i < this.values_of_objArray.length; i++) {
    if (this.values_of_objArray[i].id == this.ValueId) {
      this.selectedObj = this.values_of_objArray[i];
    }
  }
}

Now play with this.selectedObj which has the selected obj from the view.

HTML:

<select name="values_of_obj" class="form-control" [(ngModel)]="ValueId"  
        (change)="selectedValueObj($event)" required>

  <option *ngFor="let Value of values_of_objArray"
          [value]="Value.id">{{Value.name}}</option>    
</select>

How to actually search all files in Visual Studio

I think you are talking about ctrl + shift + F, by default it should be on "look in: entire solution" and there you go.

Take a list of numbers and return the average

You want to iterate through the list, sum all the numbers, and then divide the sum by the number of elements in the list. You can use a for loop to accomplish this.

average = 0
sum = 0    
for n in numbers:
    sum = sum + n
average = sum / len(numbers)

The for loop looks at each element in the list, and then adds it to the current sum. You then divide by the length of the list (or the number of elements in the list) to find the average.

I would recommend googling a python reference to find out how to use common programming concepts like loops and conditionals so that you feel comfortable when starting out. There are lots of great resources online that you could look up.

Good luck!

How to move all HTML element children to another parent using JavaScript?

Here's a simple function:

function setParent(el, newParent)
{
    newParent.appendChild(el);
}

el's childNodes are the elements to be moved, newParent is the element el will be moved to, so you would execute the function like:

var l = document.getElementById('old-parent').childNodes.length;
var a = document.getElementById('old-parent');
var b = document.getElementById('new-parent');
for (var i = l; i >= 0; i--)
{
    setParent(a.childNodes[0], b);
}

Here is the Demo

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

you must be using old version of wget i had same issue. i was using wget 1.12.so to solve this issue there are 2 way: Update wget or use curl

curl -LO 'https://example.com/filename.tar.gz'

C# switch statement limitations - why?

The first reason that comes to mind is historical:

Since most C, C++, and Java programmers are not accustomed to having such freedoms, they do not demand them.

Another, more valid, reason is that the language complexity would increase:

First of all, should the objects be compared with .Equals() or with the == operator? Both are valid in some cases. Should we introduce new syntax to do this? Should we allow the programmer to introduce their own comparison method?

In addition, allowing to switch on objects would break underlying assumptions about the switch statement. There are two rules governing the switch statement that the compiler would not be able to enforce if objects were allowed to be switched on (see the C# version 3.0 language specification, §8.7.2):

  • That the values of switch labels are constant
  • That the values of switch labels are distinct (so that only one switch block can be selected for a given switch-expression)

Consider this code example in the hypothetical case that non-constant case values were allowed:

void DoIt()
{
    String foo = "bar";
    Switch(foo, foo);
}

void Switch(String val1, String val2)
{
    switch ("bar")
    {
        // The compiler will not know that val1 and val2 are not distinct
        case val1:
            // Is this case block selected?
            break;
        case val2:
            // Or this one?
            break;
        case "bar":
            // Or perhaps this one?
            break;
    }
}

What will the code do? What if the case statements are reordered? Indeed, one of the reasons why C# made switch fall-through illegal is that the switch statements could be arbitrarily rearranged.

These rules are in place for a reason - so that the programmer can, by looking at one case block, know for certain the precise condition under which the block is entered. When the aforementioned switch statement grows into 100 lines or more (and it will), such knowledge is invaluable.

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

In JavaScript:

pageX, pageY, screenX, screenY, clientX, and clientY returns a number which indicates the number of physical “CSS pixels” a point is from the reference point. The event point is where the user clicked, the reference point is a point in the upper left. These properties return the horizontal and vertical distance from that reference point.

pageX and pageY:
Relative to the top left of the fully rendered content area in the browser. This reference point is below the URL bar and back button in the upper left. This point could be anywhere in the browser window and can actually change location if there are embedded scrollable pages embedded within pages and the user moves a scrollbar.

screenX and screenY:
Relative to the top left of the physical screen/monitor, this reference point only moves if you increase or decrease the number of monitors or the monitor resolution.

clientX and clientY:
Relative to the upper left edge of the content area (the viewport) of the browser window. This point does not move even if the user moves a scrollbar from within the browser.

For a visual on which browsers support which properties:

http://www.quirksmode.org/dom/w3c_cssom.html#t03

w3schools has an online Javascript interpreter and editor so you can see what each does

http://www.w3schools.com/jsref/tryit.asp?filename=try_dom_event_clientxy

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script>_x000D_
function show_coords(event)_x000D_
{_x000D_
  var x=event.clientX;_x000D_
  var y=event.clientY;_x000D_
  alert("X coords: " + x + ", Y coords: " + y);_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<p onmousedown="show_coords(event)">Click this paragraph, _x000D_
and an alert box will alert the x and y coordinates _x000D_
of the mouse pointer.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

This problem is caused by URLSession has two dataTask methods

open func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> URLSessionDataTask
open func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> URLSessionDataTask

The first one has URLRequest as parameter, and the second one has URL as parameter, so we need to specify which type to call, for example, I want to call the second method

let task = URLSession.shared.dataTask(with: url! as URL) {
    data, response, error in
    // Handler
}

Difference between \b and \B in regex

Let take a string like :

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-

Note: Underscore ( _ ) is not considered a special character in this case.

  1. /\bX\b/g Should begin and end with a special character or white Space

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-


  1. /\bX/g Should begin with a special character or white Space

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-


  1. /X\b/g Should end with a special character or white Space

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-


  1. /\BX\B/g
    Should not begin and not end with a special character or white Space

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-


  1. /\BX/g Should not begin with a special character or white Space

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-


  1. /X\B/g Should not end with a special character or white Space

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-


  1. /\bX\B/g Should begin and not end with a special character or white Space

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-


  1. /\BX\b/g Should not begin and should end with a special character or white Space

XIX IXI XX X I II IIXX XXII I-I X-X -X X- X-I I-X -X- -I-X -X-I I-X- X-I- X_X _X-

Remove blue border from css custom-styled button in Chrome

In my instance of this problem I had to specify box-shadow: none

button:focus {
  outline:none;
  box-shadow: none;
}

What is the way of declaring an array in JavaScript?

The preferred way is to always use the literal syntax with square brackets; its behaviour is predictable for any number of items, unlike Array's. What's more, Array is not a keyword, and although it is not a realistic situation, someone could easily overwrite it:

function Array() { return []; }

alert(Array(1, 2, 3)); // An empty alert box

However, the larger issue is that of consistency. Someone refactoring code could come across this function:

function fetchValue(n) {
    var arr = new Array(1, 2, 3);

    return arr[n];
}

As it turns out, only fetchValue(0) is ever needed, so the programmer drops the other elements and breaks the code, because it now returns undefined:

var arr = new Array(1);

How to compare two JSON have the same properties without order?

DeepCompare method to compare two json objects..

_x000D_
_x000D_
deepCompare = (arg1, arg2) => {_x000D_
  if (Object.prototype.toString.call(arg1) === Object.prototype.toString.call(arg2)){_x000D_
    if (Object.prototype.toString.call(arg1) === '[object Object]' || Object.prototype.toString.call(arg1) === '[object Array]' ){_x000D_
      if (Object.keys(arg1).length !== Object.keys(arg2).length ){_x000D_
        return false;_x000D_
      }_x000D_
      return (Object.keys(arg1).every(function(key){_x000D_
        return deepCompare(arg1[key],arg2[key]);_x000D_
      }));_x000D_
    }_x000D_
    return (arg1===arg2);_x000D_
  }_x000D_
  return false;_x000D_
}_x000D_
_x000D_
console.log(deepCompare({a:1},{a:'1'})) // false_x000D_
console.log(deepCompare({a:1},{a:1}))   // true
_x000D_
_x000D_
_x000D_

How do I output the results of a HiveQL query to CSV?

hive  --outputformat=csv2 -e "select * from yourtable" > my_file.csv

or

hive  --outputformat=csv2 -e "select * from yourtable" > [your_path]/file_name.csv

For tsv, just change csv to tsv in the above queries and run your queries

Android open camera from button

For me this worked perfectly fine .

 Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 startActivity(intent);

and add this permission to mainfest file:

<uses-permission android:name="android.permission.CAMERA">

It opens the camera,after capturing the image it saves the image to gallery with a new image set.

How to compare character ignoring case in primitive types

You have to consider the Turkish I problem when comparing characters/ lowercasing / uppercasing:

I suggest to convert to String and use toLowerCase with invariant culture (in most cases at least).

public final static Locale InvariantLocale = new Locale(Empty, Empty, Empty); str.toLowerCase(InvariantLocale)

See similar C# string.ToLower() and string.ToLowerInvariant()

Note: Don't use String.equalsIgnoreCase http://nikolajlindberg.blogspot.co.il/2008/03/beware-of-java-comparing-turkish.html

Removing duplicate rows from table in Oracle

Use the rowid pseudocolumn.

DELETE FROM your_table
WHERE rowid not in
(SELECT MIN(rowid)
FROM your_table
GROUP BY column1, column2, column3);

Where column1, column2, and column3 make up the identifying key for each record. You might list all your columns.

How to create a DOM node as an object?

I'd put it in the DOM first. I'm not sure why my first example failed. That's really weird.

var e = $("<ul><li><div class='bar'>bla</div></li></ul>");
$('li', e).attr('id','a1234');  // set the attribute 
$('body').append(e); // put it into the DOM     

Putting e (the returns elements) gives jQuery context under which to apply the CSS selector. This keeps it from applying the ID to other elements in the DOM tree.

The issue appears to be that you aren't using the UL. If you put a naked li in the DOM tree, you're going to have issues. I thought it could handle/workaround this, but it can't.

You may not be putting naked LI's in your DOM tree for your "real" implementation, but the UL's are necessary for this to work. Sigh.

Example: http://jsbin.com/iceqo

By the way, you may also be interested in microtemplating.

How to get file name when user select a file via <input type="file" />?

You can use the next code:

JS

    function showname () {
      var name = document.getElementById('fileInput'); 
      alert('Selected file: ' + name.files.item(0).name);
      alert('Selected file: ' + name.files.item(0).size);
      alert('Selected file: ' + name.files.item(0).type);
    };

HTML

<body>
    <p>
        <input type="file" id="fileInput" multiple onchange="showname()"/>
    </p>    
</body>

What is the pythonic way to detect the last element in a 'for' loop?

You can use a sliding window over the input data to get a peek at the next value and use a sentinel to detect the last value. This works on any iterable, so you don't need to know the length beforehand. The pairwise implementation is from itertools recipes.

from itertools import tee, izip, chain

def pairwise(seq):
    a,b = tee(seq)
    next(b, None)
    return izip(a,b)

def annotated_last(seq):
    """Returns an iterable of pairs of input item and a boolean that show if
    the current item is the last item in the sequence."""
    MISSING = object()
    for current_item, next_item in pairwise(chain(seq, [MISSING])):
        yield current_item, next_item is MISSING:

for item, is_last_item in annotated_last(data_list):
    if is_last_item:
        # current item is the last item

JPA: How to get entity based on field value other than ID?

This solution is from Beginning Hibernate book:

     Query<User> query = session.createQuery("from User u where u.scn=:scn", User.class);
     query.setParameter("scn", scn);
     User user = query.uniqueResult();    

What is difference between @RequestBody and @RequestParam?

@RequestParam annotation tells Spring that it should map a request parameter from the GET/POST request to your method argument. For example:

request:

GET: http://someserver.org/path?name=John&surname=Smith

endpoint code:

public User getUser(@RequestParam(value = "name") String name, 
                    @RequestParam(value = "surname") String surname){ 
    ...  
    }

So basically, while @RequestBody maps entire user request (even for POST) to a String variable, @RequestParam does so with one (or more - but it is more complicated) request param to your method argument.

Can I set variables to undefined or pass undefined as an argument?

YES, you can, because undefined is defined as undefined.

console.log(
   /*global.*/undefined === window['undefined'] &&
   /*global.*/undefined === (function(){})() &&
   window['undefined']  === (function(){})()
) //true

your case:

test("value1", undefined, "value2")

you can also create your own undefined variable:

Object.defineProperty(this, 'u', {value : undefined});
console.log(u); //undefined

How to add an image to the emulator gallery in android studio?

Try using Device File Explorer:

  1. Start the Device

  2. Navigate to View->Tool Windows->Device File Explorer to open the Device File Explorer

  3. Click on sdcard and select the folder in which you want to save the file to.

  4. Right-click on the folder and select upload to select the file from your computer.

  5. Select the file and click ok to upload

Select multiple value in DropDownList using ASP.NET and C#

Dropdown list wont allows multiple item select in dropdown.

If you need , you can use listbox control..

ASP.NET List Box

How to secure an ASP.NET Web API

Update:

I have added this link to my other answer how to use JWT authentication for ASP.NET Web API here for anyone interested in JWT.


We have managed to apply HMAC authentication to secure Web API, and it worked okay. HMAC authentication uses a secret key for each consumer which both consumer and server both know to hmac hash a message, HMAC256 should be used. Most of the cases, hashed password of the consumer is used as a secret key.

The message normally is built from data in the HTTP request, or even customized data which is added to HTTP header, the message might include:

  1. Timestamp: time that request is sent (UTC or GMT)
  2. HTTP verb: GET, POST, PUT, DELETE.
  3. post data and query string,
  4. URL

Under the hood, HMAC authentication would be:

Consumer sends a HTTP request to web server, after building the signature (output of hmac hash), the template of HTTP request:

User-Agent: {agent}   
Host: {host}   
Timestamp: {timestamp}
Authentication: {username}:{signature}

Example for GET request:

GET /webapi.hmac/api/values

User-Agent: Fiddler    
Host: localhost    
Timestamp: Thursday, August 02, 2012 3:30:32 PM 
Authentication: cuongle:LohrhqqoDy6PhLrHAXi7dUVACyJZilQtlDzNbLqzXlw=

The message to hash to get signature:

GET\n
Thursday, August 02, 2012 3:30:32 PM\n
/webapi.hmac/api/values\n

Example for POST request with query string (signature below is not correct, just an example)

POST /webapi.hmac/api/values?key2=value2

User-Agent: Fiddler    
Host: localhost    
Content-Type: application/x-www-form-urlencoded
Timestamp: Thursday, August 02, 2012 3:30:32 PM 
Authentication: cuongle:LohrhqqoDy6PhLrHAXi7dUVACyJZilQtlDzNbLqzXlw=

key1=value1&key3=value3

The message to hash to get signature

GET\n
Thursday, August 02, 2012 3:30:32 PM\n
/webapi.hmac/api/values\n
key1=value1&key2=value2&key3=value3

Please note that form data and query string should be in order, so the code on the server get query string and form data to build the correct message.

When HTTP request comes to the server, an authentication action filter is implemented to parse the request to get information: HTTP verb, timestamp, uri, form data and query string, then based on these to build signature (use hmac hash) with the secret key (hashed password) on the server.

The secret key is got from the database with the username on the request.

Then server code compares the signature on the request with the signature built; if equal, authentication is passed, otherwise, it failed.

The code to build signature:

private static string ComputeHash(string hashedPassword, string message)
{
    var key = Encoding.UTF8.GetBytes(hashedPassword.ToUpper());
    string hashString;

    using (var hmac = new HMACSHA256(key))
    {
        var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
        hashString = Convert.ToBase64String(hash);
    }

    return hashString;
}

So, how to prevent replay attack?

Add constraint for the timestamp, something like:

servertime - X minutes|seconds  <= timestamp <= servertime + X minutes|seconds 

(servertime: time of request coming to server)

And, cache the signature of the request in memory (use MemoryCache, should keep in the limit of time). If the next request comes with the same signature with the previous request, it will be rejected.

The demo code is put as here: https://github.com/cuongle/Hmac.WebApi

CSS - center two images in css side by side

Flexbox can do this with just two css rules on a surrounding div.

_x000D_
_x000D_
.social-media{_x000D_
    display: flex;_x000D_
    justify-content: center;_x000D_
}
_x000D_
<div class="social-media">_x000D_
<a href="mailto:[email protected]">_x000D_
<img class="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>_x000D_
<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">_x000D_
<img class="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Eclipse CDT project built but "Launch Failed. Binary Not Found"

On a Mac, If you also have a similar problem, as Nenad Bulatovic mentioned above, you need to change the Binary Parsers.

Press Command + I to open up properties (or right click on your project and select property)

Make sure you select Mach-O 64 Parser.

enter image description here

SQL join format - nested inner joins

Since you've already received help on the query, I'll take a poke at your syntax question:

The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join and on clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.

Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:

select
 count(*)
from Table1 as t1
join Table2 as t2
    join Table3 as t3
    on t2.Key = t3.Key                   -- join #1
    and t2.Key2 = t3.Key2 
on t1.DifferentKey = t3.DifferentKey     -- join #2  

This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:

select
 count(*)
from Table1 as t1
    join Table3 as t3
        join Table2 as t2
        on t2.Key = t3.Key                   -- join #1
        and t2.Key2 = t3.Key2   
    on t1.DifferentKey = t3.DifferentKey     -- join #2

Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.

Modulo operation with negative numbers

Modulus operator gives the remainder. Modulus operator in c usually takes the sign of the numerator

  1. x = 5 % (-3) - here numerator is positive hence it results in 2
  2. y = (-5) % (3) - here numerator is negative hence it results -2
  3. z = (-5) % (-3) - here numerator is negative hence it results -2

Also modulus(remainder) operator can only be used with integer type and cannot be used with floating point.

PHP Fatal error: Call to undefined function mssql_connect()

php.ini probably needs to read: extension=ext\php_sqlsrv_53_nts.dll

Or move the file to same directory as the php executable. This is what I did to my php5 install this week to get odbc_pdo working. :P

Additionally, that doesn't look like proper phpinfo() output. If you make a file with contents
<? phpinfo(); ?> and visit that page, the HTML output should show several sections, including one with loaded modules. (Edited to add: like shown in the screenshot of the above accepted answer)

LINQ to SQL - Left Outer Join with multiple join conditions

You need to introduce your join condition before calling DefaultIfEmpty(). I would just use extension method syntax:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in fg.Where(f => f.otherid == 17).DefaultIfEmpty()
where p.companyid == 100
select f.value

Or you could use a subquery:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in (from f in fg
             where f.otherid == 17
             select f).DefaultIfEmpty()
where p.companyid == 100
select f.value

Using module 'subprocess' with timeout

Unfortunately, I'm bound by very strict policies on the disclosure of source code by my employer, so I can't provide actual code. But for my taste the best solution is to create a subclass overriding Popen.wait() to poll instead of wait indefinitely, and Popen.__init__ to accept a timeout parameter. Once you do that, all the other Popen methods (which call wait) will work as expected, including communicate.

Where can I find Android source code online?

You can browse Android SDK samples from your smartphone using "Code Search": https://market.android.com/details?id=sqwady.codesearch

Fatal error: Call to undefined function pg_connect()

Edit. I just noticed you were mentionning MAMP. My advice is for Windows but may be useful if you know what corresponding tools to use.

Things to try:

  • Have you restarted PHP and Apache since your editing of php.ini?

  • Is the php_pgsql.dll found in your php\ext directory?

  • Are you running php as a module? If so, try copying the php_pgsql.dll file in the Apache\bin directory.

  • Are you running PHP from the command line with a flag specifying a different php.ini file?

  • You could try using a tool such as Sysinternals' Filemon to view what files are attempting to be accessed when running PHP.

  • You could try using a tool such as Dependency Walker to look at the dependencies for the postgreSQL DLL, in case you have a missing dependency. Quick search brought up ldd for Unix.

What are the ways to make an html link open a folder

Does not work in Chrome, but this other answers suggests a solution via a plugin:

Can Google Chrome open local links?

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

VBScript -- Using error handling

You can regroup your steps functions calls in a facade function :

sub facade()
    call step1()
    call step2()
    call step3()
    call step4()
    call step5()
end sub

Then, let your error handling be in an upper function that calls the facade :

sub main()
    On error resume next

    call facade()

    If Err.Number <> 0 Then
        ' MsgBox or whatever. You may want to display or log your error there
        msgbox Err.Description
        Err.Clear
    End If

    On Error Goto 0
end sub

Now, let's suppose step3() raises an error. Since facade() doesn't handle errors (there is no On error resume next in facade()), the error will be returned to main() and step4() and step5() won't be executed.

Your error handling is now refactored in 1 code block

SQLDataReader Row Count

 DataTable dt = new DataTable();
 dt.Load(reader);
 int numRows= dt.Rows.Count;

Concat all strings inside a List<string> using LINQ

You can simply use:

List<string> items = new List<string>() { "foo", "boo", "john", "doe" };

Console.WriteLine(string.Join(",", items));

Happy coding!

Add image in title bar

Add this in the head section of your html

<link rel="icon" type="image/gif/png" href="mouse_select_left.png">

File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?

Flurry Support for iPhone 5 (ARMv7s) As I mentioned in yesterday’s post, Flurry started working on a version of the iOS SDK to support the ARMv7s processor in the new iPhone 5 immediately after the announcement on Wednesday.

I am happy to tell you that the work is done and the SDK is now available on the site.

How do I find a default constraint using INFORMATION_SCHEMA?

I don't think it's in the INFORMATION_SCHEMA - you'll probably have to use sysobjects or related deprecated tables/views.

You would think there would be a type for this in INFORMATION_SCHEMA.TABLE_CONSTRAINTS, but I don't see one.

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

What's a .sh file?

sh files are unix (linux) shell executables files, they are the equivalent (but much more powerful) of bat files on windows.

So you need to run it from a linux console, just typing its name the same you do with bat files on windows.

python paramiko ssh

The code of @ThePracticalOne is great for showing the usage except for one thing: Somtimes the output would be incomplete.(session.recv_ready() turns true after the if session.recv_ready(): while session.recv_stderr_ready() and session.exit_status_ready() turned true before entering next loop)

so my thinking is to retrieving the data when it is ready to exit the session.

while True:
if session.exit_status_ready():
while True:
    while True:
        print "try to recv stdout..."
        ret = session.recv(nbytes)
        if len(ret) == 0:
            break
        stdout_data.append(ret)

    while True:
        print "try to recv stderr..."
        ret = session.recv_stderr(nbytes)
        if len(ret) == 0:
            break
        stderr_data.append(ret)
    break

OperationalError: database is locked

Just close (stop) and open (start) the database. This solved my problem.

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

You should set your RecyclerView LayoutManager to Gridlayout mode. Just change your code when you want to set your RecyclerView LayoutManager:

recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), numberOfColumns));

Error: No default engine was specified and no extension was provided

if you've got this error by using the express generator, I've solved it by using

express --view=ejs myapp

instead of

express --view=pug myapp

How can a Javascript object refer to values in itself?

This is not JSON. JSON was designed to be simple; allowing arbitrary expressions is not simple.

In full JavaScript, I don't think you can do this directly. You cannot refer to this until the object called obj is fully constructed. So you need a workaround, that someone with more JavaScript-fu than I will provide.

Spring Boot yaml configuration for a list of strings

My guess is, that the @Value can not cope with "complex" types. You can go with a prop class like this:

@Component
@ConfigurationProperties('ignore')
class IgnoreSettings {
    List<String> filenames
}

Please note: This code is Groovy - not Java - to keep the example short! See the comments for tips how to adopt.

See the complete example https://github.com/christoph-frick/so-springboot-yaml-string-list

Upload Progress Bar in PHP

HTML5 introduced a file upload api that allows you to monitor the progress of file uploads but for older browsers there's plupload a framework that specifically made to monitor file uploads and give information about them. plus it has plenty of callbacks so it can work across all browsers

Catching KeyboardInterrupt in Python during program shutdown

Checkout this thread, it has some useful information about exiting and tracebacks.

If you are more interested in just killing the program, try something like this (this will take the legs out from under the cleanup code as well):

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

How to create a string with format?

No NSString required!

String(format: "Value: %3.2f\tResult: %3.2f", arguments: [2.7, 99.8])

or

String(format:"Value: %3.2f\tResult: %3.2f", 2.7, 99.8)

How do I detect unsigned integer multiply overflow?

Clang now supports dynamic overflow checks for both signed and unsigned integers. See the -fsanitize=integer switch. For now, it is the only C++ compiler with fully supported dynamic overflow checking for debug purposes.

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

If you VS solution contains several projects, select all of them in the right pane, and press "properties". Then go to C++ -> Code Generation and chose one Run Time library option for all of them

Android, How to create option Menu

you can create options menu like below:

Menu XML code:

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

    <item
        android:id="@+id/Menu_AboutUs"
        android:icon="@drawable/ic_about_us_over_black"
        android:title="About US"/>
    <item
        android:id="@+id/Menu_LogOutMenu"
        android:icon="@drawable/ic_arrow_forward_black"
        android:title="Logout"/>
</menu>

How you can get the menu from MENU XML(Convert menu XML to java):

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.my_options_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

How to get Selected Item from Menu:

@Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){

            case R.id.Menu_AboutUs:
                //About US
                break;

            case R.id.Menu_LogOutMenu:
                //Do Logout
                break;
        }
        return super.onOptionsItemSelected(item);
    }

Javascript: Unicode string to hex

how do you get "\u6f22\u5b57" from ?? in JavaScript?

These are JavaScript Unicode escape sequences e.g. \u12AB. To convert them, you could iterate over every code unit in the string, call .toString(16) on it, and go from there.

However, it is more efficient to also use hexadecimal escape sequences e.g. \xAA in the output wherever possible.

Also note that ASCII symbols such as A, b, and - probably don’t need to be escaped.

I’ve written a small JavaScript library that does all this for you, called jsesc. It has lots of options to control the output.

Here’s an online demo of the tool in action: http://mothereff.in/js-escapes#1%E6%BC%A2%E5%AD%97


Your question was tagged as utf-8. Reading the rest of your question, UTF-8 encoding/decoding didn’t seem to be what you wanted here, but in case you ever need it: use utf8.js (online demo).

What does 'const static' mean in C and C++?

It's a small space optimization.

When you say

const int foo = 42;

You're not defining a constant, but creating a read-only variable. The compiler is smart enough to use 42 whenever it sees foo, but it will also allocate space in the initialized data area for it. This is done because, as defined, foo has external linkage. Another compilation unit can say:

extern const int foo;

To get access to its value. That's not a good practice since that compilation unit has no idea what the value of foo is. It just knows it's a const int and has to reload the value from memory whenever it is used.

Now, by declaring that it is static:

static const int foo = 42;

The compiler can do its usual optimization, but it can also say "hey, nobody outside this compilation unit can see foo and I know it's always 42 so there is no need to allocate any space for it."

I should also note that in C++, the preferred way to prevent names from escaping the current compilation unit is to use an anonymous namespace:

namespace {
    const int foo = 42; // same as static definition above
}

Python Pylab scatter plot error bars (the error on each point is unique)

>>> import matplotlib.pyplot as plt
>>> a = [1,3,5,7]
>>> b = [11,-2,4,19]
>>> plt.pyplot.scatter(a,b)
>>> plt.scatter(a,b)
<matplotlib.collections.PathCollection object at 0x00000000057E2CF8>
>>> plt.show()
>>> c = [1,3,2,1]
>>> plt.errorbar(a,b,yerr=c, linestyle="None")
<Container object of 3 artists>
>>> plt.show()

where a is your x data b is your y data c is your y error if any

note that c is the error in each direction already

Convert JS Object to form data

You can simply install qs:

npm i qs

Simply import:

import qs from 'qs'

Pass object to qs.stringify():

var item = {
   description: 'Some Item',
   price : '0.00',
   srate : '0.00',
   color : 'red',
   ...
   ...
}

qs.stringify(item)

How can I make git accept a self signed certificate?

My answer may be late but it worked for me. It may help somebody.

I tried above mentioned steps and that didn't solved the issue.

try thisgit config --global http.sslVerify false

LDAP server which is my base dn

The base dn is dc=example,dc=com.

I don't know about openca, but I will try this answer since you got very little traffic so far.

A base dn is the point from where a server will search for users. So I would try to simply use admin as a login name.

If openca behaves like most ldap aware applications, this is what is going to happen :

  1. An ldap search for the user admin will be done by the server starting at the base dn (dc=example,dc=com).
  2. When the user is found, the full dn (cn=admin,dc=example,dc=com) will be used to bind with the supplied password.
  3. The ldap server will hash the password and compare with the stored hash value. If it matches, you're in.

Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :

  • The dn your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com.
  • The authentication method. It is usually a "simple bind".
  • The user search filter. Look at the attribute named objectClass for your admin user. It will be either inetOrgPerson or user. There will be others like top, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson). Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user)).

Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.

Can a for loop increment/decrement by more than one?

for (var i = 0; i < 10; i = i + 2) {
    // code here
}?

Facebook user url by id

Accepted answer didn't work for me, this does:

https://www.facebook.com/app_scoped_user_id/10152384781676191

CSS width of a <span> tag

You can't specify the width of an element with display inline. You could put something in it like a non-breaking space ( ) and then set the padding to give it some more width but you can't control it directly.

You could use display inline-block but that isn't widely supported.

A real hack would be to put an image inside and then set the width of that. Something like a transparent 1 pixel GIF. Not the recommended approach however.

how to make negative numbers into positive

Why do you want to use strange hard commands, when you can use:

if(a < 0)
    a -= 2a;

The if statement obviously only applies when you aren't sure if the number will be positive or negative.

Otherwise you'll have to use this code:

a = abs(a) // a is an integer
a = fabs(a) // a is declared as a double
a = fabsf(a) // a is declared as a float (C++ 11 is able to use fabs(a) for floats instead of fabs)

To activate C++ 11 (if you are using Code::Blocks, you have to:

  1. Open up Code::Blocks (recommended version: 13.12).
  2. Go to Settings -> Compiler.
  3. Make sure that the compiler you use is GNU GCC Compiler.
  4. Click Compiler Settings, and inside the tab opened click Compiler Flags
  5. Scroll down until you find: Have g++ follow the C++ 11 ISO C++ language standard [-std=c++11]. Check that and then hit OK button.
  6. Restart Code::Blocks and then you are good to go!

After following these steps, you should be able to use fabs(a) for floats instead of fabsf(a), which was used only for C99 or less! (Even C++ 98 could allow you to use fabs instead of fabsf :P)

Emulating a do-while loop in Bash

We can emulate a do-while loop in Bash with while [[condition]]; do true; done like this:

while [[ current_time <= $cutoff ]]
    check_if_file_present
    #do other stuff
do true; done

For an example. Here is my implementation on getting ssh connection in bash script:

#!/bin/bash
while [[ $STATUS != 0 ]]
    ssh-add -l &>/dev/null; STATUS="$?"
    if [[ $STATUS == 127 ]]; then echo "ssh not instaled" && exit 0;
    elif [[ $STATUS == 2 ]]; then echo "running ssh-agent.." && eval `ssh-agent` > /dev/null;
    elif [[ $STATUS == 1 ]]; then echo "get session identity.." && expect $HOME/agent &> /dev/null;
    else ssh-add -l && git submodule update --init --recursive --remote --merge && return 0; fi
do true; done

It will give the output in sequence as below:

Step #0 - "gcloud": intalling expect..
Step #0 - "gcloud": running ssh-agent..
Step #0 - "gcloud": get session identity..
Step #0 - "gcloud": 4096 SHA256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX /builder/home/.ssh/id_rsa (RSA)
Step #0 - "gcloud": Submodule '.google/cloud/compute/home/chetabahana/.docker/compose' ([email protected]:chetabahana/compose) registered for path '.google/cloud/compute/home/chetabahana/.docker/compose'
Step #0 - "gcloud": Cloning into '/workspace/.io/.google/cloud/compute/home/chetabahana/.docker/compose'...
Step #0 - "gcloud": Warning: Permanently added the RSA host key for IP address 'XXX.XX.XXX.XXX' to the list of known hosts.
Step #0 - "gcloud": Submodule path '.google/cloud/compute/home/chetabahana/.docker/compose': checked out '24a28a7a306a671bbc430aa27b83c09cc5f1c62d'
Finished Step #0 - "gcloud"

Multiple selector chaining in jQuery?

You should be able to use:

$('#Edit.myClass, #Create.myClass').plugin({options here});

jQuery | Multiple Selectors

How to upgrade docker container after its image changed

I would like to add that if you want to do this process automatically (download, stop and restart a new container with the same settings as described by @Yaroslav) you can use WatchTower. A program that auto updates your containers when they are changed https://github.com/v2tec/watchtower

When is a C++ destructor called?

Yes, a destructor (a.k.a. dtor) is called when an object goes out of scope if it is on the stack or when you call delete on a pointer to an object.

  1. If the pointer is deleted via delete then the dtor will be called. If you reassign the pointer without calling delete first, you will get a memory leak because the object still exists in memory somewhere. In the latter instance, the dtor is not called.

  2. A good linked list implementation will call the dtor of all objects in the list when the list is being destroyed (because you either called some method to destory it or it went out of scope itself). This is implementation dependent.

  3. I doubt it, but I wouldn't be surprised if there is some odd circumstance out there.

Why is this rsync connection unexpectedly closed on Windows?

I had this problem, but only when I tried to rsync from a Linux (RH) server to a Solaris server. My fix was to make sure rsync had the same path on both boxes, and that the ownership of rsync was the same.

On the linux box, rsync path was /usr/bin, on Solaris box it was /usr/local/bin. So, on the Solaris box I did ln -s /usr/local/bin/rsync /usr/bin/rsync.

I still had the same problem, and noticed ownership differences. On linux it was root:root, on solaris it was bin:bin. Changing solaris to root:root fixed it.

Video streaming over websockets using JavaScript

The Media Source Extensions has been proposed which would allow for Adaptive Bitrate Streaming implementations.

Html encode in PHP

Encode.php

<h1>Encode HTML CODE</h1>

<form action='htmlencodeoutput.php' method='post'>
<textarea rows='30' cols='100'name='inputval'></textarea>
<input type='submit'>
</form>

htmlencodeoutput.php

<?php

$code=bin2hex($_POST['inputval']); 
$spilt=chunk_split($code,2,"%");
$totallen=strlen($spilt);
 $sublen=$totallen-1;
 $fianlop=substr($spilt,'0', $sublen);
$output="<script>
document.write(unescape('%$fianlop'));
</script>";

?> 
<textarea rows='20' cols='100'><?php echo $output?> </textarea> 

You can encode HTML like this .

Newline in string attribute

When you need to do it in a string (eg: in your resources) you need to use xml:space="preserve" and the ampersand character codes:

<System:String x:Key="TwoLiner" xml:space="preserve">First line&#10;Second line</System:String>

Or literal newlines in the text:

<System:String x:Key="TwoLiner" xml:space="preserve">First line 
Second line</System:String>

Warning: if you write code like the second example, you have inserted either a newline, or a carriage return and newline, depending on the line endings your operating system and/or text editor use. For instance, if you write that and commit it to git from a linux systems, everything may seem fine -- but if someone clones it to Windows, git will convert your line endings to \r\n and depending on what your string is for ... you might break the world.

Just be aware of that when you're preserving whitespace. If you write something like this:

<System:String x:Key="TwoLiner" xml:space="preserve">
First line 
Second line 
</System:String>

You've actually added four line breaks, possibly four carriage-returns, and potentially trailing white space that's invisible...

Tooltips with Twitter Bootstrap

I think your question boils down to what proper selector to use when setting up your tooltips, and the answer to that is almost whatever you want. If you want to use a class to trigger your tooltips you can do that, take the following for example:

<a href="#" class="link" data-original-title="first tooltip">Hover me for a tooltip</a>

Then you can trigger all links with the .link class attached as tooltips like so:

$('.link').tooltip()

Now, to answer your question as to why the bootstrap developers did not use a class to trigger tooltips that is because it is not needed exactly, you can pretty much use any selectors you want to target your tooltips, such as (my personal favorite) the rel attribute. With this attribute you can target all links or elements with the rel property set to tooltip, like so:

$('[rel=tooltip]').tooltip() 

And your links would look like something like this:

<a href="#" rel="tooltip" data-original-title="first tooltip">Hover me for a tooltip</a>

Of course, you can also use a container class or id to target your tooltips inside an specific container that you want to single out with an specific option or to separate from the rest of your content and you can use it like so:

$('#example').tooltip({
    selector: "a[rel=tooltip]"
})

This selector will target all of your tooltips with the rel attribute "within" your #example div, this way you can add special styles or options to that section alone. In short, you can pretty much use any valid selector to target your tooltips and there is no need to dirty your markup with an extra class to target them.

IllegalMonitorStateException on wait() call

wait is defined in Object, and not it Thread. The monitor on Thread is a little unpredictable.

Although all Java objects have monitors, it is generally better to have a dedicated lock:

private final Object lock = new Object();

You can get slightly easier to read diagnostics, at a small memory cost (about 2K per process) by using a named class:

private static final class Lock { }
private final Object lock = new Lock();

In order to wait or notify/notifyAll an object, you need to be holding the lock with the synchronized statement. Also, you will need a while loop to check for the wakeup condition (find a good text on threading to explain why).

synchronized (lock) {
    while (!isWakeupNeeded()) {
        lock.wait();
    }
}

To notify:

synchronized (lock) {
    makeWakeupNeeded();
    lock.notifyAll();
}

It is well worth getting to understand both Java language and java.util.concurrent.locks locks (and java.util.concurrent.atomic) when getting into multithreading. But use java.util.concurrent data structures whenever you can.

How to run a makefile in Windows?

If it is a "NMake Makefile", that is to say the syntax and command is compatible with NMake, it will work natively on Windows. Usually Makefile.win (the .win suffix) indicates it's a makefile compatible with Windows NMake. So you could try nmake -f Makefile.win.

Often standard Linux Makefiles are provided and NMake looks promising. However, the following link takes a simple Linux Makefile and explains some fundamental issues that one may encounter. It also suggests a few alternatives to handling Linux Makefiles on Windows.

Makefiles in Windows

Set Page Title using PHP

You parse the field from the database as usual.

Then let's say you put it in a variable called $title, you just

<html>
<head>
<title>Ultan.me - <?php echo htmlspecialchars($title);?></title>
</head>

EDIT:

I see your problem. You have to set $title BEFORE using it. That is, you should query the database before <title>...

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

Basically you tried to use a nil value in places where Swift allows only non-nil ones, by telling the compiler to trust you that there will never be nil value there, thus allowing your app to compile.

There are several scenarios that lead to this kind of fatal error:

  1. forced unwraps:

    let user = someVariable!
    

    If someVariable is nil, then you'll get a crash. By doing a force unwrap you moved the nil check responsibility from the compiler to you, basically by doing a forced unwrap you're guaranteeing to the compiler that you'll never have nil values there. And guess what it happens if somehow a nil value ends in in someVariable?

    Solution? Use optional binding (aka if-let), do the variable processing there:

    if user = someVariable {
        // do your stuff
    }
    
  2. forced (down)casts:

    let myRectangle = someShape as! Rectangle
    

    Here by force casting you tell the compiler to no longer worry, as you'll always have a Rectangle instance there. And as long as that holds, you don't have to worry. The problems start when you or your colleagues from the project start circulating non-rectangle values.

    Solution? Use optional binding (aka if-let), do the variable processing there:

    if let myRectangle = someShape as? Rectangle {
        // yay, I have a rectangle
    }
    
  3. Implicitly unwrapped optionals. Let's assume you have the following class definition:

    class User {
        var name: String!
    
        init() {
            name = "(unnamed)"
        }
    
        func nicerName() {
            return "Mr/Ms " + name
        }
    }
    

    Now, if no-one messes up with the name property by setting it to nil, then it works as expected, however if User is initialized from a JSON that lacks the name key, then you get the fatal error when trying to use the property.

    Solution? Don't use them :) Unless you're 102% sure that the property will always have a non-nil value by the time it needs to be used. In most cases converting to an optional or non-optional will work. Making it non-optional will also result in the compiler helping you by telling the code paths you missed giving a value to that property

  4. Unconnected, or not yet connected, outlets. This is a particular case of scenario #3. Basically you have some XIB-loaded class that you want to use.

    class SignInViewController: UIViewController {
    
        @IBOutlet var emailTextField: UITextField!
    }
    

    Now if you missed connecting the outlet from the XIB editor, then the app will crash as soon as you'll want to use the outlet. Solution? Make sure all outlets are connected. Or use the ? operator on them: emailTextField?.text = "[email protected]". Or declare the outlet as optional, though in this case the compiler will force you to unwrap it all over the code.

  5. Values coming from Objective-C, and that don't have nullability annotations. Let's assume we have the following Objective-C class:

    @interface MyUser: NSObject
    @property NSString *name;
    @end
    

    Now if no nullability annotations are specified (either explicitly or via NS_ASSUME_NONNULL_BEGIN/NS_ASSUME_NONNULL_END), then the name property will be imported in Swift as String! (an IUO - implicitly unwrapped optional). As soon as some swift code will want to use the value, it will crash if name is nil.

    Solution? Add nullability annotations to your Objective-C code. Beware though, the Objective-C compiler is a little bit permissive when it comes to nullability, you might end up with nil values, even if you explicitly marked them as nonnull.

ImportError: No module named - Python

make sure to include __init__.py, which makes Python know that those directories containpackages

Upload file to SFTP using PowerShell

You didn't tell us what particular problem do you have with the WinSCP, so I can really only repeat what's in WinSCP documentation.

  • Download WinSCP .NET assembly.
    The latest package as of now is WinSCP-5.17.10-Automation.zip;

  • Extract the .zip archive along your script;

  • Use a code like this (based on the official PowerShell upload example):

      # Load WinSCP .NET assembly
      Add-Type -Path "WinSCPnet.dll"
    
      # Setup session options
      $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
          Protocol = [WinSCP.Protocol]::Sftp
          HostName = "example.com"
          UserName = "user"
          Password = "mypassword"
          SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
      }
    
      $session = New-Object WinSCP.Session
    
      try
      {
          # Connect
          $session.Open($sessionOptions)
    
          # Upload
          $session.PutFiles("C:\FileDump\export.txt", "/Outbox/").Check()
      }
      finally
      {
          # Disconnect, clean up
          $session.Dispose()
      }
    

You can have WinSCP generate the PowerShell script for the upload for you:

  • Login to your server with WinSCP GUI;
  • Navigate to the target directory in the remote file panel;
  • Select the file for upload in the local file panel;
  • Invoke the Upload command;
  • On the Transfer options dialog, go to Transfer Settings > Generate Code;
  • On the Generate transfer code dialog, select the .NET assembly code tab;
  • Choose PowerShell language.

You will get a code like above with all session and transfer settings filled in.

Generate transfer code dialog

(I'm the author of WinSCP)

Git push rejected "non-fast-forward"

I'm late to the party but I found some useful instructions in github help page and I wanted to share them here.

Sometimes, Git can't make your change to a remote repository without losing commits. When this happens, your push is refused.

If another person has pushed to the same branch as you, Git won't be able to push your changes:

$ git push origin master
To https://github.com/USERNAME/REPOSITORY.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com/USERNAME/REPOSITORY.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again.  See the
'Note about fast-forwards' section of 'git push --help' for details.

You can fix this by fetching and merging the changes made on the remote branch with the changes that you have made locally:

$ git fetch origin
# Fetches updates made to an online repository
$ git merge origin YOUR_BRANCH_NAME
# Merges updates made online with your local work

Or, you can simply use git pull to perform both commands at once:

$ git pull origin YOUR_BRANCH_NAME
# Grabs online updates and merges them with your local work

SyntaxError of Non-ASCII character

You should define source code encoding, add this to the top of your script:

# -*- coding: utf-8 -*-

The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:

import sys
print sys.getdefaultencoding()

Also see:

time data does not match format

You have the month and day swapped:

'%m/%d/%Y %H:%M:%S.%f'

28 will never fit in the range for the %m month parameter otherwise.

With %m and %d in the correct order parsing works:

>>> from datetime import datetime
>>> datetime.strptime('07/28/2014 18:54:55.099000', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)

You don't need to add '000'; %f can parse shorter numbers correctly:

>>> datetime.strptime('07/28/2014 18:54:55.099', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)

How to check whether an array is empty using PHP?

I use this code

$variable = array();

if( count( $variable ) == 0 )
{
    echo "Array is Empty";
}
else
{
    echo "Array is not Empty";
}

But note that if the array has a large number of keys, this code will spend much time counting them, as compared to the other answers here.

Calculate a Running Total in SQL Server

I believe a running total can be achieved using the simple INNER JOIN operation below.

SELECT
     ROW_NUMBER() OVER (ORDER BY SomeDate) AS OrderID
    ,rt.*
INTO
    #tmp
FROM
    (
        SELECT 45 AS ID, CAST('01-01-2009' AS DATETIME) AS SomeDate, 3 AS SomeValue
        UNION ALL
        SELECT 23, CAST('01-08-2009' AS DATETIME), 5
        UNION ALL
        SELECT 12, CAST('02-02-2009' AS DATETIME), 0
        UNION ALL
        SELECT 77, CAST('02-14-2009' AS DATETIME), 7
        UNION ALL
        SELECT 39, CAST('02-20-2009' AS DATETIME), 34
        UNION ALL
        SELECT 33, CAST('03-02-2009' AS DATETIME), 6
    ) rt

SELECT
     t1.ID
    ,t1.SomeDate
    ,t1.SomeValue
    ,SUM(t2.SomeValue) AS RunningTotal
FROM
    #tmp t1
    JOIN #tmp t2
        ON t2.OrderID <= t1.OrderID
GROUP BY
     t1.OrderID
    ,t1.ID
    ,t1.SomeDate
    ,t1.SomeValue
ORDER BY
    t1.OrderID

DROP TABLE #tmp

Hide particular div onload and then show div after click

At first if you want to hide div element with id = "abc" on load and then toggle between hide and show using a button with id = "btn" then,

$(document).ready(function() {
 $("#abc").hide(); 
  $("#btn").click(function() {
     $("#abc").toggle();
  });
});

Commit history on remote repository

Here's a bash function that makes it easy to view the logs on a remote. It takes two optional arguments. The first one is the branch, it defaults to master. The second one is the remote, it defaults to staging.

git_log_remote() {
  branch=${1:-master}
  remote=${2:-staging}
  
  git fetch $remote
  git checkout $remote/$branch
  git log
  git checkout -
}

examples:

 $ git_log_remote
 $ git_log_remote development origin

Converting Milliseconds to Minutes and Seconds?

Here is a simple solution. Example calls that could be used in any method:

  • StopWatch.start();
  • StopWatch.stop();
  • StopWatch.displayDiff(); displays difference in minutes and seconds between start and stop. (elapsed time)

    import java.time.Duration;
    import java.time.Instant;
    
    
    public class StopWatch {
    
        private static Instant start;
        private static Instant stop;
    
        private void StopWatch() {
            // not called
        }
    
        public static void start() {
            start = Instant.now();
        }
    
        public static void stop() {
            stop = Instant.now();
        }
    
        public static void displayDiff() {
            Duration totalTime = Duration.between(start, stop);
            System.out.println(totalTime.toMinutes() + " Minutes " 
                               + totalTime.toMillis() / 1000 + " Seconds");
        }
    }
    

Hibernate Criteria Join with 3 Tables

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

json.dumps vs flask.jsonify

The choice of one or another depends on what you intend to do. From what I do understand:

  • jsonify would be useful when you are building an API someone would query and expect json in return. E.g: The REST github API could use this method to answer your request.

  • dumps, is more about formating data/python object into json and work on it inside your application. For instance, I need to pass an object to my representation layer where some javascript will display graph. You'll feed javascript with the Json generated by dumps.

WSDL validator?

You can try using one of their tools: http://www.ws-i.org/deliverables/workinggroup.aspx?wg=testingtools

These will check both WSDL validity and Basic Profile 1.1 compliance.

Boxplot show the value of mean

You can also use a function within stat_summary to calculate the mean and the hjust argument to place the text, you need a additional function but no additional data frame:

fun_mean <- function(x){
  return(data.frame(y=mean(x),label=mean(x,na.rm=T)))}


ggplot(PlantGrowth,aes(x=group,y=weight)) +
geom_boxplot(aes(fill=group)) +
stat_summary(fun.y = mean, geom="point",colour="darkred", size=3) +
stat_summary(fun.data = fun_mean, geom="text", vjust=-0.7)

enter image description here

Properties order in Margin

Just because @MartinCapodici 's comment is awesome I write here as an answer to give visibility.

All clockwise:

  • WPF start West (left->top->right->bottom)
  • Netscape (ie CSS) start North (top->right->bottom->left)

How do you remove Subversion control for a folder?

Also, if you are using TortoiseSVN, just export to the current working copy location and it will remove the .svn folders and files.

http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-export.html#tsvn-dug-export-unversion

Updated Answer for Subversion 1.7:
In Subversion 1.7 the working copy has been revised extensively. There is only one .svn folder, located in the base of the working copy. If you are using 1.7, then just deleting the .svn folder and its contents is an easy solution (regardless of using TortoiseSVN or command line tools).

What is the documents directory (NSDocumentDirectory)?

Your app only (on a non-jailbroken device) runs in a "sandboxed" environment. This means that it can only access files and directories within its own contents. For example Documents and Library.

See the iOS Application Programming Guide.

To access the Documents directory of your applications sandbox, you can use the following:

iOS 8 and newer, this is the recommended method

+ (NSURL *)applicationDocumentsDirectory
{
     return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

if you need to support iOS 7 or earlier

+ (NSString *) applicationDocumentsDirectory 
{    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = paths.firstObject;
    return basePath;
}

This Documents directory allows you to store files and subdirectories your app creates or may need.

To access files in the Library directory of your apps sandbox use (in place of paths above):

[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

When we create a customer directive, the scope of the directive could be in Isolated scope, It means the directive does not share a scope with the controller; both directive and controller have their own scope. However, data can be passed to the directive scope in three possible ways.

  1. Data can be passed as a string using the @ string literal, pass string value, one way binding.
  2. Data can be passed as an object using the = string literal, pass object, 2 ways binding.
  3. Data can be passed as a function the & string literal, calls external function, can pass data from directive to controller.

Javascript require() function giving ReferenceError: require is not defined

require is part of the Asynchronous Module Definition (AMD) API.

A browser implementation can be found via require.js and native support can be found in node.js.

The documentation for the library you are using should tell you what you need to use it, I suspect that it is intended to run under Node.js and not in browsers.

Cannot use a leading ../ to exit above the top directory

I know these answers are enough, but I'll show the place that's throwing an error.

If you have the structure like the below:

  • ./Src/Master.cs - (Master Form Page)
  • ./Invoice/SubFolder/InvoiceEdit.aspx - (Sub Form Page)

If you enter the sub form page, you'll get an error when you use similar like that you've used in master page: Page.ResolveClientUrl("~/Style/img/logo_small.png").

Now ResolveClientUrl is situated in the master page and trying to serve the root folder. But since you are in the subfolder, the function returns something like ../../Style/img/logo_small.png. This is the wrong way.

Because when you're up two levels, you are not in the right place; you need to go up only one level, so something like ../.

BeanFactory not initialized or already closed - call 'refresh' before

In my case, the error was valid and it was due to using try with resource

 try (ConfigurableApplicationContext cxt = new ClassPathXmlApplicationContext(
                    "classpath:application-main-config.xml")) {..
}

It auto closes the stream which should not happen if I want to reuse this context in other beans.

How to save user input into a variable in html and js

I found this to work best for me https://jsfiddle.net/Lu92akv6/ [I found this to work for me try this fiddle][1]

_x000D_
_x000D_
document.getElementById("btnmyNumber").addEventListener("click", myFunctionVar);_x000D_
function myFunctionVar() {_x000D_
  var numberr = parseInt(document.getElementById("myNumber").value, 10);_x000D_
  // alert(numberr);_x000D_
  if ( numberr > 1) {_x000D_
_x000D_
    document.getElementById("minusE5").style.display = "none";_x000D_
_x000D_
_x000D_
_x000D_
}}
_x000D_
   <form onsubmit="return false;">_x000D_
       <input class="button button3" type="number" id="myNumber" value="" min="0" max="30">_x000D_
       <input type="submit" id="btnmyNumber">_x000D_
_x000D_
       </form>
_x000D_
_x000D_
_x000D_

How to use SSH to run a local shell script on a remote machine?

If Machine A is a Windows box, you can use Plink (part of PuTTY) with the -m parameter, and it will execute the local script on the remote server.

plink root@MachineB -m local_script.sh

If Machine A is a Unix-based system, you can use:

ssh root@MachineB 'bash -s' < local_script.sh

You shouldn't have to copy the script to the remote server to run it.

jquery how to empty input field

Setting val('') will empty the input field. So you would use this:

Clear the input field when the page loads:

$(function(){
    $('#shares').val('');
});

Creating a border like this using :before And :after Pseudo-Elements In CSS?

#footer:after
{
   content: "";
    width: 40px;
    height: 3px;
    background-color: #529600;
    left: 0;
    position: relative;
    display: block;
    top: 10px;
}

How do I make a JSON object with multiple arrays?

Enclosed in {} represents an object; enclosed in [] represents an array, there can be multiple objects in the array
example object :

{
    "brand": "bwm", 
    "price": 30000
}


{
    "brand": "benz", 
    "price": 50000
}

example array:

[
    {
        "brand": "bwm", 
        "price": 30000
    }, 
    {
        "brand": "benz", 
        "price": 50000
    }
]

In order to use JSON more beautifully, you can go here JSON Viewer do format

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

Use the following extensions and just pass the action like:

_frmx.PerformSafely(() => _frmx.Show());
_frmx.PerformSafely(() => _frmx.Location = new Point(x,y));

Extension class:

public static class CrossThreadExtensions
{
    public static void PerformSafely(this Control target, Action action)
    {
        if (target.InvokeRequired)
        {
            target.Invoke(action);
        }
        else
        {
            action();
        }
    }

    public static void PerformSafely<T1>(this Control target, Action<T1> action,T1 parameter)
    {
        if (target.InvokeRequired)
        {
            target.Invoke(action, parameter);
        }
        else
        {
            action(parameter);
        }
    }

    public static void PerformSafely<T1,T2>(this Control target, Action<T1,T2> action, T1 p1,T2 p2)
    {
        if (target.InvokeRequired)
        {
            target.Invoke(action, p1,p2);
        }
        else
        {
            action(p1,p2);
        }
    }
}

How do you rotate a two dimensional array?

#!/usr/bin/env python

original = [ [1,2,3],
             [4,5,6],
             [7,8,9] ]

# Rotate matrix 90 degrees...
for i in map(None,*original[::-1]):
    print str(i) + '\n'

This causes the sides to be rotated 90 degrees (ie. 123 (top side) is now 741 (left side).

This Python solution works because it uses slicing with a negative step to reverse the row orders (bringing 7 to top)

original = [ [7,8,9],
             [4,5,6],
             [1,2,3] ]

It then uses map (along with the implied identity function which is the result of map with None as first arg) along with * to unpack all elements in sequence, to regroup the columns (ie. the first elements are put in a tuple together, the 2nd elements are put in a tuple together, and so forth). You effectively get get returned the following regrouping:

original = [[7,8,9],
             [4,5,6],
             [1,2,3]]

Cross-Origin Read Blocking (CORB)

In most cases, the blocked response should not affect the web page's behavior and the CORB error message can be safely ignored. For example, the warning may occur in cases when the body of the blocked response was empty already, or when the response was going to be delivered to a context that can't handle it (e.g., a HTML document such as a 404 error page being delivered to an tag).

https://www.chromium.org/Home/chromium-security/corb-for-developers

I had to clean my browser's cache, I was reading in this link, that, if the request get a empty response, we get this warning error. I was getting some CORS on my request, and so the response of this request got empty, All I had to do was clear the browser's cache, and the CORS got away. I was receiving CORS because the chrome had saved the PORT number on the cache, The server would just accept localhost:3010 and I was doing localhost:3002, because of the cache.

How to get current html page title with javascript

One option from DOM directly:

$(document).find("title").text();

Tested only on chrome & IE9, but logically should work on all browsers.

Or more generic

var title = document.getElementsByTagName("title")[0].innerHTML;

How do you concatenate Lists in C#?

I know this is old but I came upon this post quickly thinking Concat would be my answer. Union worked great for me. Note, it returns only unique values but knowing that I was getting unique values anyway this solution worked for me.

namespace TestProject
{
    public partial class Form1 :Form
    {
        public Form1()
        {
            InitializeComponent();

            List<string> FirstList = new List<string>();
            FirstList.Add("1234");
            FirstList.Add("4567");

            // In my code, I know I would not have this here but I put it in as a demonstration that it will not be in the secondList twice
            FirstList.Add("Three");  

            List<string> secondList = GetList(FirstList);            
            foreach (string item in secondList)
                Console.WriteLine(item);
        }

        private List<String> GetList(List<string> SortBy)
        {
            List<string> list = new List<string>();
            list.Add("One");
            list.Add("Two");
            list.Add("Three");

            list = list.Union(SortBy).ToList();

            return list;
        }
    }
}

The output is:

One
Two
Three
1234
4567

Maximum length of HTTP GET request

Technically, I have seen HTTP GET will have issues if the URL length goes beyond 2000 characters. In that case, it's better to use HTTP POST or split the URL.

change html input type by JS?

Changing the type of an <input type=password> throws a security error in some browsers (old IE and Firefox versions).

You’ll need to create a new input element, set its type to the one you want, and clone all other properties from the existing one.

I do this in my jQuery placeholder plugin: https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js#L80-84

To work in Internet Explorer:

  • dynamically create a new element
  • copy the properties of the old element into the new element
  • set the type of the new element to the new type
  • replace the old element with the new element

The function below accomplishes the above tasks for you:

<script>
function changeInputType(oldObject, oType) {
    var newObject = document.createElement('input');
    newObject.type = oType;
    if(oldObject.size) newObject.size = oldObject.size;
    if(oldObject.value) newObject.value = oldObject.value;
    if(oldObject.name) newObject.name = oldObject.name;
    if(oldObject.id) newObject.id = oldObject.id;
    if(oldObject.className) newObject.className = oldObject.className;
    oldObject.parentNode.replaceChild(newObject,oldObject);
    return newObject;
}
</script>

Short description of the scoping rules?

Essentially, the only thing in Python that introduces a new scope is a function definition. Classes are a bit of a special case in that anything defined directly in the body is placed in the class's namespace, but they are not directly accessible from within the methods (or nested classes) they contain.

In your example there are only 3 scopes where x will be searched in:

  • spam's scope - containing everything defined in code3 and code5 (as well as code4, your loop variable)

  • The global scope - containing everything defined in code1, as well as Foo (and whatever changes after it)

  • The builtins namespace. A bit of a special case - this contains the various Python builtin functions and types such as len() and str(). Generally this shouldn't be modified by any user code, so expect it to contain the standard functions and nothing else.

More scopes only appear when you introduce a nested function (or lambda) into the picture. These will behave pretty much as you'd expect however. The nested function can access everything in the local scope, as well as anything in the enclosing function's scope. eg.

def foo():
    x=4
    def bar():
        print x  # Accesses x from foo's scope
    bar()  # Prints 4
    x=5
    bar()  # Prints 5

Restrictions:

Variables in scopes other than the local function's variables can be accessed, but can't be rebound to new parameters without further syntax. Instead, assignment will create a new local variable instead of affecting the variable in the parent scope. For example:

global_var1 = []
global_var2 = 1

def func():
    # This is OK: It's just accessing, not rebinding
    global_var1.append(4) 

    # This won't affect global_var2. Instead it creates a new variable
    global_var2 = 2 

    local1 = 4
    def embedded_func():
        # Again, this doen't affect func's local1 variable.  It creates a 
        # new local variable also called local1 instead.
        local1 = 5
        print local1

    embedded_func() # Prints 5
    print local1    # Prints 4

In order to actually modify the bindings of global variables from within a function scope, you need to specify that the variable is global with the global keyword. Eg:

global_var = 4
def change_global():
    global global_var
    global_var = global_var + 1

Currently there is no way to do the same for variables in enclosing function scopes, but Python 3 introduces a new keyword, "nonlocal" which will act in a similar way to global, but for nested function scopes.

Step out of current function with GDB

You can use the finish command.

finish: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated as fin.

(See 5.2 Continuing and Stepping.)

What is Vim recording and how can it be disabled?

It sounds like you have macro recording turned on. To shut it off, press q.

Refer to ":help recording" for further information.

Related links:

jQuery selector for the label of a checkbox

Thanks Kip, for those who may be looking to achieve the same using $(this) whilst iterating or associating within a function:

$("label[for="+$(this).attr("id")+"]").addClass( "orienSel" );

I looked for a while whilst working this project but couldn't find a good example so I hope this helps others who may be looking to resolve the same issue.

In the example above, my objective was to hide the radio inputs and style the labels to provide a slicker user experience (changing the orientation of the flowchart).

You can see an example here

If you like the example, here is the css:

.orientation {      position: absolute; top: -9999px;   left: -9999px;}
    .orienlabel{background:#1a97d4 url('http://www.ifreight.solutions/process.html/images/icons/flowChart.png') no-repeat 2px 5px; background-size: 40px auto;color:#fff; width:50px;height:50px;display:inline-block; border-radius:50%;color:transparent;cursor:pointer;}
    .orR{   background-position: 9px -57px;}
    .orT{   background-position: 2px -120px;}
    .orB{   background-position: 6px -177px;}

    .orienSel {background-color:#323232;}

and the relevant part of the JavaScript:

function changeHandler() {
    $(".orienSel").removeClass( "orienSel" );
    if(this.checked) {
        $("label[for="+$(this).attr("id")+"]").addClass( "orienSel" );
    }
};

An alternate root to the original question, given the label follows the input, you could go with a pure css solution and avoid using JavaScript altogether...:

input[type=checkbox]:checked+label {}

How to label scatterplot points by name?

Well I did not think this was possible until I went and checked. In some previous version of Excel I could not do this. I am currently using Excel 2013.

This is what you want to do in a scatter plot:

  1. right click on your data point

  2. select "Format Data Labels" (note you may have to add data labels first)

  3. put a check mark in "Values from Cells"
  4. click on "select range" and select your range of labels you want on the points

Example Graph

UPDATE: Colouring Individual Labels

In order to colour the labels individually use the following steps:

  1. select a label. When you first select, all labels for the series should get a box around them like the graph above.
  2. Select the individual label you are interested in editing. Only the label you have selected should have a box around it like the graph below.
  3. On the right hand side, as shown below, Select "TEXT OPTIONS".
  4. Expand the "TEXT FILL" category if required.
  5. Second from the bottom of the category list is "COLOR", select the colour you want from the pallet.

If you have the entire series selected instead of the individual label, text formatting changes should apply to all labels instead of just one.

Colouring

How is attr_accessible used in Rails 4?

Rails 4 now uses strong parameters.

Protecting attributes is now done in the controller. This is an example:

class PeopleController < ApplicationController
  def create
    Person.create(person_params)
  end

  private

  def person_params
    params.require(:person).permit(:name, :age)
  end
end

No need to set attr_accessible in the model anymore.

Dealing with accepts_nested_attributes_for

In order to use accepts_nested_attribute_for with strong parameters, you will need to specify which nested attributes should be whitelisted.

class Person
  has_many :pets
  accepts_nested_attributes_for :pets
end

class PeopleController < ApplicationController
  def create
    Person.create(person_params)
  end

  # ...

  private

  def person_params
    params.require(:person).permit(:name, :age, pets_attributes: [:name, :category])
  end
end

Keywords are self-explanatory, but just in case, you can find more information about strong parameters in the Rails Action Controller guide.

Note: If you still want to use attr_accessible, you need to add protected_attributes to your Gemfile. Otherwise, you will be faced with a RuntimeError.

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

typedef struct vs struct definitions

If you use struct without typedef, you'll always have to write

struct mystruct myvar;

It's illegal to write

mystruct myvar;

If you use the typedef you don't need the struct prefix anymore.

Setting selected option in laravel form

Everybody talking about you go using {!! Form::select() !!} but, if all you need is to use plain simple HTML.. here is another way to do it.

<select name="myselect">
@foreach ($options as $key => $value)
    <option value="{{ $key }}"
    @if ($key == old('myselect', $model->option))
        selected="selected"
    @endif
    >{{ $value }}</option>
@endforeach
</select>

the old() function is useful when you submit the form and the validation fails. So that, old() returns the previously selected value.

String Array object in Java

public static void main(String[] args) {

        public String[] name = {"Art", "Dan", "Jen"};
        public String[] country = {"Canada", "Germant", "USA"};
        // initialize your performance array here too.

        //Your constructor takes arrays as an argument so you need to be sure to pass in the arrays and not just objects.
        Athlete art = new Athlete(name, country, performance);   

}

Center a H1 tag inside a DIV

<div id="AlertDiv" style="width:600px;height:400px;border:SOLID 1px;">
    <h1 style="width:100%;height:10%;text-align:center;position:relative;top:40%;">Yes</h1>
</div>

You can try the code here:

http://htmledit.squarefree.com/

String formatting in Python 3

That line works as-is in Python 3.

>>> sys.version
'3.2 (r32:88445, Oct 20 2012, 14:09:29) \n[GCC 4.5.2]'
>>> "(%d goals, $%d)" % (self.goals, self.penalties)
'(1 goals, $2)'

Is there a way to ignore a single FindBugs warning?

The FindBugs initial approach involves XML configuration files aka filters. This is really less convenient than the PMD solution but FindBugs works on bytecode, not on the source code, so comments are obviously not an option. Example:

<Match>
   <Class name="com.mycompany.Foo" />
   <Method name="bar" />
   <Bug pattern="DLS_DEAD_STORE_OF_CLASS_LITERAL" />
</Match>

However, to solve this issue, FindBugs later introduced another solution based on annotations (see SuppressFBWarnings) that you can use at the class or at the method level (more convenient than XML in my opinion). Example (maybe not the best one but, well, it's just an example):

@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
    value="HE_EQUALS_USE_HASHCODE", 
    justification="I know what I'm doing")

Note that since FindBugs 3.0.0 SuppressWarnings has been deprecated in favor of @SuppressFBWarnings because of the name clash with Java's SuppressWarnings.

Convert .cer certificate to .jks

Export a certificate from a keystore:

keytool -export -alias mydomain -file mydomain.crt -keystore keystore.jks

MySQL: How to reset or change the MySQL root password?

You can use this command:

UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';

after that please use flush:

FLUSH PRIVILEGES;

Shortcut for creating single item list in C#

I would just do

var list = new List<string> { "hello" };

c# regex matches example

It looks like most of post here described what you need here. However - something you might need more complex behavior - depending on what you're parsing. In your case it might be so that you won't need more complex parsing - but it depends what information you're extracting.

You can use regex groups as field name in class, after which could be written for example like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;

public class Info
{
    public String Identifier;
    public char nextChar;
};

class testRegex {

    const string input = "Lorem ipsum dolor sit %download%#456 amet, consectetur adipiscing %download%#3434 elit. " +
    "Duis non nunc nec mauris feugiat porttitor. Sed tincidunt blandit dui a viverra%download%#298. Aenean dapibus nisl %download%#893434 id nibh auctor vel tempor velit blandit.";

    static void Main(string[] args)
    {
        Regex regex = new Regex(@"%download%#(?<Identifier>[0-9]*)(?<nextChar>.)(?<thisCharIsNotNeeded>.)");
        List<Info> infos = new List<Info>();

        foreach (Match match in regex.Matches(input))
        {
            Info info = new Info();
            for( int i = 1; i < regex.GetGroupNames().Length; i++ )
            {
                String groupName = regex.GetGroupNames()[i];

                FieldInfo fi = info.GetType().GetField(regex.GetGroupNames()[i]);

                if( fi != null ) // Field is non-public or does not exists.
                    fi.SetValue( info, Convert.ChangeType( match.Groups[groupName].Value, fi.FieldType));
            }
            infos.Add(info);
        }

        foreach ( var info in infos )
        {
            Console.WriteLine(info.Identifier + " followed by '" + info.nextChar.ToString() + "'");
        }
    }

};

This mechanism uses C# reflection to set value to class. group name is matched against field name in class instance. Please note that Convert.ChangeType won't accept any kind of garbage.

If you want to add tracking of line / column - you can add extra Regex split for lines, but in order to keep for loop intact - all match patterns must have named groups. (Otherwise column index will be calculated incorrectly)

This will results in following output:

456 followed by ' '
3434 followed by ' '
298 followed by '.'
893434 followed by ' '

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

I solved the simmilar problem, when i tried to push to repo via gitlab ci/cd pipeline by the command "gem install rake && bundle install"

How to remove &quot; from my Json in javascript?

var data = $('<div>').html('[{&quot;Id&quot;:1,&quot;Name&quot;:&quot;Name}]')[0].textContent;

that should parse all the encoded values you need.

Working with Enums in android

As commented by Chris, enums require much more memory on Android that adds up as they keep being used everywhere. You should try IntDef or StringDef instead, which use annotations so that the compiler validates passed values.

public abstract class ActionBar {
...
@IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS})
@Retention(RetentionPolicy.SOURCE)
public @interface NavigationMode {}

public static final int NAVIGATION_MODE_STANDARD = 0;
public static final int NAVIGATION_MODE_LIST = 1;
public static final int NAVIGATION_MODE_TABS = 2;

@NavigationMode
public abstract int getNavigationMode();

public abstract void setNavigationMode(@NavigationMode int mode);

It can also be used as flags, allowing for binary composition (OR / AND operations).

EDIT: It seems that transforming enums into ints is one of the default optimizations in Proguard.

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

Define your own parse format string to use.

string formatString = "yyyyMMddHHmmss";
string sample = "20100611221912";
DateTime dt = DateTime.ParseExact(sample,formatString,null);

In case you got a datetime having milliseconds, use the following formatString

string format = "yyyyMMddHHmmssfff"
string dateTime = "20140123205803252";
DateTime.ParseExact(dateTime ,format,CultureInfo.InvariantCulture);

Thanks

How to Consume WCF Service with Android

Another option might be to avoid WCF all-together and just use a .NET HttpHandler. The HttpHandler can grab the query-string variables from your GET and just write back a response to the Java code.

Is there a way to view past mysql queries with phpmyadmin?

I am using phpMyAdmin Server version: 5.1.41.

It offers possibility for view sql history through phpmyadmin.pma_history table.

You can search your query in this table.

pma_history table has below structure:

enter image description here

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

Another solution that it is similar to those already exposed here is this one. Just before the closing body tag place this html:

<div id="resultLoading" style="display: none; width: 100%; height: 100%; position: fixed; z-index: 10000; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto;">
    <div style="width: 340px; height: 200px; text-align: center; position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto; z-index: 10; color: rgb(255, 255, 255);">
        <div class="uil-default-css">
            <img src="/images/loading-animation1.gif" style="max-width: 150px; max-height: 150px; display: block; margin-left: auto; margin-right: auto;" />
        </div>
        <div class="loader-text" style="display: block; font-size: 18px; font-weight: 300;">&nbsp;</div>
    </div>
    <div style="background: rgb(0, 0, 0); opacity: 0.6; width: 100%; height: 100%; position: absolute; top: 0px;"></div>
</div>

Finally, replace .loader-text element's content on the fly on every navigation event and turn on the #resultloading div, note that it is initially hidden.

var showLoader = function (text) {
    $('#resultLoading').show();
    $('#resultLoading').find('.loader-text').html(text);
};

jQuery(document).ready(function () {
    jQuery(window).on("beforeunload ", function () {
        showLoader('Loading, please wait...');
    });
});

This can be applied to any html based project with jQuery where you don't know which pages of your administration area will take too long to finish loading.

The gif image is 176x176px but you can use any transparent gif animation, please take into account that the image size is not important as it will be maxed to 150x150px.

Also, the function showLoader can be called on an element's click to perform an action that will further redirect the page, that is why it is provided ad an individual function. i hope this can also help anyone.

How can I update npm on Windows?

This might help someone. Neither "npm-windows-upgrade" nor the installer alone did it for me. Powershell was still using an older version of node and npm.

So this is what I did (worked for me): 1. Download the latest installer from nodejs.org. Install node. It will update your node; everywhere (Powershell, cmd etc.). 2. Install the npm-windows-upgrade package (npm install -g npm-windows-upgrade) and run npm-windows-upgrade.

I didn't uninstall anything and didn't set any paths.

HTML form with side by side input fields

You could use the {display: inline-flex;} this would produce this: inline-flex

Class extending more than one class Java?

No it is not possible in java (Maybe in java 8 it will be avilable). Except the case when you extend in a tree. For example:

class A
class B extends A
class C extends B

Add x and y labels to a pandas plot

The df.plot() function returns a matplotlib.axes.AxesSubplot object. You can set the labels on that object.

ax = df2.plot(lw=2, colormap='jet', marker='.', markersize=10, title='Video streaming dropout by category')
ax.set_xlabel("x label")
ax.set_ylabel("y label")

enter image description here

Or, more succinctly: ax.set(xlabel="x label", ylabel="y label").

Alternatively, the index x-axis label is automatically set to the Index name, if it has one. so df2.index.name = 'x label' would work too.

Horizontal ListView in Android?

Note: Android now supports horizontal list views using RecyclerView, so now this answer is deprecated, for information about RecyclerView : https://developer.android.com/reference/android/support/v7/widget/RecyclerView

I have developed a logic to do it without using any external horizontal scrollview library, here is the horizontal view that I achieved and I have posted my answer here:https://stackoverflow.com/a/33301582/5479863

My json response is this:

{"searchInfo":{"status":"1","message":"Success","clist":[{"id":"1de57434-795e-49ac-0ca3-5614dacecbd4","name":"Theater","image_url":"http://52.25.198.71/miisecretory/category_images/movie.png"},{"id":"62fe1c92-2192-2ebb-7e92-5614dacad69b","name":"CNG","image_url":"http://52.25.198.71/miisecretory/category_images/cng.png"},{"id":"8060094c-df4f-5290-7983-5614dad31677","name":"Wine-shop","image_url":"http://52.25.198.71/miisecretory/category_images/beer.png"},{"id":"888a90c4-a6b0-c2e2-6b3c-561788e973f6","name":"Chemist","image_url":"http://52.25.198.71/miisecretory/category_images/chemist.png"},{"id":"a39b4ec1-943f-b800-a671-561789a57871","name":"Food","image_url":"http://52.25.198.71/miisecretory/category_images/food.png"},{"id":"c644cc53-2fce-8cbe-0715-5614da9c765f","name":"College","image_url":"http://52.25.198.71/miisecretory/category_images/college.png"},{"id":"c71e8757-072b-1bf4-5b25-5614d980ef15","name":"Hospital","image_url":"http://52.25.198.71/miisecretory/category_images/hospital.png"},{"id":"db835491-d1d2-5467-a1a1-5614d9963c94","name":"Petrol-Pumps","image_url":"http://52.25.198.71/miisecretory/category_images/petrol.png"},{"id":"f13100ca-4052-c0f4-863a-5614d9631afb","name":"ATM","image_url":"http://52.25.198.71/miisecretory/category_images/atm.png"}]}}

Layout file :

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="5">    
    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="4" />
    <HorizontalScrollView
        android:id="@+id/horizontalScroll"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <LinearLayout
            android:id="@+id/ll"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:orientation="horizontal">    
        </LinearLayout>
    </HorizontalScrollView>
</LinearLayout>

class file:

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ll);
        for (int v = 0; v < collectionInfo.size(); v++) {
            /*---------------Creating frame layout----------------------*/

            FrameLayout frameLayout = new FrameLayout(ActivityMap.this);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, getPixelsToDP(90));
            layoutParams.rightMargin = getPixelsToDP(10);
            frameLayout.setLayoutParams(layoutParams);

            /*--------------end of frame layout----------------------------*/

            /*---------------Creating image view----------------------*/
            final ImageView imgView = new ImageView(ActivityMap.this); //create imageview dynamically
            LinearLayout.LayoutParams lpImage = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            imgView.setImageBitmap(collectionInfo.get(v).getCatImage());
            imgView.setLayoutParams(lpImage);
            // setting ID to retrieve at later time (same as its position)
            imgView.setId(v);
            imgView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    // getting id which is same as its position
                    Log.i(TAG, "Clicked on " + collectionInfo.get(v.getId()).getCatName());
                    // getting selected category's data list
                    new GetSelectedCategoryData().execute(collectionInfo.get(v.getId()).getCatID());
                }
            });
            /*--------------end of image view----------------------------*/

            /*---------------Creating Text view----------------------*/
            TextView textView = new TextView(ActivityMap.this);//create textview dynamically
            textView.setText(collectionInfo.get(v).getCatName());
            FrameLayout.LayoutParams lpText = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER);
            // Note: LinearLayout.LayoutParams 's gravity was not working so I putted Framelayout as 3 paramater is gravity itself
            textView.setTextColor(Color.parseColor("#43A047"));
            textView.setLayoutParams(lpText);
            /*--------------end of Text view----------------------------*/

            //Adding views at appropriate places
            frameLayout.addView(imgView);
            frameLayout.addView(textView);
            linearLayout.addView(frameLayout);

        }

 private int getPixelsToDP(int dp) {
        float scale = getResources().getDisplayMetrics().density;
        int pixels = (int) (dp * scale + 0.5f);
        return pixels;
    }

trick that is working here is the id that I have assigned to ImageView "imgView.setId(v)" and after that applying onClickListener to that I am again fetching the id of the view....I have also commented inside the code so that its easy to understand, I hope this may be very useful... Happy Coding... :)

http://i.stack.imgur.com/lXrpG.png

How to remove anaconda from windows completely?

I think this is the official solution: https://docs.anaconda.com/anaconda/install/uninstall/

[Unfortunately I did the simple remove (Uninstall-Anaconda.exe in C:\Users\username\Anaconda3 following the answers in stack overflow) before I found the official article, so I have to get rid of everything manually.]

But for the rest of you the official full removal could be interesting, so I copied it here:

To uninstall Anaconda, you can do a simple remove of the program. This will leave a few files behind, which for most users is just fine. See Option A.

If you also want to remove all traces of the configuration files and directories from Anaconda and its programs, you can download and use the Anaconda-Clean program first, then do a simple remove. See Option B.

  1. Option A. Use simple remove to uninstall Anaconda:

    • Windows–In the Control Panel, choose Add or Remove Programs or Uninstall a program, and then select Python 3.6 (Anaconda) or your version of Python.
    • [... also solutions for Mac and Linux are provided here: https://docs.anaconda.com/anaconda/install/uninstall/ ]
  2. Option B: Full uninstall using Anaconda-Clean and simple remove.

    NOTE: Anaconda-Clean must be run before simple remove.

    • Install the Anaconda-Clean package from Anaconda Prompt (Terminal on Linux or macOS):

      conda install anaconda-clean
      
    • In the same window, run one of these commands:

      • Remove all Anaconda-related files and directories with a confirmation prompt before deleting each one:

        anaconda-clean
        
      • Or, remove all Anaconda-related files and directories without being prompted to delete each one:

        anaconda-clean --yes
        

      Anaconda-Clean creates a backup of all files and directories that might be removed in a folder named .anaconda_backup in your home directory. Also note that Anaconda-Clean leaves your data files in the AnacondaProjects directory untouched.

    • After using Anaconda-Clean, follow the instructions above in Option A to uninstall Anaconda.

height: calc(100%) not working correctly in CSS

First off - check with Firebug(or what ever your preference is) whether the css property is being interpreted by the browser. Sometimes the tool used will give you the problem right there, so no more hunting.

Second off - check compatibility: http://caniuse.com/#feat=calc

And third - I ran into some problems a few hours ago and just resolved it. It's the smallest thing but it kept me busy for 30 minutes.

Here's how my CSS looked

#someElement {
    height:calc(100%-100px);
    height:-moz-calc(100%-100px);
    height:-webkit-calc(100%-100px);
}

Looks right doesn't it? WRONG Here's how it should look:

#someElement {
    height:calc(100% - 100px);
    height:-moz-calc(100% - 100px);
    height:-webkit-calc(100% - 100px);
}

Looks the same right?

Notice the spaces!!! Checked android browser, Firefox for android, Chrome for android, Chrome and Firefox for Windows and Internet Explorer 11. All of them ignored the CSS if there were no spaces.

Hope this helps someone.

ng-if, not equal to?

This is now possible as of AngularJS 1.5.10, using ng-switch-when-separator

_x000D_
_x000D_
var app = angular.module("app", []); _x000D_
_x000D_
app.controller("ctrl", function($scope) {_x000D_
    $scope.myDataSet = [{Name: 'Michelle', Gender: 'Female', DOB: '01/12/1986', Payment: [{Status: '0'}]},{Name: 'Steve', Gender: 'Male', DOB: '11/12/1982', Payment: [{Status: '1'}]},{Name: 'Dan', Gender: 'Male', DOB: '03/22/1976', Payment: [{Status: '2'}]},{Name: 'Doug', Gender: 'Male', DOB: '02/02/1980', Payment: [{Status: '3'}]},{Name: 'Mary', Gender: 'Female', DOB: '04/02/1976', Payment: [{Status: '4'}]},{Name: 'Cheyenne', Gender: 'Female', DOB: '07/10/1981', Payment: [{Status: '5'}]},{Name: 'Bob', Gender: 'Male', DOB: '02/16/1990', Payment: [{Status: '6'}]},{Name: 'Bad data', Gender: 'Blank', DOB: '01/01/1970', Payment: [{Status: '7'}]}];_x000D_
});
_x000D_
<script src="https://code.angularjs.org/1.5.10/angular.min.js"></script>_x000D_
<div ng-app="app" ng-controller="ctrl">_x000D_
    <div ng-repeat="details in myDataSet" ng-switch on="details.Payment[0].Status">_x000D_
_x000D_
        <p>{{ details.Name }}</p>_x000D_
        <p>{{ details.DOB  }}</p>_x000D_
_x000D_
        <div ng-switch-when="0">_x000D_
            <p>No payment</p>_x000D_
        </div>_x000D_
_x000D_
        <div ng-switch-when="1|2" ng-switch-when-separator="|">_x000D_
            <p>Late</p>_x000D_
        </div>_x000D_
_x000D_
        <div ng-switch-when="3|4|5" ng-switch-when-separator="|">_x000D_
            <p>Some payment made</p>_x000D_
        </div>_x000D_
_x000D_
        <div ng-switch-when="6">_x000D_
            <p>Late and further taken out</p>_x000D_
        </div>_x000D_
_x000D_
        <div ng-switch-default>_x000D_
            <p>Error</p>_x000D_
        </div>_x000D_
        _x000D_
        <p>{{ details.Gender}}</p>_x000D_
_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

rsync: how can I configure it to create target directory on server?

The -R, --relative option will do this.

For example: if you want to backup /var/named/chroot and create the same directory structure on the remote server then -R will do just that.

Right to Left support for Twitter Bootstrap 3

Bootstrap Persian version of the site http://rbootstrap.ir/ Ver.2.3.2

What is best tool to compare two SQL Server databases (schema and data)?

I've used SQL Delta before (http://www.sqldelta.com/), it's really good. Not free however, not sure how prices compare to Red-Gates

input() error - NameError: name '...' is not defined

You could either do:

x = raw_input("enter your name")
print "your name is %s " % x

or:

x = str(input("enter your name"))
print "your name is %s" % x

Multiple IF AND statements excel

Try the following:

=IF(OR(E2="in play",E2="pre play",E2="complete",E2="suspended"),
IF(E2="in play",IF(F2="closed",3,IF(F2="suspended",2,IF(ISBLANK(F2),1,-2))),
IF(E2="pre play",IF(ISBLANK(F2),-1,-2),IF(E2="completed",IF(F2="closed",2,-2),
IF(E2="suspended",IF(ISBLANK(F2),3,-2))))),-2)