Programs & Examples On #Gui designer

Best GUI designer for eclipse?

Window Builder Pro is a great GUI Designer for eclipse and is now offered for free by google.

Moving uncommitted changes to a new branch

Just create a new branch:

git checkout -b newBranch

And if you do git status you'll see that the state of the code hasn't changed and you can commit it to the new branch.

How do I sort an observable collection?

WPF provides live sorting out-of-the-box using the ListCollectionView class...

public ObservableCollection<string> MyStrings { get; set; }
private ListCollectionView _listCollectionView;
private void InitializeCollection()
{
    MyStrings = new ObservableCollection<string>();
    _listCollectionView = CollectionViewSource.GetDefaultView(MyStrings) 
              as ListCollectionView;
    if (_listCollectionView != null)
    {
        _listCollectionView.IsLiveSorting = true;
        _listCollectionView.CustomSort = new 
                CaseInsensitiveComparer(CultureInfo.InvariantCulture);
    }
}

Once this initialization is complete, there's nothing more to do. The advantage over a passive sort is that the ListCollectionView does all the heavy lifting in a way that's transparent to the developer. New items are automatically placed in their correct sort order. Any class that derives from IComparer of T is suitable for the custom sort property.

See ListCollectionView for the documentation and other features.

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

Acked Unseen sample

Hi guys! Just some observations from what I just found in my capture:

On many occasions, the packet capture reports “ACKed segment that wasn't captured” on the client side, which alerts of the condition that the client PC has sent a data packet, the server acknowledges receipt of that packet, but the packet capture made on the client does not include the packet sent by the client

Initially, I thought it indicates a failure of the PC to record into the capture a packet it sends because “e.g., machine which is running Wireshark is slow” (https://osqa-ask.wireshark.org/questions/25593/tcp-previous-segment-not-captured-is-that-a-connectivity-issue)
However, then I noticed every time I see this “ACKed segment that wasn't captured” alert I can see a record of an “invalid” packet sent by the client PC

  • In the capture example above, frame 67795 sends an ACK for 10384

  • Even though wireshark reports Bogus IP length (0), frame 67795 is reported to have length 13194

  • Frame 67800 sends an ACK for 23524
  • 10384+13194 = 23578
  • 23578 – 23524 = 54
  • 54 is in fact length of the Ethernet / IP / TCP headers (14 for Ethernt, 20 for IP, 20 for TCP)
  • So in fact, the frame 67796 does represent a large TCP packets (13194 bytes) which operating system tried to put on the wore
    • NIC driver will fragment it into smaller 1500 bytes pieces in order to transmit over the network
    • But Wireshark running on my PC fails to understand it is a valid packet and parse it. I believe Wireshark running on 2012 Windows server reads these captures correctly
  • So after all, these “Bogus IP length” and “ACKed segment that wasn't captured” alerts were in fact false positives in my case

Multipart File upload Spring Boot

@RequestMapping(value="/add/image", method=RequestMethod.POST)
public ResponseEntity upload(@RequestParam("id") Long id, HttpServletResponse response, HttpServletRequest request)
{   
    try {
        MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request;
        Iterator<String> it=multipartRequest.getFileNames();
        MultipartFile multipart=multipartRequest.getFile(it.next());
        String fileName=id+".png";
        String imageName = fileName;

        byte[] bytes=multipart.getBytes();
        BufferedOutputStream stream= new BufferedOutputStream(new FileOutputStream("src/main/resources/static/image/book/"+fileName));;

        stream.write(bytes);
        stream.close();
        return new ResponseEntity("upload success", HttpStatus.OK);

    } catch (Exception e) {
        e.printStackTrace();
        return new ResponseEntity("Upload fialed", HttpStatus.BAD_REQUEST);
    }   
}

How to find length of dictionary values

Let dictionary be :
dict={'key':['value1','value2']}

If you know the key :
print(len(dict[key]))

else :
val=[len(i) for i in dict.values()]
print(val[0])
# for printing length of 1st key value or length of values in keys if all keys have same amount of values.

sweet-alert display HTML code in text

I was upgrading from old sweetalert and found out how to do it in the new Version (official Docs):

// this is a Node object    
var span = document.createElement("span");
span.innerHTML = "Testno  sporocilo za objekt <b>test</b>";

swal({
    title: "" + txt + "", 
    content: span,
    confirmButtonText: "V redu", 
    allowOutsideClick: "true" 
});

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

Ran into this similar issue while using iframe to logout of sub sites with different domains. The solution I used was to load the iframe first, then update the source after the frame is loaded.

_x000D_
_x000D_
var frame = document.createElement('iframe');_x000D_
frame.style.display = 'none';_x000D_
frame.setAttribute('src', 'about:blank');_x000D_
document.body.appendChild(frame);_x000D_
frame.addEventListener('load', () => {_x000D_
  frame.setAttribute('src', url);_x000D_
});
_x000D_
_x000D_
_x000D_

How to detect when a youtube video finishes playing?

This can be done through the youtube player API:

http://jsfiddle.net/7Gznb/

Working example:

    <div id="player"></div>

    <script src="http://www.youtube.com/player_api"></script>

    <script>

        // create youtube player
        var player;
        function onYouTubePlayerAPIReady() {
            player = new YT.Player('player', {
              width: '640',
              height: '390',
              videoId: '0Bmhjf0rKe8',
              events: {
                onReady: onPlayerReady,
                onStateChange: onPlayerStateChange
              }
            });
        }

        // autoplay video
        function onPlayerReady(event) {
            event.target.playVideo();
        }

        // when video ends
        function onPlayerStateChange(event) {        
            if(event.data === 0) {          
                alert('done');
            }
        }

    </script>

How do I remove the old history from a git repository?

This method is easy to understand and works fine. The argument to the script ($1) is a reference (tag, hash, ...) to the commit starting from which you want to keep your history.

#!/bin/bash
git checkout --orphan temp $1 # create a new branch without parent history
git commit -m "Truncated history" # create a first commit on this branch
git rebase --onto temp $1 master # now rebase the part of master branch that we want to keep onto this branch
git branch -D temp # delete the temp branch

# The following 2 commands are optional - they keep your git repo in good shape.
git prune --progress # delete all the objects w/o references
git gc --aggressive # aggressively collect garbage; may take a lot of time on large repos

NOTE that old tags will still remain present; so you might need to remove them manually

remark: I know this is almost the same aswer as @yoyodin, but there are some important extra commands and informations here. I tried to edit the answer, but since it is a substantial change to @yoyodin's answer, my edit was rejected, so here's the information!

css h1 - only as wide as the text

You could use a <span> instead of an <h1>.

Authenticate Jenkins CI for Github private repository

If you need Jenkins to access more then 1 project you will need to:
1. add public key to one github user account
2. add this user as Owner (to access all projects) or as a Collaborator in every project.

Many public keys for one system user will not work because GitHub will find first matched deploy key and will send back error like "ERROR: Permission to user/repo2 denied to user/repo1"

http://help.github.com/ssh-issues/

mongodb group values by multiple fields

Below query will provide exactly the same result as given in the desired response:

db.books.aggregate([
    {
        $group: {
            _id: { addresses: "$addr", books: "$book" },
            num: { $sum :1 }
        }
    },
    {
        $group: {
            _id: "$_id.addresses",
            bookCounts: { $push: { bookName: "$_id.books",count: "$num" } }
        }
    },
    {
        $project: {
            _id: 1,
            bookCounts:1,
            "totalBookAtAddress": {
                "$sum": "$bookCounts.count"
            }
        }
    }

]) 

The response will be looking like below:

/* 1 */
{
    "_id" : "address4",
    "bookCounts" : [
        {
            "bookName" : "book3",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 2 */
{
    "_id" : "address90",
    "bookCounts" : [
        {
            "bookName" : "book33",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 3 */
{
    "_id" : "address15",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 4 */
{
    "_id" : "address3",
    "bookCounts" : [
        {
            "bookName" : "book9",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 5 */
{
    "_id" : "address5",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 6 */
{
    "_id" : "address1",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 3
        },
        {
            "bookName" : "book5",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 4
},

/* 7 */
{
    "_id" : "address2",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 2
        },
        {
            "bookName" : "book5",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 3
},

/* 8 */
{
    "_id" : "address77",
    "bookCounts" : [
        {
            "bookName" : "book11",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 9 */
{
    "_id" : "address9",
    "bookCounts" : [
        {
            "bookName" : "book99",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
}

AngularJs event to call after content is loaded

I use setInterval to wait for the content loaded. I hope this can help you to solve that problem.

var $audio = $('#audio');
var src = $audio.attr('src');
var a;
a = window.setInterval(function(){
    src = $audio.attr('src');
    if(src != undefined){
        window.clearInterval(a);
        $('audio').mediaelementplayer({
            audioWidth: '100%'
        });
    }
}, 0);

Android ACTION_IMAGE_CAPTURE Intent

this is a well documented bug in some versions of android. that is, on google experience builds of android, image capture doesn't work as documented. what i've generally used is something like this in a utilities class.

public boolean hasImageCaptureBug() {

    // list of known devices that have the bug
    ArrayList<String> devices = new ArrayList<String>();
    devices.add("android-devphone1/dream_devphone/dream");
    devices.add("generic/sdk/generic");
    devices.add("vodafone/vfpioneer/sapphire");
    devices.add("tmobile/kila/dream");
    devices.add("verizon/voles/sholes");
    devices.add("google_ion/google_ion/sapphire");

    return devices.contains(android.os.Build.BRAND + "/" + android.os.Build.PRODUCT + "/"
            + android.os.Build.DEVICE);

}

then when i launch image capture, i create an intent that checks for the bug.

Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (hasImageCaptureBug()) {
    i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File("/sdcard/tmp")));
} else {
    i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
}
startActivityForResult(i, mRequestCode);

then in activity that i return to, i do different things based on the device.

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
     switch (requestCode) {
         case GlobalConstants.IMAGE_CAPTURE:
             Uri u;
             if (hasImageCaptureBug()) {
                 File fi = new File("/sdcard/tmp");
                 try {
                     u = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(), fi.getAbsolutePath(), null, null));
                     if (!fi.delete()) {
                         Log.i("logMarker", "Failed to delete " + fi);
                     }
                 } catch (FileNotFoundException e) {
                     e.printStackTrace();
                 }
             } else {
                u = intent.getData();
            }
    }

this saves you having to write a new camera app, but this code isn't great either. the big problems are

  1. you never get full sized images from the devices with the bug. you get pictures that are 512px wide that are inserted into the image content provider. on devices without the bug, everything works as document, you get a big normal picture.

  2. you have to maintain the list. as written, it is possible for devices to be flashed with a version of android (say cyanogenmod's builds) that has the bug fixed. if that happens, your code will crash. the fix is to use the entire device fingerprint.

Compile/run assembler in Linux?

The assembler(GNU) is as(1)

Android Shared preferences for creating one time activity (example)

You could also take a look at a past sample project of mine, written for this purpose. I saves locally a name and retrieves it either upon a user's request or when the app starts.

But, at this time, it would be better to use commit (instead of apply) for persisting the data. More info here.

convert base64 to image in javascript/jquery

This is not exactly the OP's scenario but an answer to those of some of the commenters. It is a solution based on Cordova and Angular 1, which should be adaptable to other frameworks like jQuery. It gives you a Blob from Base64 data which you can store somewhere and reference it from client side javascript / html.

It also answers the original question on how to get an image (file) from the Base 64 data:

The important part is the Base 64 - Binary conversion:

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

Slicing is required to avoid out of memory errors.

Works with jpg and pdf files (at least that's what I tested). Should work with other mimetypes/contenttypes too. Check the browsers and their versions you aim for, they need to support Uint8Array, Blob and atob.

Here's the code to write the file to the device's local storage with Cordova / Android:

...
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {

                    // Setup filename and assume a jpg file
                    var filename = attachment.id + "-" + (attachment.fileName ? attachment.fileName : 'image') + "." + (attachment.fileType ? attachment.fileType : "jpg");
                    dirEntry.getFile(filename, { create: true, exclusive: false }, function(fileEntry) {
                        // attachment.document holds the base 64 data at this moment
                        var binary = base64toBlob(attachment.document, attachment.mimetype);
                        writeFile(fileEntry, binary).then(function() {
                            // Store file url for later reference, base 64 data is no longer required
                            attachment.document = fileEntry.nativeURL;

                        }, function(error) {
                            WL.Logger.error("Error writing local file: " + error);
                            reject(error.code);
                        });

                    }, function(errorCreateFile) {
                        WL.Logger.error("Error creating local file: " + JSON.stringify(errorCreateFile));
                        reject(errorCreateFile.code);
                    });

                }, function(errorCreateFS) {
                    WL.Logger.error("Error getting filesystem: " + errorCreateFS);
                    reject(errorCreateFS.code);
                });
...

Writing the file itself:

function writeFile(fileEntry, dataObj) {
    return $q(function(resolve, reject) {
        // Create a FileWriter object for our FileEntry (log.txt).
        fileEntry.createWriter(function(fileWriter) {

            fileWriter.onwriteend = function() {
                WL.Logger.debug(LOG_PREFIX + "Successful file write...");
                resolve();
            };

            fileWriter.onerror = function(e) {
                WL.Logger.error(LOG_PREFIX + "Failed file write: " + e.toString());
                reject(e);
            };

            // If data object is not passed in,
            // create a new Blob instead.
            if (!dataObj) {
                dataObj = new Blob(['missing data'], { type: 'text/plain' });
            }

            fileWriter.write(dataObj);
        });
    })
}

I am using the latest Cordova (6.5.0) and Plugins versions:

I hope this sets everyone here in the right direction.

C++ callback using class member

A complete working example from the code above.... for C++11:

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

#if __cplusplus <= 199711L
  #error This file needs at least a C++11 compliant compiler, try using:
  #error    $ g++ -std=c++11 ..
#endif

using namespace std;

class EventHandler {
    public:
        void addHandler(std::function<void(int)> callback) {
            printf("\nHandler added...");
            // Let's pretend an event just occured
            callback(1);
        }
};


class MyClass
{
    public:
        MyClass(int);
        // Note: No longer marked `static`, and only takes the actual argument
        void Callback(int x);

    private:
        EventHandler *pHandler;
        int private_x;
};

MyClass::MyClass(int value) {
    using namespace std::placeholders; // for `_1`

    pHandler = new EventHandler();
    private_x = value;
    pHandler->addHandler(std::bind(&MyClass::Callback, this, _1));
}

void MyClass::Callback(int x) {
    // No longer needs an explicit `instance` argument,
    // as `this` is set up properly
    printf("\nResult:%d\n\n", (x+private_x));
}

// Main method
int main(int argc, char const *argv[]) {

    printf("\nCompiler:%ld\n", __cplusplus);
    new MyClass(5);
    return 0;
}


// where $1 is your .cpp file name... this is the command used:
// g++ -std=c++11 -Wall -o $1 $1.cpp
// chmod 700 $1
// ./$1

Output should be:

Compiler:201103

Handler added...
Result:6

The connection to adb is down, and a severe error has occurred

I just got the same problem and to fix it, I opened the task manager and killed the adb.exe process, then I restarted Eclipse.

HTML set image on browser tab

It's called a Favicon, have a read.

<link rel="shortcut icon" href="http://www.example.com/myicon.ico"/>

You can use this neat tool to generate cross-browser compatible Favicons.

Why doesn't Java offer operator overloading?

Assuming Java as the implementation language then a, b, and c would all be references to type Complex with initial values of null. Also assuming that Complex is immutable as the mentioned BigInteger and similar immutable BigDecimal, I'd I think you mean the following, as you're assigning the reference to the Complex returned from adding b and c, and not comparing this reference to a.

Isn't :

Complex a, b, c; a = b + c;

much simpler than:

Complex a, b, c; a = b.add(c);

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.

#ifdef in C#

I would recommend you using the Conditional Attribute!

Update: 3.5 years later

You can use #if like this (example copied from MSDN):

// preprocessor_if.cs
#define DEBUG
#define VC_V7
using System;
public class MyClass 
{
    static void Main() 
    {
#if (DEBUG && !VC_V7)
        Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V7)
        Console.WriteLine("VC_V7 is defined");
#elif (DEBUG && VC_V7)
        Console.WriteLine("DEBUG and VC_V7 are defined");
#else
        Console.WriteLine("DEBUG and VC_V7 are not defined");
#endif
    }
}

Only useful for excluding parts of methods.

If you use #if to exclude some method from compilation then you will have to exclude from compilation all pieces of code which call that method as well (sometimes you may load some classes at runtime and you cannot find the caller with "Find all references"). Otherwise there will be errors.

If you use conditional compilation on the other hand you can still leave all pieces of code that call the method. All parameters will still be validated by the compiler. The method just won't be called at runtime. I think that it is way better to hide the method just once and not have to remove all the code that calls it as well. You are not allowed to use the conditional attribute on methods which return value - only on void methods. But I don't think this is a big limitation because if you use #if with a method that returns a value you have to hide all pieces of code that call it too.

Here is an example:


    // calling Class1.ConditionalMethod() will be ignored at runtime 
    // unless the DEBUG constant is defined


    using System.Diagnostics;
    class Class1 
    {
       [Conditional("DEBUG")]
       public static void ConditionalMethod() {
          Console.WriteLine("Executed Class1.ConditionalMethod");
       }
    }

Summary:

I would use #ifdef in C++ but with C#/VB I would use Conditional attribute. This way you hide the method definition without having to hide the pieces of code that call it. The calling code is still compiled and validated by the compiler, the method is not called at runtime though. You may want to use #if to avoid dependencies because with Conditional attribute your code is still compiled.

how to use the Box-Cox power transformation in R

According to the Box-cox transformation formula in the paper Box,George E. P.; Cox,D.R.(1964). "An analysis of transformations", I think mlegge's post might need to be slightly edited.The transformed y should be (y^(lambda)-1)/lambda instead of y^(lambda). (Actually, y^(lambda) is called Tukey transformation, which is another distinct transformation formula.)
So, the code should be:

(trans <- bc$x[which.max(bc$y)])
[1] 0.4242424
# re-run with transformation
mnew <- lm(((y^trans-1)/trans) ~ x) # Instead of mnew <- lm(y^trans ~ x) 

More information

Please correct me if I misunderstood it.

How do I create a basic UIButton programmatically?

Objective-C

// Create the Button with RoundedRect type
UIButton *mybutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// instend of "Click Me" you can write your own message/Label
[mybutton setTitle:@"Click Me" forState:UIControlStateNormal];
// create the Rectangle Frame with specified size
mybutton.frame = CGRectMake(10, 10, 300, 140); // x,y,width,height    [self.view addSubview:mybutton];// add button to your view.

Swift

let button   = UIButton(type: UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 50)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Test Button", forState: UIControlState.Normal)
self.view.addSubview(button)

java.util.NoSuchElementException: No line found

Your real problem is that you are calling "sc.nextLine()" MORE TIMES than the number of lines.

For example, if you have only TEN input lines, then you can ONLY call "sc.nextLine()" TEN times.

Every time you call "sc.nextLine()", one input line will be consumed. If you call "sc.nextLine()" MORE TIMES than the number of lines, you will have an exception called

      "java.util.NoSuchElementException: No line found".

If you have to call "sc.nextLine()" n times, then you have to have at least n lines.

Try to change your code to match the number of times you call "sc.nextLine()" with the number of lines, and I guarantee that your problem will be solved.

Adding a guideline to the editor in Visual Studio

This is originally from Sara's blog.

It also works with almost any version of Visual Studio, you just need to change the "8.0" in the registry key to the appropriate version number for your version of Visual Studio.

The guide line shows up in the Output window too. (Visual Studio 2010 corrects this, and the line only shows up in the code editor window.)

You can also have the guide in multiple columns by listing more than one number after the color specifier:

RGB(230,230,230), 4, 80

Puts a white line at column 4 and column 80. This should be the value of a string value Guides in "Text Editor" key (see bellow).

Be sure to pick a line color that will be visisble on your background. This color won't show up on the default background color in VS. This is the value for a light grey: RGB(221, 221, 221).

Here are the registry keys that I know of:

Visual Studio 2010: HKCU\Software\Microsoft\VisualStudio\10.0\Text Editor

Visual Studio 2008: HKCU\Software\Microsoft\VisualStudio\9.0\Text Editor

Visual Studio 2005: HKCU\Software\Microsoft\VisualStudio\8.0\Text Editor

Visual Studio 2003: HKCU\Software\Microsoft\VisualStudio\7.1\Text Editor

For those running Visual Studio 2010, you may want to install the following extensions rather than changing the registry yourself:

These are also part of the Productivity Power Tools, which includes many other very useful extensions.

Loop through all the rows of a temp table and call a stored procedure for each row

something like this?

DECLARE maxval, val, @ind INT;
SELECT MAX(ID) as maxval FROM table;

while (ind <= maxval  ) DO           

      select `value` as val from `table` where `ID`=ind;

      CALL fn(val);

      SET ind = ind+1;
end while;

Android get image path from drawable as string

These all are ways:

String imageUri = "drawable://" + R.drawable.image;

Other ways I tested

Uri path = Uri.parse("android.resource://com.segf4ult.test/" + R.drawable.icon);
Uri otherPath = Uri.parse("android.resource://com.segf4ult.test/drawable/icon");

String path = path.toString();
String path = otherPath .toString();

jQuery datepicker, onSelect won't work

It should be "datepicker", not "datePicker" if you are using the jQuery UI DatePicker plugin. Perhaps, you have a different but similar plugin that doesn't support the select handler.

How do I add target="_blank" to a link within a specified div?

Inline:

$('#link_other').find('a').attr('target','_blank');

PHP: Possible to automatically get all POSTed data?

As long as you don't want any special formatting: yes.

foreach ($_POST as $key => $value) 
    $body .= $key . ' -> ' . $value . '<br>';

Obviously, more formatting would be necessary, however that's the "easy" way. Unless I misunderstood the question.

You could also do something like this (and if you like the format, it's certainly easier):

$body = print_r($_POST, true);

How to redirect a page using onclick event in php?

Please try this

    <input type="button" value="Home" class="homebutton" id="btnHome" onClick="Javascript:window.location.href = 'http://www.website.com/index.php';" />

window.location.href example:

 window.location.href = 'http://www.google.com'; //Will take you to Google.

window.open() example:

     window.open('http://www.google.com'); //This will open Google in a new window.

Javascript: Easier way to format numbers?

No, there is no built-in support for number formatting, but googling will turn up loads of code snippets that will do this for you.

EDIT: I missed the last sentence of your post. Try http://code.google.com/p/jquery-utils/wiki/StringFormat for a jQuery solution.

Deleting an element from an array in PHP

You can use the array_pop method to remove the last element of an array:

<?php
    $a = array("one", "two", "Three");
    array_pop($a);
    print_r($a);
?>
The out put will be
Array ( [0] => one[1] => two)

which deletes only last element of an array LIFO operation

How to make a Java Generic method static?

I'll explain it in a simple way.

Generics defined at Class level are completely separate from the generics defined at the (static) method level.

class Greet<T> {

    public static <T> void sayHello(T obj) {
        System.out.println("Hello " + obj);
    }
}

When you see the above code anywhere, please note that the T defined at the class level has nothing to do with the T defined in the static method. The following code is also completely valid and equivalent to the above code.

class Greet<T> {

    public static <E> void sayHello(E obj) {
        System.out.println("Hello " + obj);
    }
}

Why the static method needs to have its own generics separate from those of the Class?

This is because, the static method can be called without even instantiating the Class. So if the Class is not yet instantiated, we do not yet know what is T. This is the reason why the static methods needs to have its own generics.

So, whenever you are calling the static method,

Greet.sayHello("Bob");
Greet.sayHello(123);

JVM interprets it as the following.

Greet.<String>sayHello("Bob");
Greet.<Integer>sayHello(123);

Both giving the same outputs.

Hello Bob
Hello 123

How to set a CheckBox by default Checked in ASP.Net MVC

I use viewbag with the same variable name in the Controller. E.g if the variable is called "IsActive" and I want this to default to true on the "Create" form, on the Create Action I set the value ViewBag.IsActive = true;

public ActionResult Create()
{
    ViewBag.IsActive = true;
    return View();
}

What is the Angular equivalent to an AngularJS $watch?

This does not answer the question directly, but I have on different occasions landed on this Stack Overflow question in order to solve something I would use $watch for in angularJs. I ended up using another approach than described in the current answers, and want to share it in case someone finds it useful.

The technique I use to achieve something similar $watch is to use a BehaviorSubject (more on the topic here) in an Angular service, and let my components subscribe to it in order to get (watch) the changes. This is similar to a $watch in angularJs, but require some more setup and understanding.

In my component:

export class HelloComponent {
  name: string;
  // inject our service, which holds the object we want to watch.
  constructor(private helloService: HelloService){
    // Here I am "watching" for changes by subscribing
    this.helloService.getGreeting().subscribe( greeting => {
      this.name = greeting.value;
    });
  }
}

In my service

export class HelloService {
  private helloSubject = new BehaviorSubject<{value: string}>({value: 'hello'});
  constructor(){}
  // similar to using $watch, in order to get updates of our object 
  getGreeting(): Observable<{value:string}> {
    return this.helloSubject;
  }
  // Each time this method is called, each subscriber will receive the updated greeting.
  setGreeting(greeting: string) {
    this.helloSubject.next({value: greeting});
  }
}

Here is a demo on Stackblitz

How to get the CPU Usage in C#?

You can use WMI to get CPU percentage information. You can even log into a remote computer if you have the correct permissions. Look at http://www.csharphelp.com/archives2/archive334.html to get an idea of what you can accomplish.

Also helpful might be the MSDN reference for the Win32_Process namespace.

See also a CodeProject example How To: (Almost) Everything In WMI via C#.

How to increase timeout for a single test case in mocha

For test navegation on Express:

const request = require('supertest');
const server = require('../bin/www');

describe('navegation', () => {
    it('login page', function(done) {
        this.timeout(4000);
        const timeOut = setTimeout(done, 3500);

        request(server)
            .get('/login')
            .expect(200)
            .then(res => {
                res.text.should.include('Login');
                clearTimeout(timeOut);
                done();
            })
            .catch(err => {
                console.log(this.test.fullTitle(), err);
                clearTimeout(timeOut);
                done(err);
            });
    });
});

In the example the test time is 4000 (4s).

Note: setTimeout(done, 3500) is minor for than done is called within the time of the test but clearTimeout(timeOut) it avoid than used all these time.

Python subprocess/Popen with a modified environment

you might use my_env.get("PATH", '') instead of my_env["PATH"] in case PATH somehow not defined in the original environment, but other than that it looks fine.

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

Spring Boot Rest Controller how to return different HTTP status codes?

A nice way is to use Spring's ResponseStatusException

Rather than returning a ResponseEntityor similar you simply throw the ResponseStatusException from the controller with an HttpStatus and cause, for example:

throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cause description here");

or:

throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Cause description here");

This results in a response to the client containing the HTTP status (e.g. 400 Bad request) with a body like:

{
  "timestamp": "2020-07-09T04:43:04.695+0000",
  "status": 400,
  "error": "Bad Request",
  "message": "Cause description here",
  "path": "/test-api/v1/search"
}

Remove elements from collection while iterating

In Java 8, there is another approach. Collection#removeIf

eg:

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);

list.removeIf(i -> i > 2);

How to install MinGW-w64 and MSYS2?

Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).

Anyways, if you're already planning on using MSYS2, there's no need for that installer.

  1. Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).

  2. After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit or MSYS2 32-bit in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).

  3. Install a toolchain

    a) for 32-bit:

    pacman -S mingw-w64-i686-gcc
    

    b) for 64-bit:

    pacman -S mingw-w64-x86_64-gcc
    
  4. install any libraries/tools you may need. You can search the repositories by doing

    pacman -Ss name_of_something_i_want_to_install
    

    e.g.

    pacman -Ss gsl
    

    and install using

    pacman -S package_name_of_something_i_want_to_install
    

    e.g.

    pacman -S mingw-w64-x86_64-gsl
    

    and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!

  5. Open a MinGW-w64 shell:

    a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"

    b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"

  6. Verify that the compiler is working by doing

    gcc -v
    

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin or <MSYS2 root>/mingw64/bin to your PATH.

how to convert java string to Date object

    try 
    {  
      String datestr="06/27/2007";
      DateFormat formatter; 
      Date date; 
      formatter = new SimpleDateFormat("MM/dd/yyyy");
      date = (Date)formatter.parse(datestr);  
    } 
    catch (Exception e)
    {}

month is MM, minutes is mm..

What is console.log?

This is nothing to deal with the jQuery. The console.log() is referencing to the console object's log function, which provides methods for logging information to the browser's console. These methods are intended for debugging purposes only and should not be relied on for presenting information to end users.

How to copy a directory structure but only include certain files (using windows batch files)

Under Linux and other UNIX systems, using the tar command would do this easily.

$ tar cvf /tmp/full-structure.tar *data.zip *info.txt

Then you'd cwd to the target and:

$ tar xvf /tmp/full-structure.tar 

Of course you could pipe the output from the first tar into the 2nd, but seeing it work in steps is easier to understand and explain. I'm missing the necessary cd /to/new/path/ in the following command - I just don't recall how to do it now. Someone else can add it, hopefully.

$ tar cvf -  *data.zip *info.txt |  tar xvf - 

Tar (gnutar) is available on Windows too, but I'd probably use the xcopy method myself on that platform.

Jquery Change Height based on Browser Size/Resize

$(function(){
    $(window).resize(function(){
        var h = $(window).height();
        var w = $(window).width();
        $("#elementToResize").css('height',(h < 768 || w < 1024) ? 500 : 400);
    });
});

Scrollbars etc have an effect on the window size so you may want to tweak to desired size.

Is it .yaml or .yml?

.yaml is apparently the official extension, because some applications fail when using .yml. On the other hand I am not familiar with any applications which use YAML code, but fail with a .yaml extension.

I just stumbled across this, as I was used to writing .yml in Ansible and Docker Compose. Out of habit I used .yml when writing Netplan files which failed silently. I finally figured out my mistake. The author of a popular Ansible Galaxy role for Netplan makes the same assumption in his code:

- name: Capturing Existing Configurations
  find:
    paths: /etc/netplan
    patterns: "*.yml,*.yaml"
  register: _netplan_configs

Yet any files with a .yml extension get ignored by Netplan in the same way as files with a .bak extension. As Netplan is very quiet, and gives no feedback whatsoever on success, even with netplan apply --debug, a config such as 01-netcfg.yml will fail silently without any meaningful feedback.

jQuery UI Dialog - missing close icon

I am late to this one by a while, but I'm going to blow your mind, ready?

The reason this is happening, is because you are calling bootstrap in, after you are calling jquery-ui in.

Literally, swap the two so that instead of:

<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="js/bootstrap.min.js"></script>

it becomes

<script src="js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

:)

Edit - 26/06/2015 - this keeps attracting interest months later so I thought it was worth an edit. I actually really like the noConflict solution offered in the comment underneath this answer and clarified by user Pretty Cool as a separate answer. As some have reported issues with the bootstrap tooltip when the scripts are swapped. I didn't experience that issue however because I downloaded jquery UI without the tooltip as I didn't need it because bootstrap. So this issue never came up for me.

Edit - 22/07/2015 - Don't confuse jquery-ui with jquery! While Bootstrap's JavaScript requires jQuery to be loaded before, it doesn't rely on jQuery-UI. So jquery-ui.js can be loaded after bootstrap.min.js, while jquery.js always needs to be loaded before Bootstrap.

Why is list initialization (using curly braces) better than the alternatives?

Basically copying and pasting from Bjarne Stroustrup's "The C++ Programming Language 4th Edition":

List initialization does not allow narrowing (§iso.8.5.4). That is:

  • An integer cannot be converted to another integer that cannot hold its value. For example, char to int is allowed, but not int to char.
  • A floating-point value cannot be converted to another floating-point type that cannot hold its value. For example, float to double is allowed, but not double to float.
  • A floating-point value cannot be converted to an integer type.
  • An integer value cannot be converted to a floating-point type.

Example:

void fun(double val, int val2) {

    int x2 = val;    // if val == 7.9, x2 becomes 7 (bad)

    char c2 = val2;  // if val2 == 1025, c2 becomes 1 (bad)

    int x3 {val};    // error: possible truncation (good)

    char c3 {val2};  // error: possible narrowing (good)

    char c4 {24};    // OK: 24 can be represented exactly as a char (good)

    char c5 {264};   // error (assuming 8-bit chars): 264 cannot be 
                     // represented as a char (good)

    int x4 {2.0};    // error: no double to int value conversion (good)

}

The only situation where = is preferred over {} is when using auto keyword to get the type determined by the initializer.

Example:

auto z1 {99};   // z1 is an int
auto z2 = {99}; // z2 is std::initializer_list<int>
auto z3 = 99;   // z3 is an int

Conclusion

Prefer {} initialization over alternatives unless you have a strong reason not to.

if statements matching multiple values

An extensionmethod like this would do it...

public static bool In<T>(this T item, params T[] items)
{
    return items.Contains(item);
}

Use it like this:

Console.WriteLine(1.In(1,2,3));
Console.WriteLine("a".In("a", "b"));

This view is not constrained

You need to give a value to the constraints manually when using the new layout editor or the missing constraints can be added automatically by clicking the magic wand button in the toolbar menu of the design preview.

React.js create loop through Array

In CurrentGame component you need to change initial state because you are trying use loop for participants but this property is undefined that's why you get error.,

getInitialState: function(){
    return {
       data: {
          participants: [] 
       }
    };
},

also, as player in .map is Object you should get properties from it

this.props.data.participants.map(function(player) {
   return <li key={player.championId}>{player.summonerName}</li>
   // -------------------^^^^^^^^^^^---------^^^^^^^^^^^^^^
})

Example

Failed to connect to mailserver at "localhost" port 25

On windows, nearly all AMPP (Apache,MySQL,PHP,PHPmyAdmin) packages don't include a mail server (but nearly all naked linuxes do have!). So, when using PHP under windows, you need to setup a mail server!

Imo the best and most simple tool ist this: http://smtp4dev.codeplex.com/

SMTP4Dev is a simple one-file mail server tool that does collect the mails it send (so it does not really sends mail, it just keeps them for development). Perfect tool.

Submit button doesn't work

I faced this problem today, and the issue was I was preventing event default action in document onclick:

document.onclick = function(e) {
    e.preventDefault();
}

Document onclick usually is used for event delegation but it's wrong to prevent default for every event, you must do it only for required elements:

document.onclick = function(e) {
    if (e.target instanceof HTMLAnchorElement) e.preventDefault();
}

How to access shared folder without giving username and password

I found one way to access the shared folder without giving the username and password.

We need to change the share folder protect settings in the machine where the folder has been shared.

Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.

By doing the above settings we can access the shared folder without any username/password.

Max or Default?

You could always add Double.MinValue to the sequence. This would ensure that there is at least one element and Max would return it only if it is actually the minimum. To determine which option is more efficient (Concat, FirstOrDefault or Take(1)), you should perform adequate benchmarking.

double x = context.MyTable
    .Where(y => y.MyField == value)
    .Select(y => y.MyCounter)
    .Concat(new double[]{Double.MinValue})
    .Max();

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

ASP.NET MVC 5 - Identity. How to get current ApplicationUser

My mistake, I shouldn't have used a method inside a LINQ query.

Correct code:

using Microsoft.AspNet.Identity;


string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);

Starting of Tomcat failed from Netbeans

I had the same problem but none of the answers above worked. The solution for me was to restore the Manager web application that is bundled with Tomcat.

How can I represent an infinite number in Python?

I don't know exactly what you are doing, but float("inf") gives you a float Infinity, which is greater than any other number.

How to set background color of a View

For setting the first color to be seen on screen, you can also do it in the relevant layout.xml (better design) by adding this property to the relevant View:

android:background="#FF00FF00"

Convert int to char in java

Whenever you type cast integer to char it will return the ascii value of that int (once go through the ascii table for better understanding)

    int a=68;
    char b=(char)a;

    System.out.println(b);//it will return ascii value of 68

    //output- D

SQL 'like' vs '=' performance

You are asking the wrong question. In databases is not the operator performance that matters, is always the SARGability of the expression, and the coverability of the overall query. Performance of the operator itself is largely irrelevant.

So, how do LIKE and = compare in terms of SARGability? LIKE, when used with an expression that does not start with a constant (eg. when used LIKE '%something') is by definition non-SARGabale. But does that make = or LIKE 'something%' SARGable? No. As with any question about SQL performance the answer does not lie with the query of the text, but with the schema deployed. These expression may be SARGable if an index exists to satisfy them.

So, truth be told, there are small differences between = and LIKE. But asking whether one operator or other operator is 'faster' in SQL is like asking 'What goes faster, a red car or a blue car?'. You should eb asking questions about the engine size and vechicle weight, not about the color... To approach questions about optimizing relational tables, the place to look is your indexes and your expressions in the WHERE clause (and other clauses, but it usually starts with the WHERE).

Setting custom UITableViewCells height

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    CGSize constraintSize = {245.0, 20000}
    CGSize neededSize = [ yourText sizeWithFont:[UIfont systemFontOfSize:14.0f] constrainedToSize:constraintSize  lineBreakMode:UILineBreakModeCharacterWrap]
if ( neededSize.height <= 18) 

   return 45
else return neededSize.height + 45 
//18 is the size of your text with the requested font (systemFontOfSize 14). if you change fonts you have a different number to use  
// 45 is what is required to have a nice cell as the neededSize.height is the "text"'s height only
//not the cell.

}

Using Keras & Tensorflow with AMD GPU

One can use AMD GPU via the PlaidML Keras backend.

Fastest: PlaidML is often 10x faster (or more) than popular platforms (like TensorFlow CPU) because it supports all GPUs, independent of make and model. PlaidML accelerates deep learning on AMD, Intel, NVIDIA, ARM, and embedded GPUs.

Easiest: PlaidML is simple to install and supports multiple frontends (Keras and ONNX currently)

Free: PlaidML is completely open source and doesn't rely on any vendor libraries with proprietary and restrictive licenses.

For most platforms, getting started with accelerated deep learning is as easy as running a few commands (assuming you have Python (v2 or v3) installed):

virtualenv plaidml
source plaidml/bin/activate
pip install plaidml-keras plaidbench

Choose which accelerator you'd like to use (many computers, especially laptops, have multiple):

plaidml-setup

Next, try benchmarking MobileNet inference performance:

plaidbench keras mobilenet

Or, try training MobileNet:

plaidbench --batch-size 16 keras --train mobilenet

To use it with keras set

os.environ["KERAS_BACKEND"] = "plaidml.keras.backend"

For more information

https://github.com/plaidml/plaidml

https://github.com/rstudio/keras/issues/205#issuecomment-348336284

Populating a data frame in R in a loop

Thanks Notable1, works for me with the tidytextr Create a dataframe with the name of files in one column and content in other.

    diretorio <- "D:/base"
    arquivos <- list.files(diretorio, pattern = "*.PDF")
    quantidade <- length(arquivos)

#
df = NULL
for (k in 1:quantidade) {

      nome = arquivos[k]
      print(nome)
      Sys.sleep(1) 
      dados = read_pdf(arquivos[k],ocr = T)
      print(dados)
      Sys.sleep(1)
      df = rbind(df, data.frame(nome,dados))
      Sys.sleep(1)
}
Encoding(df$text) <- "UTF-8"

Iterating over dictionaries using 'for' loops

You can check the implementation of CPython's dicttype on GitHub. This is the signature of method that implements the dict iterator:

_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
             PyObject **pvalue, Py_hash_t *phash)

CPython dictobject.c

Zero-pad digits in string

There's also str_pad

<?php
$input = "Alien";
echo str_pad($input, 10);                      // produces "Alien     "
echo str_pad($input, 10, "-=", STR_PAD_LEFT);  // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH);   // produces "__Alien___"
echo str_pad($input, 6 , "___");               // produces "Alien_"
?>

Skip first entry in for loop in python?

An alternative method:

for idx, car in enumerate(cars):
    # Skip first line.
    if not idx:
        continue
    # Skip last line.
    if idx + 1 == len(cars):
        continue
    # Real code here.
    print car

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

This might be the late response, but recently i got the same error. After lot of surfing this solution helped me.

alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 15:30']}
def myconverter(obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, datetime.datetime):
            return obj.__str__()

Call myconverter in json.dumps() like below. json.dumps(alerts, default=myconverter).

How to automatically generate getters and setters in Android Studio

Using Alt+ Insert or Right-click and choose "Generate..." You may easily generate getter and setter or Override methods in Android Studio. This has the same effect as using the Menu Bar Code -> Generate...

enter image description here enter image description here

Download multiple files as a zip-file using php

This is a working example of making ZIPs in PHP:

$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name,  ZipArchive::CREATE);
foreach ($files as $file) {
  echo $path = "uploadpdf/".$file;
  if(file_exists($path)){
  $zip->addFromString(basename($path),  file_get_contents($path));  
  }
  else{
   echo"file does not exist";
  }
}
$zip->close();

Difference between wait and sleep

sleep is a method of Thread, wait is a method of Object, so wait/notify is a technique of synchronizing shared data in Java (using monitor), but sleep is a simple method of thread to pause itself.

Get Category name from Post ID

function wp_get_post_categories( $post_id = 0, $args = array() )
{
   $post_id = (int) $post_id;
   $defaults = array('fields' => 'ids');
   $args = wp_parse_args( $args, $defaults );
   $cats = wp_get_object_terms($post_id, 'category', $args);

   return $cats;
}

Here is the second argument of function wp_get_post_categories() which you can pass the attributes of receiving data.

$category_detail = get_the_category( '4',array( 'fields' => 'names' ) ); //$post->ID
foreach( $category_detail as $cd )
{
   echo $cd->name;
}

What are invalid characters in XML

The predeclared characters are:

& < > " '

See "What are the special characters in XML?" for more information.

How to enable multidexing with the new Android Multidex support library

build.gradle

multiDexEnabled true
implementation 'androidx.multidex:multidex:2.0.1'

AndroidManifest.xml

<application
    android:name="androidx.multidex.MultiDexApplication"

How to add Android Support Repository to Android Studio?

Gradle can work with the 18.0.+ notation, it however now depends on the new support repository which is now bundled with the SDK.

Open the SDK manager and immediately under Extras the first option is "Android Support Repository" and install it

Copying PostgreSQL database to another server

Run this command with database name, you want to backup, to take dump of DB.

 pg_dump -U {user-name} {source_db} -f {dumpfilename.sql}

 eg. pg_dump -U postgres mydbname -f mydbnamedump.sql

Now scp this dump file to remote machine where you want to copy DB.

eg. scp mydbnamedump.sql user01@remotemachineip:~/some/folder/

On remote machine run following command in ~/some/folder to restore the DB.

 psql -U {user-name} -d {desintation_db}-f {dumpfilename.sql}

 eg. psql -U postgres -d mynewdb -f mydbnamedump.sql

How can I create a simple index.html file which lists all files/directories?

There's a free php script made by Celeron Dude that can do this called Celeron Dude Indexer 2. It doesn't require .htaccess The source code is easy to understand and provides a good starting point.

Here's a download link: https://gitlab.com/desbest/celeron-dude-indexer/

celeron dude indexer

Deep copy in ES6 using the spread syntax

// use: clone( <thing to copy> ) returns <new copy>
// untested use at own risk
function clone(o, m){
  // return non object values
  if('object' !==typeof o) return o
  // m: a map of old refs to new object refs to stop recursion
  if('object' !==typeof m || null ===m) m =new WeakMap()
  var n =m.get(o)
  if('undefined' !==typeof n) return n
  // shallow/leaf clone object
  var c =Object.getPrototypeOf(o).constructor
  // TODO: specialize copies for expected built in types i.e. Date etc
  switch(c) {
    // shouldn't be copied, keep reference
    case Boolean:
    case Error:
    case Function:
    case Number:
    case Promise:
    case String:
    case Symbol:
    case WeakMap:
    case WeakSet:
      n =o
      break;
    // array like/collection objects
    case Array:
      m.set(o, n =o.slice(0))
      // recursive copy for child objects
      n.forEach(function(v,i){
        if('object' ===typeof v) n[i] =clone(v, m)
      });
      break;
    case ArrayBuffer:
      m.set(o, n =o.slice(0))
      break;
    case DataView:
      m.set(o, n =new (c)(clone(o.buffer, m), o.byteOffset, o.byteLength))
      break;
    case Map:
    case Set:
      m.set(o, n =new (c)(clone(Array.from(o.entries()), m)))
      break;
    case Int8Array:
    case Uint8Array:
    case Uint8ClampedArray:
    case Int16Array:
    case Uint16Array:
    case Int32Array:
    case Uint32Array:
    case Float32Array:
    case Float64Array:
      m.set(o, n =new (c)(clone(o.buffer, m), o.byteOffset, o.length))
      break;
    // use built in copy constructor
    case Date:
    case RegExp:
      m.set(o, n =new (c)(o))
      break;
    // fallback generic object copy
    default:
      m.set(o, n =Object.assign(new (c)(), o))
      // recursive copy for child objects
      for(c in n) if('object' ===typeof n[c]) n[c] =clone(n[c], m)
  }
  return n
}

How can I fix WebStorm warning "Unresolved function or method" for "require" (Firefox Add-on SDK)

For WebStorm 2019.3 File > Preferences or Settings > Languages & Frameworks > Node.js and NPM -> Enable Coding assitance for NodeJs

Note that the additional packages that you want to use are included.

Signed to unsigned conversion in C - is it always safe?

Referring to the bible:

  • Your addition operation causes the int to be converted to an unsigned int.
  • Assuming two's complement representation and equally sized types, the bit pattern does not change.
  • Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)
  • The rules are a little more complicated in the case of combining signed and unsigned of differing sizes.

How to read files and stdout from a running Docker container

Sharing files between a docker container and the host system, or between separate containers is best accomplished using volumes.

Having your app running in another container is probably your best solution since it will ensure that your whole application can be well isolated and easily deployed. What you're trying to do sounds very close to the setup described in this excellent blog post, take a look!

Python Inverse of a Matrix

Numpy will be suitable for most people, but you can also do matrices in Sympy

Try running these commands at http://live.sympy.org/

M = Matrix([[1, 3], [-2, 3]])
M
M**-1

For fun, try M**(1/2)

How to list installed packages from a given repo using yum

On newer versions of yum, this information is stored in the "yumdb" when the package is installed. This is the only 100% accurate way to get the information, and you can use:

yumdb search from_repo repoid

(or repoquery and grep -- don't grep yum output). However the command "find-repos-of-install" was part of yum-utils for a while which did the best guess without that information:

http://james.fedorapeople.org/yum/commands/find-repos-of-install.py

As floyd said, a lot of repos. include a unique "dist" tag in their release, and you can look for that ... however from what you said, I guess that isn't the case for you?

How to negate 'isblank' function

The solution is isblank(cell)=false

How to transition to a new view controller with code only using Swift

SWIFT

Usually for normal transition we use,

let next:SecondViewController = SecondViewController()
self.presentViewController(next, animated: true, completion: nil)

But sometimes when using navigation controller, you might face a black screen. In that case, you need to use like,

let next:ThirdViewController = storyboard?.instantiateViewControllerWithIdentifier("ThirdViewController") as! ThirdViewController
self.navigationController?.pushViewController(next, animated: true)

Moreover none of the above solution preserves navigationbar when you call from storyboard or single xib to another xib. If you use nav bar and want to preserve it just like normal push, you have to use,

Let's say, "MyViewController" is identifier for MyViewController

let viewController = MyViewController(nibName: "MyViewController", bundle: nil)
self.navigationController?.pushViewController(viewController, animated: true)

Yii2 data provider default sorting

$dataProvider = new ActiveDataProvider([ 
    'query' => $query, 
    'sort'=> ['defaultOrder' => ['iUserId'=>SORT_ASC]] 
]);

How to check if JSON return is empty with jquery

if (!json[0]) alert("JSON empty");

How to set the java.library.path from Eclipse

the easiest way would to use the eclipse IDE itself. Go to the menu and set build path. Make it point to the JAVA JDK and JRE file path in your directory. afterwards you can check the build path where compiled files are going to be set. in the bin folder by default though. The best thing would be to allow eclipse to handle itself the build path and only to edit it similar to the solution that is given above

Angular 2 - Redirect to an external URL and open in a new tab

One caveat on using window.open() is that if the url that you pass to it doesn't have http:// or https:// in front of it, angular treats it as a route.

To get around this, test if the url starts with http:// or https:// and append it if it doesn't.

let url: string = '';
if (!/^http[s]?:\/\//.test(this.urlToOpen)) {
    url += 'http://';
}

url += this.urlToOpen;
window.open(url, '_blank');

Current date and time as string

Non C++11 solution: With the <ctime> header, you could use strftime. Make sure your buffer is large enough, you wouldn't want to overrun it and wreak havoc later.

#include <iostream>
#include <ctime>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;
  char buffer[80];

  time (&rawtime);
  timeinfo = localtime(&rawtime);

  strftime(buffer,sizeof(buffer),"%d-%m-%Y %H:%M:%S",timeinfo);
  std::string str(buffer);

  std::cout << str;

  return 0;
}

Datatable vs Dataset

A DataTable object represents tabular data as an in-memory, tabular cache of rows, columns, and constraints. The DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects.

SQL: set existing column as Primary Key in MySQL

ALTER TABLE your_table
ADD PRIMARY KEY (Drugid);

How do I check my gcc C++ compiler version for my Eclipse?

Just type

gcc --version

in any terminal near you.. ;-)

How to create a backup of a single table in a postgres database?

If you prefer a graphical user interface, you can use pgAdmin III (Linux/Windows/OS X). Simply right click on the table of your choice, then "backup". It will create a pg_dump command for you.

enter image description here

enter image description here

enter image description here

How do I get Fiddler to stop ignoring traffic to localhost?

To get Fiddler to capture traffic when you are debugging on local host, after you hit F5 to begin degugging change the address so that localhost has a "." after it.

For instance, you start debugging and the you have the following URL in the Address bar:

http://localhost:49573/Default.aspx

Change it to:

http://localhost.:49573/Default.aspx

Hit enter and Fidder will start picking up your traffic.

How to call a function after a div is ready?

Through jQuery.ready function you can specify function that's executed when DOM is loaded. Whole DOM, not any div you want.

So, you should use ready in a bit different way

$.ready(function() {
    createGrid();
});

This is in case when you dont use AJAX to load your div

How to indent HTML tags in Notepad++

In Notepad++ v7.8.9 you can use the Tab key to increase the indention level, and use Shift + Tab to decrease the indentation level.

How to specify a editor to open crontab file? "export EDITOR=vi" does not work

It wasn't working for me. I run crontab with sudo, so I switched to root, did the above suggestions, and crontab would open in vim, but it still wouldn't from my user account. Finally I ran sudo select-editor from the user account and that did the trick.

How do I concatenate text in a query in sql server?

You have to explicitly cast the string types to the same in order to concatenate them, In your case you may solve the issue by simply addig an 'N' in front of 'SomeText' (N'SomeText'). If that doesn't work, try Cast('SomeText' as nvarchar(8)).

How to find specified name and its value in JSON-string from Java?

Gson allows for one of the simplest possible solutions. Compared to similar APIs like Jackson or svenson, Gson by default doesn't even need the unused JSON elements to have bindings available in the Java structure. Specific to the question asked, here's a working solution.

import com.google.gson.Gson;

public class Foo
{
  static String jsonInput = 
    "{" + 
      "\"name\":\"John\"," + 
      "\"age\":\"20\"," + 
      "\"address\":\"some address\"," + 
      "\"someobject\":" +
      "{" + 
        "\"field\":\"value\"" + 
      "}" + 
    "}";

  String age;

  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    Foo thing = gson.fromJson(jsonInput, Foo.class);
    if (thing.age != null)
    {
      System.out.println("age is " + thing.age);
    }
    else
    {
      System.out.println("age element not present or value is null");
    }
  }
}

List file using ls command in Linux with full path

For listing everything with full path, only in current directory

find $PWD -maxdepth 1

Same as above but only matches a particular extension, case insensitive (.sh files in this case)

find $PWD -maxdepth 1 -iregex '.+\.sh'

$PWD is for current directory, it can be replaced with any directory

mydir="/etc/sudoers.d/" ; find $mydir -maxdepth 1

maxdepth prevents find from going into subdirectories, for example you can set it to "2" for listing items in children as well. Simply remove it if you need it recursive.

To limit it to only files, can use -type f option.

find $PWD -maxdepth 1 -type f

Is there a way to force npm to generate package-lock.json?

If your npm version is lower than version 5 then install the higher version for getting the automatic generation of package-lock.json.

Example: Upgrade your current npm to version 6.14.0

npm i -g [email protected]

You could view the latest npm version list by

npm view npm versions

How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?

Copy the diff file to the root of your repository, and then do:

git apply yourcoworkers.diff

More information about the apply command is available on its man page.

By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch on the sender and then git am on the receiver, because it also transfers the authorship info and the commit message.

If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3 option of apply that tries to merge in the changes.

It also works with Unix pipe as follows:

git diff d892531 815a3b5 | git apply

Display text from .txt file in batch file

Just set the time and date to variables if it will be something that will be in a loop then

:top
set T=%time%
set D=%Date%

echo %T%>>log.txt
echo %d%>>log.txt
echo time:%T%
echo date:%D%
pause
goto top

I suggest making it nice and clean by putting:

@echo off

in front of every thing it get rid of the rubbish C:/users/example/...

and putting

cls

after the :top to clear the screen before it add the new date and time to the display

How do you plot bar charts in gnuplot?

I would just like to expand upon the top answer, which uses GNUPlot to create a bar graph, for absolute beginners because I read the answer and was still confused from the deluge of syntax.

We begin by writing a text file of GNUplot commands. Lets call it commands.txt:

set term png
set output "graph.png"
set boxwidth 0.5
set style fill solid
plot "data.dat" using 1:3:xtic(2) with boxes

set term png will set GNUplot to output a .png file and set output "graph.png" is the name of the file it will output to.

The next two lines are rather self explanatory. The fifth line contains a lot of syntax.

plot "data.dat" using 1:3:xtic(2) with boxes

"data.dat" is the data file we are operating on. 1:3 indicates we will be using column 1 of data.dat for the x-coordinates and column 3 of data.dat for the y-coordinates. xtic() is a function that is responsible for numbering/labeling the x-axis. xtic(2), therefore, indicates that we will be using column 2 of data.dat for labels.

"data.dat" looks like this:

0 label       100
1 label2      450
2 "bar label" 75

To plot the graph, enter gnuplot commands.txt in terminal.

pip installing in global site-packages instead of virtualenv

I had a similar problem on Windows. It was caused by renaming folder structures in my project within a virtualenv folder name. The paths in files didn't change but stayed as they were when virtual env was created. As Chase Ries mentioned I've changed the paths to VIRTUAL_ENV and python.exe in files

  1. ./venv/Scripts/activate.bat, set "VIRTUAL_ENV=path_to_venv\venv" 11 line in file
  2. ./venv/Scripts/Activate.ps1, $env:VIRTUAL_ENV="path_to_venv\venv" 30 line in file
  3. ./venv/Scripts/pip.exe, #!d:\path_to_env\venv\scripts\python.exe this line is at the end of a file, in my case moved to the right in 667 line, I am working on disc d so at the begining of the path is the letter of it
  4. ./venv/Scripts/pip3.7.exe, #!d:\path_to_env\venv\scripts\python.exe this line is at the end of a file, in my case moved to the right in 667 line
  5. ./venv/Scripts/pip3.exe, #!d:\path_to_env\venv\scripts\python.exe this line is at the end of a file, in my case moved to the right in 667 line

How can I see if a Perl hash already has a certain key?

You can just go with:

if(!$strings{$string}) ....

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

The generic answer provided by "Joel Coehoorn" is good.

But, this is another way without using those GetConverter... or try/catch blocks... (i'm not sure but this may have better performance in some cases):

public static class StrToNumberExtensions
{
    public static short ToShort(this string s, short defaultValue = 0) => short.TryParse(s, out var v) ? v : defaultValue;
    public static int ToInt(this string s, int defaultValue = 0) => int.TryParse(s, out var v) ? v : defaultValue;
    public static long ToLong(this string s, long defaultValue = 0) => long.TryParse(s, out var v) ? v : defaultValue;
    public static decimal ToDecimal(this string s, decimal defaultValue = 0) => decimal.TryParse(s, out var v) ? v : defaultValue;
    public static float ToFloat(this string s, float defaultValue = 0) => float.TryParse(s, out var v) ? v : defaultValue;
    public static double ToDouble(this string s, double defaultValue = 0) => double.TryParse(s, out var v) ? v : defaultValue;

    public static short? ToshortNullable(this string s, short? defaultValue = null) => short.TryParse(s, out var v) ? v : defaultValue;
    public static int? ToIntNullable(this string s, int? defaultValue = null) => int.TryParse(s, out var v) ? v : defaultValue;
    public static long? ToLongNullable(this string s, long? defaultValue = null) => long.TryParse(s, out var v) ? v : defaultValue;
    public static decimal? ToDecimalNullable(this string s, decimal? defaultValue = null) => decimal.TryParse(s, out var v) ? v : defaultValue;
    public static float? ToFloatNullable(this string s, float? defaultValue = null) => float.TryParse(s, out var v) ? v : defaultValue;
    public static double? ToDoubleNullable(this string s, double? defaultValue = null) => double.TryParse(s, out var v) ? v : defaultValue;
}

Usage is as following:

var x1 = "123".ToInt(); //123
var x2 = "abc".ToInt(); //0
var x3 = "abc".ToIntNullable(); // (int?)null 
int x4 = ((string)null).ToInt(-1); // -1
int x5 = "abc".ToInt(-1); // -1

var y = "19.50".ToDecimal(); //19.50

var z1 = "invalid number string".ToDoubleNullable(); // (double?)null
var z2 = "invalid number string".ToDoubleNullable(0); // (double?)0

duplicate 'row.names' are not allowed error

In my case was a comma at the end of every line. By removing that worked

Android Studio shortcuts like Eclipse

Not eclipse like you can do eclipse shot cuts just do the following

File ->Settings ->keymap -> in the drop down "KeyMaps" select  Eclipse ->
Apply ->ok.

Converting Select results into Insert script - SQL Server

Native method:

for example if you have table

Users(Id, name)

You can do this:

select 'insert into Table values(Id=' + Id + ', name=' + name + ')' from Users

Access parent URL from iframe

In chrome it is possible to use location.ancestorOrigins It will return all parent urls

Find if a String is present in an array

This can be done in java 8 using Stream.

import java.util.stream.Stream;

String[] stringList = {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};

boolean contains = Stream.of(stringList).anyMatch(x -> x.equals(say.getText());

Convert a string to an enum in C#

Use Enum.TryParse<T>(String, T) (= .NET 4.0):

StatusEnum myStatus;
Enum.TryParse("Active", out myStatus);

It can be simplified even further with C# 7.0's parameter type inlining:

Enum.TryParse("Active", out StatusEnum myStatus);

How to set timer in android?

I Abstract Timer away and made it a separate class:

Timer.java

import android.os.Handler;

public class Timer {

    IAction action;
    Handler timerHandler = new Handler();
    int delayMS = 1000;

    public Timer(IAction action, int delayMS) {
        this.action = action;
        this.delayMS = delayMS;
    }

    public Timer(IAction action) {
        this(action, 1000);
    }

    public Timer() {
        this(null);
    }

    Runnable timerRunnable = new Runnable() {

        @Override
        public void run() {
            if (action != null)
                action.Task();
            timerHandler.postDelayed(this, delayMS);
        }
    };

    public void start() {
        timerHandler.postDelayed(timerRunnable, 0);
    }

    public void stop() {
        timerHandler.removeCallbacks(timerRunnable);
    }
}

And Extract main action from Timer class out as

IAction.java

public interface IAction {
    void Task();
}

And I used it just like this:

MainActivity.java

public class MainActivity extends Activity implements IAction{
...
Timer timerClass;
@Override
protected void onCreate(Bundle savedInstanceState) {
        ...
        timerClass = new Timer(this,1000);
        timerClass.start();
        ...
}
...
int i = 1;
@Override
public void Task() {
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            timer.setText(i + "");
            i++;
        }
    });
}
...
}

I Hope This Helps

Printing all variables value from a class

Generic toString() one-liner, using reflection and style customization:

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
...
public String toString()
{
  return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}

DateTime.TryParseExact() rejecting valid formats

Here you can check for couple of things.

  1. Date formats you are using correctly. You can provide more than one format for DateTime.TryParseExact. Check the complete list of formats, available here.
  2. CultureInfo.InvariantCulture which is more likely add problem. So instead of passing a NULL value or setting it to CultureInfo provider = new CultureInfo("en-US"), you may write it like. .

    if (!DateTime.TryParseExact(txtStartDate.Text, formats, 
                    System.Globalization.CultureInfo.InvariantCulture,
                    System.Globalization.DateTimeStyles.None, out startDate))
    {
        //your condition fail code goes here
        return false;
    }
    else
    {
        //success code
    }
    

Could not find main class HelloWorld

It looks that you had done all setup properly but there might be one area where it might be causing problem

Check the value of your "CLASSPATH" variable and make sure at the end you kept ;.

Note: ; is for end separator . is for including existing path at the end

What does localhost:8080 mean?

http://localhost:8080/web: localhost ( hostname ) is the machine name or IP address of the host server e.g Glassfish, Tomcat. 8080 ( port ) is the address of the port on which the host server is listening for requests.

http://localhost/web: localhost ( hostname ) is the machine name or IP address of the host server e.g Glassfish, Tomcat. host server listening to default port 80.

Can we open pdf file using UIWebView on iOS?

Swift 4

     let webView = UIWebView(frame: view.bounds)
    let targetURL = Bundle.main.url(forResource: "sampleFileName", withExtension: "pdf")
    let request = URLRequest(url: targetURL!)
    webView.loadRequest(request)
    view.addSubview(webView)

Running PowerShell as another user, and launching a script

In windows server 2012 or 2016 you can search for Windows PowerShell and then "Pin to Start". After this you will see "Run as different user" option on a right click on the start page tiles.

Should 'using' directives be inside or outside the namespace?

One wrinkle I ran into (that isn't covered in other answers):

Suppose you have these namespaces:

  • Something.Other
  • Parent.Something.Other

When you use using Something.Other outside of a namespace Parent, it refers to the first one (Something.Other).

However if you use it inside of that namespace declaration, it refers to the second one (Parent.Something.Other)!

There is a simple solution: add the "global::" prefix: docs

namespace Parent
{
   using global::Something.Other;
   // etc
}

How can I disable the default console handler, while using the java logging API?

This is strange but Logger.getLogger("global") does not work in my setup (as well as Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)).

However Logger.getLogger("") does the job well.

Hope this info also helps somebody...

Write string to text file and ensure it always overwrites the existing content.

If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?

I'm assuming your using a streams here, there are other ways to write a file.

Labels for radio buttons in rails form

If you want the object_name prefixed to any ID you should call form helpers on the form object:

- form_for(@message) do |f|
  = f.label :email

This also makes sure any submitted data is stored in memory should there be any validation errors etc.

If you can't call the form helper method on the form object, for example if you're using a tag helper (radio_button_tag etc.) you can interpolate the name using:

= radio_button_tag "#{f.object_name}[email]", @message.email

In this case you'd need to specify the value manually to preserve any submissions.

How can I access an internal class from an external assembly?

Reflection.

using System.Reflection;

Vendor vendor = new Vendor();
object tag = vendor.Tag;

Type tagt = tag.GetType();
FieldInfo field = tagt.GetField("test");

string value = field.GetValue(tag);

Use the power wisely. Don't forget error checking. :)

CSS Child vs Descendant selectors

div > p matches ps that have a div parent - <div><p> in your question

div p matches ps that have a div ancestor (parent, grandparent, great grandparent, etc.) - <div><p> and <div><div><p> in your question

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

In addition to the link provided by Floremin, which clears text selection using JavaScript to "clear" the selection, you can also use pure CSS to accomplish this. The CSS is here...

.noSelect {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

Simply add the class="noSelect" attribute to the element you wish to apply this class to. I would highly recommend giving this CSS solution a try. Nothing wrong with using the JavaScript, I just believe this could potentially be easier, and clean things up a little bit in your code.

For chrome on android -webkit-tap-highlight-color: transparent; is an additional rule you may want to experiment with for support in Android.

Matplotlib discrete colorbar

The above answers are good, except they don't have proper tick placement on the colorbar. I like having the ticks in the middle of the color so that the number -> color mapping is more clear. You can solve this problem by changing the limits of the matshow call:

import matplotlib.pyplot as plt
import numpy as np

def discrete_matshow(data):
    #get discrete colormap
    cmap = plt.get_cmap('RdBu', np.max(data)-np.min(data)+1)
    # set limits .5 outside true range
    mat = plt.matshow(data,cmap=cmap,vmin = np.min(data)-.5, vmax = np.max(data)+.5)
    #tell the colorbar to tick at integers
    cax = plt.colorbar(mat, ticks=np.arange(np.min(data),np.max(data)+1))

#generate data
a=np.random.randint(1, 9, size=(10, 10))
discrete_matshow(a)

example of discrete colorbar

How to use the pass statement?

Honestly, I think the official Python docs describe it quite well and provide some examples:

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:

>>> while True: ... pass # Busy-wait for keyboard interrupt (Ctrl+C) ...

This is commonly used for creating minimal classes:

>>> class MyEmptyClass: ... pass ...

Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The pass is silently ignored:

>>> def initlog(*args): ... pass # Remember to implement this! ...

Get the ID of a drawable in ImageView

I think if I understand correctly this is what you are doing.

ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        ImageView imageView = (ImageView) view;
        assert(R.id.someImage == imageView.getId());

        switch(getDrawableId(imageView)) {
            case R.drawable.foo:
                imageView.setDrawableResource(R.drawable.bar);
                break;
            case R.drawable.bar:
            default:
                imageView.setDrawableResource(R.drawable.foo);
            break;
        }
    });

Right? So that function getDrawableId() doesn't exist. You can't get a the id that a drawable was instantiated from because the id is just a reference to the location of data on the device on how to construct a drawable. Once the drawable is constructed it doesn't have a way to get back the resourceId that was used to create it. But you could make it work something like this using tags

ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        ImageView imageView = (ImageView) view;
        assert(R.id.someImage == imageView.getId());

        // See here
        Integer integer = (Integer) imageView.getTag();
        integer = integer == null ? 0 : integer;

        switch(integer) {
        case R.drawable.foo:
            imageView.setDrawableResource(R.drawable.bar);
            imageView.setTag(R.drawable.bar);
            break;
        case R.drawable.bar:
        default:
            imageView.setDrawableResource(R.drawable.foo);
            imageView.setTag(R.drawable.foo);
            break;
        }
    });

VBA setting the formula for a cell

Try:

.Formula = "='" & strProjectName & "'!" & Cells(2, 7).Address

If your worksheet name (strProjectName) has spaces, you need to include the single quotes in the formula string.

If this does not resolve it, please provide more information about the specific error or failure.

Update

In comments you indicate you're replacing spaces with underscores. Perhaps you are doing something like:

strProjectName = Replace(strProjectName," ", "_")

But if you're not also pushing that change to the Worksheet.Name property, you can expect these to happen:

  1. The file browse dialog appears
  2. The formula returns #REF error

The reason for both is that you are passing a reference to a worksheet that doesn't exist, which is why you get the #REF error. The file dialog is an attempt to let you correct that reference, by pointing to a file wherein that sheet name does exist. When you cancel out, the #REF error is expected.

So you need to do:

Worksheets(strProjectName).Name = Replace(strProjectName," ", "_")
strProjectName = Replace(strProjectName," ", "_")

Then, your formula should work.

How to dispatch a Redux action with a timeout?

After trying the various popular approaches (action creators, thunks, sagas, epics, effects, custom middleware), I still felt that maybe there was room for improvement so I documented my journey in this blog article, Where do I put my business logic in a React/Redux application?

Much like the discussions here, I tried to contrast and compare the various approaches. Eventually it led me to introducing a new library redux-logic which takes inspiration from epics, sagas, custom middleware.

It allows you to intercept actions to validate, verify, authorize, as well as providing a way to perform async IO.

Some common functionality can simply be declared like debouncing, throttling, cancellation, and only using the response from the latest request (takeLatest). redux-logic wraps your code providing this functionality for you.

That frees you to implement your core business logic however you like. You don't have to use observables or generators unless you want to. Use functions and callbacks, promises, async functions (async/await), etc.

The code for doing a simple 5s notification would be something like:

_x000D_
_x000D_
const notificationHide = createLogic({_x000D_
  // the action type that will trigger this logic_x000D_
  type: 'NOTIFICATION_DISPLAY',_x000D_
  _x000D_
  // your business logic can be applied in several_x000D_
  // execution hooks: validate, transform, process_x000D_
  // We are defining our code in the process hook below_x000D_
  // so it runs after the action hit reducers, hide 5s later_x000D_
  process({ getState, action }, dispatch) {_x000D_
    setTimeout(() => {_x000D_
      dispatch({ type: 'NOTIFICATION_CLEAR' });_x000D_
    }, 5000);_x000D_
  }_x000D_
});_x000D_
    
_x000D_
_x000D_
_x000D_

I have a more advanced notification example in my repo that works similar to what Sebastian Lorber described where you could limit the display to N items and rotate through any that queued up. redux-logic notification example

I have a variety of redux-logic jsfiddle live examples as well as full examples. I'm continuing to work on docs and examples.

I'd love to hear your feedback.

How to remove leading whitespace from each line in a file

For what it's worth, if you are editing this file, you can probably highlight all the lines and use your un-tab button.

  • In Vim, use Shift + V to highlight the lines, then press <<
  • If you're on a Mac, then you can use Atom, Sublime Text, etc., then highlight with your mouse and then press Shift + Tab

I am not sure if there is some requirement that this must be done from the command line. If so, then :thumbs-up: to the accepted answer! =)

How to use timeit module

import timeit


def oct(x):
   return x*x


timeit.Timer("for x in range(100): oct(x)", "gc.enable()").timeit()

Make copy of an array

All solution that call length from array, add your code redundant null checkersconsider example:

int[] a = {1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();

//What if array a comes as local parameter? You need to use null check:

public void someMethod(int[] a) {
    if (a!=null) {
        int[] b = Arrays.copyOf(a, a.length);
        int[] c = a.clone();
    }
}

I recommend you not inventing the wheel and use utility class where all necessary checks have already performed. Consider ArrayUtils from apache commons. You code become shorter:

public void someMethod(int[] a) {
    int[] b = ArrayUtils.clone(a);
}

Apache commons you can find there

Listening for variable changes in JavaScript

As Luke Schafer's answer (note: this refers to his original post; but the whole point here remains valid after the edit), I would also suggest a pair of Get/Set methods to access your value.

However I would suggest some modifications (and that's why I'm posting...).

A problem with that code is that the field a of the object myobj is directly accessible, so it's possible to access it / change its value without triggering the listeners:

var myobj = { a : 5, get_a : function() { return this.a;}, set_a : function(val) { this.a = val; }}
/* add listeners ... */
myobj.a = 10; // no listeners called!

Encapsulation

So, to guarantee that the listeners are actually called, we would have to prohibit that direct access to the field a. How to do so? Use a closure!

var myobj = (function() { // Anonymous function to create scope.

    var a = 5;            // 'a' is local to this function
                          // and cannot be directly accessed from outside
                          // this anonymous function's scope

    return {
        get_a : function() { return a; },   // These functions are closures:
        set_a : function(val) { a = val; }  // they keep reference to
                                            // something ('a') that was on scope
                                            // where they were defined
    };
})();

Now you can use the same method to create and add the listeners as Luke proposed, but you can rest assured that there's no possible way to read from or write to a going unnoticed!

Adding encapsulated fields programmatically

Still on Luke's track, I propose now a simple way to add encapsulated fields and the respective getters/setters to objects by the means of a simple function call.

Note that this will only work properly with value types. For this to work with reference types, some kind of deep copy would have to be implemented (see this one, for instance).

function addProperty(obj, name, initial) {
    var field = initial;
    obj["get_" + name] = function() { return field; }
    obj["set_" + name] = function(val) { field = val; }
}

This works the same as before: we create a local variable on a function, and then we create a closure.

How to use it? Simple:

var myobj = {};
addProperty(myobj, "total", 0);
window.alert(myobj.get_total() == 0);
myobj.set_total(10);
window.alert(myobj.get_total() == 10);

Kill process by name?

psutil can find process by name and kill it:

import psutil

PROCNAME = "python.exe"

for proc in psutil.process_iter():
    # check whether the process name matches
    if proc.name() == PROCNAME:
        proc.kill()

Get User's Current Location / Coordinates

import Foundation
import CoreLocation

enum Result<T> {
  case success(T)
  case failure(Error)
}

final class LocationService: NSObject {
    private let manager: CLLocationManager

    init(manager: CLLocationManager = .init()) {
        self.manager = manager
        super.init()
        manager.delegate = self
    }

    var newLocation: ((Result<CLLocation>) -> Void)?
    var didChangeStatus: ((Bool) -> Void)?

    var status: CLAuthorizationStatus {
        return CLLocationManager.authorizationStatus()
    }

    func requestLocationAuthorization() {
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestWhenInUseAuthorization()
        if CLLocationManager.locationServicesEnabled() {
            manager.startUpdatingLocation()
            //locationManager.startUpdatingHeading()
        }
    }

    func getLocation() {
        manager.requestLocation()
    }

    deinit {
        manager.stopUpdatingLocation()
    }

}

 extension LocationService: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        newLocation?(.failure(error))
        manager.stopUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.sorted(by: {$0.timestamp > $1.timestamp}).first {
            newLocation?(.success(location))
        }
        manager.stopUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .notDetermined, .restricted, .denied:
            didChangeStatus?(false)
        default:
            didChangeStatus?(true)
        }
    }
}

Needs to write this code in required ViewController.

 //NOTE:: Add permission in info.plist::: NSLocationWhenInUseUsageDescription


let locationService = LocationService()

 @IBAction func action_AllowButtonTapped(_ sender: Any) {
     didTapAllow()
 }

 func didTapAllow() {
     locationService.requestLocationAuthorization()
 }

 func getCurrentLocationCoordinates(){
   locationService.newLocation = {result in
     switch result {
      case .success(let location):
      print(location.coordinate.latitude, location.coordinate.longitude)
      case .failure(let error):
      assertionFailure("Error getting the users location \(error)")
   }
  }
}

func getCurrentLocationCoordinates() {
    locationService.newLocation = { result in
        switch result {
        case .success(let location):
            print(location.coordinate.latitude, location.coordinate.longitude)
            CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
                if error != nil {
                    print("Reverse geocoder failed with error" + (error?.localizedDescription)!)
                    return
                }
                if (placemarks?.count)! > 0 {
                    print("placemarks", placemarks!)
                    let pmark = placemarks?[0]
                    self.displayLocationInfo(pmark)
                } else {
                    print("Problem with the data received from geocoder")
                }
            })
        case .failure(let error):
            assertionFailure("Error getting the users location \(error)")
        }
    }
}

How to convert a string of bytes into an int?

In Python 2.x, you could use the format specifiers <B for unsigned bytes, and <b for signed bytes with struct.unpack/struct.pack.

E.g:

Let x = '\xff\x10\x11'

data_ints = struct.unpack('<' + 'B'*len(x), x) # [255, 16, 17]

And:

data_bytes = struct.pack('<' + 'B'*len(data_ints), *data_ints) # '\xff\x10\x11'

That * is required!

See https://docs.python.org/2/library/struct.html#format-characters for a list of the format specifiers.

how to change text in Android TextView

@Zordid @Iambda answer is great, but I found that if I put

mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);

in the run() method and

mHandler.postDelayed(mUpdateUITimerTask, 0);

in the onCreate method make the thing keep updating.

How do I download a file from the internet to my linux server with Bash

You can use the command wget to download from command line. Specifically, you could use

wget http://download.oracle.com/otn-pub/java/jdk/7u10-b18/jdk-7u10-linux-x64.tar.gz

However because Oracle requires you to accept a license agreement this may not work (and I am currently unable to test it).

How do I reload a page without a POSTDATA warning in Javascript?

If you use GET method instead of POST then we can't the form filed values. If you use window.opener.location.href = window.opener.location.href; then we can fire the db and we can get the value but only thing is the JSP is not refreshing eventhough the scriplet having the form values.

How to resolve the C:\fakepath?

I am happy that browsers care to save us from intrusive scripts and the like. I am not happy with IE putting something into the browser that makes a simple style-fix look like a hack-attack!

I've used a < span > to represent the file-input so that I could apply appropriate styling to the < div > instead of the < input > (once again, because of IE). Now due to this IE want's to show the User a path with a value that's just guaranteed to put them on guard and in the very least apprehensive (if not totally scare them off?!)... MORE IE-CRAP!

Anyhow, thanks to to those who posted the explanation here: IE Browser Security: Appending "fakepath" to file path in input[type="file"], I've put together a minor fixer-upper...

The code below does two things - it fixes a lte IE8 bug where the onChange event doesn't fire until the upload field's onBlur and it updates an element with a cleaned filepath that won't scare the User.

// self-calling lambda to for jQuery shorthand "$" namespace
(function($){
    // document onReady wrapper
    $().ready(function(){
        // check for the nefarious IE
        if($.browser.msie) {
            // capture the file input fields
            var fileInput = $('input[type="file"]');
            // add presentational <span> tags "underneath" all file input fields for styling
            fileInput.after(
                $(document.createElement('span')).addClass('file-underlay')
            );
            // bind onClick to get the file-path and update the style <div>
            fileInput.click(function(){
                // need to capture $(this) because setTimeout() is on the
                // Window keyword 'this' changes context in it
                var fileContext = $(this);
                // capture the timer as well as set setTimeout()
                // we use setTimeout() because IE pauses timers when a file dialog opens
                // in this manner we give ourselves a "pseudo-onChange" handler
                var ieBugTimeout = setTimeout(function(){
                    // set vars
                    var filePath     = fileContext.val(),
                        fileUnderlay = fileContext.siblings('.file-underlay');
                    // check for IE's lovely security speil
                    if(filePath.match(/fakepath/)) {
                        // update the file-path text using case-insensitive regex
                        filePath = filePath.replace(/C:\\fakepath\\/i, '');
                    }
                    // update the text in the file-underlay <span>
                    fileUnderlay.text(filePath);
                    // clear the timer var
                    clearTimeout(ieBugTimeout);
                }, 10);
            });
        }
    });
})(jQuery);

What is the difference between pip and conda?

Here is a short rundown:

pip

  • Python packages only.
  • Compiles everything from source. EDIT: pip now installs binary wheels, if they are available.
  • Blessed by the core Python community (i.e., Python 3.4+ includes code that automatically bootstraps pip).

conda

  • Python agnostic. The main focus of existing packages are for Python, and indeed Conda itself is written in Python, but you can also have Conda packages for C libraries, or R packages, or really anything.
  • Installs binaries. There is a tool called conda build that builds packages from source, but conda install itself installs things from already built Conda packages.
  • External. Conda is the package manager of Anaconda, the Python distribution provided by Continuum Analytics, but it can be used outside of Anaconda too. You can use it with an existing Python installation by pip installing it (though this is not recommended unless you have a good reason to use an existing installation).

In both cases:

  • Written in Python
  • Open source (Conda is BSD and pip is MIT)

The first two bullet points of Conda are really what make it advantageous over pip for many packages. Since pip installs from source, it can be painful to install things with it if you are unable to compile the source code (this is especially true on Windows, but it can even be true on Linux if the packages have some difficult C or FORTRAN library dependencies). Conda installs from binary, meaning that someone (e.g., Continuum) has already done the hard work of compiling the package, and so the installation is easy.

There are also some differences if you are interested in building your own packages. For instance, pip is built on top of setuptools, whereas Conda uses its own format, which has some advantages (like being static, and again, Python agnostic).

Format date and time in a Windows batch script

This bat file (save as datetimestr.bat) produces the datetime string 3 times: (1) long datetime string with day of week and seconds, (2) short datetime string without them and (3) short version of the code.

@echo off
REM "%date: =0%" replaces spaces with zeros
set d=%date: =0%
REM "set yyyy=%d:~-4%" pulls the last 4 characters
set yyyy=%d:~-4%
set mm=%d:~4,2%
set dd=%d:~7,2%
set dow=%d:~0,3%
set d=%yyyy%-%mm%-%dd%_%dow%

set t=%TIME: =0%
REM "%t::=%" removes semi-colons
REM Instead of above, you could use "%t::=-%" to 
REM replace semi-colons with hyphens (or any 
REM non-special character)
set t=%t::=%
set t=%t:.=%

set datetimestr=%d%_%t%
@echo  Long date time str = %datetimestr%

set d=%d:~0,10%
set t=%t:~0,4%
set datetimestr=%d%_%t%
@echo Short date time str = %datetimestr%


@REM Short version of the code above
set d=%date: =0%
set t=%TIME: =0%
set datetimestr=%d:~-4%-%d:~4,2%-%d:~7,2%_%d:~0,3%_%t:~0,2%%t:~3,2%%t:~6,2%%t:~9,2%
@echo Datetimestr = %datetimestr%

pause

To give proper credit, I merged the concepts from Peter Mortensen (Jun 18 '14 at 21:02) and opello (Aug 25 '11 at 14:27).

You can write this much shorter, but this long version makes reading and understanding the code easy.

Left-pad printf with spaces

If you want exactly 40 spaces before the string then you should just do:

printf("                                        %s\n", myStr );

If that is too dirty, you can do (but it will be slower than manually typing the 40 spaces): printf("%40s%s", "", myStr );

If you want the string to be lined up at column 40 (that is, have up to 39 spaces proceeding it such that the right most character is in column 40) then do this: printf("%40s", myStr);

You can also put "up to" 40 spaces AfTER the string by doing: printf("%-40s", myStr);

BULK INSERT with identity (auto-increment) column

I had this exact same problem which made loss hours so i'm inspired to share my findings and solutions that worked for me.

1. Use an excel file

This is the approach I adopted. Instead of using a csv file, I used an excel file (.xlsx) with content like below.

id  username   email                token website

    johndoe   [email protected]        divostar.com
    bobstone  [email protected]        divosays.com

Notice that the id column has no value.

Next, connect to your DB using Microsoft SQL Server Management Studio and right click on your database and select import data (submenu under task). Select Microsoft Excel as source. When you arrive at the stage called "Select Source Tables and Views", click edit mappings. For id column under destination, click on it and select ignore . Don't check Enable Identity insert unless you want to mantain ids incases where you are importing data from another database and would like to maintain the auto increment id of the source db. Proceed to finish and that's it. Your data will be imported smoothly.

2. Using CSV file

In your csv file, make sure your data is like below.

id,username,email,token,website
,johndoe,[email protected],,divostar.com
,bobstone,[email protected],,divosays.com

Run the query below:

BULK INSERT Metrics FROM 'D:\Data Management\Data\CSV2\Production Data 2004 - 2016.csv '
WITH (FIRSTROW = 2, FIELDTERMINATOR = ',', ROWTERMINATOR = '\n');

The problem with this approach is that the CSV should be in the DB server or some shared folder that the DB can have access to otherwise you may get error like "Cannot opened file. The operating system returned error code 21 (The device is not ready)".

If you are connecting to a remote database, then you can upload your CSV to a directory on that server and reference the path in bulk insert.

3. Using CSV file and Microsoft SQL Server Management Studio import option

Launch your import data like in the first approach. For source, select Flat file Source and browse for your CSV file. Make sure the right menu (General, Columns, Advanced, Preview) are ok. Make sure to set the right delimiter under columns menu (Column delimiter). Just like in the excel approach above, click edit mappings. For id column under destination, click on it and select ignore .

Proceed to finish and that's it. Your data will be imported smoothly.

JavaScript alert not working in Android WebView

The following code will work:

private WebView mWebView;
final Activity activity = this;

// private Button b;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            activity.setProgress(progress * 1000);
        }
    });

    mWebView.loadUrl("file:///android_asset/raw/NewFile1.html");
}

How to run a Runnable thread in Android at defined intervals?

An interesting example is you can continuously see a counter/stop-watch running in separate thread. Also showing GPS-Location. While main activity User Interface Thread is already there.

Excerpt:

try {    
    cnt++; scnt++;
    now=System.currentTimeMillis();
    r=rand.nextInt(6); r++;    
    loc=lm.getLastKnownLocation(best);    

    if(loc!=null) { 
        lat=loc.getLatitude();
        lng=loc.getLongitude(); 
    }    

    Thread.sleep(100); 
    handler.sendMessage(handler.obtainMessage());
} catch (InterruptedException e) {   
    Toast.makeText(this, "Error="+e.toString(), Toast.LENGTH_LONG).show();
}

To look at code see here:

Thread example displaying GPS Location and Current Time runnable alongside main-activity's User Interface Thread

How to enable MySQL Query Log?

To enable the query log in MAC Machine:

Open the following file:

vi /private/etc/my.cnf

Set the query log url under 'mysqld' section as follows:

[mysqld]

general_log_file=/Users/kumanan/Documents/mysql_query.log

Few machine’s are not logging query properly, So that case you can enable it from MySQL console

mysql> SET global general_log = 1;

How can I parse a YAML file in Python

To access any element of a list in a YAML file like this:

global:
  registry:
    url: dtr-:5000/
    repoPath:
  dbConnectionString: jdbc:oracle:thin:@x.x.x.x:1521:abcd

You can use following python script:

import yaml

with open("/some/path/to/yaml.file", 'r') as f:
    valuesYaml = yaml.load(f, Loader=yaml.FullLoader)

print(valuesYaml['global']['dbConnectionString'])

how to change listen port from default 7001 to something different?

If you still get the exception in the server startup after changing listen port, you should try changing Pointbase server port and debug port in setDomainEnv.cmd

How to start rails server?

In a Rails 2.3 app it is just ./script/server start

How to generate UML diagrams (especially sequence diagrams) from Java code?

What is your codebase? Java or C++?

alt text

eUML2 for Java is a powerful UML modeler designed for Java developper in Eclipse. The free edition can be used for commercial use. It supports the following features:

  • CVS and Team Support
  • Designed for large project with multiple and customizable model views
  • Helios Compliant
  • Real-time code/model synchronization
  • UML2.1 compliant and support of OMG XMI
  • JDK 1.4 and 1.5 support
  • The commercial edition provides:

  • Advanced reversed engineering

  • Powerful true dependency analyze tools
  • UML Profile and MDD
  • Database tools
  • Customizable template support

Get IP address of visitors using Flask for Python

httpbin.org uses this method:

return jsonify(origin=request.headers.get('X-Forwarded-For', request.remote_addr))

Stacking DIVs on top of each other?

All the answers seem pretty old :) I'd prefer CSS grid for a better page layout (absolute divs can be overridden by other divs in the page.)

<div class="container">
  <div class="inner" style="background-color: white;"></div>
  <div class="inner" style="background-color: red;"></div>
  <div class="inner" style="background-color: green;"></div>
  <div class="inner" style="background-color: blue;"></div>
  <div class="inner" style="background-color: purple;"></div>
  <div class="inner no-display" style="background-color: black;"></div>
</div>

<style>
.container {
  width: 300px;
  height: 300px;
  margin: 0 auto;
  background-color: yellow;
  display: grid;
  place-items: center;
  grid-template-areas:
                  "inners";
}

.inner {
  grid-area: inners;
  height: 100px;
  width: 100px;
}

.no-display {
  display: none;
}
</style>

Here's a working link

How to run an android app in background?

As apps run in the background anyway. I’m assuming what your really asking is how do you make apps do stuff in the background. The solution below will make your app do stuff in the background after opening the app and after the system has rebooted.

Below, I’ve added a link to a fully working example (in the form of an Android Studio Project)

This subject seems to be out of the scope of the Android docs, and there doesn’t seem to be any one comprehensive doc on this. The information is spread across a few docs.

The following docs tell you indirectly how to do this: https://developer.android.com/reference/android/app/Service.html

https://developer.android.com/reference/android/content/BroadcastReceiver.html

https://developer.android.com/guide/components/bound-services.html

In the interests of getting your usage requirements correct, the important part of this above doc to read carefully is: #Binder, #Messenger and the components link below:

https://developer.android.com/guide/components/aidl.html

Here is the link to a fully working example (in Android Studio format): http://developersfound.com/BackgroundServiceDemo.zip

This project will start an Activity which binds to a service; implementing the AIDL.

This project is also useful to re-factor for the purpose of IPC across different apps.

This project is also developed to start automatically when Android restarts (provided the app has been run at least one after installation and app is not installed on SD card)

When this app/project runs after reboot, it dynamically uses a transparent view to make it look like no app has started but the service of the associated app starts cleanly.

This code is written in such a way that it’s very easy to tweak to simulate a scheduled service.

This project is developed in accordance to the above docs and is subsequently a clean solution.

There is however a part of this project which is not clean being: I have not found a way to start a service on reboot without using an Activity. If any of you guys reading this post have a clean way to do this please post a comment.

Listen for key press in .NET console app

You can change your approach slightly - use Console.ReadKey() to stop your app, but do your work in a background thread:

static void Main(string[] args)
{
    var myWorker = new MyWorker();
    myWorker.DoStuff();
    Console.WriteLine("Press any key to stop...");
    Console.ReadKey();
}

In the myWorker.DoStuff() function you would then invoke another function on a background thread (using Action<>() or Func<>() is an easy way to do it), then immediately return.

Floating point exception( core dump

Floating Point Exception happens because of an unexpected infinity or NaN. You can track that using gdb, which allows you to see what is going on inside your C program while it runs. For more details: https://www.cs.swarthmore.edu/~newhall/unixhelp/howto_gdb.php

In a nutshell, these commands might be useful...

gcc -g myprog.c

gdb a.out

gdb core a.out

ddd a.out

What is the easiest way to clear a database from the CLI with manage.py in Django?

If you don't care about data:

Best way would be to drop the database and run syncdb again. Or you can run:

For Django >= 1.5

python manage.py flush

For Django < 1.5

python manage.py reset appname

(you can add --no-input to the end of the command for it to skip the interactive prompt.)

If you do care about data:

From the docs:

syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.

If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes.

https://docs.djangoproject.com/en/dev/ref/django-admin/

Reference: FAQ - https://docs.djangoproject.com/en/dev/faq/models/#if-i-make-changes-to-a-model-how-do-i-update-the-database

People also recommend South ( http://south.aeracode.org/docs/about.html#key-features ), but I haven't tried it.

Search for all occurrences of a string in a mysql database

Scott gives a good example of how to do it, but the question is why would you want to? If you need to do a find-and-replace on a specific string, you could also try doing a mysqldump of your database, do a find-and-replace in an editor, then re-load the database.

Maybe if you gave some background on what you are trying to achieve, others might be able to provide better answers.

Microsoft Web API: How do you do a Server.MapPath?

I can't tell from the context you supply, but if it's something you just need to do at app startup, you can still use Server.MapPath in WebApiHttpApplication; e.g. in Application_Start().

I'm just answering your direct question; the already-mentioned HostingEnvironment.MapPath() is probably the preferred solution.

.htaccess 301 redirect of single page

You could also use a RewriteRule if you wanted the ability to template match and redirect urls.

Function to close the window in Tkinter

def quit(self):
    self.root.destroy()

Add parentheses after destroy to call the method.

When you use command=self.root.destroy you pass the method to Tkinter.Button without the parentheses because you want Tkinter.Button to store the method for future calling, not to call it immediately when the button is created.

But when you define the quit method, you need to call self.root.destroy() in the body of the method because by then the method has been called.

'foo' was not declared in this scope c++

In general, in C++ functions have to be declared before you call them. So sometime before the definition of getSkewNormal(), the compiler needs to see the declaration:

double integrate (double start, double stop, int numSteps, Evaluatable evalObj);

Mostly what people do is put all the declarations (only) in the header file, and put the actual code -- the definitions of the functions and methods -- into a separate source (*.cc or *.cpp) file. This neatly solves the problem of needing all the functions to be declared.

Check whether user has a Chrome extension installed

There's another method shown at this Google Groups post. In short, you could try detecting whether the extension icon loads successfully. This may be helpful if the extension you're checking for isn't your own.

ImportError: No module named psycopg2

check correctly if you had ON your virtual env of your peoject, if it's OFF then make it ON. execute following cammands:

workon <your_env_name>
python manage.py runserver

It's working for me

In SQL, is UPDATE always faster than DELETE+INSERT?

Just tried updating 43 fields on a table with 44 fields, the remaining field was the primary clustered key.

The update took 8 seconds.

A Delete + Insert is faster than the minimum time interval that the "Client Statistics" reports via SQL Management Studio.

Peter

MS SQL 2008

Purpose of a constructor in Java?

Let us consider we are storing the student details of 3 students. These 3 students are having different values for sno, sname and sage, but all 3 students belongs to same department CSE. So it is better to initialize "dept" variable inside a constructor so that this value can be taken by all the 3 student objects.

To understand clearly, see the below simple example:

class Student
{
    int sno,sage;
    String sname,dept;
    Student()
    {
        dept="CSE";
    }
    public static void main(String a[])
    {
        Student s1=new Student();
        s1.sno=101;
        s1.sage=33;
        s1.sname="John";

        Student s2=new Student();
        s2.sno=102;
        s2.sage=99;
        s2.sname="Peter";


        Student s3=new Student();
        s3.sno=102;
        s3.sage=99;
        s3.sname="Peter";
        System.out.println("The details of student1 are");
        System.out.println("The student no is:"+s1.sno);
        System.out.println("The student age is:"+s1.sage);
        System.out.println("The student name is:"+s1.sname);
        System.out.println("The student dept is:"+s1.dept);


        System.out.println("The details of student2 are");`enter code here`
        System.out.println("The student no is:"+s2.sno);
        System.out.println("The student age is:"+s2.sage);
        System.out.println("The student name is:"+s2.sname);
        System.out.println("The student dept is:"+s2.dept);

        System.out.println("The details of student2 are");
        System.out.println("The student no is:"+s3.sno);
        System.out.println("The student age is:"+s3.sage);
        System.out.println("The student name is:"+s3.sname);
        System.out.println("The student dept is:"+s3.dept);
    }
}

Output:

The details of student1 are
The student no is:101
The student age is:33
The student name is:John
The student dept is:CSE
The details of student2 are
The student no is:102
The student age is:99
The student name is:Peter
The student dept is:CSE
The details of student2 are
The student no is:102
The student age is:99
The student name is:Peter
The student dept is:CSE

What is a serialVersionUID and why should I use it?

What is SerialVersionUID? Answer : - Lets say there are two persons, one from HQ and another from ODC, both are going to perform serialization and deserialization respectively. In this case to authenticate that the receiver who is in ODC is the authenticated person, JVM creates a Unique ID which is known as SerialVersionUID.

Here is a nice explanation based on the scenario,

Why SerialVersionUID?

Serialization : At the time of serialization, with every object sender side JVM will save a Unique Identifier. JVM is responsible to generate that unique ID based on the corresponding .class file which is present in the sender system.

Deserialization: At the time of deserialization, receiver side JVM will compare the unique ID associated with the Object with local class Unique ID i.e. JVM will also create a Unique ID based on the corresponding .class file which is present in the receiver system. If both unique ID matched then only deserialization will be performed. Otherwise we will get Runtime Exception saying InvalidClassException. This unique Identifier is nothing but SerialVersionUID

What does enctype='multipart/form-data' mean?

  • enctype(ENCode TYPE) attribute specifies how the form-data should be encoded when submitting it to the server.
  • multipart/form-data is one of the value of enctype attribute, which is used in form element that have a file upload. multi-part means form data divides into multiple parts and send to server.

Fast way to discover the row count of a table in PostgreSQL

You can get the count by the below query (without * or any column names).

select from table_name;

Is null reference possible?

Yes:

#include <iostream>
#include <functional>

struct null_ref_t {
   template <typename T>
   operator T&() {
      union TypeSafetyBreaker {
         T *ptr;

         // see https://stackoverflow.com/questions/38691282/use-of-union-with-reference
         std::reference_wrapper<T> ref; 
      };

      TypeSafetyBreaker ptr = {.ptr = nullptr};

      // unwrap the reference
      return ptr.ref.get();
   }
};

null_ref_t nullref;


int main() {
   int &a = nullref;

   // Segmentation fault
   a = 4;
   return 0;
}

Open Facebook page from Android app?

Declare constants

  private String FACEBOOK_URL="https://www.facebook.com/approids";
    private String FACEBOOK_PAGE_ID="approids";

Declare Method

public String getFacebookPageURL(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;

            boolean activated =  packageManager.getApplicationInfo("com.facebook.katana", 0).enabled;
            if(activated){
                if ((versionCode >= 3002850)) {
                    Log.d("main","fb first url");
                    return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
                } else {
                    return "fb://page/" + FACEBOOK_PAGE_ID;
                }
            }else{
                return FACEBOOK_URL;
            }
        } catch (PackageManager.NameNotFoundException e) {
            return FACEBOOK_URL;
        }
    }

Call Function

Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
                String facebookUrl = getFacebookPageURL(MainActivity.this);
                facebookIntent.setData(Uri.parse(facebookUrl));
                startActivity(facebookIntent);

Getting output of system() calls in Ruby

I'd like to expand & clarify chaos's answer a bit.

If you surround your command with backticks, then you don't need to (explicitly) call system() at all. The backticks execute the command and return the output as a string. You can then assign the value to a variable like so:

output = `ls`
p output

or

printf output # escapes newline chars

How can I know if a process is running?

reshefm had a pretty nice answer; however, it does not account for a situation in which the process was never started to begin with.

Here is a a modified version of what he posted.

    public static bool IsRunning(this Process process)
    {
        try  {Process.GetProcessById(process.Id);}
        catch (InvalidOperationException) { return false; }
        catch (ArgumentException){return false;}
        return true;
    }

I removed his ArgumentNullException because its actually suppose to be a null reference exception and it gets thrown by the system anyway and I also accounted for the situation in which the process was never started to begin with or the close() method was used to close the process.

Convert Python dictionary to JSON array

If you are fine with non-printable symbols in your json, then add ensure_ascii=False to dumps call.

>>> json.dumps(your_data, ensure_ascii=False)

If ensure_ascii is false, then the return value will be a unicode instance subject to normal Python str to unicode coercion rules instead of being escaped to an ASCII str.

Android studio Gradle icon error, Manifest Merger

If nothing of that work, close Android Studio. Go on app/src/main, open the file AndroidManifest.xml in a text editor (like sublime), remove/replace the erros lines, save and reopen android studio.

How do I create directory if it doesn't exist to create a file?

You can use following code

  DirectoryInfo di = Directory.CreateDirectory(path);

Best way to specify whitespace in a String.Split operation

If repeating the same code is the issue, write an extension method on the String class that encapsulates the splitting logic.

How would I check a string for a certain letter in Python?

Use the in keyword without is.

if "x" in dog:
    print "Yes!"

If you'd like to check for the non-existence of a character, use not in:

if "x" not in dog:
    print "No!"

git checkout all the files

If you want to checkout all the files 'anywhere'

git checkout -- $(git rev-parse --show-toplevel)

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

In C++ the finally is NOT required because of RAII.

RAII moves the responsibility of exception safety from the user of the object to the designer (and implementer) of the object. I would argue this is the correct place as you then only need to get exception safety correct once (in the design/implementation). By using finally you need to get exception safety correct every time you use an object.

Also IMO the code looks neater (see below).

Example:

A database object. To make sure the DB connection is used it must be opened and closed. By using RAII this can be done in the constructor/destructor.

C++ Like RAII

void someFunc()
{
    DB    db("DBDesciptionString");
    // Use the db object.

} // db goes out of scope and destructor closes the connection.
  // This happens even in the presence of exceptions.

The use of RAII makes using a DB object correctly very easy. The DB object will correctly close itself by the use of a destructor no matter how we try and abuse it.

Java Like Finally

void someFunc()
{
    DB      db = new DB("DBDesciptionString");
    try
    {
        // Use the db object.
    }
    finally
    {
        // Can not rely on finaliser.
        // So we must explicitly close the connection.
        try
        {
            db.close();
        }
        catch(Throwable e)
        {
           /* Ignore */
           // Make sure not to throw exception if one is already propagating.
        }
    }
}

When using finally the correct use of the object is delegated to the user of the object. i.e. It is the responsibility of the object user to correctly to explicitly close the DB connection. Now you could argue that this can be done in the finaliser, but resources may have limited availability or other constraints and thus you generally do want to control the release of the object and not rely on the non deterministic behavior of the garbage collector.

Also this is a simple example.
When you have multiple resources that need to be released the code can get complicated.

A more detailed analysis can be found here: http://accu.org/index.php/journals/236

String Pattern Matching In Java

If you want to check if some string is present in another string, use something like String.contains

If you want to check if some pattern is present in a string, append and prepend the pattern with '.*'. The result will accept strings that contain the pattern.

Example: Suppose you have some regex a(b|c) that checks if a string matches ab or ac
.*(a(b|c)).* will check if a string contains a ab or ac.

A disadvantage of this method is that it will not give you the location of the match.

Can't find how to use HttpContent

Just use...

var stringContent = new StringContent(jObject.ToString());
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);

Or,

var stringContent = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);

Change DataGrid cell colour based on values

If you need to do it with a set number of columns, H.B.'s way is best. But if you don't know how many columns you are dealing with until runtime, then the below code [read: hack] will work. I am not sure if there is a better solution with an unknown number of columns. It took me two days working at it off and on to get it, so I'm sticking with it regardless.

C#

public class ValueToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int input;
        try
        {
            DataGridCell dgc = (DataGridCell)value;
            System.Data.DataRowView rowView = (System.Data.DataRowView)dgc.DataContext;
            input = (int)rowView.Row.ItemArray[dgc.Column.DisplayIndex];
        }
        catch (InvalidCastException e)
        {
            return DependencyProperty.UnsetValue;
        }
        switch (input)
        {
            case 1: return Brushes.Red;
            case 2: return Brushes.White;
            case 3: return Brushes.Blue;
            default: return DependencyProperty.UnsetValue;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

XAML

<UserControl.Resources>
    <conv:ValueToBrushConverter x:Key="ValueToBrushConverter"/>
    <Style x:Key="CellStyle" TargetType="DataGridCell">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self}, Converter={StaticResource ValueToBrushConverter}}" />
    </Style>
</UserControl.Resources>
<DataGrid x:Name="dataGrid" CellStyle="{StaticResource CellStyle}">
</DataGrid>

rbind error: "names do not match previous names"

easy enough to use the unname() function:

data.frame <- unname(data.frame)