Programs & Examples On #Pgp

Pretty Good Privacy (PGP) is a data encryption and decryption computer program that provides cryptographic privacy and authentication for data communication.

Can't check signature: public key not found

I got the same message but my files are decrypted as expected. Please check in your destination path if you could see the output file file.

How to delete the top 1000 rows from a table using Sql Server 2008?

It is fast. Try it:

DELETE FROM YourTABLE
FROM (SELECT TOP XX PK FROM YourTABLE) tbl
WHERE YourTABLE.PK = tbl.PK

Replace YourTABLE by table name, XX by a number, for example 1000, pk is the name of the primary key field of your table.

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

We have the following string which is a valid JSON ...

Clearly the JSON parser disagrees!

However, the exception says that the error is at "line 1: column 9", and there is no "http" token near the beginning of the JSON. So I suspect that the parser is trying to parse something different than this string when the error occurs.

You need to find what JSON is actually being parsed. Run the application within a debugger, set a breakpoint on the relevant constructor for JsonParseException ... then find out what is in the ByteArrayInputStream that it is attempting to parse.

Hashing a string with Sha256

The shortest and fastest way ever. Only 1 line!

public static string StringSha256Hash(string text) =>
    string.IsNullOrEmpty(text) ? string.Empty : BitConverter.ToString(new System.Security.Cryptography.SHA256Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(text))).Replace("-", string.Empty);

Maven: How to run a .java file from command line passing arguments

Adding a shell script e.g. run.sh makes it much more easier:

#!/usr/bin/env bash
export JAVA_PROGRAM_ARGS=`echo "$@"`
mvn exec:java -Dexec.mainClass="test.Main" -Dexec.args="$JAVA_PROGRAM_ARGS"

Then you are able to execute:

./run.sh arg1 arg2 arg3

How to stop an app on Heroku?

If you are using eclipse plugin, double click on the app-name in My Heroku Applications. In Processes tab, press Scale Button. A small window will pop-up. Increase/decrease the count and just say OK.

Convert string to variable name in python

You can use a Dictionary to keep track of the keys and values.

For instance...

dictOfStuff = {} ##Make a Dictionary

x = "Buffalo" ##OR it can equal the input of something, up to you.

dictOfStuff[x] = 4 ##Get the dict spot that has the same key ("name") as what X is equal to. In this case "Buffalo". and set it to 4. Or you can set it to  what ever you like

print(dictOfStuff[x]) ##print out the value of the spot in the dict that same key ("name") as the dictionary.

A dictionary is very similar to a real life dictionary. You have a word and you have a definition. You can look up the word and get the definition. So in this case, you have the word "Buffalo" and it's definition is 4. It can work with any other word and definition. Just make sure you put them into the dictionary first.

How can I make the cursor turn to the wait cursor?

OK so I created a static async method. That disabled the control that launches the action and changes the application cursor. It runs the action as a task and waits for to finish. Control returns to the caller while it waits. So the application remains responsive, even while the busy icon spins.

async public static void LengthyOperation(Control control, Action action)
{
    try
    {
        control.Enabled = false;
        Application.UseWaitCursor = true;
        Task doWork = new Task(() => action(), TaskCreationOptions.LongRunning);
        Log.Info("Task Start");
        doWork.Start();
        Log.Info("Before Await");
        await doWork;
        Log.Info("After await");
    }
    finally
    {
        Log.Info("Finally");
        Application.UseWaitCursor = false;
        control.Enabled = true;
    }

Here's the code form the main form

    private void btnSleep_Click(object sender, EventArgs e)
    {
        var control = sender as Control;
        if (control != null)
        {
            Log.Info("Launching lengthy operation...");
            CursorWait.LengthyOperation(control, () => DummyAction());
            Log.Info("...Lengthy operation launched.");
        }

    }

    private void DummyAction()
    {
        try
        {
            var _log = NLog.LogManager.GetLogger("TmpLogger");
            _log.Info("Action - Sleep");
            TimeSpan sleep = new TimeSpan(0, 0, 16);
            Thread.Sleep(sleep);
            _log.Info("Action - Wakeup");
        }
        finally
        {
        }
    }

I had to use a separate logger for the dummy action (I am using Nlog) and my main logger is writing to the UI (a rich text box). I wasn't able to get the busy cursor show only when over a particular container on the form (but I didn't try very hard.) All controls have a UseWaitCursor property, but it doesn't seem have any effect on the controls I tried (maybe because they weren't on top?)

Here's the main log, which shows things happening in the order we expect:

16:51:33.1064 Launching lengthy operation...
16:51:33.1215 Task Start
16:51:33.1215 Before Await
16:51:33.1215 ...Lengthy operation launched.
16:51:49.1276 After await
16:51:49.1537 Finally

OpenCV & Python - Image too big to display

Although I was expecting an automatic solution (fitting to the screen automatically), resizing solves the problem as well.

import cv2
cv2.namedWindow("output", cv2.WINDOW_NORMAL)        # Create window with freedom of dimensions
im = cv2.imread("earth.jpg")                        # Read image
imS = cv2.resize(im, (960, 540))                    # Resize image
cv2.imshow("output", imS)                            # Show image
cv2.waitKey(0)                                      # Display the image infinitely until any keypress

Export table data from one SQL Server to another

Just for the kicks.

Since I wasnt able to create linked server and since just connecting to production server was not enough to use INSERT INTO i did the following:

  • created a backup of production server database
  • restored the database on my test server
  • executed the insert into statements

Its a backdoor solution, but since i had problems it worked for me.

Since i have created empty tables using SCRIPT TABLE AS / CREATE in order to transfer all the keys and indexes I couldnt use SELECT INTO. SELECT INTO only works if the tables do not exist on the destination location but it does not copy keys and indexes, so you have to do that manualy. The downside of using INSERT INTO statement is that you have to manualy provide with all the column names, plus it might give you some problems if some foreign key constraints fail.

Thanks to all anwsers, there are some great solutions but i have decided to accept marc_s anwser.

The conversion of the varchar value overflowed an int column

Thanks Ravi and other users .... Nevertheless I have got the solution

SELECT @phoneNumber=
CASE 
  WHEN  ISNULL(rdg2.nPhoneNumber  ,'0') in ('0','-',NULL)
THEN ISNULL(rdg2.nMobileNumber, '0') 
  WHEN ISNULL(rdg2.nMobileNumber, '0')  in ('0','-',NULL)
THEN '0'
  ELSE ISNULL(rdg2.nPhoneNumber  ,'0')
END 
FROM tblReservation_Details_Guest  rdg2 
WHERE nReservationID=@nReservationID

Just need to put '0' instead of 0

What is the proper way to URL encode Unicode characters?

IRI (RFC 3987) is the latest standard that replaces the URI/URL (RFC 3986 and older) standards. URI/URL do not natively support Unicode (well, RFC 3986 adds provisions for future URI/URL-based protocols to support it, but does not update past RFCs). The "%uXXXX" scheme is a non-standard extension to allow Unicode in some situations, but is not universally implemented by everyone. IRI, on the other hand, fully supports Unicode, and requires that text be encoded as UTF-8 before then being percent-encoded.

Fragment pressing back button

if you are using webview inside a fragment than use this in your onCreateView method

webView.setOnKeyListener(new View.OnKeyListener(){

        @Override
        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            if((i==KeyEvent.KEYCODE_BACK)&& webView.canGoBack()){
                webView.goBack();
                return true;
            }
            return false;
        }
    });

and import this class

import android.view.KeyEvent;

How to detect installed version of MS-Office?

Despite the fact that this question has been answered long time ago, I found some interesting facts to add that are related to the answers above.

As Dirk mentioned, there seems to be a weird fashion of version control from MS, starting from Office 365 / 2019. You cannot distinguish among the three(2016, 2019, O365), by seeing at the executable paths anymore. And just like he reputed himself, looking at the builds of the executable, as a mean of telling which is what, isn't quite effective either.

After some researching, I found a feasible solution. The solution lies under the registry subkey Computer\HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Common\Licensing\LicensingNext.

So, my logic follows below:

Case 1: If the computer has the MSOffice 2016 installed, there is no subkeys under Licensing.

Case 2: if the computer has MSOffice 2019 installed, there is the name of the value (which is one of the Office Product ID). (e.g. Standard2019Volume)

Case 3: if the computer has Office365 installed, there is a value called o365bussinessretail(which is also a product ID) along with some other values.

The possible productIds are provided here.

To distinguish the three, I just opened the key and see if fails. If the open fails, its Office 2016. Then I enumerate LicensingNext and try to see if any name has a prefix o365, if it finds it then its O365. If it does not, then its Office 2019.

Frankly speaking, I did not have enough time to test the logic under varying environment. So please, note that.

Hope this will help whoever's interest.

GridView VS GridLayout in Android Apps

A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.

This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.

Whereas a GridLayout is a layout that places its children in a rectangular grid.

It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.

Update Tkinter Label from variable

This is the easiest one , Just define a Function and then a Tkinter Label & Button . Pressing the Button changes the text in the label. The difference that you would when defining the Label is that use the text variable instead of text. Code is tested and working.

    from tkinter import *
    master = Tk()
    
    def change_text():
        my_var.set("Second click")
    
    my_var = StringVar()
    my_var.set("First click")
    label = Label(mas,textvariable=my_var,fg="red")
    button = Button(mas,text="Submit",command = change_text)
    button.pack()
    label.pack()
    
    master.mainloop()

Why aren't Xcode breakpoints functioning?

Also make sure that the AppStore distribution of the app is not also installed on the device.

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

Based on the hint and link provided in Simone Giannis answer, this is my hack to fix this.

I am testing on uri.getAuthority(), because UNC path will report an Authority. This is a bug - so I rely on the existence of a bug, which is evil, but it apears as if this will stay forever (since Java 7 solves the problem in java.nio.Paths).

Note: In my context I will receive absolute paths. I have tested this on Windows and OS X.

(Still looking for a better way to do it)

package com.christianfries.test;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

public class UNCPathTest {

    public static void main(String[] args) throws MalformedURLException, URISyntaxException {
        UNCPathTest upt = new UNCPathTest();

        upt.testURL("file://server/dir/file.txt");  // Windows UNC Path

        upt.testURL("file:///Z:/dir/file.txt");     // Windows drive letter path

        upt.testURL("file:///dir/file.txt");        // Unix (absolute) path
    }

    private void testURL(String urlString) throws MalformedURLException, URISyntaxException {
        URL url = new URL(urlString);
        System.out.println("URL is: " + url.toString());

        URI uri = url.toURI();
        System.out.println("URI is: " + uri.toString());

        if(uri.getAuthority() != null && uri.getAuthority().length() > 0) {
            // Hack for UNC Path
            uri = (new URL("file://" + urlString.substring("file:".length()))).toURI();
        }

        File file = new File(uri);
        System.out.println("File is: " + file.toString());

        String parent = file.getParent();
        System.out.println("Parent is: " + parent);

        System.out.println("____________________________________________________________");
    }

}

Converting Dictionary to List?

 >>> a = {'foo': 'bar', 'baz': 'quux', 'hello': 'world'}
 >>> list(reduce(lambda x, y: x + y, a.items()))
 ['foo', 'bar', 'baz', 'quux', 'hello', 'world']

To explain: a.items() returns a list of tuples. Adding two tuples together makes one tuple containing all elements. Thus the reduction creates one tuple containing all keys and values and then the list(...) makes a list from that.

How to manage local vs production settings in Django?

I am also working with Laravel and I like the implementation there. I tried to mimic it and combining it with the solution proposed by T. Stone (look above):

PRODUCTION_SERVERS = ['*.webfaction.com','*.whatever.com',]

def check_env():
    for item in PRODUCTION_SERVERS:
        match = re.match(r"(^." + item + "$)", socket.gethostname())
        if match:
            return True

if check_env():
    PRODUCTION = True
else:
    PRODUCTION = False

DEBUG = not PRODUCTION

Maybe something like this would help you.

Uninstall all installed gems, in OSX?

Rubygems >= 2.1.0

gem uninstall -aIx

If Terminal returns below error

ERROR:  While executing gem ... (Gem::FilePermissionError)
You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory.

Then write above command as below

sudo gem uninstall -aIx

And enter your mac os account password Done!!

Edit a specific Line of a Text File in C#

You need to Open the output file for write access rather than using a new StreamReader, which always overwrites the output file.

StreamWriter stm = null;
fi = new FileInfo(@"C:\target.xml");
if (fi.Exists)
   stm = fi.OpenWrite();

Of course, you will still have to seek to the correct line in the output file, which will be hard since you can't read from it, so unless you already KNOW the byte offset to seek to, you probably really want read/write access.

FileStream stm = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);

with this stream, you can read until you get to the point where you want to make changes, then write. Keep in mind that you are writing bytes, not lines, so to overwrite a line you will need to write the same number of characters as the line you want to change.

How to define a relative path in java

Example for Spring Boot. My WSDL-file is in Resources in "wsdl" folder. The path to the WSDL-file is:

resources/wsdl/WebServiceFile.wsdl

To get the path from some method to this file you can do the following:

String pathToWsdl = this.getClass().getClassLoader().
                    getResource("wsdl\\WebServiceFile.wsdl").toString();

CSS: fixed to bottom and centered

There are 2 potential issues that I see:

1 - IE has had trouble with position:fixed in the past. If you are using IE7+ with a valid doctype or a non-IE browser this isn't part of the problem

2 - You need to specify a width for the footer if you want the footer object to be centered. Otherwise it defaults to the full width of the page and the auto margin for the left and right get set to 0. If you want the footer bar to take up the width (like the StackOverflow notice bar) and center the text, then you need to add "text-align: center" to your definition.

How to interpret "loss" and "accuracy" for a machine learning model

Just to clarify the Training/Validation/Test data sets: The training set is used to perform the initial training of the model, initializing the weights of the neural network.

The validation set is used after the neural network has been trained. It is used for tuning the network's hyperparameters, and comparing how changes to them affect the predictive accuracy of the model. Whereas the training set can be thought of as being used to build the neural network's gate weights, the validation set allows fine tuning of the parameters or architecture of the neural network model. It's useful as it allows repeatable comparison of these different parameters/architectures against the same data and networks weights, to observe how parameter/architecture changes affect the predictive power of the network.

Then the test set is used only to test the predictive accuracy of the trained neural network on previously unseen data, after training and parameter/architecture selection with the training and validation data sets.

What's the difference between compiled and interpreted language?

Interpreted language is executed at the run time according to the instructions like in shell scripting and compiled language is one which is compiled (changed into Assembly language, which CPU can understand ) and then executed like in c++.

Setting the zoom level for a MKMapView

Based on the fact that longitude lines are spaced apart equally at any point of the map, there is a very simple implementation to set the centerCoordinate and zoomLevel:

@interface MKMapView (ZoomLevel)

@property (assign, nonatomic) NSUInteger zoomLevel;

- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                  zoomLevel:(NSUInteger)zoomLevel
                   animated:(BOOL)animated;

@end


@implementation MKMapView (ZoomLevel)

- (void)setZoomLevel:(NSUInteger)zoomLevel {
    [self setCenterCoordinate:self.centerCoordinate zoomLevel:zoomLevel animated:NO];
}

- (NSUInteger)zoomLevel {
    return log2(360 * ((self.frame.size.width/256) / self.region.span.longitudeDelta)) + 1;
}

- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
zoomLevel:(NSUInteger)zoomLevel animated:(BOOL)animated {
    MKCoordinateSpan span = MKCoordinateSpanMake(0, 360/pow(2, zoomLevel)*self.frame.size.width/256);
    [self setRegion:MKCoordinateRegionMake(centerCoordinate, span) animated:animated];
}

@end

How can I delete all Git branches which have been merged?

$ git config --global alias.cleanup
'!git branch --merged origin/master | egrep -v "(^\*|master|staging|dev)" | xargs git branch -d'

(Split into multiple lines for readability)

Calling "git cleanup" will delete local branches that have already been merged into origin/master. It skips master, staging, and dev because we don't want to delete those in normal circumstances.

Breaking this down, this is what it's doing:

  1. git config --global alias.cleanup
    • This is creating a global alias called "cleanup" (across all your repos)
  2. The ! at the beginning of the command is saying that we will be using some non-git commands as part of this alias so we need to actually run bash commands here
  3. git branch --merged origin/master
    • This command returns the list of branch names that have already been merged into origin/master
  4. egrep -v "(^\*|master|staging|dev)"
    • This removes the master, staging, and dev branch from the list of branches that have already been merged. We don't want to remove these branches since they are not features.
  5. xargs git branch -d
    • This will run the git branch -d xxxxx command for each of the unmerged branches. This deletes the local branches one by one.

How to set size for local image using knitr for markdown?

Had the same issue today and found another option with knitr 1.16 when knitting to PDF (which requires that you have pandoc installed):

![Image Title](path/to/your/image){width=70%}

This method may require that you do a bit of trial and error to find the size that works for you. It is especially convenient because it makes putting two images side by side a prettier process. For example:

![Image 1](path/to/image1){width=70%}![Image 2](path/to/image2){width=30%}

You can get creative and stack a couple of these side by side and size them as you see fit. See https://rpubs.com/RatherBit/90926 for more ideas and examples.

Apache Spark: map vs mapPartitions?

What's the difference between an RDD's map and mapPartitions method?

The method map converts each element of the source RDD into a single element of the result RDD by applying a function. mapPartitions converts each partition of the source RDD into multiple elements of the result (possibly none).

And does flatMap behave like map or like mapPartitions?

Neither, flatMap works on a single element (as map) and produces multiple elements of the result (as mapPartitions).

How to declare a static const char* in your header file?

class A{
public:
   static const char* SOMETHING() { return "something"; }
};

I do it all the time - especially for expensive const default parameters.

class A{
   static
   const expensive_to_construct&
   default_expensive_to_construct(){
      static const expensive_to_construct xp2c(whatever is needed);
      return xp2c;
   }
};

How to get Url Hash (#) from server side

Possible solution for GET requests:

New Link format: http://example.com/yourDirectory?hash=video01

Call this function toward top of controller or http://example.com/yourDirectory/index.php:

function redirect()
{
    if (!empty($_GET['hash'])) {
        /** Sanitize & Validate $_GET['hash']
               If valid return string
               If invalid: return empty or false
        ******************************************************/
        $validHash = sanitizeAndValidateHashFunction($_GET['hash']);
        if (!empty($validHash)) {
            $url = './#' . $validHash;
        } else {
            $url = '/your404page.php';
        }
        header("Location: $url");
    }
}

How to remove a file from the index in git?

Only use git rm --cached [file] to remove a file from the index.

git reset <filename> can be used to remove added files from the index given the files are never committed.

% git add First.txt
% git ls-files
First.txt
% git commit -m "First"   
% git ls-files            
First.txt
% git reset First.txt
% git ls-files              
First.txt

NOTE: git reset First.txt has no effect on index after the commit.

Which brings me to the topic of git restore --staged <file>. It can be used to (presumably after the first commit) remove added files from the index given the files are never committed.

% git add Second.txt              
% git status        
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
    new file:   Second.txt
% git ls-files       
First.txt
Second.txt
% git restore --staged Second.txt
% git ls-files 
First.txt
% git add Second.txt 
% git commit -m "Second"
% git status            
On branch master
nothing to commit, working tree clean
% git ls-files 
First.txt         
Second.txt
Desktop/Test% git restore --staged .
Desktop/Test% git ls-files
First.txt                   
Second.txt
Desktop/Test% git reset .                    
Desktop/Test% git ls-files
First.txt
Second.txt
% git rm --cached -r .
rm 'First.txt'
rm 'Second.txt'
% git ls-files  

tl;dr Look at last 15 lines. If you don't want to be confused with first commit, second commit, before commit, after commit.... always use git rm --cached [file]

Read each line of txt file to new array element

<?php
$file = fopen("members.txt", "r");
$members = array();

while (!feof($file)) {
   $members[] = fgets($file);
}

fclose($file);

var_dump($members);
?>

Java output formatting for Strings

System.out.println(String.format("%-20s= %s" , "label", "content" ));
  • Where %s is a placeholder for you string.
  • The '-' makes the result left-justified.
  • 20 is the width of the first string

The output looks like this:

label               = content

As a reference I recommend Javadoc on formatter syntax

IPC performance: Named Pipe vs Socket

Best results you'll get with Shared Memory solution.

Named pipes are only 16% better than TCP sockets.

Results are get with IPC benchmarking:

  • System: Linux (Linux ubuntu 4.4.0 x86_64 i7-6700K 4.00GHz)
  • Message: 128 bytes
  • Messages count: 1000000

Pipe benchmark:

Message size:       128
Message count:      1000000
Total duration:     27367.454 ms
Average duration:   27.319 us
Minimum duration:   5.888 us
Maximum duration:   15763.712 us
Standard deviation: 26.664 us
Message rate:       36539 msg/s

FIFOs (named pipes) benchmark:

Message size:       128
Message count:      1000000
Total duration:     38100.093 ms
Average duration:   38.025 us
Minimum duration:   6.656 us
Maximum duration:   27415.040 us
Standard deviation: 91.614 us
Message rate:       26246 msg/s

Message Queue benchmark:

Message size:       128
Message count:      1000000
Total duration:     14723.159 ms
Average duration:   14.675 us
Minimum duration:   3.840 us
Maximum duration:   17437.184 us
Standard deviation: 53.615 us
Message rate:       67920 msg/s

Shared Memory benchmark:

Message size:       128
Message count:      1000000
Total duration:     261.650 ms
Average duration:   0.238 us
Minimum duration:   0.000 us
Maximum duration:   10092.032 us
Standard deviation: 22.095 us
Message rate:       3821893 msg/s

TCP sockets benchmark:

Message size:       128
Message count:      1000000
Total duration:     44477.257 ms
Average duration:   44.391 us
Minimum duration:   11.520 us
Maximum duration:   15863.296 us
Standard deviation: 44.905 us
Message rate:       22483 msg/s

Unix domain sockets benchmark:

Message size:       128
Message count:      1000000
Total duration:     24579.846 ms
Average duration:   24.531 us
Minimum duration:   2.560 us
Maximum duration:   15932.928 us
Standard deviation: 37.854 us
Message rate:       40683 msg/s

ZeroMQ benchmark:

Message size:       128
Message count:      1000000
Total duration:     64872.327 ms
Average duration:   64.808 us
Minimum duration:   23.552 us
Maximum duration:   16443.392 us
Standard deviation: 133.483 us
Message rate:       15414 msg/s

Convert list of dictionaries to a pandas DataFrame

How do I convert a list of dictionaries to a pandas DataFrame?

The other answers are correct, but not much has been explained in terms of advantages and limitations of these methods. The aim of this post will be to show examples of these methods under different situations, discuss when to use (and when not to use), and suggest alternatives.


DataFrame(), DataFrame.from_records(), and .from_dict()

Depending on the structure and format of your data, there are situations where either all three methods work, or some work better than others, or some don't work at all.

Consider a very contrived example.

np.random.seed(0)
data = pd.DataFrame(
    np.random.choice(10, (3, 4)), columns=list('ABCD')).to_dict('r')

print(data)
[{'A': 5, 'B': 0, 'C': 3, 'D': 3},
 {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 {'A': 2, 'B': 4, 'C': 7, 'D': 6}]

This list consists of "records" with every keys present. This is the simplest case you could encounter.

# The following methods all produce the same output.
pd.DataFrame(data)
pd.DataFrame.from_dict(data)
pd.DataFrame.from_records(data)

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

Word on Dictionary Orientations: orient='index'/'columns'

Before continuing, it is important to make the distinction between the different types of dictionary orientations, and support with pandas. There are two primary types: "columns", and "index".

orient='columns'
Dictionaries with the "columns" orientation will have their keys correspond to columns in the equivalent DataFrame.

For example, data above is in the "columns" orient.

data_c = [
 {'A': 5, 'B': 0, 'C': 3, 'D': 3},
 {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 {'A': 2, 'B': 4, 'C': 7, 'D': 6}]
pd.DataFrame.from_dict(data_c, orient='columns')

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

Note: If you are using pd.DataFrame.from_records, the orientation is assumed to be "columns" (you cannot specify otherwise), and the dictionaries will be loaded accordingly.

orient='index'
With this orient, keys are assumed to correspond to index values. This kind of data is best suited for pd.DataFrame.from_dict.

data_i ={
 0: {'A': 5, 'B': 0, 'C': 3, 'D': 3},
 1: {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 2: {'A': 2, 'B': 4, 'C': 7, 'D': 6}}
pd.DataFrame.from_dict(data_i, orient='index')

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

This case is not considered in the OP, but is still useful to know.

Setting Custom Index

If you need a custom index on the resultant DataFrame, you can set it using the index=... argument.

pd.DataFrame(data, index=['a', 'b', 'c'])
# pd.DataFrame.from_records(data, index=['a', 'b', 'c'])

   A  B  C  D
a  5  0  3  3
b  7  9  3  5
c  2  4  7  6

This is not supported by pd.DataFrame.from_dict.

Dealing with Missing Keys/Columns

All methods work out-of-the-box when handling dictionaries with missing keys/column values. For example,

data2 = [
     {'A': 5, 'C': 3, 'D': 3},
     {'A': 7, 'B': 9, 'F': 5},
     {'B': 4, 'C': 7, 'E': 6}]
# The methods below all produce the same output.
pd.DataFrame(data2)
pd.DataFrame.from_dict(data2)
pd.DataFrame.from_records(data2)

     A    B    C    D    E    F
0  5.0  NaN  3.0  3.0  NaN  NaN
1  7.0  9.0  NaN  NaN  NaN  5.0
2  NaN  4.0  7.0  NaN  6.0  NaN

Reading Subset of Columns

"What if I don't want to read in every single column"? You can easily specify this using the columns=... parameter.

For example, from the example dictionary of data2 above, if you wanted to read only columns "A', 'D', and 'F', you can do so by passing a list:

pd.DataFrame(data2, columns=['A', 'D', 'F'])
# pd.DataFrame.from_records(data2, columns=['A', 'D', 'F'])

     A    D    F
0  5.0  3.0  NaN
1  7.0  NaN  5.0
2  NaN  NaN  NaN

This is not supported by pd.DataFrame.from_dict with the default orient "columns".

pd.DataFrame.from_dict(data2, orient='columns', columns=['A', 'B'])
ValueError: cannot use columns parameter with orient='columns'

Reading Subset of Rows

Not supported by any of these methods directly. You will have to iterate over your data and perform a reverse delete in-place as you iterate. For example, to extract only the 0th and 2nd rows from data2 above, you can use:

rows_to_select = {0, 2}
for i in reversed(range(len(data2))):
    if i not in rows_to_select:
        del data2[i]

pd.DataFrame(data2)
# pd.DataFrame.from_dict(data2)
# pd.DataFrame.from_records(data2)

     A    B  C    D    E
0  5.0  NaN  3  3.0  NaN
1  NaN  4.0  7  NaN  6.0

The Panacea: json_normalize for Nested Data

A strong, robust alternative to the methods outlined above is the json_normalize function which works with lists of dictionaries (records), and in addition can also handle nested dictionaries.

pd.json_normalize(data)

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6
pd.json_normalize(data2)

     A    B  C    D    E
0  5.0  NaN  3  3.0  NaN
1  NaN  4.0  7  NaN  6.0

Again, keep in mind that the data passed to json_normalize needs to be in the list-of-dictionaries (records) format.

As mentioned, json_normalize can also handle nested dictionaries. Here's an example taken from the documentation.

data_nested = [
  {'counties': [{'name': 'Dade', 'population': 12345},
                {'name': 'Broward', 'population': 40000},
                {'name': 'Palm Beach', 'population': 60000}],
   'info': {'governor': 'Rick Scott'},
   'shortname': 'FL',
   'state': 'Florida'},
  {'counties': [{'name': 'Summit', 'population': 1234},
                {'name': 'Cuyahoga', 'population': 1337}],
   'info': {'governor': 'John Kasich'},
   'shortname': 'OH',
   'state': 'Ohio'}
]
pd.json_normalize(data_nested, 
                          record_path='counties', 
                          meta=['state', 'shortname', ['info', 'governor']])

         name  population    state shortname info.governor
0        Dade       12345  Florida        FL    Rick Scott
1     Broward       40000  Florida        FL    Rick Scott
2  Palm Beach       60000  Florida        FL    Rick Scott
3      Summit        1234     Ohio        OH   John Kasich
4    Cuyahoga        1337     Ohio        OH   John Kasich

For more information on the meta and record_path arguments, check out the documentation.


Summarising

Here's a table of all the methods discussed above, along with supported features/functionality.

enter image description here

* Use orient='columns' and then transpose to get the same effect as orient='index'.

Setting max-height for table cell contents

Just put the labels in a div inside the TD and put the height and overflow.. like below.

<table>
<tr>
  <td><div style="height:40px; overflow:hidden">Sample</div></td>
  <td><div style="height:40px; overflow:hidden">Text</div></td>
  <td><div style="height:40px; overflow:hidden">Here</div></td>
</tr>
</table>

Select something that has more/less than x character

If your experiencing the same problem while querying a DB2 database, you'll need to use the below query.

SELECT * 
FROM OPENQUERY(LINK_DB,'SELECT
CITY,
cast(STATE as varchar(40)) 
FROM DATABASE')

HTML favicon won't show on google chrome

A common issue where the favicon will not show up when expected is cache, if your .htaccess for example reads: ExpiresByType image/x-icon "access plus 1 month"

Then simply add a random value to your favicon reference: <link rel="shortcut icon" href="https://example.com/favicon.ico?r=31241" type="image/x-icon" />

Works every time for me even with heavy caching.

How to model type-safe enum types?

You can use a sealed abstract class instead of the enumeration, for example:

sealed abstract class Constraint(val name: String, val verifier: Int => Boolean)

case object NotTooBig extends Constraint("NotTooBig", (_ < 1000))
case object NonZero extends Constraint("NonZero", (_ != 0))
case class NotEquals(x: Int) extends Constraint("NotEquals " + x, (_ != x))

object Main {

  def eval(ctrs: Seq[Constraint])(x: Int): Boolean =
    (true /: ctrs){ case (accum, ctr) => accum && ctr.verifier(x) }

  def main(args: Array[String]) {
    val ctrs = NotTooBig :: NotEquals(5) :: Nil
    val evaluate = eval(ctrs) _

    println(evaluate(3000))
    println(evaluate(3))
    println(evaluate(5))
  }

}

Best practice to validate null and empty collection in Java

If you use Spring frameworks, then you can use CollectionUtils to check against both Collections (List, Array) and Map etc.

if(CollectionUtils.isEmpty(...)) {...}

What’s the best way to check if a file exists in C++? (cross platform)

How about access?

#include <io.h>

if (_access(filename, 0) == -1)
{
    // File does not exist
}

Eclipse: Java was started but returned error code=13

Like Vito mentions, this error occurs after Java updates as the path:

C:\ProgramData\Oracle\Java\javapath

is added to the Path environment variable, causing Eclipse to run using the wrong java version.

To fix the problem:

1) Right-click on Computer and choose Properties.

2) Click Advanced system settings

3) Click Environment Variables...

4) Find the Path variable in the System variables section.

5) Choose it and click Edit...

6) Find and delete the above mentioned path.

This fixed it for me. I should mention that I already have the path:

c:\Program Files\Java\jdk1.7.0_21\bin

in the Path variable, but the new path was added to the beginning of the Path variable and therefore resolution would use that path first.

Marker in leaflet, click event

Here's a jsfiddle with a function call: https://jsfiddle.net/8282emwn/

var marker = new L.Marker([46.947, 7.4448]).on('click', markerOnClick).addTo(map);

function markerOnClick(e)
{
  alert("hi. you clicked the marker at " + e.latlng);
}

Using R to list all files with a specified extension

files <- list.files(pattern = "\\.dbf$")

$ at the end means that this is end of string. "dbf$" will work too, but adding \\. (. is special character in regular expressions so you need to escape it) ensure that you match only files with extension .dbf (in case you have e.g. .adbf files).

When and how should I use a ThreadLocal variable?

There is very good example in book Java Concurrency in Practice. Where author (Joshua Bloch) explains how Thread confinement is one of the simplest ways to achieve thread safety and ThreadLocal is more formal means of maintaining thread confinement. In the end he also explain how people can abuse it by using it as global variables.

I have copied the text from the mentioned book but code 3.10 is missing as it is not much important to understand where ThreadLocal should be use.

Thread-local variables are often used to prevent sharing in designs based on mutable Singletons or global variables. For example, a single-threaded application might maintain a global database connection that is initialized at startup to avoid having to pass a Connection to every method. Since JDBC connections may not be thread-safe, a multithreaded application that uses a global connection without additional coordination is not thread-safe either. By using a ThreadLocal to store the JDBC connection, as in ConnectionHolder in Listing 3.10, each thread will have its own connection.

ThreadLocal is widely used in implementing application frameworks. For example, J2EE containers associate a transaction context with an executing thread for the duration of an EJB call. This is easily implemented using a static Thread-Local holding the transaction context: when framework code needs to determine what transaction is currently running, it fetches the transaction context from this ThreadLocal. This is convenient in that it reduces the need to pass execution context information into every method, but couples any code that uses this mechanism to the framework.

It is easy to abuse ThreadLocal by treating its thread confinement property as a license to use global variables or as a means of creating “hidden” method arguments. Like global variables, thread-local variables can detract from reusability and introduce hidden couplings among classes, and should therefore be used with care.

How to write inside a DIV box with javascript

_x000D_
_x000D_
document.getElementById('log').innerHTML += '<br>Some new content!';
_x000D_
<div id="log">initial content</div>
_x000D_
_x000D_
_x000D_

How do I calculate the MD5 checksum of a file in Python?

In Python 3.8+ you can do

import hashlib

with open("your_filename.png", "rb") as f:
    file_hash = hashlib.md5()
    while chunk := f.read(8192):
        file_hash.update(chunk)

print(file_hash.digest())
print(file_hash.hexdigest())  # to get a printable str instead of bytes

On Python 3.7 and below:

with open("your_filename.png", "rb") as f:
    file_hash = hashlib.md5()
    chunk = f.read(8192)
    while chunk:
        file_hash.update(chunk)
        chunk = f.read(8192)

print(file_hash.hexdigest())

This reads the file 8192 (or 2¹³) bytes at a time instead of all at once with f.read() to use less memory.


Consider using hashlib.blake2b instead of md5 (just replace md5 with blake2b in the above snippets). It's cryptographically secure and faster than MD5.

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

TypeError: 'in <string>' requires string as left operand, not int

You simply need to make cab a string:

cab = '6176'

As the error message states, you cannot do <int> in <string>:

>>> 1 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>> 

because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").

In fact, Python only allows you to use the in operator with a right operand of type string if the left operand is also of type string:

>>> '1' in '123'  # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>

Simple way to copy or clone a DataRow?

You can use ImportRow method to copy Row from DataTable to DataTable with the same schema:

var row = SourceTable.Rows[RowNum];
DestinationTable.ImportRow(row);

Update:

With your new Edit, I believe:

var desRow = dataTable.NewRow();
var sourceRow = dataTable.Rows[rowNum];
desRow.ItemArray = sourceRow.ItemArray.Clone() as object[];

will work

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

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)

Merging multiple PDFs using iTextSharp in c#.net

I found a very nice solution on this site : http://weblogs.sqlteam.com/mladenp/archive/2014/01/10/simple-merging-of-pdf-documents-with-itextsharp-5-4-5.aspx

I update the method in this mode :

    public static bool MergePDFs(IEnumerable<string> fileNames, string targetPdf)
    {
        bool merged = true;
        using (FileStream stream = new FileStream(targetPdf, FileMode.Create))
        {
            Document document = new Document();
            PdfCopy pdf = new PdfCopy(document, stream);
            PdfReader reader = null;
            try
            {
                document.Open();
                foreach (string file in fileNames)
                {
                    reader = new PdfReader(file);
                    pdf.AddDocument(reader);
                    reader.Close();
                }
            }
            catch (Exception)
            {
                merged = false;
                if (reader != null)
                {
                    reader.Close();
                }
            }
            finally
            {
                if (document != null)
                {
                    document.Close();
                }
            }
        }
        return merged;
    }

What's an easy way to read random line from a file in Unix command line?

Another way using 'awk'

awk NR==$((${RANDOM} % `wc -l < file.name` + 1)) file.name

pythonw.exe or python.exe?

In my experience the pythonw.exe is faster at least with using pygame.

How to get a vCard (.vcf file) into Android contacts from website

Just to let you know: I just tried it using a vCard 2.1 file created according to the vCard 2.1 spec. I found that vCard 2.1, despite being an old version, already covered everything I needed, including a base64-encoded photo and international character sets.

It worked perfectly on my unmodified Android 4.1.1 device (Galaxy S3). It also worked on an old iPhone 3GS (iOS 5, via the Evernote app) and a coworker's unmodified old Android 2.1 device. You only need to set the Content-disposition to attachment as suggested above.

A minor problem was that I triggered the VCF download using a QR code, which I scanned with the Microsoft Tag app. That app told me Android couldn't handle the text/x-vcard media type (or just text/vcard, no matter). Once I opened the link in a Web browser (I tried Chrome and the Android default browser), it worked fine.

How to remove the arrows from input[type="number"] in Opera

There is no way.

This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.

If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.

For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}"> could be adequate. It is of course implementation-dependent how it will be handled.

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

To inject an Object, its class must be known to the CDI mechanism. Usualy adding the @Named annotation will do the trick.

Custom pagination view in Laravel 5

Thanks to MantisD's post, for Bootstrap 4 this worked nicely.

<?php
$link_limit = 7; // maximum number of links (a little bit inaccurate, but will be ok for now)
?>

@if ($paginator->lastPage() > 1)
    <div id="news_paginate" class="dataTables_paginate paging_simple_numbers">
        <ul class="pagination">
            <li id="news_previous" class="paginate_button page-item previous {{ ($paginator->currentPage() == 1) ? ' disabled' : '' }}">
                <a class="page-link" tabindex="0" href="{{ $paginator->url(1) }}">Previous</a>
            </li>
            @for ($i = 1; $i <= $paginator->lastPage(); $i++)
                <?php
                    $half_total_links = floor($link_limit / 2);
                    $from = $paginator->currentPage() - $half_total_links;
                    $to = $paginator->currentPage() + $half_total_links;
                    if ($paginator->currentPage() < $half_total_links) {
                        $to += $half_total_links - $paginator->currentPage();
                    }
                    if ($paginator->lastPage() - $paginator->currentPage() < $half_total_links) {
                        $from -= $half_total_links - ($paginator->lastPage() - $paginator->currentPage()) - 1;
                    }
                ?>
                @if ($from < $i && $i < $to)
                    <li class="paginate_button page-item {{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
                        <a class="page-link" href="{{ $paginator->url($i) }}">{{ $i }}</a>
                    </li>
                @endif
            @endfor
            <li id="news_next" class="paginate_button page-item {{ ($paginator->currentPage() == $paginator->lastPage()) ? ' disabled' : '' }}">
                @if($paginator->currentPage() == $paginator->lastPage())
                    <a class="page-link" tabindex="0" href="{{ $paginator->url($paginator->currentPage()) }}" >End</a>
                @else
                    <a class="page-link" tabindex="0" href="{{ $paginator->url($paginator->currentPage()+1) }}" >Next</a>
                @endif
            </li>
        </ul>
    </div>
@endif

Launch Minecraft from command line - username and password as prefix

Those are all ways to start the standard minecraft launcher with those credentials in the text boxes.

There used to be a way to login to minecraft without the launcher using the command line, but it has since been patched.

If you want to make a custom launcher using the command line then good luck, the only way to login to the minecraft jar(IE: the way the launcher does it) is to send a post request to https://login.minecraft.net/ with the username,password,launcher version, and a RSA key. It then parses the pseudo Json, and uses the session token from that to authenticate the jar from the command line with a load of arguments.

If you are trying to make a minecraft launcher and you have no knowledge of java,http requests or json then you have no chance.

Swift

Laravel 5.2 redirect back with success message

You can use laravel MessageBag to add our own messages to existing messages.

To use MessageBag you need to use:

use Illuminate\Support\MessageBag;

In the controller:

MessageBag $message_bag

$message_bag->add('message', trans('auth.confirmation-success'));

return redirect('login')->withSuccess($message_bag);

Hope it will help some one.

  • Adi

Firebase (FCM) how to get token

FirebaseInstanceId.getInstance().getInstanceId() deprecated. Now get user FCM token

 FirebaseMessaging.getInstance().getToken()
            .addOnCompleteListener(new OnCompleteListener<String>() {
                @Override
                public void onComplete(@NonNull Task<String> task) {
                    if (!task.isSuccessful()) {
                        System.out.println("--------------------------");
                        System.out.println(" " + task.getException());
                        System.out.println("--------------------------");
                        return;
                    }

                    // Get new FCM registration token
                    String token = task.getResult();

                    // Log 
                    String msg = "GET TOKEN " + token;
                    System.out.println("--------------------------");
                    System.out.println(" " + msg);
                    System.out.println("--------------------------");

                }
            });

Convert string into Date type on Python

Use datetime.datetime.strptime:

>>> import datetime
>>> date = datetime.datetime.strptime('2012-02-10', '%Y-%m-%d')
>>> date.isoweekday()
5

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

Cleanest version specially good if you just want to get the .value from the element.

document.getElementById('elementsid') ? function_if_exists(); function_if_doesnt_exists();

iOS for VirtualBox

Additional to the above - the QEMU website has good documentation about setting up an ARM based emulator: http://qemu.weilnetz.de/qemu-doc.html#ARM-System-emulator

Python 3 string.join() equivalent?

str.join() works fine in Python 3, you just need to get the order of the arguments correct

>>> str.join('.', ('a', 'b', 'c'))
'a.b.c'

C# equivalent of C++ map<string,double>

Although System.Collections.Generic.Dictionary matches the tag "hashmap" and will work well in your example, it is not an exact equivalent of C++'s std::map - std::map is an ordered collection.

If ordering is important you should use SortedDictionary.

Syntax for async arrow function

My async function

const getAllRedis = async (key) => {
  let obj = [];

  await client.hgetall(key, (err, object) => {
    console.log(object);
    _.map(object, (ob)=>{
      obj.push(JSON.parse(ob));
    })
    return obj;
    // res.send(obj);
});
}

How to format DateTime columns in DataGridView?

string stringtodate = ((DateTime)row.Cells[4].Value).ToString("MM-dd-yyyy");
textBox9.Text = stringtodate;

How to hide element using Twitter Bootstrap and show it using jQuery?

Another way to address this annoyance is to create your own CSS class that does not set the !important at the end of rule, like this:

.hideMe {
    display: none;
}

and used like so :

<div id="header-mask" class="hideMe"></div>

and now jQuery hiding works

$('#header-mask').show();

How do I copy to the clipboard in JavaScript?

In Chrome you can use copy('the text or variable etc'). While this isn't cross-browser (and doesn't work in a snippet?), you could add it to the other cross-browser answers.

Pass Javascript variable to PHP via ajax

Alternatively, try removing "data" and making the URL "logtime.php?userID="+userId

I like Brian's answer better, this answer is just because you're trying to use URL parameter syntax in "data" and I wanted to demonstrate where you can use that syntax correctly.

Error: Unfortunately you can't have non-Gradle Java modules and > Android-Gradle modules in one project

Tried all above. Didn't work.

Here's what worked. Go to the file called modules.xml

Delete all the modules there. Clean and rebuild.

Using underscores in Java variables and method names

I think any style that breaks a language's own style guidelines (without due reason) is ugly and therefore "bad".

No doubt the code you've seen was written by someone who used to work on a language where underscores were acceptable.

Some people just cannot adapt to new coding styles...

How to display Woocommerce Category image?

This solution with few code. I think is better.

<?php echo wp_get_attachment_image( get_term_meta( get_queried_object_id(), 'thumbnail_id', 1 ), 'thumbnail' ); ?>

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

How do you create a yes/no boolean field in SQL server?

bit will be the simplest and also takes up the least space. Not very verbose compared to "Y/N" but I am fine with it.

How to parse an RSS feed using JavaScript?

You can use jquery-rss or Vanilla RSS, which comes with nice templating and is super easy to use:

// Example for jquery.rss
$("#your-div").rss("https://stackoverflow.com/feeds/question/10943544", {
    limit: 3,
    layoutTemplate: '<ul class="inline">{entries}</ul>',
    entryTemplate: '<li><a href="{url}">[{author}@{date}] {title}</a><br/>{shortBodyPlain}</li>'
})

// Example for Vanilla RSS
const RSS = require('vanilla-rss');
const rss = new RSS(
    document.querySelector("#your-div"),
    "https://stackoverflow.com/feeds/question/10943544",
    { 
      // options go here
    }
);
rss.render().then(() => {
  console.log('Everything is loaded and rendered');
});

See http://jsfiddle.net/sdepold/ozq2dn9e/1/ for a working example.

What are Keycloak's OAuth2 / OpenID Connect endpoints?

You can also see this information by going into Admin Console -> Realm Settings -> Clicking the hyperlink on the Endpoints field.

enter image description here

Using `date` command to get previous, current and next month

If you happen to be using date in a MacOS environment, try this:

ST1:~ ejf$ date
Mon Feb 20 21:55:48 CST 2017
ST1:~ ejf$ date -v-1m +%m
01
ST1:~ ejf$ date -v+1m +%m
03

Also, I'd rather calculate the previous and next month on the first day of each month, this way you won't have issues with months ending the 30/31 or 28/29 (Feb/Feb leap year)

What's the best way to store Phone number in Django models

I will describe what I use:

Validation: string contains more than 5 digits.

Cleaning: removing all non digits symbols, write in db only numbers. I'm lucky, because in my country (Russia) everybody has phone numbers with 10 digits. So I store in db only 10 diits. If you are writing multi-country application, then you should make a comprehensive validation.

Rendering: I write custom template tag to render it in template nicely. Or even render it like a picture - it is more safe to prevent sms spam.

In-place type conversion of a NumPy array

You can make a view with a different dtype, and then copy in-place into the view:

import numpy as np
x = np.arange(10, dtype='int32')
y = x.view('float32')
y[:] = x

print(y)

yields

array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.], dtype=float32)

To show the conversion was in-place, note that copying from x to y altered x:

print(x)

prints

array([         0, 1065353216, 1073741824, 1077936128, 1082130432,
       1084227584, 1086324736, 1088421888, 1090519040, 1091567616])

Difference between app.use and app.get in express.js

Difference between app.use & app.get:

app.use ? It is generally used for introducing middlewares in your application and can handle all type of HTTP requests.

app.get ? It is only for handling GET HTTP requests.

Now, there is a confusion between app.use & app.all. No doubt, there is one thing common in them, that both can handle all kind of HTTP requests. But there are some differences which recommend us to use app.use for middlewares and app.all for route handling.

  1. app.use() ? It takes only one callback.
    app.all() ? It can take multiple callbacks.

  2. app.use() will only see whether url starts with specified path.
    But, app.all() will match the complete path.

For example,

app.use( "/book" , middleware);
// will match /book
// will match /book/author
// will match /book/subject

app.all( "/book" , handler);
// will match /book
// won't match /book/author   
// won't match /book/subject    

app.all( "/book/*" , handler);
// won't match /book        
// will match /book/author
// will match /book/subject
  1. next() call inside the app.use() will call either the next middleware or any route handler, but next() call inside app.all() will invoke the next route handler (app.all(), app.get/post/put... etc.) only. If there is any middleware after, it will be skipped. So, it is advisable to put all the middlewares always above the route handlers.

How to sort an array in descending order in Ruby

I see that we have (beside others) basically two options:

a.sort_by { |h| -h[:bar] }

and

a.sort_by { |h| h[:bar] }.reverse

While both ways give you the same result when your sorting key is unique, keep in mind that the reverse way will reverse the order of keys that are equal.

Example:

a = [{foo: 1, bar: 1},{foo: 2,bar: 1}]
a.sort_by {|h| -h[:bar]}
 => [{:foo=>1, :bar=>1}, {:foo=>2, :bar=>1}]
a.sort_by {|h| h[:bar]}.reverse
 => [{:foo=>2, :bar=>1}, {:foo=>1, :bar=>1}]

While you often don't need to care about this, sometimes you do. To avoid such behavior you could introduce a second sorting key (that for sure needs to be unique at least for all items that have the same sorting key):

a.sort_by {|h| [-h[:bar],-h[:foo]]}
 => [{:foo=>2, :bar=>1}, {:foo=>1, :bar=>1}]
a.sort_by {|h| [h[:bar],h[:foo]]}.reverse
 => [{:foo=>2, :bar=>1}, {:foo=>1, :bar=>1}]

How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

  1. All new browser support video to be auto-played with being muted only so please put

<video autoplay muted="muted" loop id="myVideo"> <source src="https://w.r.glob.net/Coastline-3581.mp4" type="video/mp4"> </video>

Something like this

  1. URL of video should match the SSL status if your site is running with https then video URL should also in https and same for HTTP

How do I run Selenium in Xvfb?

This is the setup I use:

Before running the tests, execute:

export DISPLAY=:99
/etc/init.d/xvfb start

And after the tests:

/etc/init.d/xvfb stop

The init.d file I use looks like this:

#!/bin/bash

XVFB=/usr/bin/Xvfb
XVFBARGS="$DISPLAY -ac -screen 0 1024x768x16"
PIDFILE=${HOME}/xvfb_${DISPLAY:1}.pid
case "$1" in
  start)
    echo -n "Starting virtual X frame buffer: Xvfb"
    /sbin/start-stop-daemon --start --quiet --pidfile $PIDFILE --make-pidfile --background --exec $XVFB -- $XVFBARGS
    echo "."
    ;;
  stop)
    echo -n "Stopping virtual X frame buffer: Xvfb"
    /sbin/start-stop-daemon --stop --quiet --pidfile $PIDFILE
    echo "."
    ;;
  restart)
    $0 stop
    $0 start
    ;;
  *)
  echo "Usage: /etc/init.d/xvfb {start|stop|restart}"
  exit 1
esac
exit 0

How to call jQuery function onclick?

Please have a look at http://jsfiddle.net/2dJAN/59/

$("#submit").click(function () {
var url = $(location).attr('href');
$('#spn_url').html('<strong>' + url + '</strong>');
});

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

For forms, use the [FromForm] attribute instead of the [FromBody] attribute.

The below controller works with ASP.NET Core 1.1:

public class MyController : Controller
{
    [HttpPost]
    public async Task<IActionResult> Submit([FromForm] MyModel model)
    {
        //...
    }
}

Note: [FromXxx] is required if your controller is annotated with [ApiController]. For normal view controllers it can be omitted.

Rollback to last git commit

Caveat Emptor - Destructive commands ahead.

Mitigation - git reflog can save you if you need it.


1) UNDO local file changes and KEEP your last commit

git reset --hard

2) UNDO local file changes and REMOVE your last commit

git reset --hard HEAD^

3) KEEP local file changes and REMOVE your last commit

git reset --soft HEAD^

how to filter out a null value from spark dataframe

df.where(df.col("friend_id").isNull)

SQL Server: Error converting data type nvarchar to numeric

In case of float values with characters 'e' '+' it errors out if we try to convert in decimal. ('2.81104e+006'). It still pass ISNUMERIC test.

SELECT ISNUMERIC('2.81104e+006') 

returns 1.

SELECT convert(decimal(15,2), '2.81104e+006') 

returns

error: Error converting data type varchar to numeric.

And

SELECT try_convert(decimal(15,2), '2.81104e+006') 

returns NULL.

SELECT convert(float, '2.81104e+006') 

returns the correct value 2811040.

How to Parse JSON Array with Gson

[
      {
           id : '1',
           title: 'sample title',
           ....
      },
      {
           id : '2',
           title: 'sample title',
           ....
     },
      ...
 ]

Check Easy code for this output

 Gson gson=new GsonBuilder().create();
                List<Post> list= Arrays.asList(gson.fromJson(yourResponse.toString,Post[].class));

How to convert a number to string and vice versa in C++

In C++17, new functions std::to_chars and std::from_chars are introduced in header charconv.

std::to_chars is locale-independent, non-allocating, and non-throwing.

Only a small subset of formatting policies used by other libraries (such as std::sprintf) is provided.

From std::to_chars, same for std::from_chars.

The guarantee that std::from_chars can recover every floating-point value formatted by to_chars exactly is only provided if both functions are from the same implementation

 // See en.cppreference.com for more information, including format control.
#include <cstdio>
#include <cstddef>
#include <cstdlib>
#include <cassert>
#include <charconv>

using Type =  /* Any fundamental type */ ;
std::size_t buffer_size = /* ... */ ;

[[noreturn]] void report_and_exit(int ret, const char *output) noexcept 
{
    std::printf("%s\n", output);
    std::exit(ret);
}
void check(const std::errc &ec) noexcept
{
    if (ec ==  std::errc::value_too_large)
        report_and_exit(1, "Failed");
}
int main() {
    char buffer[buffer_size];        
    Type val_to_be_converted, result_of_converted_back;

    auto result1 = std::to_chars(buffer, buffer + buffer_size,  val_to_be_converted);
    check(result1.ec);
    *result1.ptr = '\0';

    auto result2 = std::from_chars(buffer, result1.ptr, result_of_converted_back);
    check(result2.ec);

    assert(val_to_be_converted == result_of_converted_back);
    report_and_exit(0, buffer);
}

Although it's not fully implemented by compilers, it definitely will be implemented.

How to check if a String contains any of some strings

Here's a LINQ solution which is virtually the same but more scalable:

new[] { "a", "b", "c" }.Any(c => s.Contains(c))

Date only from TextBoxFor()

The DisplayFormat attribute did not work for me in either form upon initial load. I created an EditorTemplate instead:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %>
<%@ Import Namespace="System.Web.Mvc.Html" %>
<%=
    Html.TextBox("", Model.ToShortDateString(), new { @class = "date-range" }) %>

How to find the logs on android studio?

In ubuntu it should be under

/home/user_name/product_name/system/log

where user_name is logged in user name and product_name could be e.g. .AndroidStudio1.5

How can I view all historical changes to a file in SVN

Slightly different from what you described, but I think this might be what you actually need:

svn blame filename

It will print the file with each line prefixed by the time and author of the commit that last changed it.

How to concatenate strings in twig

In Symfony you can use this for protocol and host:

{{ app.request.schemeAndHttpHost }}

Though @alessandro1997 gave a perfect answer about concatenation.

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

Since Facebook's Android SDK v4.0 you need to execute the following:

LoginManager.getInstance().logOut();

This is not sufficient. This will simply clear cached access token and profile so that AccessToken.getCurrentAccessToken() and Profile.getCurrentProfile() will now become null.

To completely logout you need to revoke permissions and then call LoginManager.getInstance().logOut();. To revoke permission execute following graph API -

    GraphRequest delPermRequest = new GraphRequest(AccessToken.getCurrentAccessToken(), "/{user-id}/permissions/", null, HttpMethod.DELETE, new GraphRequest.Callback() {
        @Override
        public void onCompleted(GraphResponse graphResponse) {
            if(graphResponse!=null){
                FacebookRequestError error =graphResponse.getError();
                if(error!=null){
                    Log.e(TAG, error.toString());
                }else {
                    finish();
                }
            }
        }
    });
    Log.d(TAG,"Executing revoke permissions with graph path" + delPermRequest.getGraphPath());
    delPermRequest.executeAsync();

How do I detect a page refresh using jquery?

All the code is client side, I hope you fine this helpful:

First thing there are 3 functions we will use:

    function setCookie(c_name, value, exdays) {
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + exdays);
            var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
            document.cookie = c_name + "=" + c_value;
        }

    function getCookie(c_name) {
        var i, x, y, ARRcookies = document.cookie.split(";");
        for (i = 0; i < ARRcookies.length; i++) {
            x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
            y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
            x = x.replace(/^\s+|\s+$/g, "");
            if (x == c_name) {
                return unescape(y);
            }
        }
    }

    function DeleteCookie(name) {
            document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
        }

Now we will start with the page load:

$(window).load(function () {
 //if IsRefresh cookie exists
 var IsRefresh = getCookie("IsRefresh");
 if (IsRefresh != null && IsRefresh != "") {
    //cookie exists then you refreshed this page(F5, reload button or right click and reload)
    //SOME CODE
    DeleteCookie("IsRefresh");
 }
 else {
    //cookie doesnt exists then you landed on this page
    //SOME CODE
    setCookie("IsRefresh", "true", 1);
 }
})

How to fix corrupt HDFS FIles

start all daemons and run the command as "hadoop namenode -recover -force" stop the daemons and start again.. wait some time to recover data.

ImageView - have height match width?

Here's how I solved that problem:

int pHeight =  picture.getHeight();
int pWidth = picture.getWidth();
int vWidth = preview.getWidth();
preview.getLayoutParams().height = (int)(vWidth*((double)pHeight/pWidth));

preview - imageView with width setted to "match_parent" and scaleType to "cropCenter"

picture - Bitmap object to set in imageView src.

That's works pretty well for me.

Center content in responsive bootstrap navbar

V4 of BootStrap is adding Center (justify-content-center) and Right Alignment (justify-content-end) as per: https://v4-alpha.getbootstrap.com/components/navs/#horizontal-alignment

<ul class="nav justify-content-center">
  <li class="nav-item">
    <a class="nav-link active" href="#">Active</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link disabled" href="#">Disabled</a>
  </li>
</ul>

How to add a second css class with a conditional value in razor MVC 4

This:

    <div class="details @(Model.Details.Count > 0 ? "show" : "hide")">

will render this:

    <div class="details hide">

and is the mark-up I want.

Convert True/False value read from file to boolean

Use ast.literal_eval:

>>> import ast
>>> ast.literal_eval('True')
True
>>> ast.literal_eval('False')
False

Why is flag always converting to True?

Non-empty strings are always True in Python.

Related: Truth Value Testing


If NumPy is an option, then:

>>> import StringIO
>>> import numpy as np
>>> s = 'True - False - True'
>>> c = StringIO.StringIO(s)
>>> np.genfromtxt(c, delimiter='-', autostrip=True, dtype=None) #or dtype=bool
array([ True, False,  True], dtype=bool)

regex.test V.S. string.match to know if a string matches a regular expression

Don't forget to take into consideration the global flag in your regexp :

var reg = /abc/g;
!!'abcdefghi'.match(reg); // => true
!!'abcdefghi'.match(reg); // => true
reg.test('abcdefghi');    // => true
reg.test('abcdefghi');    // => false <=

This is because Regexp keeps track of the lastIndex when a new match is found.

Javascript to sort contents of select element

This is a a recompilation of my 3 favorite answers on this board:

  • jOk's best and simplest answer.
  • Terry Porter's easy jQuery method.
  • SmokeyPHP's configurable function.

The results are an easy to use, and easily configurable function.

First argument can be a select object, the ID of a select object, or an array with at least 2 dimensions.

Second argument is optional. Defaults to sorting by option text, index 0. Can be passed any other index so sort on that. Can be passed 1, or the text "value", to sort by value.

Sort by text examples (all would sort by text):

 sortSelect('select_object_id');
 sortSelect('select_object_id', 0);
 sortSelect(selectObject);
 sortSelect(selectObject, 0);

Sort by value (all would sort by value):

 sortSelect('select_object_id', 'value');
 sortSelect('select_object_id', 1);
 sortSelect(selectObject, 1);

Sort any array by another index:

var myArray = [
  ['ignored0', 'ignored1', 'Z-sortme2'],
  ['ignored0', 'ignored1', 'A-sortme2'],
  ['ignored0', 'ignored1', 'C-sortme2'],
];

sortSelect(myArray,2);

This last one will sort the array by index-2, the sortme's.

Main sort function

function sortSelect(selElem, sortVal) {

    // Checks for an object or string. Uses string as ID. 
    switch(typeof selElem) {
        case "string":
            selElem = document.getElementById(selElem);
            break;
        case "object":
            if(selElem==null) return false;
            break;
        default:
            return false;
    }

    // Builds the options list.
    var tmpAry = new Array();
    for (var i=0;i<selElem.options.length;i++) {
        tmpAry[i] = new Array();
        tmpAry[i][0] = selElem.options[i].text;
        tmpAry[i][1] = selElem.options[i].value;
    }

    // allows sortVal to be optional, defaults to text.
    switch(sortVal) {
        case "value": // sort by value
            sortVal = 1;
            break;
        default: // sort by text
            sortVal = 0;
    }
    tmpAry.sort(function(a, b) {
        return a[sortVal] == b[sortVal] ? 0 : a[sortVal] < b[sortVal] ? -1 : 1;
    });

    // removes all options from the select.
    while (selElem.options.length > 0) {
        selElem.options[0] = null;
    }

    // recreates all options with the new order.
    for (var i=0;i<tmpAry.length;i++) {
        var op = new Option(tmpAry[i][0], tmpAry[i][1]);
        selElem.options[i] = op;
    }

    return true;
}

Convert integer to string Jinja

The OP needed to cast as string outside the {% set ... %}. But if that not your case you can do:

{% set curYear = 2013 | string() %}

Note that you need the parenthesis on that jinja filter.

If you're concatenating 2 variables, you can also use the ~ custom operator.

Checking if a worksheet-based checkbox is checked

Sub Button167_Click()
 If ThisWorkbook.Worksheets(1).Shapes("Check Box 1").OLEFormat.Object.Value = 1 Then
 Range("Y12").Value = 1
 Else
 Range("Y12").Value = 0
 End If
End Sub

1 is checked, -4146 is unchecked, 2 is mixed (grey box)

vertical align middle in <div>

You can use Line height a big as height of the div. But for me best solution is this --> position:relative; top:50%; transform:translate(0,50%);

did you specify the right host or port? error on Kubernetes

Regardless of your environment (gcloud or not ) , you need to point your kubectl to kubeconfig. By default, kubectl expects the path as $HOME/.kube/config or point your custom path as env variable (for scripting etc ) export KUBECONFIG=/your_kubeconfig_path

Please refer :: https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/

If you don't have a kubeconfig file for your cluster, create one by referring :: https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/

It is required to find cluster's ca.crt , apiserver-kubelet-client key and cert.

how to bold words within a paragraph in HTML/CSS?

Although your answer has many solutions I think this is a great way to save lines of code. Try using spans which is great for situations like yours.

  1. Create a class for making any item bold. So for paragraph text it would be
span.bold(This name can be anything do not include parenthesis) {
   font-weight: bold;
}
  1. In your html you can access that class like by using the span tags and adding a class of bold or whatever name you have chosen

How can I take a screenshot with Selenium WebDriver?

C#

using System;
using OpenQA.Selenium.PhantomJS;
using System.Drawing.Imaging;

namespace example.com
{
    class Program
    {
        public static PhantomJSDriver driver;

        public static void Main(string[] args)
        {
            driver = new PhantomJSDriver();
            driver.Manage().Window.Size = new System.Drawing.Size(1280, 1024);
            driver.Navigate().GoToUrl("http://www.example.com/");
            driver.GetScreenshot().SaveAsFile("screenshot.png", ImageFormat.Png);
            driver.Quit();
        }
    }
}

It requires NuGet packages:

  1. PhantomJS 2.0.0
  2. Selenium.Support 2.48.2
  3. Selenium.WebDriver 2.48.2

It was Tested with .NET Framework v4.5.2.

Combine two integer arrays

Yes but it is not quite that easy. Create a third array that is the size of the two arrays combined and loop through each original array and move the items over. Also look into System.arraycopy().

Is it wrong to place the <script> tag after the </body> tag?

IE doesn't allow this anymore (since Version 10, I believe) and will ignore such scripts. FF and Chrome still tolerate them, but there are chances that some day they will drop this as non-standard.

beyond top level package error in relative import

Edit: 2020-05-08: Is seems the website I quoted is no longer controlled by the person who wrote the advice, so I'm removing the link to the site. Thanks for letting me know baxx.


If someone's still struggling a bit after the great answers already provided, I found advice on a website that no longer is available.

Essential quote from the site I mentioned:

"The same can be specified programmatically in this way:

import sys

sys.path.append('..')

Of course the code above must be written before the other import statement.

It's pretty obvious that it has to be this way, thinking on it after the fact. I was trying to use the sys.path.append('..') in my tests, but ran into the issue posted by OP. By adding the import and sys.path defintion before my other imports, I was able to solve the problem.

Transition of background-color

As far as I know, transitions currently work in Safari, Chrome, Firefox, Opera and Internet Explorer 10+.

This should produce a fade effect for you in these browsers:

_x000D_
_x000D_
a {_x000D_
    background-color: #FF0;_x000D_
}_x000D_
_x000D_
a:hover {_x000D_
    background-color: #AD310B;_x000D_
    -webkit-transition: background-color 1000ms linear;_x000D_
    -ms-transition: background-color 1000ms linear;_x000D_
    transition: background-color 1000ms linear;_x000D_
}
_x000D_
<a>Navigation Link</a>
_x000D_
_x000D_
_x000D_

Note: As pointed out by Gerald in the comments, if you put the transition on the a, instead of on a:hover it will fade back to the original color when your mouse moves away from the link.

This might come in handy, too: CSS Fundamentals: CSS 3 Transitions

When to use 'npm start' and when to use 'ng serve'?

For a project that's using the CLI, you will usually use ng serve. In other cases you may want to use npm start. Here the detailed explanation:

ng serve

Will serve a project that is 'Angular CLI aware', i.e. a project that has been created using the Angular CLI, particularly using:

ng new app-name

So, if you've scaffolded a project using the CLI, you'll probably want to use ng serve

npm start

This can be used in the case of a project that is not Angular CLI aware (or it can simply be used to run 'ng serve' for a project that's Angular CLI aware)

As the other answers state, this is an npm command that will run the npm command(s) from the package.json that have the identifier 'start', and it doesn't just have to run 'ng serve'. It's possible to have something like the following in the package.json:

   "scripts": {
     "build:watch": "tsc -p src/ -w",
     "serve": "lite-server -c=bs-config.json",
     "start": "concurrently \"npm run build:watch\" \"npm run serve\""
     ...
   },
   "devDependencies": {
     "concurrently": "^3.2.0",
     "lite-server": "^2.2.2",

In this case, 'npm start' will result in the following commands to be run:

concurrently "npm run build:watch" "npm run serve"

This will concurrently run the TypeScript compiler (watching for code changes), and run the Node lite-server (which users BrowserSync)

Adding div element to body or document in JavaScript

Using Javascript

var elemDiv = document.createElement('div');
elemDiv.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';
document.body.appendChild(elemDiv);

Using jQuery

$('body').append('<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>');

How to log in to phpMyAdmin with WAMP, what is the username and password?

In my case it was

username : root
password : mysql

Using : Wamp server 3.1.0

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

How to handle the `onKeyPress` event in ReactJS?

Keypress event is deprecated, You should use Keydown event instead.

https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event

handleKeyDown(event) {
    if(event.keyCode === 13) { 
        console.log('Enter key pressed')
  }
}

render() { 
    return <input type="text" onKeyDown={this.handleKeyDown} /> 
}

print arraylist element?

Here is an updated solution for Java8, using lambdas and streams:

System.out.println(list.stream()
                       .map(Object::toString)
                       .collect(Collectors.joining("\n")));

Or, without joining the list into one large string:

list.stream().forEach(System.out::println);

Rails 3 execute custom sql query without a model

How about this :

@client = TinyTds::Client.new(
      :adapter => 'mysql2',
      :host => 'host',
      :database => 'siteconfig_development',
      :username => 'username',
      :password => 'password'

sql = "SELECT * FROM users"

result = @client.execute(sql)

results.each do |row|
puts row[0]
end

You need to have TinyTds gem installed, since you didn't specify it in your question I didn't use Active Record

Check if two unordered lists are equal

Python has a built-in datatype for an unordered collection of (hashable) things, called a set. If you convert both lists to sets, the comparison will be unordered.

set(x) == set(y)

Documentation on set


EDIT: @mdwhatcott points out that you want to check for duplicates. set ignores these, so you need a similar data structure that also keeps track of the number of items in each list. This is called a multiset; the best approximation in the standard library is a collections.Counter:

>>> import collections
>>> compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
>>> 
>>> compare([1,2,3], [1,2,3,3])
False
>>> compare([1,2,3], [1,2,3])
True
>>> compare([1,2,3,3], [1,2,2,3])
False
>>> 

Copy files on Windows Command Line with Progress

If you want to copy files and see a "progress" I suggest the script below in Batch that I used from another script as a base

I used a progress bar and a percentage while the script copies the game files Nuclear throne:

@echo off
title NTU Installer
setlocal EnableDelayedExpansion

@echo Iniciando instalacao...
if not exist "C:\NTU" (
    md "C:\NTU
)
if not exist "C:\NTU\Profile" (
    md "C:\NTU\Profile"
)
ping -n 5 localhost >nul

for %%f in (*.*) do set/a vb+=1
set "barra="
::loop da barra
for /l %%i in (1,1,70) do set "barra=!barra!Û"
rem barra vaiza para ser preenchida
set "resto="
rem loop da barra vazia
for /l %%i in (1,1,110) do set "resto=!resto!"
set i=0
rem carregameno de arquivos
for %%f in (*.*) do (
    >>"log_ntu.css" (
        copy "%%f" "C:\NTU">nul
        echo Copiado:%%f
    )
    cls
    set /a i+=1,percent=i*100/vb,barlen=70*percent/100
    for %%a in (!barlen!) do echo  !percent!%% /                         
    [!barra:~0,%%a!%resto%]
    echo Instalado:[%%f] / Complete:[!percent!%%/100%]
    ping localhost -n 1.9  >nul
)
xcopy /e "Profile" "C:\NTU\Profile">"log_profile.css"              

@echo Criando atalho na area de trabalho...
copy "NTU.lnk" "C:\Users\%username%\Desktop">nul
ping localhost -n 4  >nul

@echo Arquivos instalados!
pause

Where is Ubuntu storing installed programs?

If you are looking for the folder such as brushes, curves, etc. you can try:

/home/<username>/.gimp-2.8

This folder will contain all the gimp folders.

Good Luck.

scroll up and down a div on button click using jquery

To solve your other problem, where you need to set scrolled if the user scrolls manually, you'd have to attach a handler to the window scroll event. Generally this is a bad idea as the handler will fire a lot, a common technique is to set a timeout, like so:

var timer = 0;
$(window).scroll(function() {
  if (timer) {
    clearTimeout(timer);
  }
  timer = setTimeout(function() {
    scrolled = $(window).scrollTop();
  }, 250);
});

ValueError: unsupported format character while forming strings

Well, why do you have %20 url-quoting escapes in a formatting string in first place? Ideally you'd do the interpolation formatting first:

formatting_template = 'Hello World%s'
text = '!'
full_string = formatting_template % text

Then you url quote it afterwards:

result = urllib.quote(full_string)

That is better because it would quote all url-quotable things in your string, including stuff that is in the text part.

C++ convert from 1 char to string?

I honestly thought that the casting method would work fine. Since it doesn't you can try stringstream. An example is below:

#include <sstream>
#include <string>
std::stringstream ss;
std::string target;
char mychar = 'a';
ss << mychar;
ss >> target;

Split varchar into separate columns in Oracle

Simple way is to convert into column

SELECT COLUMN_VALUE FROM TABLE (SPLIT ('19869,19572,19223,18898,10155,'))

CREATE TYPE split_tbl as TABLE OF VARCHAR2(32767);

CREATE OR REPLACE FUNCTION split (p_list VARCHAR2, p_del VARCHAR2 := ',')
   RETURN split_tbl
   PIPELINED IS
   l_idx PLS_INTEGER;
   l_list VARCHAR2 (32767) := p_list;
   l_value VARCHAR2 (32767);
BEGIN
   LOOP
      l_idx := INSTR (l_list, p_del);

      IF l_idx > 0 THEN
         PIPE ROW (SUBSTR (l_list, 1, l_idx - 1));
         l_list := SUBSTR (l_list, l_idx + LENGTH (p_del));
      ELSE
         PIPE ROW (l_list);
         EXIT;
      END IF;
   END LOOP;

   RETURN;
END split;

How to Import Excel file into mysql Database from PHP

You are probably having a problem with the sort of CSV file that you have.

Open the CSV file with a text editor, check that all the separations are done with the comma, and not semicolon and try the script again. It should work fine.

Numbering rows within groups in a data frame

I would like to add a data.table variant using the rank() function which provides the additional possibility to change the ordering and thus makes it a bit more flexible than the seq_len() solution and is pretty similar to row_number functions in RDBMS.

# Variant with ascending ordering
library(data.table)
dt <- data.table(df)
dt[, .( val
   , num = rank(val))
    , by = list(cat)][order(cat, num),]

    cat        val num
 1: aaa 0.05638315   1
 2: aaa 0.25767250   2
 3: aaa 0.30776611   3
 4: aaa 0.46854928   4
 5: aaa 0.55232243   5
 6: bbb 0.17026205   1
 7: bbb 0.37032054   2
 8: bbb 0.48377074   3
 9: bbb 0.54655860   4
10: bbb 0.81240262   5
11: ccc 0.28035384   1
12: ccc 0.39848790   2
13: ccc 0.62499648   3
14: ccc 0.76255108   4

# Variant with descending ordering
dt[, .( val
   , num = rank(-val))
    , by = list(cat)][order(cat, num),]

figure of imshow() is too small

I'm new to python too. Here is something that looks like will do what you want to

axes([0.08, 0.08, 0.94-0.08, 0.94-0.08]) #[left, bottom, width, height]
axis('scaled')`

I believe this decides the size of the canvas.

SQL LEFT-JOIN on 2 fields for MySQL

Let's try this way:

select 
    a.ip, 
    a.os, 
    a.hostname, 
    a.port, 
    a.protocol, 
    b.state
from a
left join b 
    on a.ip = b.ip 
        and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/

So, in where clause you can filter result set by column from right table only on this way:

...
where b.somecolumn <> (=) null

What are the RGB codes for the Conditional Formatting 'Styles' in Excel?

The easiest way to do this is to format a cell the way you want it, then use the "cell format ..." contextual menu to get to the fill and format colours, use the "more colors ..." button to get to the hexagon colour selector, select the custom tab.

The RGB colours are as in the table at the bottom of the pane. If you prefer HSL values change the color model from RGB to HSL. I have used this to change the saturation on my bad cells. A higher luminosity gives a worse results and the shade of all the cells is the same just the deepness of the colour is modified.

Rounding BigDecimal to *always* have two decimal places

value = value.setScale(2, RoundingMode.CEILING)

How do I rename both a Git local and remote branch name?

This can be done even without renaming the local branch in three simple steps:

  1. Go to your repository in GitHub
  2. Create a new branch from the old branch which you want to rename
  3. Delete the old branch

PHP cURL HTTP PUT

In a POST method, you can put an array. However, in a PUT method, you should use http_build_query to build the params like this:

curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $postArr ) );

Adding input elements dynamically to form

You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():

If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.

Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.

Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.

_x000D_
_x000D_
<html>
<head>
    <script type='text/javascript'>
        function addFields(){
            // Number of inputs to create
            var number = document.getElementById("member").value;
            // Container <div> where dynamic content will be placed
            var container = document.getElementById("container");
            // Clear previous contents of the container
            while (container.hasChildNodes()) {
                container.removeChild(container.lastChild);
            }
            for (i=0;i<number;i++){
                // Append a node with a random text
                container.appendChild(document.createTextNode("Member " + (i+1)));
                // Create an <input> element, set its type and name attributes
                var input = document.createElement("input");
                input.type = "text";
                input.name = "member" + i;
                container.appendChild(input);
                // Append a line break 
                container.appendChild(document.createElement("br"));
            }
        }
    </script>
</head>
<body>
    <input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
    <a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
    <div id="container"/>
</body>
</html>
_x000D_
_x000D_
_x000D_

See a working sample in this JSFiddle.

Save classifier to disk in scikit-learn

In many cases, particularly with text classification it is not enough just to store the classifier but you'll need to store the vectorizer as well so that you can vectorize your input in future.

import pickle
with open('model.pkl', 'wb') as fout:
  pickle.dump((vectorizer, clf), fout)

future use case:

with open('model.pkl', 'rb') as fin:
  vectorizer, clf = pickle.load(fin)

X_new = vectorizer.transform(new_samples)
X_new_preds = clf.predict(X_new)

Before dumping the vectorizer, one can delete the stop_words_ property of vectorizer by:

vectorizer.stop_words_ = None

to make dumping more efficient. Also if your classifier parameters is sparse (as in most text classification examples) you can convert the parameters from dense to sparse which will make a huge difference in terms of memory consumption, loading and dumping. Sparsify the model by:

clf.sparsify()

Which will automatically work for SGDClassifier but in case you know your model is sparse (lots of zeros in clf.coef_) then you can manually convert clf.coef_ into a csr scipy sparse matrix by:

clf.coef_ = scipy.sparse.csr_matrix(clf.coef_)

and then you can store it more efficiently.

bootstrap 4 row height

Use the sizing utility classes...

  • h-50 = height 50%
  • h-100 = height 100%

http://www.codeply.com/go/Y3nG0io2uE

 <div class="container">
        <div class="row">
            <div class="col-md-8 col-lg-6 B">
                <div class="card card-inverse card-primary">
                    <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
                </div>
            </div>
            <div class="col-md-4 col-lg-3 G">
                <div class="row h-100">
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse card-success h-100">

                        </div>
                    </div>
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse bg-success h-100">

                        </div>
                    </div>
                    <div class="col-md-12 h-50">
                        <div class="card card-inverse bg-danger h-100">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column on the row, and h-100 on the child cols.

<div class="container">
    <div class="row">
        <div class="col-md-8 col-lg-6 B">
            <div class="card card-inverse card-primary">
                <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
            </div>
        </div>
        <div class="col-md-4 col-lg-3 G ">
            <div class="row d-flex flex-column h-100">
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-12 h-100">
                    <div class="card bg-danger h-100">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

https://www.codeply.com/go/tgzFAH8vaW

How to write html code inside <?php ?>, I want write html code within the PHP script so that it can be echoed from Backend

You can do like

HTML in PHP :

<?php
     echo "<table>";
     echo "<tr>";
     echo "<td>Name</td>";
     echo "<td>".$name."</td>";
     echo "</tr>";
     echo "</table>";
?>

Or You can write like.

PHP in HTML :

<?php /*Do some PHP calculation or something*/ ?>
     <table>
         <tr>
             <td>Name</td>
             <td><?php echo $name;?></td>
         </tr>
     </table>


<?php /*Do some PHP calculation or something*/ ?> Means:
You can open a PHP tag with <?php, now add your PHP code, then close the tag with ?> and then write your html code. When needed to add more PHP, just open another PHP tag with <?php.

Alternative to mysql_real_escape_string without connecting to DB

It is impossible to safely escape a string without a DB connection. mysql_real_escape_string() and prepared statements need a connection to the database so that they can escape the string using the appropriate character set - otherwise SQL injection attacks are still possible using multi-byte characters.

If you are only testing, then you may as well use mysql_escape_string(), it's not 100% guaranteed against SQL injection attacks, but it's impossible to build anything safer without a DB connection.

Difference between JE/JNE and JZ/JNZ

  je : Jump if equal:

  399  3fb:   64 48 33 0c 25 28 00    xor    %fs:0x28,%rcx
  400  402:   00 00
  401  404:   74 05                   je     40b <sims_get_counter+0x51>

How does one create an InputStream from a String?

Here you go:

InputStream is = new ByteArrayInputStream( myString.getBytes() );

Update For multi-byte support use (thanks to Aaron Waibel's comment):

InputStream is = new ByteArrayInputStream(Charset.forName("UTF-16").encode(myString).array());

Please see ByteArrayInputStream manual.

It is safe to use a charset argument in String#getBytes(charset) method above.

After JDK 7+ you can use

java.nio.charset.StandardCharsets.UTF_16

instead of hardcoded encoding string:

InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(myString).array());

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

I've observed this with STS and Eclipse and running java from CMD too on Windows 7/8/10 and following was my simple solution:

Actually, when I installed JDK 8 and STS/Eclipse it created one directory i.e. C:\ProgramData\Oracle\Java\javapath with the following files:

  • C:\ProgramData\Oracle\Java\javapath\java.exe
  • C:\ProgramData\Oracle\Java\javapath\javaw.exe
  • C:\ProgramData\Oracle\Java\javapath\javaws.exe

Along with that, it appended Path Environment variable of System with this location C:\ProgramData\Oracle\Java\javapath

I've just removed above entry from Path Environment variable of System and added the location of the actual JDK instead i.e. C:\Program Files\Java\jdk1.8.0_131\bin

Now that is not necessary to add that -vm option in eclipse.ini or SpringToolSuite4.ini either.

PHP expects T_PAAMAYIM_NEKUDOTAYIM?

It’s a name for the :: operator in PHP. It literally means "double colon". For some reason they named it in Hebrew. Check your code syntax, and put a :: where appropriate :-)

How can I change the date format in Java?

tl;dr

LocalDate.parse( 
    "23/01/2017" ,  
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK ) 
).format(
    DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK )
)

2017/01/23

Avoid legacy date-time classes

The answer by Christopher Parker is correct but outdated. The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.

Using java.time

Parse the input string as a date-time object, then generate a new String object in the desired format.

The LocalDate class represents a date-only value without time-of-day and without time zone.

DateTimeFormatter fIn = DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK );  // As a habit, specify the desired/expected locale, though in this case the locale is irrelevant.
LocalDate ld = LocalDate.parse( "23/01/2017" , fIn );

Define another formatter for the output.

DateTimeFormatter fOut = DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK );
String output = ld.format( fOut );

2017/01/23

By the way, consider using standard ISO 8601 formats for strings representing date-time values.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section here is left for the sake of history.

For fun, here is his code adapted for using the Joda-Time library.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";

// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;

DateTimeFormatter formatterOld = DateTimeFormat.forPattern(OLD_FORMAT);
DateTimeFormatter formatterNew = DateTimeFormat.forPattern(NEW_FORMAT);
LocalDate localDate = formatterOld.parseLocalDate( oldDateString );
newDateString = formatterNew.print( localDate );

Dump to console…

System.out.println( "localDate: " + localDate );
System.out.println( "newDateString: " + newDateString );

When run…

localDate: 2010-08-12
newDateString: 2010/08/12

Html.Raw() in ASP.NET MVC Razor view

Html.Raw() returns IHtmlString, not the ordinary string. So, you cannot write them in opposite sides of : operator. Remove that .ToString() calling

@{int count = 0;}
@foreach (var item in Model.Resources)
{
    @(count <= 3 ? Html.Raw("<div class=\"resource-row\">"): Html.Raw("")) 
    // some code
    @(count <= 3 ? Html.Raw("</div>") : Html.Raw("")) 
    @(count++)

}

By the way, returning IHtmlString is the way MVC recognizes html content and does not encode it. Even if it hasn't caused compiler errors, calling ToString() would destroy meaning of Html.Raw()

Is there a better way to do optional function parameters in JavaScript?

Correct me if I'm wrong, but this seems like the simplest way (for one argument, anyway):

function myFunction(Required,Optional)
{
    if (arguments.length<2) Optional = "Default";
    //Your code
}

HTML encoding issues - "Â" character showing up instead of "&nbsp;"

If any one had the same problem as me and the charset was already correct, simply do this:

  1. Copy all the code inside the .html file.
  2. Open notepad (or any basic text editor) and paste the code.
  3. Go "File -> Save As"
  4. Enter you file name "example.html" (Select "Save as type: All Files (.)")
  5. Select Encoding as UTF-8
  6. Hit Save and you can now delete your old .html file and the encoding should be fixed

Oracle ORA-12154: TNS: Could not resolve service name Error?

Going on the assumption you're using TNSNAMES naming, here's a couple of things to do:

  • Create/modify the tnsnames.ora file in the network/admin subdirectory associated with OraHome90 to include an entry for your oracle database:
> SERVICENAME_alias =
>    (DESCRIPTION =
>     (ADDRESS = (PROTOCOL = TCP)(HOST = HOST.XYZi.com)(PORT = 1521))
>     (CONNECT_DATA = (SERVICE_NAME = SERVICENAME))

This is assuming you're using the standard Oracle port of 1521. Note that servicename_alias can be any name you want to use on the local system. You may also find that you need to specify (SID = SERVICENAME) instead of (SERVICENAME=SERVICENAME).

  • Execute tnsping servicename_alias to verify connectivity. Get this working before going any further. This will tell you if you're past the 12154 error.
  • Assuming a good connection, create an ODBC DSN using the control panel, specifying the ODBC driver for Oracle of your choice (generally there's a Microsoft ODBC driver at least, and it should work adequately as a proof of concept). I'll assume the name you gave of DATASOURCE. Use the servicename_alias as the Server name in the ODBC configuration.
  • At this point you should be able to connect to your database via Access. I am not a VB programmer, but I know you should be able to go to File->Get External Data->Link Tables and connect to your ODBC source. I would assume your code would work as well.

Is it better to use std::memcpy() or std::copy() in terms to performance?

Just a minor addition: The speed difference between memcpy() and std::copy() can vary quite a bit depending on if optimizations are enabled or disabled. With g++ 6.2.0 and without optimizations memcpy() clearly wins:

Benchmark             Time           CPU Iterations
---------------------------------------------------
bm_memcpy            17 ns         17 ns   40867738
bm_stdcopy           62 ns         62 ns   11176219
bm_stdcopy_n         72 ns         72 ns    9481749

When optimizations are enabled (-O3), everything looks pretty much the same again:

Benchmark             Time           CPU Iterations
---------------------------------------------------
bm_memcpy             3 ns          3 ns  274527617
bm_stdcopy            3 ns          3 ns  272663990
bm_stdcopy_n          3 ns          3 ns  274732792

The bigger the array the less noticeable the effect gets, but even at N=1000 memcpy() is about twice as fast when optimizations aren't enabled.

Source code (requires Google Benchmark):

#include <string.h>
#include <algorithm>
#include <vector>
#include <benchmark/benchmark.h>

constexpr int N = 10;

void bm_memcpy(benchmark::State& state)
{
  std::vector<int> a(N);
  std::vector<int> r(N);

  while (state.KeepRunning())
  {
    memcpy(r.data(), a.data(), N * sizeof(int));
  }
}

void bm_stdcopy(benchmark::State& state)
{
  std::vector<int> a(N);
  std::vector<int> r(N);

  while (state.KeepRunning())
  {
    std::copy(a.begin(), a.end(), r.begin());
  }
}

void bm_stdcopy_n(benchmark::State& state)
{
  std::vector<int> a(N);
  std::vector<int> r(N);

  while (state.KeepRunning())
  {
    std::copy_n(a.begin(), N, r.begin());
  }
}

BENCHMARK(bm_memcpy);
BENCHMARK(bm_stdcopy);
BENCHMARK(bm_stdcopy_n);

BENCHMARK_MAIN()

/* EOF */

How do I print the elements of a C++ vector in GDB?

A little late to the party, so mostly a reminder to me next time I do this search!

I have been able to use:

p/x *(&vec[2])@4

to print 4 elements (as hex) from vec starting at vec[2].

iPhone X / 8 / 8 Plus CSS media queries

iPhone X

@media only screen 
    and (device-width : 375px) 
    and (device-height : 812px) 
    and (-webkit-device-pixel-ratio : 3) { }

iPhone 8

@media only screen 
    and (device-width : 375px) 
    and (device-height : 667px) 
    and (-webkit-device-pixel-ratio : 2) { }

iPhone 8 Plus

@media only screen 
    and (device-width : 414px) 
    and (device-height : 736px) 
    and (-webkit-device-pixel-ratio : 3) { }


iPhone 6+/6s+/7+/8+ share the same sizes, while the iPhone 7/8 also do.


Looking for a specific orientation ?

Portrait

Add the following rule:

    and (orientation : portrait) 

Landscape

Add the following rule:

    and (orientation : landscape) 



References:

Cleanest way to build an SQL string in Java

For arbitrary SQL, use jOOQ. jOOQ currently supports SELECT, INSERT, UPDATE, DELETE, TRUNCATE, and MERGE. You can create SQL like this:

String sql1 = DSL.using(SQLDialect.MYSQL)  
                 .select(A, B, C)
                 .from(MY_TABLE)
                 .where(A.equal(5))
                 .and(B.greaterThan(8))
                 .getSQL();

String sql2 = DSL.using(SQLDialect.MYSQL)  
                 .insertInto(MY_TABLE)
                 .values(A, 1)
                 .values(B, 2)
                 .getSQL();

String sql3 = DSL.using(SQLDialect.MYSQL)  
                 .update(MY_TABLE)
                 .set(A, 1)
                 .set(B, 2)
                 .where(C.greaterThan(5))
                 .getSQL();

Instead of obtaining the SQL string, you could also just execute it, using jOOQ. See

http://www.jooq.org

(Disclaimer: I work for the company behind jOOQ)

Changing the Git remote 'push to' default

git remote set-url --push origin should work, as you mentioned, but you need to explicitly provide the url instead of an alternative remote name, e.g.

git remote set-url --push origin [email protected]:contributor/repo.git

You can confirm whether this worked by doing a git remote -v. E.g.

? ~/go/src/github.com/stretchr/testify/ master git remote -v
fork    [email protected]:contributor/testify.git (fetch)
fork    [email protected]:contributor/testify.git (push)
origin  [email protected]:stretchr/testify (fetch)
origin  [email protected]:contributor/testify.git (push)

Installing a dependency with Bower from URL and specify version

Just an update.

Now if it's a github repository then using just a github shorthand is enough if you do not mind the version of course.

GitHub shorthand

$ bower install desandro/masonry

Java: Identifier expected

You can't call methods outside a method. Code like this cannot float around in the class.

You need something like:

public class MyClass {

  UserInput input = new UserInput();

  public void foo() {
      input.name();
  }
}

or inside a constructor:

public class MyClass {

  UserInput input = new UserInput();

  public MyClass() {
      input.name();
  }
}

FloatingActionButton example with Support Library

for AndroidX use like

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/ic_add" />

Setting Margin Properties in code

The Margin property returns a Thickness structure, of which Left is a property. What the statement does is copying the structure value from the Margin property and setting the Left property value on the copy. You get an error because the value that you set will not be stored back into the Margin property.

(Earlier versions of C# would just let you do it without complaining, causing a lot of questions in newsgroups and forums on why a statement like that had no effect at all...)

To set the property you would need to get the Thickness structure from the Margin property, set the value and store it back:

Thickness m = MyControl.Margin;
m.Left = 10;
MyControl.Margin = m;

If you are going to set all the margins, just create a Thickness structure and set them all at once:

MyControl.Margin = new Thickness(10, 10, 10, 10);

DISABLE the Horizontal Scroll

I just had to deal with it myself. After all I found this method most easy and useful. Just add

overflow-x: hidden;

To your outer parent. In my case it looks like this:

<body style="overflow-x: hidden;">

You have to use overflow-x because if you use simply use overflow you disable the vertical scrolling too, namely overflow-y

If the vertical scrolling is still disabled you can enable it explicitly with:

overflow-y: scroll;

I know its somewhat not a proper way because if everything was setup well one would not have to use this quick and dirty method.

Routing HTTP Error 404.0 0x80070002

The solution suggested

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true" >
    <remove name="UrlRoutingModule"/>    
  </modules>
</system.webServer>

works, but can degrade performance and can even cause errors, because now all registered HTTP modules run on every request, not just managed requests (e.g. .aspx). This means modules will run on every .jpg .gif .css .html .pdf etc.

A more sensible solution is to include this in your web.config:

<system.webServer>
  <modules>
    <remove name="UrlRoutingModule-4.0" />
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
  </modules>
</system.webServer>

Credit for his goes to Colin Farr. Check-out his post about this topic at http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html.

How can I define colors as variables in CSS?

Do not use css3 variables due to support.

I would do the following if you want a pure css solution.

  1. Use color classes with semenatic names.

    .bg-primary   { background: #880000; }
    
    .bg-secondary { background: #008800; }
    
    .bg-accent    { background: #F5F5F5; }
    
  2. Separate the structure from the skin (OOCSS)

    /* Instead of */
    
    h1 { 
        font-size: 2rem;
        line-height: 1.5rem;
        color: #8000;
    }
    
    /* use this */
    
    h1 { 
        font-size: 2rem;
        line-height: 1.5rem;
    }
    
    .bg-primary {
        background: #880000;
    }
    
    /* This will allow you to reuse colors in your design */
    
  3. Put these inside a separate css file to change as needed.

How do I parse a URL into hostname and path in javascript?

The modern way:

new URL("http://example.com/aa/bb/")

Returns an object with properties hostname and pathname, along with a few others.

The first argument is a relative or absolute URL; if it's relative, then you need to specify the second argument (the base URL). For example, for a URL relative to the current page:

new URL("/aa/bb/", location)

In addition to browsers, this API is also available in Node.js since v7, through require('url').URL.

How to use this boolean in an if statement?

The problem here is

if (stop = true) is an assignation not a comparision.

Try if (stop == true)

Also take a look to the Top Ten Errors Java Programmers Make.

How to insert new cell into UITableView in Swift

Here is your code for add data into both tableView:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var table1Text: UITextField!
    @IBOutlet weak var table2Text: UITextField!
    @IBOutlet weak var table1: UITableView!
    @IBOutlet weak var table2: UITableView!

    var table1Data = ["a"]
    var table2Data = ["1"]

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func addData(sender: AnyObject) {

        //add your data into tables array from textField
        table1Data.append(table1Text.text)
        table2Data.append(table2Text.text)

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //reload your tableView
            self.table1.reloadData()
            self.table2.reloadData()
        })


        table1Text.resignFirstResponder()
        table2Text.resignFirstResponder()
    }

    //delegate methods
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == table1 {
            return table1Data.count
        }else if tableView == table2 {
            return table2Data.count
        }
        return Int()
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        if tableView == table1 {
            let cell = table1.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

            let row = indexPath.row
            cell.textLabel?.text = table1Data[row]

            return cell
        }else if tableView == table2 {

            let cell = table2.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as! UITableViewCell

            let row = indexPath.row
            cell.textLabel?.text = table2Data[row]

            return cell
        }

        return UITableViewCell()
    }
}

And your result will be:

enter image description here

Get public/external IP address?

checkip.dyndns.org is not always works correctly. For example, for my machine it shows internal after-NAT address:

Current IP Address: 192.168.1.120

I think its happening, because of I have my local DNS-zone behind NAT, and my browser sends to checkip its local IP address, which is returned back.

Also, http is heavy weight and text oriented TCP-based protocol, so not very suitable for quick and efficient regular request for external IP address. I suggest to use UDP-based, binary STUN, especially designed for this purposes:

http://en.wikipedia.org/wiki/STUN

STUN-server is like "UDP mirror". You looking to it, and see "how I looks".

There is many public STUN-servers over the world, where you can request your external IP. For example, see here:

http://www.voip-info.org/wiki/view/STUN

You can download any STUN-client library, from Internet, for example, here:

http://www.codeproject.com/Articles/18492/STUN-Client

And use it.

How to programmatically tell if a Bluetooth device is connected?

There is an isConnected function in BluetoothDevice system API in https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/bluetooth/BluetoothDevice.java

If you want to know if the a bounded(paired) device is currently connected or not, the following function works fine for me:

public static boolean isConnected(BluetoothDevice device) {
    try {
        Method m = device.getClass().getMethod("isConnected", (Class[]) null);
        boolean connected = (boolean) m.invoke(device, (Object[]) null);
        return connected;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

PHP to write Tab Characters inside a file?

The tab character is \t. Notice the use of " instead of '.

$chunk = "abc\tdef\tghi";

PHP Strings - Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

...

\t horizontal tab (HT or 0x09 (9) in ASCII)


Also, let me recommend the fputcsv() function which is for the purpose of writing CSV files.

Global Git ignore

You should create an exclude file for this. Check out this gist which is pretty self explanatory.

To address your question though, you may need to either de-index the .tmproj file (if you've already added it to the index) with git rm --cached path/to/.tmproj, or git add and commit your .gitignore file.

How do I output text without a newline in PowerShell?

Write-Host is terrible, a destroyer of worlds, yet you can use it just to display progress to a user whilst using Write-Output to log (not that the OP asked for logging).

Write-Output "Enabling feature XYZ" | Out-File "log.txt" # Pipe to log file
Write-Host -NoNewLine "Enabling feature XYZ......."
$result = Enable-SPFeature
$result | Out-File "log.txt"
# You could try{}catch{} an exception on Enable-SPFeature depending on what it's doing
if ($result -ne $null) {
    Write-Host "complete"
} else {
    Write-Host "failed"
}

Fastest Convert from Collection to List<T>

You could try:

List<ManagementObject> managementList = new List<ManagementObject>(managementObjects.ToArray());

Not sure if .ToArray() is available for the collection. If you do use the code you posted, make sure you initialize the List with the number of existing elements:

List<ManagementObject> managementList = new List<ManagementObject>(managementObjects.Count);  // or .Length

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

There are some great answers here, and so before I give my own I'd like to highlight a few of the gems (no ruby pun intended) I've read here.

  • Python is not a pure OOP language -- it's a general purpose, multi-paradigm language that allows the programmer to use the paradigm they are most comfortable with and/or the paradigm that is best suited for their solution.
  • Python has first-class functions, so len is actually an object. Ruby, on the other hand, doesn't have first class functions. So the len function object has it's own methods that you can inspect by running dir(len).

If you don't like the way this works in your own code, it's trivial for you to re-implement the containers using your preferred method (see example below).

>>> class List(list):
...     def len(self):
...         return len(self)
...
>>> class Dict(dict):
...     def len(self):
...         return len(self)
...
>>> class Tuple(tuple):
...     def len(self):
...         return len(self)
...
>>> class Set(set):
...     def len(self):
...         return len(self)
...
>>> my_list = List([1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'])
>>> my_dict = Dict({'key': 'value', 'site': 'stackoverflow'})
>>> my_set = Set({1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'})
>>> my_tuple = Tuple((1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'))
>>> my_containers = Tuple((my_list, my_dict, my_set, my_tuple))
>>>
>>> for container in my_containers:
...     print container.len()
...
15
2
15
15

Parsing command-line arguments in C

A command is basically a string. In general it can be split into two parts - the command's name and the command's arguments.

Example:

ls

is used for listing the contents of a directory:

user@computer:~$ ls
Documents Pictures Videos ...

The ls above is executed inside home folder of a user. Here the argument which folder to list is implicitly added to the command. We can explicitly pass some arguments:

user@computer:~$ ls Picture
image1.jpg image2.jpg ...

Here I have explicitly told ls which folder's contents I'd like to see. We can use another argument for example l for listing the details of each file and folder such as access permissions, size etc.:

user@computer:~$ ls Pictures
-rw-r--r-- 1 user user   215867 Oct 12  2014 image1.jpg
-rw-r--r-- 1 user user   268800 Jul 31  2014 image2.jpg
...

Oh, the size looks really weird (215867, 268800). Let's add the h flag for human-friendly output:

user@computer:~$ ls -l -h Pictures
-rw-r--r-- 1 user user  211K Oct 12  2014 image1.jpg
-rw-r--r-- 1 user user  263K Jul 31  2014 image2.jpg
...

Some commands allow their arguments to be combined (in the above case we might as well write ls -lh and we'll get the same output), using short (a single letter usually but sometimes more; abbreviation) or long names (in case of ls we have the -a or --all for listing all files including hidden ones with --all being the long name for -a) etc. There are commands where the order of the arguments is very important but there are also others where the order of the arguments is not important at all.

For example it doesn't matter if I use ls -lh or ls -hl however in the case of mv (moving/renaming files) you have less flexibility for your last 2 arguments that is mv [OPTIONS] SOURCE DESTINATION.

In order to get a grip of commands and their arguments you can use man (example: man ls) or info (example: info ls).

In many languages including C/C++ you have a way of parsing command line arguments that the user has attached to the call of the executable (the command). There are also numerous libraries available for this task since in its core it's actually not that easy to do it properly and at the same time offer a large amount of arguments and their varieties:

  • getopt
  • argp_parse
  • gflags
  • ...

Every C/C++ application has the so called entry point, which is basically where your code starts - the main function:

int main (int argc, char *argv[]) { // When you launch your application the first line of code that is ran is this one - entry point
    // Some code here
    return 0; // Exit code of the application - exit point
}

No matter if you use a library (like one of the above I've mentioned; but this is clearly not allowed in your case ;)) or do it on your own your main function has the two arguments:

  • argc - represents the number of arguments
  • argv - a pointer to an array of strings (you can also see char** argv which is basically the same but more difficult to use).

NOTE: main actually also has a third argument char *envp[] which allows passing environment variables to your command but this is a more advanced thing and I really don't think that it's required in your case.

The processing of command line arguments consists of two parts:

  1. Tokenizing - this is the part where each argument gets a meaning. Its the process of breaking your arguments list into meaningful elements (tokens). In the case of ls -l the l is not only a valid character but also a token in itself since it represents a complete, valid argument.

Here is an example how to output the number of arguments and the (unchecked for validity) characters that may or may not actually be arguments:

#include <iostream>
using std::cout;
using std::endl;

int main (int argc, char *argv[]) {
    cout << "Arguments' count=%d" << argc << endl;

    // First argument is ALWAYS the command itself
    cout << "Command: " << argv[0] << endl;

    // For additional arguments we start from argv[1] and continue (if any)
    for (int i = 1; i < argc; i++) {
        cout << "arg[" << i << "]: " << argv[i] << endl;
    }

    cout << endl;
    return 0;
}
  1. Parsing - after acquiring the tokens (arguments and their values) you need to check if your command supports these. For example:

    user@computer:~$ ls -y
    

    will return

    ls: invalid option -- 'y'
    Try 'ls --help' for more information.
    

    This is because the parsing has failed. Why? Because y (and -y respectively; note that -, --, : etc. is not required and its up to the parsing of the arguments whether you want that stuff there or not; in Unix/Linux systems this is a sort of a convention but you are not bind to it) is an unknown argument for the ls command.

For each argument (if successfully recognized as such) you trigger some sort of change in your application. You can use an if-else for example to check if a certain argument is valid and what it does followed by changing whatever you want that argument to change in the execution of the rest of your code. You can go the old C-style or C++-style:

* `if (strcmp(argv[1], "x") == 0) { ... }` - compare the pointer value
* `if (std::string(argv[1]) == "x") { ... }` - convert to string and then compare

I actually like (when not using a library) to convert argv to an std::vector of strings like this:

std::vector<std::string> args(argv, argv+argc);
for (size_t i = 1; i < args.size(); ++i) {
    if (args[i] == "x") {
        // Handle x
    }
    else if (args[i] == "y") {
        // Handle y
    }
    // ...
}

The std::vector<std::string> args(argv, argv+argc); part is just an easier C++-ish way to handle the array of strings since char * is a C-style string (with char *argv[] being an array of such strings) which can easily be converted to a C++ string that is std::string. Then we can add all converted strings to a vector by giving the starting address of argv and then also pointing to its last address namely argv + argc (we add argc number of string to the base address of argv which is basically pointing at the last address of our array).

Inside the for loop above you can see that I check (using simple if-else) if a certain argument is available and if yes then handle it accordingly. A word of caution: by using such a loop the order of the arguments doesn't matter. As I've mentioned at the beginning some commands actually have a strict order for some or all of their arguments. You can handle this in a different way by manually calling the content of each args (or argv if you use the initial char* argv[] and not the vector solution):

// No for loop!
if (args[1] == "x") {
    // Handle x
}
else if (args[2] == "y") {
    // Handle y
}
// ...

This makes sure that at position 1 only the x will be expected etc. The problem with this is that you can shoot yourself in the leg by going out of bounds with the indexing so you have to make sure that your index stays within the range set by argc:

if (argc > 1 && argc <= 3) {
    if (args[1] == "x") {
        // Handle x
    }
    else if (args[2] == "y") {
        // Handle y
    }
}

The example above makes sure you have content at index 1 and 2 but not beyond.

Last but not least the handling of each argument is a thing that is totally up to you. You can use boolean flags that are set when a certain argument is detected (example: if (args[i] == "x") { xFound = true; } and later on in your code do something based on the bool xFound and its value), numerical types if the argument is a number OR consists of number along with the argument's name (example: mycommand -x=4 has an argument -x=4 which you can additionally parse as x and 4 the last being the value of x) etc. Based on the task at hand you can go crazy and add an insane amount of complexity to your command line arguments.

Hope this helps. Let me know if something is unclear or you need more examples.

ZIP file content type for HTTP request

The standard MIME type for ZIP files is application/zip. The types for the files inside the ZIP does not matter for the MIME type.

As always, it ultimately depends on your server setup.

SQL Server - Convert varchar to another collation (code page) to fix character encoding

Must be used convert, not cast:

SELECT
 CONVERT(varchar(50), N'æøåáälcçcédnoöruýtžš')
 COLLATE Cyrillic_General_CI_AI

(http://blog.sqlpositive.com/2010/03/using-convert-with-collate-to-strip-accents-from-unicode-strings/)

Get nodes where child node contains an attribute

Years later, but a useful option would be to utilize XPath Axes (https://www.w3schools.com/xml/xpath_axes.asp). More specifically, you are looking to use the descendants axes.

I believe this example would do the trick:

//book[descendant::title[@lang='it']]

This allows you to select all book elements that contain a child title element (regardless of how deep it is nested) containing language attribute value equal to 'it'.

I cannot say for sure whether or not this answer is relevant to the year 2009 as I am not 100% certain that the XPath Axes existed at that time. What I can confirm is that they do exist today and I have found them to be extremely useful in XPath navigation and I am sure you will as well.

Getting Class type from String

It should be:

Class.forName(String classname)

C# declare empty string array

You can try this

string[] arr = {};

jquery animate .css

If you are needing to use CSS with the jQuery .animate() function, you can use set the duration.

$("#my_image").css({
    'left':'1000px',
    6000, ''
});

We have the duration property set to 6000.

This will set the time in thousandth of seconds: 6 seconds.

After the duration our next property "easing" changes how our CSS happens.

We have our positioning set to absolute.

There are two default ones to the absolute function: 'linear' and 'swing'.

In this example I am using linear.

It allows for it to use a even pace.

The other 'swing' allows for a exponential speed increase.

There are a bunch of really cool properties to use with animate like bounce, etc.

$(document).ready(function(){
    $("#my_image").css({
        'height': '100px',
        'width':'100px',
        'background-color':'#0000EE',
        'position':'absolute'
    });// property than value

    $("#my_image").animate({
        'left':'1000px'
    },6000, 'linear', function(){
        alert("Done Animating");
    });
});

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

Quick fix that works for me. Navigate to the root directory of your folder from command line (cmd). then once you are on your root directory, type:

code . 

Then, press enter. Note the ".", don't forget it. Now try to debug and see if you get the same error.

Subscript out of range error in this Excel VBA script

Private Sub CommandButton1_Click()

    Dim Data As Object, Employee As Object

    Application.ScreenUpdating = False

    Set Data = ThisWorkbook.Sheets("Data")

    Set Employee = ThisWorkbook.Sheets("Employee Names")

    Data.Range("AK1").Value = "Lookup"

    Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Formula = "=VLOOKUP(E2,'Employee Names'!$A:$A,1,0)"

    Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Value = Data.Range("AK2:AK" & Data.Range("A1").End(xlDown).Row).Value

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=5, Criteria1:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=37, Criteria1:="#N/A"

    Application.DisplayAlerts = False

    Data.AutoFilter.Range.Offset(1, 0).Rows.SpecialCells(xlCellTypeVisible).Delete (xlShiftUp)

    Data.Range("AK:AK").Delete

    Data.AutoFilterMode = False

    'Selection.AutoFilter

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=7, Criteria1:="="

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="<>"

    Worksheets("Data").Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "DrfeeRequested"

    Set Dr = ThisWorkbook.Worksheets("DrfeeRequested")

    Dr.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.AutoFilterMode = False

    'DrfeeRequested.AutoFilterMode = False

    Selection.AutoFilter

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "RateLockfollowup"
    Set Ratefolup = ThisWorkbook.Worksheets("RateLockfollowup")

    Ratefolup.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.AutoFilterMode = False

    Selection.AutoFilter

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="="

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Lockedlefollowup"
    Set Lockfolup = ThisWorkbook.Worksheets("Lockedlefollowup")

    Lockfolup.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.AutoFilterMode = False

    Selection.AutoFilter

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="="

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Hoifollowup"

    Set Hoifolup = ThisWorkbook.Worksheets("Hoifollowup")

    Hoifolup.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.AutoFilterMode = False

    Selection.AutoFilter

    TodayDT = Format(Now())

    Weekdy = Weekday(Now())

    If Weekdy = 2 Then
       LastTwoDays = Now() - Weekday(Now(), 3)
    ElseIf Weekdy = 3 Then
       LastTwoDays = Now() - Weekday(Now(), 3)
    ElseIf Weekdy = 4 Then
       LastTwoDays = Now() - Weekday(Now(), 3)
    ElseIf Weekdy = 5 Then
       LastTwoDays = Now() - Weekday(Now(), 3)
    ElseIf Weekdy = 6 Then
       LastTwoDays = Now() - Weekday(Now(), 3)
    Else
       MsgBox "Today Satuarday OR Sunday Data is not Available"
    End If

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="="

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=11, Criteria1:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=11, Criteria1:=" TodayDT", Operator:=xlAnd, Criteria2:="LastTwoDays"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "DRfeefollowup"

    Set Drfreefolup = ThisWorkbook.Worksheets("DRfeefollowup")

    Drfreefolup.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.AutoFilterMode = False

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=15, Criteria1:="yes"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=19, Criteria1:="x"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=12, Criteria1:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=13, Criteria1:="<>"

    'Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).AutoFilter Field:=14, criterial:="<>"

    Data.Range("A1:AK" & Data.Range("A1").End(xlDown).Row).Copy

    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Drworkblefiles"

    Set Drworkblefiles = ThisWorkbook.Worksheets("Drworkblefiles")

    Drworkblefiles.Range("A1").PasteSpecial Paste:=xlPasteValues

    Application.CutCopyMode = False

    Data.Range("A1").AutoFilter

   End Sub

 Private Sub CommandButton2_Click()


    Sheets("Data").Range("A1:AJ" & Sheets("Data").Range("A1").End(xlDown).Row).Clear

    MsgBox "Please paste new data in data sheet"


End Sub

What exactly does Perl's "bless" do?

Short version: it's marking that hash as attached to the current package namespace (so that that package provides its class implementation).

How to make a great R reproducible example

Reproducible code is key to get help. However, there are many users that might be skeptical of pasting even a chunk of their data. For instance, they could be working with sensitive data or on an original data collected to use in a research paper. For any reason, I thought it would be nice to have a handy function for "deforming" my data before pasting it publicly. The anonymize function from the package SciencesPo is very silly, but for me it works nicely with dput function.

install.packages("SciencesPo")

dt <- data.frame(
    Z = sample(LETTERS,10),
    X = sample(1:10),
    Y = sample(c("yes", "no"), 10, replace = TRUE)
)

> dt
   Z  X   Y
1  D  8  no
2  T  1 yes
3  J  7  no
4  K  6  no
5  U  2  no
6  A 10 yes
7  Y  5  no
8  M  9 yes
9  X  4 yes
10 Z  3  no

Then I anonymize it:

> anonymize(dt)
     Z    X  Y
1   b2  2.5 c1
2   b6 -4.5 c2
3   b3  1.5 c1
4   b4  0.5 c1
5   b7 -3.5 c1
6   b1  4.5 c2
7   b9 -0.5 c1
8   b5  3.5 c2
9   b8 -1.5 c2
10 b10 -2.5 c1

One may also want to sample few variables instead of the whole data before apply anonymization and dput command.

    # sample two variables without replacement
> anonymize(sample.df(dt,5,vars=c("Y","X")))
   Y    X
1 a1 -0.4
2 a1  0.6
3 a2 -2.4
4 a1 -1.4
5 a2  3.6

How to force file download with PHP

you can use download attribute to force download a file:

_x000D_
_x000D_
<a href="https://test.com/aaa.exe" download>click here to download</a>
_x000D_
_x000D_
_x000D_

How to turn on line numbers in IDLE?

As @StahlRat already answered. I would like to add another method for it. There is extension pack for Python Default idle editor Python Extensions Package.

jQuery - Increase the value of a counter when a button is clicked

You are trying to set "++" on a jQuery element!

YOu could declare a js variable

var counter = 0;

and in jQuery code do:

$("#counter").html(counter++);

Pass arguments to Constructor in VBA

Using the trick

Attribute VB_PredeclaredId = True

I found another more compact way:

Option Explicit
Option Base 0
Option Compare Binary

Private v_cBox As ComboBox

'
' Class creaor
Public Function New_(ByRef cBox As ComboBox) As ComboBoxExt_c
  If Me Is ComboBoxExt_c Then
    Set New_ = New ComboBoxExt_c
    Call New_.New_(cBox)
  Else
    Set v_cBox = cBox
  End If
End Function

As you can see the New_ constructor is called to both create and set the private members of the class (like init) only problem is, if called on the non-static instance it will re-initialize the private member. but that can be avoided by setting a flag.

AngularJS $http-post - convert binary to excel file and download

You could as well take an alternative approach -- you don't have to use $http, you don't need any extra libraries, and it ought to work in any browser.

Just place an invisible form on your page.

<form name="downloadForm" action="/MyApp/MyFiles/Download" method="post" target="_self">
    <input type="hidden" name="value1" value="{{ctrl.value1}}" />
    <input type="hidden" name="value2" value="{{ctrl.value2}}" />
</form>

And place this code in your angular controller.

ctrl.value1 = 'some value 1';  
ctrl.value2 = 'some value 2';  
$timeout(function () {
    $window.document.forms['downloadForm'].submit();
});

This code will post your data to /MyApp/MyFiles/Download and you'll receive a file in your Downloads folder.
It works with Internet Explorer 10.

If a conventional HTML form doesn't let you post your complex object, then you have two options:

1. Stringify your object and put it into one of the form fields as a string.

<input type="hidden" name="myObjJson" value="{{ctrl.myObj | json:0}}" />


2. Consider HTML JSON forms: https://www.w3.org/TR/html-json-forms/

Disable scrolling in all mobile devices

use this in style

body
{
overflow:hidden;
width:100%;
}

Use this in head tag

<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />

Hiding axis text in matplotlib plots

If you want to hide just the axis text keeping the grid lines:

frame1 = plt.gca()
frame1.axes.xaxis.set_ticklabels([])
frame1.axes.yaxis.set_ticklabels([])

Doing set_visible(False) or set_ticks([]) will also hide the grid lines.

How do I decode a string with escaped unicode?

UPDATE: Please note that this is a solution that should apply to older browsers or non-browser platforms, and is kept alive for instructional purposes. Please refer to @radicand 's answer below for a more up to date answer.


This is a unicode, escaped string. First the string was escaped, then encoded with unicode. To convert back to normal:

var x = "http\\u00253A\\u00252F\\u00252Fexample.com";
var r = /\\u([\d\w]{4})/gi;
x = x.replace(r, function (match, grp) {
    return String.fromCharCode(parseInt(grp, 16)); } );
console.log(x);  // http%3A%2F%2Fexample.com
x = unescape(x);
console.log(x);  // http://example.com

To explain: I use a regular expression to look for \u0025. However, since I need only a part of this string for my replace operation, I use parentheses to isolate the part I'm going to reuse, 0025. This isolated part is called a group.

The gi part at the end of the expression denotes it should match all instances in the string, not just the first one, and that the matching should be case insensitive. This might look unnecessary given the example, but it adds versatility.

Now, to convert from one string to the next, I need to execute some steps on each group of each match, and I can't do that by simply transforming the string. Helpfully, the String.replace operation can accept a function, which will be executed for each match. The return of that function will replace the match itself in the string.

I use the second parameter this function accepts, which is the group I need to use, and transform it to the equivalent utf-8 sequence, then use the built - in unescape function to decode the string to its proper form.