Programs & Examples On #Gitosis

Gitosis is software to manage a collection of Git repositories on a server accessible by SSH, without creating local accounts for the users. It has not been updated since 2009. Gitolite is an actively developed alternative with a richer feature set. Use this tag for help with Gitosis installation and usage.

git push says "everything up-to-date" even though I have local changes

Another possibility is that you have commits that don't affect the directory you're pushing. So in my case I had a structure like

- .git
- README.md
- client/
 - package.json
 - example.js
- api/
 - requirements.txt
 - example.py

And I made a commit to master modifying README.md, then ran git subtree push --prefix client heroku-client master and got the message Everything up-to-date

How do I find Waldo with Mathematica?

I agree with @GregoryKlopper that the right way to solve the general problem of finding Waldo (or any object of interest) in an arbitrary image would be to train a supervised machine learning classifier. Using many positive and negative labeled examples, an algorithm such as Support Vector Machine, Boosted Decision Stump or Boltzmann Machine could likely be trained to achieve high accuracy on this problem. Mathematica even includes these algorithms in its Machine Learning Framework.

The two challenges with training a Waldo classifier would be:

  1. Determining the right image feature transform. This is where @Heike's answer would be useful: a red filter and a stripped pattern detector (e.g., wavelet or DCT decomposition) would be a good way to turn raw pixels into a format that the classification algorithm could learn from. A block-based decomposition that assesses all subsections of the image would also be required ... but this is made easier by the fact that Waldo is a) always roughly the same size and b) always present exactly once in each image.
  2. Obtaining enough training examples. SVMs work best with at least 100 examples of each class. Commercial applications of boosting (e.g., the face-focusing in digital cameras) are trained on millions of positive and negative examples.

A quick Google image search turns up some good data -- I'm going to have a go at collecting some training examples and coding this up right now!

However, even a machine learning approach (or the rule-based approach suggested by @iND) will struggle for an image like the Land of Waldos!

When should I use a struct rather than a class in C#?

Structure types in C# or other .net languages are generally used to hold things that should behave like fixed-sized groups of values. A useful aspect of structure types is that the fields of a structure-type instance can be modified by modifying the storage location in which it is held, and in no other way. It's possible to code a structure in such a way that the only way to mutate any field is to construct a whole new instance and then use a struct assignment to mutate all the fields of the target by overwriting them with values from the new instance, but unless a struct provides no means of creating an instance where its fields have non-default values, all of its fields will be mutable if and if the struct itself is stored in a mutable location.

Note that it's possible to design a structure type so that it will essentially behave like a class type, if the structure contains a private class-type field, and redirects its own members to that of the wrapped class object. For example, a PersonCollection might offer properties SortedByName and SortedById, both of which hold an "immutable" reference to a PersonCollection (set in their constructor) and implement GetEnumerator by calling either creator.GetNameSortedEnumerator or creator.GetIdSortedEnumerator. Such structs would behave much like a reference to a PersonCollection, except that their GetEnumerator methods would be bound to different methods in the PersonCollection. One could also have a structure wrap a portion of an array (e.g. one could define an ArrayRange<T> structure which would hold a T[] called Arr, an int Offset, and an int Length, with an indexed property which, for an index idx in the range 0 to Length-1, would access Arr[idx+Offset]). Unfortunately, if foo is a read-only instance of such a structure, current compiler versions won't allow operations like foo[3]+=4; because they have no way to determine whether such operations would attempt to write to fields of foo.

It's also possible to design a structure to behave a like a value type which holds a variable-sized collection (which will appear to be copied whenever the struct is) but the only way to make that work is to ensure that no object to which the struct holds a reference will ever be exposed to anything which might mutate it. For example, one could have an array-like struct which holds a private array, and whose indexed "put" method creates a new array whose content is like that of the original except for one changed element. Unfortunately, it can be somewhat difficult to make such structs perform efficiently. While there are times that struct semantics can be convenient (e.g. being able to pass an array-like collection to a routine, with the caller and callee both knowing that outside code won't modify the collection, may be better than requiring both caller and callee to defensively copy any data they're given), the requirement that class references point to objects that will never be mutated is often a pretty severe constraint.

How do I determine the current operating system with Node.js

You are looking for the OS native module for Node.js:

v4: https://nodejs.org/dist/latest-v4.x/docs/api/os.html#os_os_platform

or v5 : https://nodejs.org/dist/latest-v5.x/docs/api/os.html#os_os_platform

os.platform()

Returns the operating system platform. Possible values are 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'. Returns the value of process.platform.

OrderBy pipe issue

Please see https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe for the full discussion. This quote is most relevant. Basically, for large scale apps that should be minified aggressively the filtering and sorting logic should move to the component itself.

"Some of us may not care to minify this aggressively. That's our choice. But the Angular product should not prevent someone else from minifying aggressively. Therefore, the Angular team decided that everything shipped in Angular will minify safely.

The Angular team and many experienced Angular developers strongly recommend that you move filtering and sorting logic into the component itself. The component can expose a filteredHeroes or sortedHeroes property and take control over when and how often to execute the supporting logic. Any capabilities that you would have put in a pipe and shared across the app can be written in a filtering/sorting service and injected into the component."

How set the android:gravity to TextView from Java side in Android

textView.setGravity(Gravity.CENTER | Gravity.BOTTOM);

This will set gravity of your textview.

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

You can install the Active Directory snap-in with Powershell on Windows Server 2012 using the following command:

Install-windowsfeature -name AD-Domain-Services –IncludeManagementTools

This helped me when I had problems with the Features screen due to AppFabric and Windows Update errors.

What does %s mean in a python format string?

%s indicates a conversion type of string when using python's string formatting capabilities. More specifically, %s converts a specified value to a string using the str() function. Compare this with the %r conversion type that uses the repr() function for value conversion.

Take a look at the docs for string formatting.

hibernate: LazyInitializationException: could not initialize proxy

By default, all one-to-many and many-to-many associations are fetched lazily upon being accessed for the first time.

In your use case, you could overcome this issue by wrapping all DAO operations into one logical transaction:

transactionTemplate.execute(new TransactionCallback<Void>() {
    @Override
    public Void doInTransaction(TransactionStatus transactionStatus) {

        int startingCount = sfdao.count();

        sfdao.create( sf );

        SecurityFiling sf2 = sfdao.read( sf.getId() );

        sfdao.delete( sf );

        int endingCount = sfdao.count();

        assertTrue( startingCount == endingCount );
        assertTrue( sf.getId().longValue() == sf2.getId().longValue() );
        assertTrue( sf.getSfSubmissionType().equals( sf2.getSfSubmissionType() ) );
        assertTrue( sf.getSfTransactionNumber().equals( sf2.getSfTransactionNumber() ) );

        return null;
    }
});

Another option is to fetch all LAZY associations upon loading your entity, so that:

SecurityFiling sf2 = sfdao.read( sf.getId() );

should fetch the LAZY submissionType too:

select sf
from SecurityFiling sf
left join fetch.sf.submissionType

This way, you eagerly fetch all lazy properties and you can access them after the Session gets closed too.

You can fetch as many [one|many]-to-one associations and one "[one|many]-to-many" List associations (because of running a Cartesian Product).

To initialize multiple "[one|many]-to-many", you should use Hibernate.initialize(collection), right after loading your root entity.

Purpose of Unions in C and C++

@bobobobo code is correct as @Joshua pointed out (sadly I'm not allowed to add comments, so doing it here, IMO bad decision to disallow it in first place):

https://en.cppreference.com/w/cpp/language/data_members#Standard_layout tells that it is fine to do so, at least since C++14

In a standard-layout union with an active member of non-union class type T1, it is permitted to read a non-static data member m of another union member of non-union class type T2 provided m is part of the common initial sequence of T1 and T2 (except that reading a volatile member through non-volatile glvalue is undefined).

since in the current case T1 and T2 donate the same type anyway.

Download TS files from video stream

Easy youtube-dl example on macOS (in the command line Terminal; Windows supported too):

# List variants (resolutions/bitrates)
$ youtube-dl -F https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8
[generic] f08e80da-bf1d-4e3d-8899-f0f6155f6efa: Requesting header
[generic] f08e80da-bf1d-4e3d-8899-f0f6155f6efa: Downloading m3u8 information
[info] Available formats for f08e80da-bf1d-4e3d-8899-f0f6155f6efa:
format code           extension  resolution note
audio-English_stereo  mp4        audio only [en] 
628                   mp4        320x180     628k , avc1.42c00d, video only
928                   mp4        480x270     928k , avc1.42c00d, video only
1728                  mp4        640x360    1728k , avc1.42c00d, video only
2528                  mp4        960x540    2528k , avc1.42c00d, video only
4928                  mp4        1280x720   4928k , avc1.42c00d, video only
9728                  mp4        1920x1080  9728k , avc1.42c00d, video only (best)

# Choose a variant to download, and use its format code below
$ youtube-dl --format 628 https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8
...
frame= 5257 fps=193 q=-1.0 Lsize=    6746kB time=00:03:30.16 bitrate= 263.0kbits/s speed=7.73x    
video:6679kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.998669%
[ffmpeg] Downloaded 6907810 bytes
[download] 100% of 6.59MiB in 00:29

$ open f08e80da-bf1d-4e3d-8899-f0f6155f6efa-f08e80da-bf1d-4e3d-8899-f0f6155f6efa.mp4

Use the browser's Developer Tools > Network to get the m3u8 (HLS manifest) URL when starting a streaming video.

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

BTW, Yandex Metrica also uses IDFA.

./Pods/YandexMobileMetrica/libYandexMobileMetrica.a

They say on their GitHub page that

"Starting from version 1.6.0 Yandex AppMetrica became also a tracking instrument and uses Apple idfa to attribute installs. Because of that during submitting your application to the AppStore you will be prompted with three checkboxes to state your intentions for idfa usage. As Yandex AppMetrica uses idfa for attributing app installations you need to select Attribute this app installation to a previously served advertisement."

So, I will try to select this checkbox and send my app without actually no any ads in it.

Border color on default input style

If I understand your question correctly this should solve it:

http://jsfiddle.net/wvk2mnsf/

HTML - create a simple input field.

<input type="text" id="giraffe" />

CSS - clear out the native outline so you can set your own and it doesn't look weird with a bluey red outline.

input:focus {
    outline: none;
}
.error-input-border {
    border: 1px solid #FF0000;
}

JS - on typing in the field set red border class declared in the CSS

document.getElementById('giraffe').oninput = function() { this.classList.add('error-input-border'); }

This has a lot of information on the latest standards too: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation

how to load CSS file into jsp

I use this version

<style><%@include file="/WEB-INF/css/style.css"%></style>

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

I juste made this code, from some StackOverflow discussions. I didn't test on Linux environment yet. It is made in order to delete a file or a directory, completely :

function splRm(SplFileInfo $i)
{
    $path = $i->getRealPath();

    if ($i->isDir()) {
        echo 'D - ' . $path . '<br />';
        rmdir($path);
    } elseif($i->isFile()) {
        echo 'F - ' . $path . '<br />';
        unlink($path);
    }
}

function splRrm(SplFileInfo $j)
{
    $path = $j->getRealPath();

    if ($j->isDir()) {
        $rdi = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);
        $rii = new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::CHILD_FIRST);
        foreach ($rii as $i) {
            splRm($i);
        }
    }
    splRm($j);

}

splRrm(new SplFileInfo(__DIR__.'/../dirOrFileName'));

How can I compile a Java program in Eclipse without running it?

Go to the project explorer block ... right click on project name select "Build Path"-----------> "Configuration Build Path"

then the pop up window will get open.

in this pop up window you will find 4 tabs. 1)source 2) project 3)Library 4)order and export

Click on 1) Source

select the project (under which that file is present which you want to compile)

and then click on ok....

Go to the workspace location of the project open a bin folder and search that class file ...

you will get that java file compiled...

just to cross verify check the changed timing.

hope this will help.

Thanks.

How would I get everything before a : in a string Python

I have benchmarked these various technics under Python 3.7.0 (IPython).

TLDR

  • fastest (when the split symbol c is known): pre-compiled regex.
  • fastest (otherwise): s.partition(c)[0].
  • safe (i.e., when c may not be in s): partition, split.
  • unsafe: index, regex.

Code

import string, random, re

SYMBOLS = string.ascii_uppercase + string.digits
SIZE = 100

def create_test_set(string_length):
    for _ in range(SIZE):
        random_string = ''.join(random.choices(SYMBOLS, k=string_length))
        yield (random.choice(random_string), random_string)

for string_length in (2**4, 2**8, 2**16, 2**32):
    print("\nString length:", string_length)
    print("  regex (compiled):", end=" ")
    test_set_for_regex = ((re.compile("(.*?)" + c).match, s) for (c, s) in test_set)
    %timeit [re_match(s).group() for (re_match, s) in test_set_for_regex]
    test_set = list(create_test_set(16))
    print("  partition:       ", end=" ")
    %timeit [s.partition(c)[0] for (c, s) in test_set]
    print("  index:           ", end=" ")
    %timeit [s[:s.index(c)] for (c, s) in test_set]
    print("  split (limited): ", end=" ")
    %timeit [s.split(c, 1)[0] for (c, s) in test_set]
    print("  split:           ", end=" ")
    %timeit [s.split(c)[0] for (c, s) in test_set]
    print("  regex:           ", end=" ")
    %timeit [re.match("(.*?)" + c, s).group() for (c, s) in test_set]

Results

String length: 16
  regex (compiled): 156 ns ± 4.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        19.3 µs ± 430 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            26.1 µs ± 341 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  26.8 µs ± 1.26 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            26.3 µs ± 835 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            128 µs ± 4.02 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

String length: 256
  regex (compiled): 167 ns ± 2.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        20.9 µs ± 694 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  index:            28.6 µs ± 2.73 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  27.4 µs ± 979 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            31.5 µs ± 4.86 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            148 µs ± 7.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

String length: 65536
  regex (compiled): 173 ns ± 3.95 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        20.9 µs ± 613 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            27.7 µs ± 515 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  27.2 µs ± 796 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            26.5 µs ± 377 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            128 µs ± 1.5 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

String length: 4294967296
  regex (compiled): 165 ns ± 1.2 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        19.9 µs ± 144 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            27.7 µs ± 571 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  26.1 µs ± 472 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            28.1 µs ± 1.69 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            137 µs ± 6.53 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

HTML5 Email Validation

I know you are not after the Javascript solution however there are some things such as the customized validation message that, from my experience, can only be done using JS.

Also, by using JS, you can dynamically add the validation to all input fields of type email within your site instead of having to modify every single input field.

var validations ={
    email: [/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/, 'Please enter a valid email address']
};
$(document).ready(function(){
    // Check all the input fields of type email. This function will handle all the email addresses validations
    $("input[type=email]").change( function(){
        // Set the regular expression to validate the email 
        validation = new RegExp(validations['email'][0]);
        // validate the email value against the regular expression
        if (!validation.test(this.value)){
            // If the validation fails then we show the custom error message
            this.setCustomValidity(validations['email'][1]);
            return false;
        } else {
            // This is really important. If the validation is successful you need to reset the custom error message
            this.setCustomValidity('');
        }
    });
})

File Upload using AngularJS

I am able to upload files using AngularJS by using below code:

The file for the argument that needs to be passed for the function ngUploadFileUpload is $scope.file as per your question.

The key point here is to use transformRequest: []. This will prevent $http with messing with the contents of the file.

       function getFileBuffer(file) {
            var deferred = new $q.defer();
            var reader = new FileReader();
            reader.onloadend = function (e) {
                deferred.resolve(e.target.result);
            }
            reader.onerror = function (e) {
                deferred.reject(e.target.error);
            }

            reader.readAsArrayBuffer(file);
            return deferred.promise;
        }

        function ngUploadFileUpload(endPointUrl, file) {

            var deferred = new $q.defer();
            getFileBuffer(file).then(function (arrayBuffer) {

                $http({
                    method: 'POST',
                    url: endPointUrl,
                    headers: {
                        "accept": "application/json;odata=verbose",
                        'X-RequestDigest': spContext.securityValidation,
                        "content-length": arrayBuffer.byteLength
                    },
                    data: arrayBuffer,
                    transformRequest: []
                }).then(function (data) {
                    deferred.resolve(data);
                }, function (error) {
                    deferred.reject(error);
                    console.error("Error", error)
                });
            }, function (error) {
                console.error("Error", error)
            });

            return deferred.promise;

        }

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

I encountered the same problem, probably when I uninstalled it and tried to install it again. This happens because of the database file containing login details is still stored in the pc, and the new password will not match the older one. So you can solve this by just uninstalling mysql, and then removing the left over folder from the C: drive (or wherever you must have installed).

python numpy ValueError: operands could not be broadcast together with shapes

It's possible that the error didn't occur in the dot product, but after. For example try this

a = np.random.randn(12,1)
b = np.random.randn(1,5)
c = np.random.randn(5,12)
d = np.dot(a,b) * c

np.dot(a,b) will be fine; however np.dot(a, b) * c is clearly wrong (12x1 X 1x5 = 12x5 which cannot element-wise multiply 5x12) but numpy will give you

ValueError: operands could not be broadcast together with shapes (12,1) (1,5)

The error is misleading; however there is an issue on that line.

How to find files recursively by file type and copy them to a directory while in ssh?

Try this:

find . -name "*.pdf" -type f -exec cp {} ./pdfsfolder \;

CSS flex, how to display one item on first line and two on the next line

The answer given by Nico O is correct. However this doesn't get the desired result on Internet Explorer 10 to 11 and Firefox.

For IE, I found that changing

.flex > div
{
   flex: 1 0 50%;
}

to

.flex > div
{
   flex: 1 0 45%;
}

seems to do the trick. Don't ask me why, I haven't gone any further into this but it might have something to do with how IE renders the border-box or something.

In the case of Firefox I solved it by adding

display: inline-block;

to the items.

How to identify a strong vs weak relationship on ERD?

We draw a solid line if and only if we have an ID-dependent relationship; otherwise it would be a dashed line.

Consider a weak but not ID-dependent relationship; We draw a dashed line because it is a weak relationship.

Verify a certificate chain using openssl verify

After breaking an entire day on the exact same issue , with no prior knowledge on SSL certificates, i downloaded the CERTivity Keystores Manager and imported my keystore to it, and got a clear-cut visualisation of the certificate chain.

Screenshot :

enter image description here

Encrypting & Decrypting a String in C#

If you are targeting ASP.NET Core that does not support RijndaelManaged yet, you can use IDataProtectionProvider.

First, configure your application to use data protection:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDataProtection();
    }
    // ...
}

Then you'll be able to inject IDataProtectionProvider instance and use it to encrypt/decrypt data:

public class MyService : IService
{
    private const string Purpose = "my protection purpose";
    private readonly IDataProtectionProvider _provider;

    public MyService(IDataProtectionProvider provider)
    {
        _provider = provider;
    }

    public string Encrypt(string plainText)
    {
        var protector = _provider.CreateProtector(Purpose);
        return protector.Protect(plainText);
    }

    public string Decrypt(string cipherText)
    {
        var protector = _provider.CreateProtector(Purpose);
        return protector.Unprotect(cipherText);
    }
}

See this article for more details.

How do I check two or more conditions in one <c:if>?

This look like a duplicate of JSTL conditional check.

The error is having the && outside the expression. Instead use

<c:if test="${ISAJAX == 0 && ISDATE == 0}">

cin and getline skipping input

If you're using getline after cin >> something, you need to flush the newline out of the buffer in between.

My personal favourite for this if no characters past the newline are needed is cin.sync(). However, it is implementation defined, so it might not work the same way as it does for me. For something solid, use cin.ignore(). Or make use of std::ws to remove leading whitespace if desirable:

int a;

cin >> a;
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); 
//discard characters until newline is found

//my method: cin.sync(); //discard unread characters

string s;
getline (cin, s); //newline is gone, so this executes

//other method: getline(cin >> ws, s); //remove all leading whitespace

Git, fatal: The remote end hung up unexpectedly

Even after configuring post buffer the issue was not resolved.

My problem was solved when I changed my wifi network from broadband to my mobile hotspot. This might not be the logically correct answer but it solved the issue.

Make sure you have good internet speed.

ContractFilter mismatch at the EndpointDispatcher exception

I had this problem and found that in my proxy generator, which I copied from another service, I forgot to change the name of the service.

I changed this...

Return New Service1DataClient(binding, New EndpointAddress(My.Settings.WCFServiceURL & "/Service1Data.svc"))

to...

Return New Service2DataClient(binding, New EndpointAddress(My.Settings.WCFServiceURL & "/Service2Data.svc"))

It was a simple code error, but nearly impossible to debug. I hope this saves someone time.

What is ADT? (Abstract Data Type)

Abstract Data type is a mathematical module that includes data with various operations. Implementation details are hidden and that's why it is called abstract. Abstraction allowed you to organise the complexity of the task by focusing on logical properties of data and actions.

CSS selector for disabled input type="submit"

Does that work in IE6?

No, IE6 does not support attribute selectors at all, cf. CSS Compatibility and Internet Explorer.

You might find How to workaround: IE6 does not support CSS “attribute” selectors worth the read.


EDIT
If you are to ignore IE6, you could do (CSS2.1):

input[type=submit][disabled=disabled],
button[disabled=disabled] {
    ...
}

CSS3 (IE9+):

input[type=submit]:disabled,
button:disabled {
    ...
}

You can substitute [disabled=disabled] (attribute value) with [disabled] (attribute presence).

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

Try -

$("#column_select").change(function () {
    $("#layout_select").children('option').hide();
    $("#layout_select").children("option[value^=" + $(this).val() + "]").show()
})  

If you were going to use this solution you'd need to hide all of the elements apart from the one with the 'none' value in your document.ready function -

$(document).ready(function() {
    $("#layout_select").children('option:gt(0)').hide();
    $("#column_select").change(function() {
        $("#layout_select").children('option').hide();
        $("#layout_select").children("option[value^=" + $(this).val() + "]").show()
    })
})

Demo - http://jsfiddle.net/Mxkfr/2

EDIT

I might have got a bit carried away with this, but here's a further example that uses a cache of the original select list options to ensure that the 'layout_select' list is completely reset/cleared (including the 'none' option) after the 'column_select' list is changed -

$(document).ready(function() {
    var optarray = $("#layout_select").children('option').map(function() {
        return {
            "value": this.value,
            "option": "<option value='" + this.value + "'>" + this.text + "</option>"
        }
    })

    $("#column_select").change(function() {
        $("#layout_select").children('option').remove();
        var addoptarr = [];
        for (i = 0; i < optarray.length; i++) {
            if (optarray[i].value.indexOf($(this).val()) > -1) {
                addoptarr.push(optarray[i].option);
            }
        }
        $("#layout_select").html(addoptarr.join(''))
    }).change();
})

Demo - http://jsfiddle.net/N7Xpb/1/

How to style readonly attribute with CSS?

If you select the input by the id and then add the input[readonly="readonly"] tag in the css, something like:

 #inputID input[readonly="readonly"] {
     background-color: #000000;
 }

That will not work. You have to select a parent class or id an then the input. Something like:

 .parentClass, #parentID input[readonly="readonly"] {
     background-color: #000000;
 }

My 2 cents while waiting for new tickets at work :D

Undo git update-index --assume-unchanged <file>

To get undo/show dir's/files that are set to assume-unchanged run this:

git update-index --no-assume-unchanged <file>

To get a list of dir's/files that are assume-unchanged run this:

git ls-files -v|grep '^h'

Abstract class in Java

Class which can have both concrete and non-concrete methods i.e. with and without body.

  1. Methods without implementation must contain 'abstract' keyword.
  2. Abstract class can't be instantiated.

Javascript - validation, numbers only

No need for the long code for number input restriction just try this code.

It also accepts valid int & float both values.

Javascript Approach

_x000D_
_x000D_
onload =function(){ _x000D_
  var ele = document.querySelectorAll('.number-only')[0];_x000D_
  ele.onkeypress = function(e) {_x000D_
     if(isNaN(this.value+""+String.fromCharCode(e.charCode)))_x000D_
        return false;_x000D_
  }_x000D_
  ele.onpaste = function(e){_x000D_
     e.preventDefault();_x000D_
  }_x000D_
}
_x000D_
<p> Input box that accepts only valid int and float values.</p>_x000D_
<input class="number-only" type=text />
_x000D_
_x000D_
_x000D_

jQuery Approach

_x000D_
_x000D_
$(function(){_x000D_
_x000D_
  $('.number-only').keypress(function(e) {_x000D_
 if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;_x000D_
  })_x000D_
  .on("cut copy paste",function(e){_x000D_
 e.preventDefault();_x000D_
  });_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p> Input box that accepts only valid int and float values.</p>_x000D_
<input class="number-only" type=text />
_x000D_
_x000D_
_x000D_

The above answers are for most common use case - validating input as a number.

But to allow few special cases like negative numbers & showing the invalid keystrokes to user before removing it, so below is the code snippet for such special use cases.

_x000D_
_x000D_
$(function(){_x000D_
      _x000D_
  $('.number-only').keyup(function(e) {_x000D_
        if(this.value!='-')_x000D_
          while(isNaN(this.value))_x000D_
            this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')_x000D_
                                   .split('').reverse().join('');_x000D_
    })_x000D_
    .on("cut copy paste",function(e){_x000D_
     e.preventDefault();_x000D_
    });_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p> Input box that accepts only valid int and float values.</p>_x000D_
<input class="number-only" type=text />
_x000D_
_x000D_
_x000D_

How to create/read/write JSON files in Qt5

An example on how to use that would be great. There is a couple of examples at the Qt forum, but you're right that the official documentation should be expanded.

QJsonDocument on its own indeed doesn't produce anything, you will have to add the data to it. That's done through the QJsonObject, QJsonArray and QJsonValue classes. The top-level item needs to be either an array or an object (because 1 is not a valid json document, while {foo: 1} is.)

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

On top pointing my hostname to 127.0.0.1 in hosts (just run hostname in cmd to get it) as well as doing what David GC mentioned, for me the error cleared and debugging worked when I went into the tomcat configuration and changed the debugging startup script from startup.bat (which was just my monkeying around) back to the catalina.bat start default.

How do I show multiple recaptchas on a single page?

A good option is to generate a recaptcha input for each form on the fly (I've done it with two but you could probably do three or more forms). I'm using jQuery, jQuery validation, and jQuery form plugin to post the form via AJAX, along with the Recaptcha AJAX API -

https://developers.google.com/recaptcha/docs/display#recaptcha_methods

When the user submits one of the forms:

  1. intercept the submission - I used jQuery Form Plugin's beforeSubmit property
  2. destroy any existing recaptcha inputs on the page - I used jQuery's $.empty() method and Recaptcha.destroy()
  3. call Recaptcha.create() to create a recaptcha field for the specific form
  4. return false.

Then, they can fill out the recaptcha and re-submit the form. If they decide to submit a different form instead, well, your code checks for existing recaptchas so you'll only have one recaptcha on the page at a time.

Java random number with given length

For the follow-up question, you can get a number between 36^5 and 36^6 and convert it in base 36

UPDATED:

using this code

http://javaconfessions.com/2008/09/convert-between-base-10-and-base-62-in_28.html

It's written BaseConverterUtil.toBase36(60466176+r.nextInt(2116316160))

but in your use case, it can be optimized by using a StringBuilder and having the number in the reverse order ie 71 should be converted in Z1 instead of 1Z

EDITED:

How to include *.so library in Android Studio?

This is my build.gradle file, Please note the line

jniLibs.srcDirs = ['libs']

This will include libs's *.so file to apk.

sourceSets {
    main {
        manifest.srcFile 'AndroidManifest.xml'
        java.srcDirs = ['src']
        resources.srcDirs = ['src']
        aidl.srcDirs = ['src']
        renderscript.srcDirs = ['src']
        res.srcDirs = ['res']
        assets.srcDirs = ['assets']
        jniLibs.srcDirs = ['libs']
    }

    // Move the tests to tests/java, tests/res, etc...
    instrumentTest.setRoot('tests')

    // Move the build types to build-types/<type>
    // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
    // This moves them out of them default location under src/<type>/... which would
    // conflict with src/ being used by the main source set.
    // Adding new build types or product flavors should be accompanied
    // by a similar customization.
    debug.setRoot('build-types/debug')
    release.setRoot('build-types/release')
}

Using FileUtils in eclipse

Now selenium supports following code:

FileHandler.copy(src, dest);

How can I configure my makefile for debug and release builds?

You could also add something simple to your Makefile such as

ifeq ($(DEBUG),1)
   OPTS = -g
endif

Then compile it for debugging

make DEBUG=1

How do I get a computer's name and IP address using VB.NET?

Dim ipAddress As IPAddress
Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName())
ipAddress = ipHostInfo.AddressList(0)

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

I think what TCSgrad was trying to ask (a few years ago) was how to make Linux behave like his Windows machine does. That is, there is an agent (pageant) which holds a decrypted copy of a private key so that the passphrase only needs to be put in once. Then, the ssh client, putty, can log in to machines where his public key is listed as "authorized" without a password prompt.

The analog for this is that Linux, acting as an ssh client, has an agent holding a decrypted private key so that when TCSgrad types "ssh host" the ssh command will get his private key and go without being prompted for a password. host would, of course, have to be holding the public key in ~/.ssh/authorized_keys.

The Linux analog to this scenario is accomplished using ssh-agent (the pageant analog) and ssh-add (the analog to adding a private key to pageant).

The method that worked for me was to use: $ ssh-agent $SHELL That $SHELL was the magic trick I needed to make the agent run and stay running. I found that somewhere on the 'net and it ended a few hours of beating my head against the wall.

Now we have the analog of pageant running, an agent with no keys loaded.

Typing $ ssh-add by itself will add (by default) the private keys listed in the default identity files in ~/.ssh .

A web article with a lot more details can be found here

What is the use of "object sender" and "EventArgs e" parameters?

Those two parameters (or variants of) are sent, by convention, with all events.

  • sender: The object which has raised the event
  • e an instance of EventArgs including, in many cases, an object which inherits from EventArgs. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.

In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs are Empty as there is no further information about the event.

Looking at the 2 parameters separately, here are some examples where they are useful.

sender

Say you have multiple buttons on a form. These buttons could contain a Tag describing what clicking them should do. You could handle all the Click events with the same handler, and depending on the sender do something different

private void HandleButtonClick(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    if(btn.Tag == "Hello")
      MessageBox.Show("Hello")
    else if(btn.Tag == "Goodbye")
       Application.Exit();
    // etc.
}

Disclaimer : That's a contrived example; don't do that!

e

Some events are cancelable. They send CancelEventArgs instead of EventArgs. This object adds a simple boolean property Cancel on the event args. Code handling this event can cancel the event:

private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
    if(/* some condition*/)
    {
       // Cancel this event
       e.Cancel = true;
    }
}

CSS - Syntax to select a class within an id

Here's two options. I prefer the navigationAlt option since it involves less work in the end:

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <style type="text/css">_x000D_
    #navigation li {_x000D_
      color: green;_x000D_
    }_x000D_
    #navigation li .navigationLevel2 {_x000D_
      color: red;_x000D_
    }_x000D_
    #navigationAlt {_x000D_
      color: green;_x000D_
    }_x000D_
    #navigationAlt ul {_x000D_
      color: red;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <ul id="navigation">_x000D_
    <li>Level 1 item_x000D_
      <ul>_x000D_
        <li class="navigationLevel2">Level 2 item</li>_x000D_
      </ul>_x000D_
    </li>_x000D_
  </ul>_x000D_
  <ul id="navigationAlt">_x000D_
    <li>Level 1 item_x000D_
      <ul>_x000D_
        <li>Level 2 item</li>_x000D_
      </ul>_x000D_
    </li>_x000D_
  </ul>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Closing a file after File.Create

The reason is because a FileStream is returned from your method to create a file. You should return the FileStream into a variable or call the close method directly from it after the File.Create.

It is a best practice to let the using block help you implement the IDispose pattern for a task like this. Perhaps what might work better would be:

if(!File.Exists(myPath)){
   using(FileStream fs = File.Create(myPath))
   using(StreamWriter writer = new StreamWriter(fs)){
      // do your work here
   }
}

Simple Random Samples from a Sql database

Try

SELECT TOP 10000 * FROM table ORDER BY NEWID()

Would this give the desired results, without being too over complicated?

Get device information (such as product, model) from adb command

The correct way to do it would be:

adb -s 123abc12 shell getprop

Which will give you a list of all available properties and their values. Once you know which property you want, you can give the name as an argument to getprop to access its value directly, like this:

adb -s 123abc12 shell getprop ro.product.model

The details in adb devices -l consist of the following three properties: ro.product.name, ro.product.model and ro.product.device.

Note that ADB shell ends lines with \r\n, which depending on your platform might or might not make it more difficult to access the exact value (e.g. instead of Nexus 7 you might get Nexus 7\r).

How do I add a new class to an element dynamically?

Since everyone has given you jQuery/JS answers to this, I will provide an additional solution. The answer to your question is still no, but using LESS (a CSS Pre-processor) you can do this easily.

.first-class {
  background-color: yellow;
}
.second-class:hover {
  .first-class;
}

Quite simply, any time you hover over .second-class it will give it all the properties of .first-class. Note that it won't add the class permanently, just on hover. You can learn more about LESS here: Getting Started with LESS

Here is a SASS way to do it as well:

.first-class {
  background-color: yellow;
}
.second-class {
  &:hover {
    @extend .first-class;
  }
}

How to prevent Right Click option using jquery

$(document).mousedown(function(e) {
    if( e.button == 2 ) {
         e.preventDefault();
        return false;
    } 
});

Relative paths in Python

Instead of using

import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

as in the accepted answer, it would be more robust to use:

import inspect
import os
dirname = os.path.dirname(os.path.abspath(inspect.stack()[0][1]))
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

because using __file__ will return the file from which the module was loaded, if it was loaded from a file, so if the file with the script is called from elsewhere, the directory returned will not be correct.

These answers give more detail: https://stackoverflow.com/a/31867043/5542253 and https://stackoverflow.com/a/50502/5542253

Call to undefined function curl_init().?

You have to enable curl with php.

Here is the instructions for same

error: command 'gcc' failed with exit status 1 while installing eventlet

For Fedora:

sudo yum install python-devel

sudo yum install libevent-devel

and finally:

sudo easy_install gevent

Showing an image from console in Python

If you would like to show it in a new window, you could use Tkinter + PIL library, like so:

import tkinter as tk
from PIL import ImageTk, Image

def show_imge(path):
    image_window = tk.Tk()
    img = ImageTk.PhotoImage(Image.open(path))
    panel = tk.Label(image_window, image=img)
    panel.pack(side="bottom", fill="both", expand="yes")
    image_window.mainloop()

This is a modified example that can be found all over the web.

Returning pointer from a function

To my knowledge the use of the keyword new, does relatively the same thing as malloc(sizeof identifier). The code below demonstrates how to use the keyword new.

    void main(void){
        int* test;
        test = tester();
        printf("%d",*test);
        system("pause");
    return;
}
    int* tester(void){
        int *retMe;
        retMe = new int;//<----Here retMe is getting malloc for integer type
        *retMe = 12;<---- Initializes retMe... Note * dereferences retMe 
    return retMe;
}

Link to the issue number on GitHub within a commit message

they have an nice write up about the new issues 2.0 on their blog https://github.blog/2011-04-09-issues-2-0-the-next-generation/

synonyms include

  • fixes #xxx
  • fixed #xxx
  • fix #xxx
  • closes #xxx
  • close #xxx
  • closed #xxx

using any of the keywords in a commit message will make your commit either mentioned or close an issue.

How to implement linear interpolation?

import scipy.interpolate
y_interp = scipy.interpolate.interp1d(x, y)
print y_interp(5.0)

scipy.interpolate.interp1d does linear interpolation by and can be customized to handle error conditions.

Docker: Multiple Dockerfiles in project

In Intellij, I simple changed the name of the docker files to *.Dockerfile, and associated the file type *.Dockerfile to docker syntax.

Google Geocoding API - REQUEST_DENIED

For those who are looking this page in 2017 or beyond, like me

Sensor is not required anymore, I tried and got the error:

SensorNotRequired

I just needed to activate my Google Maps Geocoding API, that seems to be necessary nowadays.

Hope it helps someone like me.

(Excel) Conditional Formatting based on Adjacent Cell Value

I don't know if maybe it's a difference in Excel version but this question is 6 years old and the accepted answer didn't help me so this is what I figured out:

Under Conditional Formatting > Manage Rules:

  1. Make a new rule with "Use a formula to determine which cells to format"
  2. Make your rule, but put a dollar sign only in front of the letter: $A2<$B2
  3. Under "Applies to", Manually select the second column (It would not work for me if I changed the value in the box, it just kept snapping back to what was already there), so it looks like $B$2:$B$100 (assuming you have 100 rows)

This worked for me in Excel 2016.

How to find out if a file exists in C# / .NET?

System.IO.File:

using System.IO;

if (File.Exists(path)) 
{
    Console.WriteLine("file exists");
} 

How to add new column to MYSQL table?

Based on your comment it looks like your'e only adding the new column if: mysql_query("SELECT * FROM assessment"); returns false. That's probably not what you wanted. Try removing the '!' on front of $sql in the first 'if' statement. So your code will look like:

$sql=mysql_query("SELECT * FROM assessment");
if ($sql) {
 mysql_query("ALTER TABLE assessment ADD q6 INT(1) NOT NULL AFTER q5");
 echo 'Q6 created'; 
}else...

Convert string to BigDecimal in java

The BigDecimal(double) constructor can have unpredictable behaviors. It is preferable to use BigDecimal(String) or BigDecimal.valueOf(double).

System.out.println(new BigDecimal(135.69)); //135.68999999999999772626324556767940521240234375
System.out.println(new BigDecimal("135.69")); // 135.69
System.out.println(BigDecimal.valueOf(135.69)); // 135.69

The documentation for BigDecimal(double) explains in detail:

  1. The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.
  2. The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.
  3. When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result, use the static valueOf(double) method.

Mongoose query where value is not null

total count the documents where the value of the field is not equal to the specified value.

async function getRegisterUser() {
    return Login.count({"role": { $ne: 'Super Admin' }}, (err, totResUser) => {
        if (err) {
            return err;
        }
        return totResUser;
    })
}

How to check postgres user and password?

You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.

Usually, you can login as the postgres user:

Open a Terminal and do sudo su postgres. Now, after entering your admin password, you are able to launch psql and do

CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';

This creates a new admin user. If you want to list the existing users, you could also do

\du

to list all users and then

ALTER USER yourusername WITH PASSWORD 'yournewpass';

Python Matplotlib figure title overlaps axes label when using twiny

ax.set_title('My Title\n', fontsize="15", color="red")
plt.imshow(myfile, origin="upper")

If you put '\n' right after your title string, the plot is drawn just below the title. That might be a fast solution too.

How to create an empty file with Ansible?

Building on the accepted answer, if you want the file to be checked for permissions on every run, and these changed accordingly if the file exists, or just create the file if it doesn't exist, you can use the following:

- stat: path=/etc/nologin
  register: p

- name: create fake 'nologin' shell
  file: path=/etc/nologin 
        owner=root
        group=sys
        mode=0555
        state={{ "file" if  p.stat.exists else "touch"}}

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

I think this error can happen for various reasons, but it can be specific to the module you're using. For example I saw this using the uwsgi module, so had to set "uwsgi_read_timeout".

ab load testing

Steps to set up Apache Bench(AB) on windows (IMO - Recommended).

Step 1 - Install Xampp.
Step 2 - Open CMD.
Step 3 - Go to the apache bench destination (cd C:\xampp\apache\bin) from CMD
Step 4 - Paste the command (ab -n 100 -c 10 -k -H "Accept-Encoding: gzip, deflate" http://localhost:yourport/)
Step 5 - Wait for it. Your done

How to assign string to bytes array

Go, convert a string to a bytes slice

You need a fast way to convert a []string to []byte type. To use in situations such as storing text data into a random access file or other type of data manipulation that requires the input data to be in []byte type.

package main

func main() {

    var s string

    //...

    b := []byte(s)

    //...
}

which is useful when using ioutil.WriteFile, which accepts a bytes slice as its data parameter:

WriteFile func(filename string, data []byte, perm os.FileMode) error

Another example

package main

import (
    "fmt"
    "strings"
)

func main() {

    stringSlice := []string{"hello", "world"}

    stringByte := strings.Join(stringSlice, " ")

    // Byte array value
    fmt.Println([]byte(stringByte))

    // Corresponding string value
    fmt.Println(string([]byte(stringByte)))
}

Output:

[104 101 108 108 111 32 119 111 114 108 100] hello world

Please check the link playground

What is the Gradle artifact dependency graph command?

For those looking to debug gradle dependencies in react-native projects, the command is (executed from projectname/android)

./gradlew app:dependencies --configuration compile

Cell color changing in Excel using C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

How do I convert two lists into a dictionary?

For those who need simple code and aren’t familiar with zip:

List1 = ['This', 'is', 'a', 'list']
List2 = ['Put', 'this', 'into', 'dictionary']

This can be done by one line of code:

d = {List1[n]: List2[n] for n in range(len(List1))}

Python integer division yields float

Take a look at PEP-238: Changing the Division Operator

The // operator will be available to request floor division unambiguously.

Best way to check function arguments?

Edit: as of 2019 there is more support for using type annotations and static checking in Python; check out the typing module and mypy. The 2013 answer follows:


Type checking is generally not Pythonic. In Python, it is more usual to use duck typing. Example:

In you code, assume that the argument (in your example a) walks like an int and quacks like an int. For instance:

def my_function(a):
    return a + 7

This means that not only does your function work with integers, it also works with floats and any user defined class with the __add__ method defined, so less (sometimes nothing) has to be done if you, or someone else, want to extend your function to work with something else. However, in some cases you might need an int, so then you could do something like this:

def my_function(a):
    b = int(a) + 7
    c = (5, 6, 3, 123541)[b]
    return c

and the function still works for any a that defines the __int__ method.

In answer to your other questions, I think it is best (as other answers have said to either do this:

def my_function(a, b, c):
    assert 0 < b < 10
    assert c        # A non-empty string has the Boolean value True

or

def my_function(a, b, c):
    if 0 < b < 10:
        # Do stuff with b
    else:
        raise ValueError
    if c:
        # Do stuff with c
    else:
        raise ValueError

Some type checking decorators I made:

import inspect

def checkargs(function):
    def _f(*arguments):
        for index, argument in enumerate(inspect.getfullargspec(function)[0]):
            if not isinstance(arguments[index], function.__annotations__[argument]):
                raise TypeError("{} is not of type {}".format(arguments[index], function.__annotations__[argument]))
        return function(*arguments)
    _f.__doc__ = function.__doc__
    return _f

def coerceargs(function):
    def _f(*arguments):
        new_arguments = []
        for index, argument in enumerate(inspect.getfullargspec(function)[0]):
            new_arguments.append(function.__annotations__[argument](arguments[index]))
        return function(*new_arguments)
    _f.__doc__ = function.__doc__
    return _f

if __name__ == "__main__":
    @checkargs
    def f(x: int, y: int):
        """
        A doc string!
        """
        return x, y

    @coerceargs
    def g(a: int, b: int):
        """
        Another doc string!
        """
        return a + b

    print(f(1, 2))
    try:
        print(f(3, 4.0))
    except TypeError as e:
        print(e)

    print(g(1, 2))
    print(g(3, 4.0))

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

The file that I was using was saved through Powershell in UTF-8 format. I changed it to ANSI and it fixed the problem.

How to center canvas in html5

You can give your canvas the ff CSS properties:

#myCanvas
{
    display: block;
    margin: 0 auto;
}

How can I fix "Design editor is unavailable until a successful build" error?

Go online before starting android studio. Then go file->New project Follow onscreen steps. Then wait It will download the necessary files over internet. And that should fix it.

How do I read any request header in PHP

Since PHP 5.4.0 you can use getallheaders function which returns all request headers as an associative array:

var_dump(getallheaders());

// array(8) {
//   ["Accept"]=>
//   string(63) "text/html[...]"
//   ["Accept-Charset"]=>
//   string(31) "ISSO-8859-1[...]"
//   ["Accept-Encoding"]=>
//   string(17) "gzip,deflate,sdch"
//   ["Accept-Language"]=>
//   string(14) "en-US,en;q=0.8"
//   ["Cache-Control"]=>
//   string(9) "max-age=0"
//   ["Connection"]=>
//   string(10) "keep-alive"
//   ["Host"]=>
//   string(9) "localhost"
//   ["User-Agent"]=>
//   string(108) "Mozilla/5.0 (Windows NT 6.1; WOW64) [...]"
// }

Earlier this function worked only when PHP was running as an Apache/NSAPI module.

ExecuteNonQuery doesn't return results

You use EXECUTENONQUERY() for INSERT,UPDATE and DELETE.

But for SELECT you must use EXECUTEREADER().........

Convert a JSON Object to Buffer and Buffer to JSON Object back

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

And for converting string to json obj :

var temp = JSON.parse(buf.toString());

Query error with ambiguous column name in SQL

One of your tables has the same column name's which brings a confusion in the query as to which columns of the tables are you referring to. Copy this code and run it.

SELECT 
    v.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount
FROM Vendors AS v
JOIN Invoices AS i ON (v.VendorID = .VendorID)
JOIN InvoiceLineItems AS iL ON (i.InvoiceID = iL.InvoiceID)
WHERE  
    I.InvoiceID IN
        (SELECT iL.InvoiceSequence 
         FROM InvoiceLineItems
         WHERE iL.InvoiceSequence > 1)
ORDER BY 
    V.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount

Clearing NSUserDefaults

I love extensions when they make the code cleaner:

extension NSUserDefaults {
    func clear() {
        guard let domainName = NSBundle.mainBundle().bundleIdentifier else {
            return
        }

        self.removePersistentDomainForName(domainName)
    }
}

Swift 5

extension UserDefaults {
    func clear() {
        guard let domainName = Bundle.main.bundleIdentifier else {
            return
        }
        removePersistentDomain(forName: domainName)
        synchronize()
    }
}

CSS: styled a checkbox to look like a button, is there a hover?

it looks like you need a rule very similar to your checked rule

http://jsfiddle.net/VWBN4/3

#ck-button input:hover + span {
    background-color:#191;
    color:#fff;
}

and for hover and clicked state:

#ck-button input:checked:hover + span {
    background-color:#c11;
    color:#fff;
}

the order is important though.

jQuery addClass onClick

$('#button').click(function(){
    $(this).addClass('active');
});

How to view unallocated free space on a hard disk through terminal

Just follow below.

  • find out the dev type, whether it is /dev/sda /dev/hda /dev/vda etc.

  • look for vi /etc/fstab and find out the mounted partisions and there UUIDs etc

  • say, your harddisk is labeled as /dev/sda and you know number of /dev/sda under df -hT

then you need to find out remaining /dev/sda* right.

so,

fdisk -l /dev/sda* will give the ALL /dev/sda* and you will find for example, /dev/sda4 or /dev/sda5

then find out UUIDs of mounted partisions and those are not listed in /etc/fstab are the ones you can format and mount.

just follow this up. a world to wise is sufficient.

Can I run HTML files directly from GitHub, instead of just viewing their source?

This solution only for chrome browser. I am not sure about other browser.

  1. Add "Modify Content-Type Options" extension in chrome browser.
  2. Open "chrome-extension://jnfofbopfpaoeojgieggflbpcblhfhka/options.html" url in browser.
  3. Add the rule for raw file url. For example:
    • URL Filter: https:///raw/master//fileName.html
    • Original Type: text/plain
    • Replacement Type: text/html
  4. Open the file browser which you added url in rule (in step 3).

How do you perform a left outer join using linq extension methods

Improving on Ocelot20's answer, if you have a table you're left outer joining with where you just want 0 or 1 rows out of it, but it could have multiple, you need to Order your joined table:

var qry = Foos.GroupJoin(
      Bars.OrderByDescending(b => b.Id),
      foo => foo.Foo_Id,
      bar => bar.Foo_Id,
      (f, bs) => new { Foo = f, Bar = bs.FirstOrDefault() });

Otherwise which row you get in the join is going to be random (or more specifically, whichever the db happens to find first).

How to delete a certain row from mysql table with same column values?

There are already answers for Deleting row by LIMIT. Ideally you should have primary key in your table. But if there is not.

I will give other ways:

  1. By creating Unique index

I see id_users and id_product should be unique in your example.

ALTER IGNORE TABLE orders ADD UNIQUE INDEX unique_columns_index (id_users, id_product)

These will delete duplicate rows with same data.

But if you still get an error, even if you use IGNORE clause, try this:

ALTER TABLE orders ENGINE MyISAM;
ALTER IGNORE TABLE orders ADD UNIQUE INDEX unique_columns_index (id_users, id_product)
ALTER TABLE orders ENGINE InnoDB; 
  1. By creating table again

If there are multiple rows who have duplicate values, then you can also recreate table

RENAME TABLE `orders` TO `orders2`;

CREATE TABLE `orders` 
SELECT * FROM `orders2` GROUP BY id_users, id_product;

add/remove active class for ul list with jquery?

Try this,

 $('.nav-list li').click(function() {

    $('.nav-list li.active').removeClass('active');
    $(this).addClass('active');
});

In your context $(this) will points to the UL element not the Li. Hence you are not getting the expected results.

How to have an automatic timestamp in SQLite?

If you use the SQLite DB-Browser you can change the default value in this way:

  1. Choose database structure
  2. select the table
  3. modify table
  4. in your column put under 'default value' the value: =(datetime('now','localtime'))

I recommend to make an update of your database before, because a wrong format in the value can lead to problems in the SQLLite Browser.

Create a .csv file with values from a Python list

To create and write into a csv file

The below example demonstrate creating and writing a csv file. to make a dynamic file writer we need to import a package import csv, then need to create an instance of the file with file reference Ex:- with open("D:\sample.csv","w",newline="") as file_writer

here if the file does not exist with the mentioned file directory then python will create a same file in the specified directory, and "w" represents write, if you want to read a file then replace "w" with "r" or to append to existing file then "a". newline="" specifies that it removes an extra empty row for every time you create row so to eliminate empty row we use newline="", create some field names(column names) using list like fields=["Names","Age","Class"], then apply to writer instance like writer=csv.DictWriter(file_writer,fieldnames=fields) here using Dictionary writer and assigning column names, to write column names to csv we use writer.writeheader() and to write values we use writer.writerow({"Names":"John","Age":20,"Class":"12A"}) ,while writing file values must be passed using dictionary method , here the key is column name and value is your respective key value

import csv 

with open("D:\\sample.csv","w",newline="") as file_writer:

   fields=["Names","Age","Class"]

   writer=csv.DictWriter(file_writer,fieldnames=fields)

   writer.writeheader()

   writer.writerow({"Names":"John","Age":21,"Class":"12A"})

How can I sanitize user input with PHP?

Methods for sanitizing user input with PHP:

  • Use Modern Versions of MySQL and PHP.

  • Set charset explicitly:

    • $mysqli->set_charset("utf8");
      manual
    • $pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF8', $user, $password);
      manual
    • $pdo->exec("set names utf8");
      manual
    • $pdo = new PDO(
      "mysql:host=$host;dbname=$db", $user, $pass, 
      array(
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
      )
      );
      manual
    • mysql_set_charset('utf8')
      [deprecated in PHP 5.5.0, removed in PHP 7.0.0].
  • Use secure charsets:

    • Select utf8, latin1, ascii.., dont use vulnerable charsets big5, cp932, gb2312, gbk, sjis.
  • Use spatialized function:

    • MySQLi prepared statements:
      $stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1'); 
      $param = "' OR 1=1 /*";
      $stmt->bind_param('s', $param);
      $stmt->execute();
    • PDO::quote() - places quotes around the input string (if required) and escapes special characters within the input string, using a quoting style appropriate to the underlying driver:

      $pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF8', $user, $password);explicit set the character set
      $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);disable emulating prepared statements to prevent fallback to emulating statements that MySQL can't prepare natively (to prevent injection)
      $var = $pdo->quote("' OR 1=1 /*");not only escapes the literal, but also quotes it (in single-quote ' characters) $stmt = $pdo->query("SELECT * FROM test WHERE name = $var LIMIT 1");

    • PDO Prepared Statements: vs MySQLi prepared statements supports more database drivers and named parameters:

      $pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF8', $user, $password);explicit set the character set
      $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);disable emulating prepared statements to prevent fallback to emulating statements that MySQL can't prepare natively (to prevent injection) $stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1'); $stmt->execute(["' OR 1=1 /*"]);

    • mysql_real_escape_string [deprecated in PHP 5.5.0, removed in PHP 7.0.0].
    • mysqli_real_escape_string Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection. But recommended to use Prepared Statements because they are not simply escaped strings, a statement comes up with a complete query execution plan, including which tables and indexes it would use, it is a optimized way.
    • Use single quotes (' ') around your variables inside your query.
  • Check the variable contains what you are expecting for:

    • If you are expecting an integer, use:
      ctype_digit — Check for numeric character(s);
      $value = (int) $value;
      $value = intval($value);
      $var = filter_var('0755', FILTER_VALIDATE_INT, $options);
    • For Strings use:
      is_string() — Find whether the type of a variable is string

      Use Filter Function filter_var() — filters a variable with a specified filter:
      $email = filter_var($email, FILTER_SANITIZE_EMAIL);
      $newstr = filter_var($str, FILTER_SANITIZE_STRING);
      more predefined filters
    • filter_input() — Gets a specific external variable by name and optionally filters it:
      $search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
    • preg_match() — Perform a regular expression match;
    • Write Your own validation function.

How to serve up images in Angular2?

Add your image path like fullPathname='assets/images/therealdealportfoliohero.jpg' in your constructor. It will work definitely.

CHECK constraint in MySQL is not working

Update to MySQL 8.0.16 to use checks:

As of MySQL 8.0.16, CREATE TABLE permits the core features of table and column CHECK constraints, for all storage engines. CREATE TABLE permits the following CHECK constraint syntax, for both table constraints and column constraints

MySQL Checks Documentation

Get bitcoin historical data

Actually, you CAN get the whole Bitcoin trades history from Bitcoincharts in CSV format here : http://api.bitcoincharts.com/v1/csv/

it is updated twice a day for active exchanges, and there is a few dead exchanges, too.

EDIT: Since there are no column headers in the CSVs, here's what they are : column 1) the trade's timestamp, column 2) the price, column 3) the volume of the trade

"Series objects are mutable and cannot be hashed" error

Shortly: gene_name[x] is a mutable object so it cannot be hashed. To use an object as a key in a dictionary, python needs to use its hash value, and that's why you get an error.

Further explanation:

Mutable objects are objects which value can be changed. For example, list is a mutable object, since you can append to it. int is an immutable object, because you can't change it. When you do:

a = 5;
a = 3;

You don't change the value of a, you create a new object and make a point to its value.

Mutable objects cannot be hashed. See this answer.

To solve your problem, you should use immutable objects as keys in your dictionary. For example: tuple, string, int.

Jackson enum Serializing and DeSerializer

I've found a very nice and concise solution, especially useful when you cannot modify enum classes as it was in my case. Then you should provide a custom ObjectMapper with a certain feature enabled. Those features are available since Jackson 1.6. So you only need to write toString() method in your enum.

public class CustomObjectMapper extends ObjectMapper {
    @PostConstruct
    public void customConfiguration() {
        // Uses Enum.toString() for serialization of an Enum
        this.enable(WRITE_ENUMS_USING_TO_STRING);
        // Uses Enum.toString() for deserialization of an Enum
        this.enable(READ_ENUMS_USING_TO_STRING);
    }
}

There are more enum-related features available, see here:

https://github.com/FasterXML/jackson-databind/wiki/Serialization-Features https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features

Convert ndarray from float64 to integer

Use .astype.

>>> a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
>>> a
array([ 1.,  2.,  3.,  4.])
>>> a.astype(numpy.int64)
array([1, 2, 3, 4])

See the documentation for more options.

Android studio- "SDK tools directory is missing"

for me, i did this and it worked. just go to C:\Users\$your username$\AppData(which is hidden most likely)\Local\ then at this location try to find this Folder : "Android" if you don't have it already make one with the exact name and try to open the android studio again.

Find out the history of SQL queries

    select v.SQL_TEXT,
           v.PARSING_SCHEMA_NAME,
           v.FIRST_LOAD_TIME,
           v.DISK_READS,
           v.ROWS_PROCESSED,
           v.ELAPSED_TIME,
           v.service
      from v$sql v
where to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss')>ADD_MONTHS(trunc(sysdate,'MM'),-2)

where clause is optional. You can sort the results according to FIRST_LOAD_TIME and find the records up to 2 months ago.

ERROR 1064 (42000) in MySQL

I got this error

ERROR 1064 (42000)

because the downloaded .sql.tar file was somehow corrupted. Downloading and extracting it again solved the issue.

Finding duplicate values in a SQL table

This is the easy thing I've come up with. It uses a common table expression (CTE) and a partition window (I think these features are in SQL 2008 and later).

This example finds all students with duplicate name and dob. The fields you want to check for duplication go in the OVER clause. You can include any other fields you want in the projection.

with cte (StudentId, Fname, LName, DOB, RowCnt)
as (
SELECT StudentId, FirstName, LastName, DateOfBirth as DOB, SUM(1) OVER (Partition By FirstName, LastName, DateOfBirth) as RowCnt
FROM tblStudent
)
SELECT * from CTE where RowCnt > 1
ORDER BY DOB, LName

How to convert String to DOM Document object in java?

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //remove the parameter UTF-8 if you don't want to specify the Encoding type.

this works well for me even though the XML structure is complex.

And please make sure your xmlString is valid for XML, notice the escape character should be added "\" at the front.

The main problem might not come from the attributes.

Filter values only if not null using lambda in Java8

In this particular example I think @Tagir is 100% correct get it into one filter and do the two checks. I wouldn't use Optional.ofNullable the Optional stuff is really for return types not to be doing logic... but really neither here nor there.

I wanted to point out that java.util.Objects has a nice method for this in a broad case, so you can do this:

cars.stream()
    .filter(Objects::nonNull)

Which will clear out your null objects. For anyone not familiar, that's the short-hand for the following:

cars.stream()
    .filter(car -> Objects.nonNull(car))

To partially answer the question at hand to return the list of car names that starts with "M":

cars.stream()
    .filter(car -> Objects.nonNull(car))
    .map(car -> car.getName())
    .filter(carName -> Objects.nonNull(carName))
    .filter(carName -> carName.startsWith("M"))
    .collect(Collectors.toList());

Once you get used to the shorthand lambdas you could also do this:

cars.stream()
    .filter(Objects::nonNull)
    .map(Car::getName)        // Assume the class name for car is Car
    .filter(Objects::nonNull)
    .filter(carName -> carName.startsWith("M"))
    .collect(Collectors.toList());

Unfortunately once you .map(Car::getName) you'll only be returning the list of names, not the cars. So less beautiful but fully answers the question:

cars.stream()
    .filter(car -> Objects.nonNull(car))
    .filter(car -> Objects.nonNull(car.getName()))
    .filter(car -> car.getName().startsWith("M"))
    .collect(Collectors.toList());

How to temporarily exit Vim and go back

You can also do that by :sus to fall into shell and back by fg.

Add common prefix to all cells in Excel

Another way to do this:

  1. Put your prefix in one column say column A in excel
  2. Put the values to which you want to add prefix in another column say column B in excel
  3. In Column C, use this formula;

"C1=A1&B1"

  1. Copy all the values in column C and paste it again in the same selection but as values only.

How to revert initial git commit?

Under the conditions stipulated in the question:

  • The commit is the first commit in the repository.
  • Which means there have been very few commands executed:
    • a git init,
    • presumably some git add operations,
    • and a git commit,
    • and that's all!

If those preconditions are met, then the simplest way to undo the initial commit would be:

rm -fr .git

from the directory where you did git init. You can then redo the git init to recreate the Git repository, and redo the additions with whatever changes are sensible that you regretted not making the first time, and redo the initial commit.

DANGER! This removes the Git repository directory.

It removes the Git repository directory permanently and irrecoverably, unless you've got backups somewhere. Under the preconditions, you've nothing you want to keep in the repository, so you're not losing anything. All the files you added are still available in the working directories, assuming you have not modified them yet and have not deleted them, etc. However, doing this is safe only if you have nothing else in your repository at all. Under the circumstances described in the question 'commit repository first time — then regret it', it is safe. Very often, though, it is not safe.

It's also safe to do this to remove an unwanted cloned repository; it does no damage to the repository that it was cloned from. It throws away anything you've done in your copy, but doesn't affect the original repository otherwise.

Be careful, but it is safe and effective when the preconditions are met.

If you've done other things with your repository that you want preserved, then this is not the appropriate technique — your repository no longer meets the preconditions for this to be appropriate.

Select <a> which href ends with some string

Just in case you don't want to import a big library like jQuery to accomplish something this trivial, you can use the built-in method querySelectorAll instead. Almost all selector strings used for jQuery work with DOM methods as well:

const anchors = document.querySelectorAll('a[href$="ABC"]');

Or, if you know that there's only one matching element:

const anchor = document.querySelector('a[href$="ABC"]');

You may generally omit the quotes around the attribute value if the value you're searching for is alphanumeric, eg, here, you could also use

a[href$=ABC]

but quotes are more flexible and generally more reliable.

What version of javac built my jar?

Since I needed to analyze fat jars I was interested in the version of each individual class in a jar file. Therefore I took Joe Liversedge approach https://stackoverflow.com/a/27877215/1497139 and combined it with David J. Liszewski' https://stackoverflow.com/a/3313839/1497139 class number version table to create a bash script jarv to show the versions of all class files in a jar file.

usage

usage: ./jarv jarfile
 -h|--help: show this usage

Example

jarv $Home/.m2/repository/log4j/log4j/1.2.17/log4j-1.2.17.jar

java 1.4 org.apache.log4j.Appender
java 1.4 org.apache.log4j.AppenderSkeleton
java 1.4 org.apache.log4j.AsyncAppender$DiscardSummary
java 1.4 org.apache.log4j.AsyncAppender$Dispatcher
...

Bash script jarv

#!/bin/bash
# WF 2018-07-12
# find out the class versions with in jar file
# see https://stackoverflow.com/questions/3313532/what-version-of-javac-built-my-jar

# uncomment do debug
# set -x

#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'  
red='\033[0;31m'  
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'

#
# a colored message 
#   params:
#     1: l_color - the color of the message
#     2: l_msg - the message to display
#
color_msg() {
  local l_color="$1"
  local l_msg="$2"
  echo -e "${l_color}$l_msg${endColor}"
}

#
# error
#
#   show an error message and exit
#
#   params:
#     1: l_msg - the message to display
error() {
  local l_msg="$1"
  # use ansi red for error
  color_msg $red "Error: $l_msg" 1>&2
  exit 1
}

#
# show the usage
#
usage() {
  echo "usage: $0 jarfile"
  # -h|--help|usage|show this usage
  echo " -h|--help: show this usage"
  exit 1 
}

#
# showclassversions
#
showclassversions() {
  local l_jar="$1"
  jar -tf "$l_jar" | grep '.class' | while read classname
  do
    class=$(echo $classname | sed -e 's/\.class$//')
    class_version=$(javap -classpath "$l_jar" -verbose $class | grep 'major version' | cut -f2 -d ":" | cut -c2-)
    class_pretty=$(echo $class | sed -e 's#/#.#g')
    case $class_version in
      45.3) java_version="java 1.1";;
      46) java_version="java 1.2";;
      47) java_version="java 1.3";;
      48) java_version="java 1.4";;
      49) java_version="java5";;
      50) java_version="java6";;
      51) java_version="java7";;
      52) java_version="java8";;
      53) java_version="java9";;
      54) java_version="java10";;
      *) java_version="x${class_version}x";;
    esac
    echo $java_version $class_pretty
  done
}

# check the number of parameters
if [ $# -lt 1 ]
then
  usage
fi

# start of script
# check arguments
while test $# -gt 0
do
  case $1 in
    # -h|--help|usage|show this usage
    -h|--help) 
      usage
      exit 1
      ;;
    *)
     showclassversions "$1"
  esac
  shift
done 

How do I load an url in iframe with Jquery

$("#frame").click(function () { 
    this.src="http://www.google.com/";
});

Sometimes plain JavaScript is even cooler and faster than jQuery ;-)

Working with Enums in android

There has been some debate around this point of contention, but even in the most recent documents android suggests that it's not such a good idea to use enums in an android application. The reason why is because they use up more memory than a static constants variable. Here is a document from a page of 2014 that advises against the use of enums in an android application. http://developer.android.com/training/articles/memory.html#Overhead

I quote:

Be aware of memory overhead

Be knowledgeable about the cost and overhead of the language and libraries you are using, and keep this information in mind when you design your app, from start to finish. Often, things on the surface that look innocuous may in fact have a large amount of overhead. Examples include:

  • Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.

  • Every class in Java (including anonymous inner classes) uses about 500 bytes of code.

  • Every class instance has 12-16 bytes of RAM overhead.

  • Putting a single entry into a HashMap requires the allocation of an additional entry object that takes 32 bytes (see the previous section about optimized data containers).

A few bytes here and there quickly add up—app designs that are class- or object-heavy will suffer from this overhead. That can leave you in the difficult position of looking at a heap analysis and realizing your problem is a lot of small objects using up your RAM.

There has been some places where they say that these tips are outdated and no longer valuable, but the reason they keep repeating it, must be there is some truth to it. Writing an android application is something you should keep as lightweight as possible for a smooth user experience. And every little inch of performance counts!

non static method cannot be referenced from a static context

You are calling nextInt statically by using Random.nextInt.

Instead, create a variable, Random r = new Random(); and then call r.nextInt(10).

It would be definitely worth while to check out:

Update:

You really should replace this line,

Random Random = new Random(); 

with something like this,

Random r = new Random();

If you use variable names as class names you'll run into a boat load of problems. Also as a Java convention, use lowercase names for variables. That might help avoid some confusion.

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

After lot of failed tried attempts ,I found the solution

It was the ";" at end of JAVA_HOME which I always put at end of each new variable I set. So get rid of the ;.

JAVA_HOME set it in User Variable also (without the ";" ofcourse)

Windows.history.back() + location.reload() jquery

window.history.back(); Sometimes it's an issue with javascript compatibility with ajax call or design-related challenges.

I would use this below function for go back with the refresh.

function GoBackWithRefresh(event) {
    if ('referrer' in document) {
        window.location = document.referrer;
        /* OR */
        //location.replace(document.referrer);
    } else {
        window.history.back();
    }
}

In your html, use:

<a href="#" onclick="GoBackWithRefresh();return false;">BACK</a>`

For more customization you can use history.js plugins.

How to delete shared preferences data from App in Android

To remove the key-value pairs from preference, you can easily do the following

getActivity().getSharedPreference().edit().remove("key").apply();

I have also developed a library for easy manipulation of shared preferences. You may find the following link

https://github.com/farruhha/SimplePrefs

Spring .properties file: get element as an Array

With a Spring Boot one can do the following:

application.properties

values[0]=abc
values[1]=def

Configuration class

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@ConfigurationProperties
public class Configuration {

    List<String> values = new ArrayList<>();

    public List<String> getValues() {
        return values;
    }

}

This is needed, without this class or without the values in class it is not working.

Spring Boot Application class

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.List;

@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {

    private static Logger LOG = LoggerFactory.getLogger(SpringBootConsoleApplication.class);

    // notice #{} is used instead of ${}
    @Value("#{configuration.values}")
    List<String> values;

    public static void main(String[] args) {
        SpringApplication.run(SpringBootConsoleApplication.class, args);
    }

    @Override
    public void run(String... args) {
        LOG.info("values: {}", values);
    }

}

Is there a way to follow redirects with command line cURL?

Use the location header flag:

curl -L <URL>

How can I convert a VBScript to an executable (EXE) file?

More info

To find a compiler, you'll have 1 per .net version installed, type in a command prompt.

dir c:\Windows\Microsoft.NET\vbc.exe /a/s

Windows Forms

For a Windows Forms version (no console window and we don't get around to actually creating any forms - though you can if you want).

Compile line in a command prompt.

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe "%userprofile%\desktop\VBS2Exe.vb"

Text for VBS2EXE.vb

Imports System.Windows.Forms 

Partial Class MyForm : Inherits Form 

Private Sub InitializeComponent() 


End Sub

Public Sub New() 

InitializeComponent() 

End Sub

Public Shared Sub Main() 

Dim sc as object 
Dim Scrpt as string

sc = createObject("MSScriptControl.ScriptControl")

Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34)

With SC 
.Language = "VBScript" 
.UseSafeSubset = False 
.AllowUI = True 
End With


sc.addcode(Scrpt)


End Sub

End Class

Using these optional parameters gives you an icon and manifest. A manifest allows you to specify run as normal, run elevated if admin, only run elevated.

/win32icon: Specifies a Win32 icon file (.ico) for the default Win32 resources.

/win32manifest: The provided file is embedded in the manifest section of the output PE.

In theory, I have UAC off so can't test, but put this text file on the desktop and call it vbs2exe.manifest, save as UTF-8.

The command line

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" "%userprofile%\desktop\VBS2Exe.vb"

The manifest

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
  <assembly xmlns="urn:schemas-microsoft-com:asm.v1" 
  manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" 
  processorArchitecture="*" name="VBS2EXE" type="win32" /> 
  <description>Script to Exe</description> 
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> 
  <security> <requestedPrivileges> 
  <requestedExecutionLevel level="requireAdministrator" 
  uiAccess="false" /> </requestedPrivileges> 
  </security> </trustInfo> </assembly>

Hopefully it will now ONLY run as admin.

Give Access To a Host's Objects

Here's an example giving the vbscript access to a .NET object.

Imports System.Windows.Forms 

Partial Class MyForm : Inherits Form 

Private Sub InitializeComponent() 


End Sub 

Public Sub New() 

InitializeComponent() 

End Sub 

Public Shared Sub Main() 

Dim sc as object
Dim Scrpt as string 

sc = createObject("MSScriptControl.ScriptControl") 

Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34) & ":msgbox meScript.state" 

With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
.addobject("meScript", SC, true)
End With 


sc.addcode(Scrpt) 


End Sub 

End Class 

To Embed version info

Download vbs2exe.res file from https://skydrive.live.com/redir?resid=E2F0CE17A268A4FA!121 and put on desktop.

Download ResHacker from http://www.angusj.com/resourcehacker

Open vbs2exe.res file in ResHacker. Edit away. Click Compile button. Click File menu - Save.

Type

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" /win32resource:"%userprofile%\desktop\VBS2Exe.res" "%userprofile%\desktop\VBS2Exe.vb"

Best way to remove from NSMutableArray while iterating?

If all objects in your array are unique or you want to remove all occurrences of an object when found, you could fast enumerate on an array copy and use [NSMutableArray removeObject:] to remove the object from the original.

NSMutableArray *myArray;
NSArray *myArrayCopy = [NSArray arrayWithArray:myArray];

for (NSObject *anObject in myArrayCopy) {
    if (shouldRemove(anObject)) {
        [myArray removeObject:anObject];
    }
}

Delete duplicate records from a SQL table without a primary key

With duplicates

As
(Select *, ROW_NUMBER() Over (PARTITION by EmpID,EmpSSN Order by EmpID,EmpSSN) as Duplicate From Employee)

delete From duplicates

Where Duplicate > 1 ;

This will update Table and remove all duplicates from the Table!

Multiple distinct pages in one HTML file

Solution 1

One solution for this, not requiring any JavaScript, is simply to create a single page in which the multiple pages are simply regular content that is separated by a lot of white space. They can be wrapped into div containers, and an inline style sheet can endow them with the margin:

<style>
.subpage { margin-bottom: 2048px; }
</style>
... main page ...

<div class="subpage">
<!-- first one is empty on purpose: just a place holder for margin;
     alternative is to use this for the main part of the page also! -->
</div>

<div class="subpage">
</div>

<div class="subpage">
</div>

You get the picture. Each "page" is just a section followed by a whopping amount of vertical space so that the next one doesn't show.

I'm using this trick to add "disambiguation navigation links" into a large document (more than 430 pages long in its letter-sized PDF form), which I would greatly prefer to keep as a single .html file. I emphasize that this is not a web site, but a document.

When the user clicks on a key word hyperlink in the document for which there are multiple possible topics associated with word, the user is taken a small navigation menu presenting several topic choices. This menu appears at top of what looks like a blank browser window, and so effectively looks like a page.

The only clue that the menu isn't a separate page is the state of the browser's vertical scroll bar, which is largely irrelevant in this navigation use case. If the user notices that, and starts scrolling around, the whole ruse is revealed, at which point the user will smile and appreciate not having been required to unpack a .zip file full of little pages and go hunting for the index.html.

Solution 2

It's actually possible to embed a HTML page within HTML. It can be done using the somewhat obscure data: URL in the href attribute. As a simple test, try sticking this somewhere in a HTML page:

<a href="data:text/html;charset=utf-8,<h3>FOO</h3>">blah</a>

In Firefox, I get a "blah" hyperlink, which navigates to a page showing the FOO heading. (Note that I don't have a fully formed HTML page here, just a HTML snippet; it's just a hello-world example).

The downside of this technique is that the entire target page is in the URL, which is stuffed into the browser's address input box.

If it is large, it could run into some issues, perhaps browser-specific; I don't have much experience with it.

Another disadvantage is that the entire HTML has to be properly escaped so that it can appear as the argument of the href attribute. Obviously, it cannot contain a plain double quote character anywhere.

A third disadvantage is that each such link has to replicates the data: material, since it isn't semantically a link at all, but a copy and paste embedding. It's not an attractive solution if the page-to-be-embeddded is large, and there are to be numerous links to it.

How to run jenkins as a different user

If you really want to run Jenkins as you, I suggest you check out my Jenkins.app. An alternative, easy way to run Jenkins on Mac.

See https://github.com/stisti/jenkins-app/

Download it from https://github.com/stisti/jenkins-app/downloads

How to upload a file and JSON data in Postman?

Use below code in spring rest side :

@PostMapping(value = Constant.API_INITIAL + "/uploadFile")
    public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file,String jsonFileVo) {
        FileUploadVo fileUploadVo = null;
        try {
            fileUploadVo = new ObjectMapper().readValue(jsonFileVo, FileUploadVo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

enter image description here

AFNetworking Post Request

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                       height, @"user[height]",
                       weight, @"user[weight]",
                       nil];

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:
                                             [NSURL URLWithString:@"http://localhost:8080/"]];

[client postPath:@"/mypage.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
     NSString *text = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
     NSLog(@"Response: %@", text);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     NSLog(@"%@", [error localizedDescription]);
}];

Foreign key referencing a 2 columns primary key in SQL Server

Note that the fields must be in the same order. If the Primary Key you are referencing is specified as (Application, ID) then your foreign key must reference (Application, ID) and NOT (ID, Application) as they are seen as two different keys.

Height of status bar in Android

If you know exactly the size VS height

like

for example in a device with 320 X 480 screen size the status bar height is 25px, for a device with 480 x 800 the status bar height must be 38px

then you can just get the width of your view / the screen size you can just use an if else statement to get the height of status bar

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

Get the list of stored procedures created and / or modified on a particular date?

SELECT name
FROM sys.objects
WHERE type = 'P'
AND (DATEDIFF(D,modify_date, GETDATE()) < 7
     OR DATEDIFF(D,create_date, GETDATE()) < 7)

Forms authentication timeout vs sessionState timeout

For anyone stumbling across this question refer to this documentation from MS - it has really good details regarding FormsAuthentication Timeout setting.

This doc explains in detail about the comment bmode is making in the Accepted Answer - about the Persistent Cookie (Session vs Expires)

https://docs.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-security/introduction/forms-authentication-configuration-and-advanced-topics-cs#specifying-the-tickets-timeout-value

In Tkinter is there any way to make a widget not visible?

For hiding a widget you can use function pack_forget() and to again show it you can use pack() function and implement them both in separate functions.

from Tkinter import *
root = Tk()
label=Label(root,text="I was Hidden")
def labelactive():
    label.pack()
def labeldeactive():
    label.pack_forget()
Button(root,text="Show",command=labelactive).pack()
Button(root,text="Hide",command=labeldeactive).pack()
root.mainloop()

Cannot overwrite model once compiled Mongoose

You can easily solve this by doing

delete mongoose.connection.models['users'];
const usersSchema = mongoose.Schema({...});
export default mongoose.model('users', usersSchema);

Docker for Windows error: "Hardware assisted virtualization and data execution protection must be enabled in the BIOS"

If everything is fine with BIOS option I just forced disabling and enabling all HyperV features and this solved my issue --cmd Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All --restart Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V –All

Excel VBA to Export Selected Sheets to PDF

I'm pretty mixed up on this. I am also running Excel 2010. I tried saving two sheets as a single PDF using:

    ThisWorkbook.Sheets(Array(1,2)).Select
    **Selection**.ExportAsFixedFormat xlTypePDF, FileName & ".pdf", , , False

but I got nothing but blank pages. It saved both sheets, but nothing on them. It wasn't until I used:

    ThisWorkbook.Sheets(Array(1,2)).Select
    **ActiveSheet**.ExportAsFixedFormat xlTypePDF, FileName & ".pdf", , , False

that I got a single PDF file with both sheets.

I tried manually saving these two pages using Selection in the Options dialog to save the two sheets I had selected, but got blank pages. When I tried the Active Sheet(s) option, I got what I wanted. When I recorded this as a macro, Excel used ActiveSheet when it successfully published the PDF. What gives?

How to parse SOAP XML?

why don't u try using an absolute xPath

//soap:Envelope[1]/soap:Body[1]/PaymentNotification[1]/payment

or since u know that it is a payment and payment doesn't have any attributes just select directly from payment

//soap:Envelope[1]/soap:Body[1]/PaymentNotification[1]/payment/*

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

(Updated as of May 27, 2017)

Xcode 8. Swift Project - importing Objective C.

Things to know:

  1. Bridging header file MUST be saved within the project's folder. (i.e. not saved at the same level that .xcodeproj is saved, but instead one level further down into the folders where all your swift and objective c files are saved). It can still find the file at the top level, but it will not correctly link and be able to import Objective C files into the bridging header file
  2. Bridging header file can be named anything, as long as it's a .h header file
  3. Be sure the path in Build Settings > Swift Compiler - General > Objective C Bridging Header is correctly pointing to you bridging header file that you made
  4. IMPORTANT: if you're still getting "not found", try to first empty your bridging header file and erase any imports you currently have written there. Be sure that the bridging header file can be found first, then start to add objective c imports to that file. For some reason, it will kick back the same "not found" error even if it is found but it doesn't like the import your trying for some reason
  5. You should not #import "MyBridgingHeaderFile.h" in any of your objective C files. This will also cause a "file not found" error

jQuery Datepicker with text input that doesn't allow user input

$("#my_txtbox").prop('readonly', true)

worked like a charm..

Convert string to integer type in Go?

If you control the input data, you can use the mini version

package main

import (
    "testing"
    "strconv"
)

func Atoi (s string) int {
    var (
        n uint64
        i int
        v byte
    )   
    for ; i < len(s); i++ {
        d := s[i]
        if '0' <= d && d <= '9' {
            v = d - '0'
        } else if 'a' <= d && d <= 'z' {
            v = d - 'a' + 10
        } else if 'A' <= d && d <= 'Z' {
            v = d - 'A' + 10
        } else {
            n = 0; break        
        }
        n *= uint64(10) 
        n += uint64(v)
    }
    return int(n)
}

func BenchmarkAtoi(b *testing.B) {
    for i := 0; i < b.N; i++ {
        in := Atoi("9999")
        _ = in
    }   
}

func BenchmarkStrconvAtoi(b *testing.B) {
    for i := 0; i < b.N; i++ {
        in, _ := strconv.Atoi("9999")
        _ = in
    }   
}

the fastest option (write your check if necessary). Result :

Path>go test -bench=. atoi_test.go
goos: windows
goarch: amd64
BenchmarkAtoi-2                 100000000               14.6 ns/op
BenchmarkStrconvAtoi-2          30000000                51.2 ns/op
PASS
ok      path     3.293s

Convert JSON format to CSV format for MS Excel

I created a JsFiddle here based on the answer given by Zachary. It provides a more accessible user interface and also escapes double quotes within strings properly.

How to call a asp:Button OnClick event using JavaScript?

Set style= "display:none;". By setting visible=false, it will not render button in the browser. Thus,client side script wont execute.

<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />

html markup should be

<button id="btnsave" onclick="fncsave()">Save</button>

Change javascript to

<script type="text/javascript">
     function fncsave()
     {
        document.getElementById('<%= savebtn.ClientID %>').click();
     }
</script>

Changing background color of selected cell?

I created UIView and set the property of cell selectedBackgroundView:

UIView *v = [[UIView alloc] init];
v.backgroundColor = [UIColor redColor];
cell.selectedBackgroundView = v;

MySQL: update a field only if condition is met

Try this:

UPDATE test
SET
   field = 1
WHERE id = 123 and condition

Fastest way to convert an iterator to a list

since python 3.5 you can use * iterable unpacking operator:

user_list = [*your_iterator]

but the pythonic way to do it is:

user_list  = list(your_iterator)

How to study design patterns?

I read three books and still did not understand patterns very well until I read Head First Design Patterns by OReilly. This book opened my eyes and really explained well.

alt text

Update my gradle dependencies in eclipse

I tried all above options but was still getting error, in my case issue was I have not setup gradle installation directory in eclipse, following worked:

eclipse -> Window -> Preferences -> Gradle -> "Select Local Installation Directory"

Click on Browse button and provide path.

Even though question is answered, thought to share in case somebody else is facing similar issue.

Cheers !

Django: Model Form "object has no attribute 'cleaned_data'"

I would write the code like this:

def search_book(request):
    form = SearchForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        stitle = form.cleaned_data['title']
        sauthor = form.cleaned_data['author']
        scategory = form.cleaned_data['category']
        return HttpResponseRedirect('/thanks/')
    return render_to_response("books/create.html", {
        "form": form,
    }, context_instance=RequestContext(request))

Pretty much like the documentation.

Built in Python hash() function

The value of PYTHONHASHSEED might be used to initialize the hash values.

Try:

PYTHONHASHSEED python -c 'print(hash('http://stackoverflow.com'))'

What is "Signal 15 received"

This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

If you need a quick cheatsheet of signal numbers, open a bash shell and:

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
 5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

You can determine the sender by using an appropriate signal handler like:

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

void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
  fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
      info->si_pid);
  exit(0);
}

int main (void)
{
  struct sigaction action = {
    .sa_handler = NULL,
    .sa_sigaction = sigterm_handler,
    .sa_mask = 0,
    .sa_flags = SA_SIGINFO,
    .sa_restorer = NULL
  };

  sigaction(SIGTERM, &action, NULL);
  sleep(60);

  return 0;
}

Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

What's the yield keyword in JavaScript?

Late answering, probably everybody knows about yield now, but some better documentation has come along.

Adapting an example from "Javascript's Future: Generators" by James Long for the official Harmony standard:

function * foo(x) {
    while (true) {
        x = x * 2;
        yield x;
    }
}

"When you call foo, you get back a Generator object which has a next method."

var g = foo(2);
g.next(); // -> 4
g.next(); // -> 8
g.next(); // -> 16

So yield is kind of like return: you get something back. return x returns the value of x, but yield x returns a function, which gives you a method to iterate toward the next value. Useful if you have a potentially memory intensive procedure that you might want to interrupt during the iteration.

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

UPDATE: Another writeup here: How to add publisher in Installshield 2018 (might be better).


I am not too well informed about this issue, but please see if this answer to another question tells you anything useful (and let us know so I can evolve a better answer here): How to pass the Windows Defender SmartScreen Protection? That question relates to BitRock - a non-MSI installer technology, but the overall issue seems to be the same.

Extract from one of the links pointed to in my answer above: "...a certificate just isn't enough anymore to gain trust... SmartScreen is reputation based, not unlike the way StackOverflow works... SmartScreen trusts installers that don't cause problems. Windows machines send telemetry back to Redmond about installed programs and how much trouble they cause. If you get enough thumbs-up then SmartScreen stops blocking your installer automatically. This takes time and lots of installs to get sufficient thumbs. There is no way to find out how far along you got."

Honestly this is all news to me at this point, so do get back to us with any information you dig up yourself.


The actual dialog text you have marked above definitely relates to the Zone.Identifier alternate data stream with a value of 3 that is added to any file that is downloaded from the Internet (see linked answer above for more details).


I was not able to mark this question as a duplicate of the previous one, since it doesn't have an accepted answer. Let's leave both question open for now? (one question is for MSI, one is for non-MSI).

How to get the Android device's primary e-mail address

The suggested answers won't work anymore as there is a new restriction imposed from android 8 onwards.

more info here: https://developer.android.com/about/versions/oreo/android-8.0-changes.html#aaad

Float vs Decimal in ActiveRecord

In Rails 3.2.18, :decimal turns into :integer when using SQLServer, but it works fine in SQLite. Switching to :float solved this issue for us.

The lesson learned is "always use homogeneous development and deployment databases!"

How can I tell when HttpClient has timed out?

I am reproducing the same issue and it's really annoying. I've found these useful:

HttpClient - dealing with aggregate exceptions

Bug in HttpClient.GetAsync should throw WebException, not TaskCanceledException

Some code in case the links go nowhere:

var c = new HttpClient();
c.Timeout = TimeSpan.FromMilliseconds(10);
var cts = new CancellationTokenSource();
try
{
    var x = await c.GetAsync("http://linqpad.net", cts.Token);  
}
catch(WebException ex)
{
    // handle web exception
}
catch(TaskCanceledException ex)
{
    if(ex.CancellationToken == cts.Token)
    {
        // a real cancellation, triggered by the caller
    }
    else
    {
        // a web request timeout (possibly other things!?)
    }
}

How to call code behind server method from a client side JavaScript function?

// include jquery.js
//javascript function
var a1="aaa";
var b1="bbb";
                         **pagename/methodname**     *parameters*
CallServerFunction("Default.aspx/FunPubGetTasks", "{a:'" + a1+ "',b:'" + b1+ "'}",
            function(result)
            {

            }
);
function CallServerFunction(StrPriUrl,ObjPriData,CallBackFunction)
 {

    $.ajax({
        type: "post",
        url: StrPriUrl,
        contentType: "application/json; charset=utf-8",
        data: ObjPriData,
        dataType: "json",
        success: function(result) 
        {
            if(CallBackFunction!=null && typeof CallBackFunction !='undefined')
            {
                CallBackFunction(result);
            }

        },
        error: function(result) 
        {
            alert('error occured');
            alert(result.responseText);
            window.location.href="FrmError.aspx?Exception="+result.responseText;
        },
        async: true
    });
 }

//page name is Default.aspx & FunPubGetTasks method
///your code behind function
     [System.Web.Services.WebMethod()]
        public static object FunPubGetTasks(string a, string b)
        {
            //return Ienumerable or array   
        }

Facebook Open Graph not clearing cache

The most voted question is quite outdated:

These are the only 2 options that should be used as of November 2014:

For non developers

  1. Use the FB Debugger: https://developers.facebook.com/tools/debug/og/object
  2. Paste the url you want to recache. (Make sure you use the same url included on your og:url tag)
  3. Click the Fetch Scrape information again Button

For Developers

  1. Make a GET call programmatically to this URL: https://graph.facebook.com/?id=[YOUR_URL_HERE]&scrape=true (see: https://developers.facebook.com/docs/games_payments/takingpayments#scraping)
  2. Make sure the og:url tag included on the head on that page matches with the one you are passing.
  3. you can even parse the json response to get the number of shares of that URL.

Additional Info About Updating Images

  • If the og:image URL remains the same but the image has actually changed it won't be updated nor recached by Facebook scrapers even doing the above. (even passing a ?last_update=[TIMESTAMP] at the end of the image url didn't work for me).
  • The only effective workaround for me has been to assign a new name to the image.

Note regarding image or video updates on previously posted posts:

  • When you call the debugger to scrap changes on your og:tags of your page, all previous Facebook shares of that URL will still show the old image/video. There is no way to update all previous posts and it's this way by design for security reasons. Otherwise, someone would be able to pretend that a user shared something that he/she actually didn't.

CSS3 Transition not working

HTML:

<div class="foo">
    /* whatever is required */
</div>

CSS:

.foo {
    top: 0;
    transition: top ease 0.5s;
}

.foo:hover{
    top: -10px;
}

This is just a basic transition to ease the div tag up by 10px when it is hovered on. The transition property's values can be edited along with the class.hover properties to determine how the transition works.

SQL query, if value is null then return 1

try like below...

CASE 
WHEN currate.currentrate is null THEN 1
ELSE currate.currentrate
END as currentrate

adb server version doesn't match this client

It helped me to

  • stop the HTC Sync (in system tray)

  • rename HTC's adb.exe which I found at that path:

     C:\Program Files (x86)\HTC\HTC Sync 3.0\adb.exe.
    

Custom fonts and XML layouts (Android)

Peter's answer is the best, but it can be improved by using the styles.xml from Android to customize your fonts for all textviews in your app.

My code is here

How does the Spring @ResponseBody annotation work?

@RequestBody annotation binds the HTTPRequest body to the domain object. Spring automatically deserializes incoming HTTP Request to object using HttpMessageConverters. HttpMessageConverter converts body of request to resolve the method argument depending on the content type of the request. Many examples how to use converters https://upcodein.com/search/jc/mg/ResponseBody/page/0

Error running android: Gradle project sync failed. Please fix your project and try again

Solution is

  1. Connect your computer to the internet

  2. Click

Sync project with Gradle files

On toolbar enter image description here

It will automatically sync the gradle.

Ruby convert Object to Hash

Implement #to_hash?

class Gift
  def to_hash
    hash = {}
    instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) }
    hash
  end
end


h = Gift.new("Book", 19).to_hash

jquery: change the URL address without redirecting?

NOTE: history.pushState() is now supported - see other answers.

You cannot change the whole url without redirecting, what you can do instead is change the hash.

The hash is the part of the url that goes after the # symbol. That was initially intended to direct you (locally) to sections of your HTML document, but you can read and modify it through javascript to use it somewhat like a global variable.


If applied well, this technique is useful in two ways:

  1. the browser history will remember each different step you took (since the url+hash changed)
  2. you can have an address which links not only to a particular html document, but also gives your javascript a clue about what to do. That means you end up pointing to a state inside your web app.

To change the hash you can do:

document.location.hash = "show_picture";

To watch for hash changes you have to do something like:

window.onhashchange = function(){
    var what_to_do = document.location.hash;    
    if (what_to_do=="#show_picture")
        show_picture();
}

Of course the hash is just a string, so you can do pretty much what you like with it. For example you can put a whole object there if you use JSON to stringify it.

There are very good JQuery libraries to do advanced things with that.

Binding ng-model inside ng-repeat loop in AngularJS

<h4>Order List</h4>
<ul>
    <li ng-repeat="val in filter_option.order">
        <span>
            <input title="{{filter_option.order_name[$index]}}" type="radio" ng-model="filter_param.order_option" ng-value="'{{val}}'" />
            &nbsp;{{filter_option.order_name[$index]}}
        </span>
        <select title="" ng-model="filter_param[val]">
            <option value="asc">Asc</option>
            <option value="desc">Desc</option>
        </select>
    </li>
</ul>

Is there a way to iterate over a range of integers?

Here is a program to compare the two ways suggested so far

import (
    "fmt"

    "github.com/bradfitz/iter"
)

func p(i int) {
    fmt.Println(i)
}

func plain() {
    for i := 0; i < 10; i++ {
        p(i)
    }
}

func with_iter() {
    for i := range iter.N(10) {
        p(i)
    }
}

func main() {
    plain()
    with_iter()
}

Compile like this to generate disassembly

go build -gcflags -S iter.go

Here is plain (I've removed the non instructions from the listing)

setup

0035 (/home/ncw/Go/iter.go:14) MOVQ    $0,AX
0036 (/home/ncw/Go/iter.go:14) JMP     ,38

loop

0037 (/home/ncw/Go/iter.go:14) INCQ    ,AX
0038 (/home/ncw/Go/iter.go:14) CMPQ    AX,$10
0039 (/home/ncw/Go/iter.go:14) JGE     $0,45
0040 (/home/ncw/Go/iter.go:15) MOVQ    AX,i+-8(SP)
0041 (/home/ncw/Go/iter.go:15) MOVQ    AX,(SP)
0042 (/home/ncw/Go/iter.go:15) CALL    ,p+0(SB)
0043 (/home/ncw/Go/iter.go:15) MOVQ    i+-8(SP),AX
0044 (/home/ncw/Go/iter.go:14) JMP     ,37
0045 (/home/ncw/Go/iter.go:17) RET     ,

And here is with_iter

setup

0052 (/home/ncw/Go/iter.go:20) MOVQ    $10,AX
0053 (/home/ncw/Go/iter.go:20) MOVQ    $0,~r0+-24(SP)
0054 (/home/ncw/Go/iter.go:20) MOVQ    $0,~r0+-16(SP)
0055 (/home/ncw/Go/iter.go:20) MOVQ    $0,~r0+-8(SP)
0056 (/home/ncw/Go/iter.go:20) MOVQ    $type.[]struct {}+0(SB),(SP)
0057 (/home/ncw/Go/iter.go:20) MOVQ    AX,8(SP)
0058 (/home/ncw/Go/iter.go:20) MOVQ    AX,16(SP)
0059 (/home/ncw/Go/iter.go:20) PCDATA  $0,$48
0060 (/home/ncw/Go/iter.go:20) CALL    ,runtime.makeslice+0(SB)
0061 (/home/ncw/Go/iter.go:20) PCDATA  $0,$-1
0062 (/home/ncw/Go/iter.go:20) MOVQ    24(SP),DX
0063 (/home/ncw/Go/iter.go:20) MOVQ    32(SP),CX
0064 (/home/ncw/Go/iter.go:20) MOVQ    40(SP),AX
0065 (/home/ncw/Go/iter.go:20) MOVQ    DX,~r0+-24(SP)
0066 (/home/ncw/Go/iter.go:20) MOVQ    CX,~r0+-16(SP)
0067 (/home/ncw/Go/iter.go:20) MOVQ    AX,~r0+-8(SP)
0068 (/home/ncw/Go/iter.go:20) MOVQ    $0,AX
0069 (/home/ncw/Go/iter.go:20) LEAQ    ~r0+-24(SP),BX
0070 (/home/ncw/Go/iter.go:20) MOVQ    8(BX),BP
0071 (/home/ncw/Go/iter.go:20) MOVQ    BP,autotmp_0006+-32(SP)
0072 (/home/ncw/Go/iter.go:20) JMP     ,74

loop

0073 (/home/ncw/Go/iter.go:20) INCQ    ,AX
0074 (/home/ncw/Go/iter.go:20) MOVQ    autotmp_0006+-32(SP),BP
0075 (/home/ncw/Go/iter.go:20) CMPQ    AX,BP
0076 (/home/ncw/Go/iter.go:20) JGE     $0,82
0077 (/home/ncw/Go/iter.go:20) MOVQ    AX,autotmp_0005+-40(SP)
0078 (/home/ncw/Go/iter.go:21) MOVQ    AX,(SP)
0079 (/home/ncw/Go/iter.go:21) CALL    ,p+0(SB)
0080 (/home/ncw/Go/iter.go:21) MOVQ    autotmp_0005+-40(SP),AX
0081 (/home/ncw/Go/iter.go:20) JMP     ,73
0082 (/home/ncw/Go/iter.go:23) RET     ,

So you can see that the iter solution is considerably more expensive even though it is fully inlined in the setup phase. In the loop phase there is an extra instruction in the loop, but it isn't too bad.

I'd use the simple for loop.

Confused about UPDLOCK, HOLDLOCK

UPDLOCK is used when you want to lock a row or rows during a select statement for a future update statement. The future update might be the very next statement in the transaction.

Other sessions can still see the data. They just cannot obtain locks that are incompatiable with the UPDLOCK and/or HOLDLOCK.

You use UPDLOCK when you wan to keep other sessions from changing the rows you have locked. It restricts their ability to update or delete locked rows.

You use HOLDLOCK when you want to keep other sessions from changing any of the data you are looking at. It restricts their ability to insert, update, or delete the rows you have locked. This allows you to run the query again and see the same results.

Find all special characters in a column in SQL Server 2008

Select * from TableName Where ColumnName LIKE '%[^A-Za-z0-9, ]%'

This will give you all the row which contains any special character.

Characters allowed in GET parameter

From RFC 1738 on which characters are allowed in URLs:

Only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.

The reserved characters are ";", "/", "?", ":", "@", "=" and "&", which means you would need to URL encode them if you wish to use them.

Angular2 RC6: '<component> is not a known element'

A newbie mistake was generating the same error message in my case.

The app-root tag wasn't present in index.html

Break out of a While...Wend loop

Another option would be to set a flag variable as a Boolean and then change that value based on your criteria.

Dim count as Integer 
Dim flag as Boolean

flag = True

While flag
    count = count + 1 

    If count = 10 Then
        'Set the flag to false         '
        flag = false
    End If 
Wend

Android splash screen image sizes to fit all devices

Some time ago i created an excel file with supported dimensions
Hope this will be helpful for somebody

To be honest i lost the idea, but it refers another screen feature as size (not only density)
https://developer.android.com/guide/practices/screens_support.html
Please inform me if there are some mistakes

Link1: dimensions.xlsx

Link2: dimensions.xlsx

Copy files on Windows Command Line with Progress

The Esentutl /y option allows copyng (single) file files with progress bar like this :

enter image description here

the command should look like :

esentutl /y "FILE.EXT" /d "DEST.EXT" /o

The command is available on every windows machine but the y option is presented in windows vista. As it works only with single files does not look very useful for a small ones. Other limitation is that the command cannot overwrite files. Here's a wrapper script that checks the destination and if needed could delete it (help can be seen by passing /h).

.htaccess: where is located when not in www base dir

The .htaccess is either in the root-directory of your webpage or in the directory you want to protect.

Make sure to make them visible in your filesystem, because AFAIK (I'm no unix expert either) files starting with a period are invisible by default on unix-systems.

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

XML shape drawable not rendering desired color

In drawable I use this xml code to define the border and background:

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

Error Dropping Database (Can't rmdir '.test\', errno: 17)

If it is XAMPP, Do the following:

cd /opt/lampp/var/mysql;
sudo su;
rm -rf test;

Hope this helps.

Remove sensitive files and their commits from Git history

For all practical purposes, the first thing you should be worried about is CHANGING YOUR PASSWORDS! It's not clear from your question whether your git repository is entirely local or whether you have a remote repository elsewhere yet; if it is remote and not secured from others you have a problem. If anyone has cloned that repository before you fix this, they'll have a copy of your passwords on their local machine, and there's no way you can force them to update to your "fixed" version with it gone from history. The only safe thing you can do is change your password to something else everywhere you've used it.


With that out of the way, here's how to fix it. GitHub answered exactly that question as an FAQ:

Note for Windows users: use double quotes (") instead of singles in this command

git filter-branch --index-filter \
'git update-index --remove PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA' <introduction-revision-sha1>..HEAD
git push --force --verbose --dry-run
git push --force

Update 2019:

This is the current code from the FAQ:

  git filter-branch --force --index-filter \
  "git rm --cached --ignore-unmatch PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA" \
  --prune-empty --tag-name-filter cat -- --all
  git push --force --verbose --dry-run
  git push --force

Keep in mind that once you've pushed this code to a remote repository like GitHub and others have cloned that remote repository, you're now in a situation where you're rewriting history. When others try pull down your latest changes after this, they'll get a message indicating that the changes can't be applied because it's not a fast-forward.

To fix this, they'll have to either delete their existing repository and re-clone it, or follow the instructions under "RECOVERING FROM UPSTREAM REBASE" in the git-rebase manpage.

Tip: Execute git rebase --interactive


In the future, if you accidentally commit some changes with sensitive information but you notice before pushing to a remote repository, there are some easier fixes. If you last commit is the one to add the sensitive information, you can simply remove the sensitive information, then run:

git commit -a --amend

That will amend the previous commit with any new changes you've made, including entire file removals done with a git rm. If the changes are further back in history but still not pushed to a remote repository, you can do an interactive rebase:

git rebase -i origin/master

That opens an editor with the commits you've made since your last common ancestor with the remote repository. Change "pick" to "edit" on any lines representing a commit with sensitive information, and save and quit. Git will walk through the changes, and leave you at a spot where you can:

$EDITOR file-to-fix
git commit -a --amend
git rebase --continue

For each change with sensitive information. Eventually, you'll end up back on your branch, and you can safely push the new changes.

Android ListView with onClick items

I was able to go around the whole thing by replacing the context reference from this or Context.this to getapplicationcontext.

How to force a line break in a long word in a DIV?

I solved my problem with code below.

display: table-caption;

Check if value already exists within list of dictionaries?

Perhaps a function along these lines is what you're after:

 def add_unique_to_dict_list(dict_list, key, value):
  for d in dict_list:
     if key in d:
        return d[key]

  dict_list.append({ key: value })
  return value

How to make the HTML link activated by clicking on the <li>?

You could try an "onclick" event inside the LI tag, and change the "location.href" as in javascript.

You could also try placing the li tags within the a tags, however this is probably not valid HTML.

How to run a Python script in the background even after I logout SSH?

Run nohup python bgservice.py & to get the script to ignore the hangup signal and keep running. Output will be put in nohup.out.

Ideally, you'd run your script with something like supervise so that it can be restarted if (when) it dies.

Using multiple parameters in URL in express

app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
    var data = {
        "fruit": {
            "apple": req.params.fruitName,
            "color": req.params.fruitColor
        }
    }; 

    send.json(data);
});

If that doesn't work, try using console.log(req.params) to see what it is giving you.

Understanding dict.copy() - shallow or deep?

Take this example:

original = dict(a=1, b=2, c=dict(d=4, e=5))
new = original.copy()

Now let's change a value in the 'shallow' (first) level:

new['a'] = 10
# new = {'a': 10, 'b': 2, 'c': {'d': 4, 'e': 5}}
# original = {'a': 1, 'b': 2, 'c': {'d': 4, 'e': 5}}
# no change in original, since ['a'] is an immutable integer

Now let's change a value one level deeper:

new['c']['d'] = 40
# new = {'a': 10, 'b': 2, 'c': {'d': 40, 'e': 5}}
# original = {'a': 1, 'b': 2, 'c': {'d': 40, 'e': 5}}
# new['c'] points to the same original['d'] mutable dictionary, so it will be changed

Write a number with two decimal places SQL Server

This work for me and always keeps two digits fractions

23.1 ==> 23.10

25.569 ==> 25.56

1 ==> 1.00

Cast(CONVERT(DECIMAL(10,2),Value1) as nvarchar) AS Value2

Code screenshot

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

Faced same problem after migrating to python 3. Apparently, MySQL-python is incompatible, so as per official django docs, installed mysqlclient using pip install mysqlclient on Mac. Note that there are some OS specific issues mentioned in docs.

Quoting from docs:

Prerequisites

You may need to install the Python and MySQL development headers and libraries like so:

sudo apt-get install python-dev default-libmysqlclient-dev # Debian / Ubuntu

sudo yum install python-devel mysql-devel # Red Hat / CentOS

brew install mysql-connector-c # macOS (Homebrew) (Currently, it has bug. See below)

On Windows, there are binary wheels you can install without MySQLConnector/C or MSVC.

Note on Python 3 : if you are using python3 then you need to install python3-dev using the following command :

sudo apt-get install python3-dev # debian / Ubuntu

sudo yum install python3-devel # Red Hat / CentOS

Note about bug of MySQL Connector/C on macOS

See also: https://bugs.mysql.com/bug.php?id=86971

Versions of MySQL Connector/C may have incorrect default configuration options that cause compilation errors when mysqlclient-python is installed. (As of November 2017, this is known to be true for homebrew's mysql-connector-c and official package)

Modification of mysql_config resolves these issues as follows.

Change

# on macOS, on or about line 112:
# Create options
libs="-L$pkglibdir"
libs="$libs -l "

to

# Create options
libs="-L$pkglibdir"
libs="$libs -lmysqlclient -lssl -lcrypto"

An improper ssl configuration may also create issues; see, e.g, brew info openssl for details on macOS.

Install from PyPI

pip install mysqlclient

NOTE: Wheels for Windows may be not released with source package. You should pin version in your requirements.txt to avoid trying to install newest source package.

Install from source

  1. Download source by git clone or zipfile.
  2. Customize site.cfg
  3. python setup.py install

What does ':' (colon) do in JavaScript?

It can be used to list objects in a variable. Also, it is used a little bit in the shorthand of an if sentence:

var something = {face: 'hello',man: 'hey',go: 'sup'};

And calling it like this

alert(something.man);

Also the if sentence:

function something() {  
  (some) ? doathing() : dostuff(); // if some = true doathing();, else dostuff();
}

Delete specified file from document directory

I checked your code. It's working for me. Check any error you are getting using the modified code below

- (void)removeImage:(NSString *)filename
{
  NSFileManager *fileManager = [NSFileManager defaultManager];
  NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

  NSString *filePath = [documentsPath stringByAppendingPathComponent:filename];
  NSError *error;
  BOOL success = [fileManager removeItemAtPath:filePath error:&error];
  if (success) {
      UIAlertView *removedSuccessFullyAlert = [[UIAlertView alloc] initWithTitle:@"Congratulations:" message:@"Successfully removed" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
      [removedSuccessFullyAlert show];
  }
  else
  {
      NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
  }
}

Equivalent of *Nix 'which' command in PowerShell?

Check this PowerShell Which.

The code provided there suggests this:

($Env:Path).Split(";") | Get-ChildItem -filter notepad.exe

Convert HTML5 into standalone Android App

Create an Android app using Eclipse.

Create a layout that has a <WebView> control.

Move your HTML code to /assets folder.

Load webview with your file:///android_asset/ file.

And you have an android app!

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

Bump...

I just had the same error. I noticed that I was invoking super.doPost(request, response); when overriding the doPost() method as well as explicitly invoking the superclass constructor

    public ScheduleServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

As soon as I commented out the super.doPost(request, response); from within doPost() statement it worked perfectly...

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

        //super.doPost(request, response);
        // More code here...

}

Needless to say, I need to re-read on super() best practices :p

Calling Web API from MVC controller

well, you can do it a lot of ways... one of them is to create a HttpRequest. I would advise you against calling your own webapi from your own MVC (the idea is redundant...) but, here's a end to end tutorial.

How to copy Docker images from one host to another without using a repository

I want to move all images with tags.

```
OUT=$(docker images --format '{{.Repository}}:{{.Tag}}')
OUTPUT=($OUT)
docker save $(echo "${OUTPUT[*]}") -o /dir/images.tar
``` 

Explanation:

First OUT gets all tags but separated with new lines. Second OUTPUT gets all tags in an array. Third $(echo "${OUTPUT[*]}") puts all tags for a single docker save command so that all images are in a single tar.

Additionally, this can be zipped using gzip. On target, run:

tar xvf images.tar.gz -O | docker load

-O option to tar puts contents on stdin which can be grabbed by docker load.