Programs & Examples On #Binary decision diagram

In the field of computer science, a binary decision diagram (BDD) or branching program, like a negation normal form (NNF) or a propositional directed acyclic graph (PDAG), is a data structure that is used to represent a Boolean function. On a more abstract level, BDDs can be considered as a compressed representation of sets or relations.

What's the fastest way of checking if a point is inside a polygon in python

I will just leave it here, just rewrote the code above using numpy, maybe somebody finds it useful:

def ray_tracing_numpy(x,y,poly):
    n = len(poly)
    inside = np.zeros(len(x),np.bool_)
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        idx = np.nonzero((y > min(p1y,p2y)) & (y <= max(p1y,p2y)) & (x <= max(p1x,p2x)))[0]
        if p1y != p2y:
            xints = (y[idx]-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
        if p1x == p2x:
            inside[idx] = ~inside[idx]
        else:
            idxx = idx[x[idx] <= xints]
            inside[idxx] = ~inside[idxx]    

        p1x,p1y = p2x,p2y
    return inside    

Wrapped ray_tracing into

def ray_tracing_mult(x,y,poly):
    return [ray_tracing(xi, yi, poly[:-1,:]) for xi,yi in zip(x,y)]

Tested on 100000 points, results:

ray_tracing_mult 0:00:00.850656
ray_tracing_numpy 0:00:00.003769

getApplication() vs. getApplicationContext()

It seems to have to do with context wrapping. Most classes derived from Context are actually a ContextWrapper, which essentially delegates to another context, possibly with changes by the wrapper.

The context is a general abstraction that supports mocking and proxying. Since many contexts are bound to a limited-lifetime object such as an Activity, there needs to be a way to get a longer-lived context, for purposes such as registering for future notifications. That is achieved by Context.getApplicationContext(). A logical implementation is to return the global Application object, but nothing prevents a context implementation from returning a wrapper or proxy with a suitable lifetime instead.

Activities and services are more specifically associated with an Application object. The usefulness of this, I believe, is that you can create and register in the manifest a custom class derived from Application and be certain that Activity.getApplication() or Service.getApplication() will return that specific object of that specific type, which you can cast to your derived Application class and use for whatever custom purpose.

In other words, getApplication() is guaranteed to return an Application object, while getApplicationContext() is free to return a proxy instead.

How to print a dictionary's key?

Since we're all trying to guess what "print a key name" might mean, I'll take a stab at it. Perhaps you want a function that takes a value from the dictionary and finds the corresponding key? A reverse lookup?

def key_for_value(d, value):
    """Return a key in `d` having a value of `value`."""
    for k, v in d.iteritems():
        if v == value:
            return k

Note that many keys could have the same value, so this function will return some key having the value, perhaps not the one you intended.

If you need to do this frequently, it would make sense to construct the reverse dictionary:

d_rev = dict(v,k for k,v in d.iteritems())

How to determine the version of android SDK installed in computer?

Type in android list target into your command line to see what android API you are using.

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

Calling multiple JavaScript functions on a button click

At times it gives syntax error that "return is not a function" so in that case just remove return and it will work fine :) as shown below

OnClientClick="var b = validateView(); if(b) var b = ShowDiv1(); b;"

How to color the Git console?

In your ~/.gitconfig file, simply add this:

[color]
  ui = auto

It takes care of all your git commands.

Could not load file or assembly 'Microsoft.Web.Infrastructure,

It turns out after doing a Reference Cleaning, it removed Microsoft.Web.Infrastructure, but not from the packages.config file. After trying to add it again using the Package Manager Console, Visual Studio says that it is already installed which is false because it was removed.

I then removed the line of code in the packages.config file

<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" />

and ran the command again

PM> Install-Package Microsoft.Web.Infrastructure

After this, now it works fine.

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

In package manager console execute: Update-Package –reinstall Newtonsoft.Json.

UPDATE

I originally posted this as a comment but as @OwenBlacker suggested I'll just put it here:

If you still get an error after doing this, then what worked for me eventually is that I deleted Json.Net's <dependentAssembly> section from my .config file. Reinstall brings it back if it's not there and apparently you need to delete it. Until there will be a normal solution in the package itself, I'm afraid this manual step is a must.

Note: Please read the comments below before doing this.

As per René's comment below BE AWARE that the command posted in the answer will reinstall the package in every project in your solution. So if you use the Newtonsoft.Json package in several projects and maybe use different versions, just executing the above command might have unwanted consequences.

Why is quicksort better than mergesort?

That's hard to say.The worst of MergeSort is n(log2n)-n+1,which is accurate if n equals 2^k(I have already proved this).And for any n,it's between (n lg n - n + 1) and (n lg n + n + O(lg n)).But for quickSort,its best is nlog2n(also n equals 2^k).If you divide Mergesort by quickSort,it equals one when n is infinite.So it's as if the worst case of MergeSort is better than the best case of QuickSort,why do we use quicksort?But remember,MergeSort is not in place,it require 2n memeroy space.And MergeSort also need to do many array copies,which we don't include in the analysis of algorithm.In a word,MergeSort is really faseter than quicksort in theroy,but in reality you need to consider memeory space,the cost of array copy,merger is slower than quick sort.I once made an experiment where I was given 1000000 digits in java by Random class,and it took 2610ms by mergesort,1370ms by quicksort.

Postgresql query between date ranges

Just in case somebody land here... since 8.1 you can simply use:

SELECT user_id 
FROM user_logs 
WHERE login_date BETWEEN SYMMETRIC '2014-02-01' AND '2014-02-28'

From the docs:

BETWEEN SYMMETRIC is the same as BETWEEN except there is no requirement that the argument to the left of AND be less than or equal to the argument on the right. If it is not, those two arguments are automatically swapped, so that a nonempty range is always implied.

How can I display two div in one line via css inline property

You don't need to use display:inline to achieve this:

.inline { 
    border: 1px solid red;
    margin:10px;
    float:left;/*Add float left*/
    margin :10px;
}

You can use float-left.

Using float:left is best way to place multiple div elements in one line. Why? Because inline-block does have some problem when is viewed in IE older versions.

fiddle

Can I get a patch-compatible output from git-diff?

  1. I save the diff of the current directory (including uncommitted files) against the current HEAD.
  2. Then you can transport the save.patch file to wherever (including binary files).
  3. On your target machine, apply the patch using git apply <file>

Note: it diff's the currently staged files too.

$ git diff --binary --staged HEAD > save.patch
$ git reset --hard
$ <transport it>
$ git apply save.patch

How to tell PowerShell to wait for each command to end before starting the next?

There's always cmd. It may be less annoying if you have trouble quoting arguments to start-process:

cmd /c start /wait notepad

Or

notepad | out-host

git: patch does not apply

What I looked for is not exactly pointed out in here in SO, I'm writing for the benefit of others who might search for similar. I faced an issue with one file (present in old repo) getting removed in the repo. And when I apply the patch, it fails as it couldn't find the file to be applied. (so my case is git patch fails for file got removed) '#git apply --reject' definitely gave a view but didn't quite get me to the fix. I couldn't use wiggle as it is not available for us in our build servers. In my case, I got through this problem by removing the entry of the 'file which got removed in the repo' from patch file I've tried applying, so I got all other changes applied without an issue (using 3 way merge, avoiding white space errors), And then manually merging content of file removed into where its moved.

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

    <sonar.language>java</sonar.language>
    <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
    <sonar.jacoco.reportPath>${user.dir}/target/jacoco.exec</sonar.jacoco.reportPath>
    <sonar.jacoco.itReportPath>${user.dir}/target/jacoco-it.exec</sonar.jacoco.itReportPath>
    <sonar.exclusions>
        file:**/target/generated-sources/**,
        file:**/target/generated-test-sources/**,
        file:**/target/test-classes/**,
        file:**/model/*.java,
        file:**/*Config.java,
        file:**/*App.java
    </sonar.exclusions>

            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.7.9</version>
                <executions>
                    <execution>
                        <id>default-prepare-agent</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <destFile>${sonar.jacoco.reportPath}</destFile>
                            <append>true</append>
                            <propertyName>surefire.argLine</propertyName>
                        </configuration>
                    </execution>
                    <execution>
                        <id>default-prepare-agent-integration</id>
                        <goals>
                            <goal>prepare-agent-integration</goal>
                        </goals>
                        <configuration>
                            <destFile>${sonar.jacoco.itReportPath}</destFile>
                            <append>true</append>
                            <propertyName>failsafe.argLine</propertyName>
                        </configuration>
                    </execution>
                    <execution>
                        <id>default-report</id>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>default-report-integration</id>
                        <goals>
                            <goal>report-integration</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>             

plotting different colors in matplotlib

for color in ['r', 'b', 'g', 'k', 'm']:
    plot(x, y, color=color)

How does Facebook Sharer select Images and other metadata when sharing my URL?

As of 2013, if you're using facebook.com/sharer.php (PHP) you can simply make any button/link like:

<a class="btn" target="_blank" href="http://www.facebook.com/sharer.php?s=100&amp;p[title]=<?php echo urlencode(YOUR_TITLE);?>&amp;p[summary]=<?php echo urlencode(YOUR_PAGE_DESCRIPTION) ?>&amp;p[url]=<?php echo urlencode(YOUR_PAGE_URL); ?>&amp;p[images][0]=<?php echo urlencode(YOUR_LINK_THUMBNAIL); ?>">share on facebook</a>

Link query parameters:

p[title] = Define a page title
p[summary] = An URL description, most likely describing the contents of the page
p[url] = The absolute URL for the page you're sharing 
p[images][0] = The URL of the thumbnail image to be used as post thumbnail on facebook

It's plain simple: you do not need any js or other settings. Is just an HTML raw link. Style the A tag in any way you want to.

Block direct access to a file over http but allow php script access

That is how I prevented direct access from URL to my ini files. Paste the following code in .htaccess file on root. (no need to create extra folder)

<Files ~ "\.ini$">
  Order allow,deny
  Deny from all
</Files>

my settings.ini file is on the root, and without this code is accessible www.mydomain.com/settings.ini

What does the clearfix class do in css?

How floats work

When floating elements exist on the page, non-floating elements wrap around the floating elements, similar to how text goes around a picture in a newspaper. From a document perspective (the original purpose of HTML), this is how floats work.

float vs display:inline

Before the invention of display:inline-block, websites use float to set elements beside each other. float is preferred over display:inline since with the latter, you can't set the element's dimensions (width and height) as well as vertical paddings (top and bottom) - which floated elements can do since they're treated as block elements.

Float problems

The main problem is that we're using float against its intended purpose.

Another is that while float allows side-by-side block-level elements, floats do not impart shape to its container. It's like position:absolute, where the element is "taken out of the layout". For instance, when an empty container contains a floating 100px x 100px <div>, the <div> will not impart 100px in height to the container.

Unlike position:absolute, it affects the content that surrounds it. Content after the floated element will "wrap" around the element. It starts by rendering beside it and then below it, like how newspaper text would flow around an image.

Clearfix to the rescue

What clearfix does is to force content after the floats or the container containing the floats to render below it. There are a lot of versions for clear-fix, but it got its name from the version that's commonly being used - the one that uses the CSS property clear.

Examples

Here are several ways to do clearfix , depending on the browser and use case. One only needs to know how to use the clear property in CSS and how floats render in each browser in order to achieve a perfect cross-browser clear-fix.

What you have

Your provided style is a form of clearfix with backwards compatibility. I found an article about this clearfix. It turns out, it's an OLD clearfix - still catering the old browsers. There is a newer, cleaner version of it in the article also. Here's the breakdown:

  • The first clearfix you have appends an invisible pseudo-element, which is styled clear:both, between the target element and the next element. This forces the pseudo-element to render below the target, and the next element below the pseudo-element.

  • The second one appends the style display:inline-block which is not supported by earlier browsers. inline-block is like inline but gives you some properties that block elements, like width, height as well as vertical padding. This was targeted for IE-MAC.

  • This was the reapplication of display:block due to IE-MAC rule above. This rule was "hidden" from IE-MAC.

All in all, these 3 rules keep the .clearfix working cross-browser, with old browsers in mind.

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

I had to use Debug.print instead of Print, which works in the Immediate window.

Sub SendEmail()
    'Dim objHTTP As New MSXML2.XMLHTTP
    'Set objHTTP = New MSXML2.XMLHTTP60
    'Dim objHTTP As New MSXML2.XMLHTTP60
    Dim objHTTP As New WinHttp.WinHttpRequest
    'Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    'Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    URL = "http://localhost:8888/rest/mail/send"
    objHTTP.Open "POST", URL, False
    objHTTP.setRequestHeader "Content-Type", "application/json"
    objHTTP.send ("{""key"":null,""from"":""[email protected]"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
    Debug.Print objHTTP.Status
    Debug.Print objHTTP.ResponseText

End Sub

What is the size limit of a post request?

It is up to the http server to decide if there is a limit. The product I work on allows the admin to configure the limit.

Formatting floats in a numpy array

You can use round function. Here some example

numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53,   8.13,   3.97,  10.08])

IF you want change just display representation, I would not recommended to alter printing format globally, as it suggested above. I would format my output in place.

>>a=np.array([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01])
>>> print([ "{:0.2f}".format(x) for x in a ])
['21.53', '8.13', '3.97', '10.08']

How to swap two variables in JavaScript

Since ES6, you can also swap variables more elegantly:

var a = 1,
    b = 2;

[a, b] = [b, a];

console.log('a:', a, 'b:', b); // a: 2 b: 1

Passing an array as parameter in JavaScript

JavaScript is a dynamically typed language. This means that you never need to declare the type of a function argument (or any other variable). So, your code will work as long as arrayP is an array and contains elements with a value property.

How to define several include path in Makefile

Make's substitutions feature is nice and helped me to write

%.i: src/%.c $(INCLUDE)
        gcc -E $(CPPFLAGS) $(INCLUDE:%=-I %) $< > $@

You might find this useful, because it asks make to check for changes in include folders too

How do I list all tables in a schema in Oracle SQL?

To see all tables in another schema, you need to have one or more of the following system privileges:

SELECT ANY DICTIONARY
(SELECT | INSERT | UPDATE | DELETE) ANY TABLE

or the big-hammer, the DBA role.

With any of those, you can select:

SELECT DISTINCT OWNER, OBJECT_NAME 
  FROM DBA_OBJECTS
 WHERE OBJECT_TYPE = 'TABLE'
   AND OWNER = '[some other schema]'

Without those system privileges, you can only see tables you have been granted some level of access to, whether directly or through a role.

SELECT DISTINCT OWNER, OBJECT_NAME 
  FROM ALL_OBJECTS
 WHERE OBJECT_TYPE = 'TABLE'
   AND OWNER = '[some other schema]'

Lastly, you can always query the data dictionary for your own tables, as your rights to your tables cannot be revoked (as of 10g):

SELECT DISTINCT OBJECT_NAME 
  FROM USER_OBJECTS
 WHERE OBJECT_TYPE = 'TABLE'

Prevent form submission on Enter key press

Detect Enter key pressed on whole document:

$(document).keypress(function (e) {
    if (e.which == 13) {
        alert('enter key is pressed');
    }
});

http://jsfiddle.net/umerqureshi/dcjsa08n/3/

How to download files using axios

For axios POST request, the request should be something like this: The key here is that the responseType and header fields must be in the 3rd parameter of Post. The 2nd parameter is the application parameters.

export const requestDownloadReport = (requestParams) => async dispatch => { 
  let response = null;
  try {
    response = await frontEndApi.post('createPdf', {
      requestParams: requestParams,
    },
    {
      responseType: 'arraybuffer', // important...because we need to convert it to a blob. If we don't specify this, response.data will be the raw data. It cannot be converted to blob directly.
      headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/pdf'
      }
  });          
  }
  catch(err) {
    console.log('[requestDownloadReport][ERROR]', err);
    return err
  }

  return response;
}

Javascript: The prettiest way to compare one value against multiple values

(foobar == foo || foobar == bar) otherwise if you are comparing expressions based only on a single integer, enumerated value, or String object you can use switch. See The switch Statement. You can also use the method suggested by André Alçada Padez. Ultimately what you select will need to depend on the details of what you are doing.

Comparing object properties in c#

sometimes you don't want to compare all public properties and want to compare only the subset of them, so in this case you can just move logic to compare the desired list of properties to abstract class

public abstract class ValueObject<T> where T : ValueObject<T>
{
    protected abstract IEnumerable<object> GetAttributesToIncludeInEqualityCheck();

    public override bool Equals(object other)
    {
        return Equals(other as T);
    }

    public bool Equals(T other)
    {
        if (other == null)
        {
            return false;
        }

        return GetAttributesToIncludeInEqualityCheck()
            .SequenceEqual(other.GetAttributesToIncludeInEqualityCheck());
    }

    public static bool operator ==(ValueObject<T> left, ValueObject<T> right)
    {
        return Equals(left, right);
    }

    public static bool operator !=(ValueObject<T> left, ValueObject<T> right)
    {
        return !(left == right);
    }

    public override int GetHashCode()
    {
        int hash = 17;
        foreach (var obj in this.GetAttributesToIncludeInEqualityCheck())
            hash = hash * 31 + (obj == null ? 0 : obj.GetHashCode());

        return hash;
    }
}

and use this abstract class later to compare the objects

public class Meters : ValueObject<Meters>
{
    ...

    protected decimal DistanceInMeters { get; private set; }

    ...

    protected override IEnumerable<object> GetAttributesToIncludeInEqualityCheck()
    {
        return new List<Object> { DistanceInMeters };
    }
}

Doing a join across two databases with different collations on SQL Server and getting an error

You can use the collate clause in a query (I can't find my example right now, so my syntax is probably wrong - I hope it points you in the right direction)

select sone_field collate SQL_Latin1_General_CP850_CI_AI
  from table_1
    inner join table_2
      on (table_1.field collate SQL_Latin1_General_CP850_CI_AI = table_2.field)
  where whatever

How to check a boolean condition in EL?

Both works. Instead of == you can write eq

jQuery Ajax error handling, show custom exception messages

This is probably caused by the JSON field names not having quotation marks.

Change the JSON structure from:

{welcome:"Welcome"}

to:

{"welcome":"Welcome"}

Java ArrayList copy

Yes l1 and l2 will point to the same reference, same object.

If you want to create a new ArrayList based on the other ArrayList you do this:

List<String> l1 = new ArrayList<String>();
l1.add("Hello");
l1.add("World");
List<String> l2 = new ArrayList<String>(l1); //A new arrayList.
l2.add("Everybody");

The result will be l1 will still have 2 elements and l2 will have 3 elements.

Save Javascript objects in sessionStorage

The solution is to stringify the object before calling setItem on the sessionStorage.

var user = {'name':'John'};
sessionStorage.setItem('user', JSON.stringify(user));
var obj = JSON.parse(sessionStorage.user);

Dynamically create Bootstrap alerts box through JavaScript

function bootstrap_alert() {
        create = function (message, color) {
            $('#alert_placeholder')
                .html('<div class="alert alert-' + color
                    + '" role="alert"><a class="close" data-dismiss="alert">×</a><span>' + message
                    + '</span></div>');
        };
        warning = function (message) {
            create(message, "warning");
        };
        info = function (message) {
            create(message, "info");
        };
        light = function (message) {
            create(message, "light");
        };
        transparent = function (message) {
            create(message, "transparent");
        };
        return {
            warning: warning,
            info: info,
            light: light,
            transparent: transparent
        };
    }

Rownum in postgresql

Postgresql does not have an equivalent of Oracle's ROWNUM. In many cases you can achieve the same result by using LIMIT and OFFSET in your query.

Using PowerShell to remove lines from a text file if it contains a string

The pipe character | has a special meaning in regular expressions. a|b means "match either a or b". If you want to match a literal | character, you need to escape it:

... | Select-String -Pattern 'H\|159' -NotMatch | ...

Android button with icon and text

You can use the Material Components Library and the MaterialButton component.
Use the app:icon and app:iconGravity="start" attributes.

Something like:

  <com.google.android.material.button.MaterialButton
        style="@style/Widget.MaterialComponents.Button.Icon"
        app:icon="@drawable/..."
        app:iconGravity="start"
        ../>

enter image description here

reading from stdin in c++

You have not defined the variable input_line.

Add this:

string input_line;

And add this include.

#include <string>

Here is the full example. I also removed the semi-colon after the while loop, and you should have getline inside the while to properly detect the end of the stream.

#include <iostream>
#include <string>

int main() {
    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }
    return 0;
}

Need to combine lots of files in a directory

Assuming these are text files (since you are using notepad++) and that you are on Windows, you could fashion a simple batch script to concatenate them together.

For example, in the directory with all the text files, execute the following:

for %f in (*.txt) do type "%f" >> combined.txt

This will merge all files matching *.txt into one file called combined.txt.

For more information:

http://www.howtogeek.com/howto/keyboard-ninja/keyboard-ninja-concatenate-multiple-text-files-in-windows/

what is difference between success and .done() method of $.ajax

In short, decoupling success callback function from the ajax function so later you can add your own handlers without modifying the original code (observer pattern).

Please find more detailed information from here: https://stackoverflow.com/a/14754681/1049184

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

If the numbers are evenly distributed we can use Counting sort. We should keep the number of times that each number is repeated in an array. Available space is: 1 MB - 3 KB = 1045504 B or 8364032 bits Number of bits per number= 8364032/1000000 = 8 Therefore, we can store the number of times each number is repeated to the maximum of 2^8-1=255. Using this approach we have an extra 364032 bits unused that can be used to handle cases where a number is repeated more than 255 times. For example we can say a number 255 indicates a repetition greater than or equal to 255. In this case we should store a sequence of numbers+repetitions. We can handle 7745 special cases as shown bellow:

364032/ (bits need to represent each number + bits needed to represent 1 million)= 364032 / (27+20)=7745

Array functions in jQuery

The Visual jQuery site has some great examples of jQuery's array functionality. (Click "Utilities" on the left-hand tab, and then "Array and Object operations".)

What Vim command(s) can be used to quote/unquote words?

I wrote a script that does this:

function! WrapSelect (front)
    "puts characters around the selected text.
    let l:front = a:front
    if (a:front == '[')
        let l:back = ']'
    elseif (a:front == '(')
        let l:back = ')'
    elseif (a:front == '{')
        let l:back = '}'
    elseif (a:front == '<')
        let l:back = '>'
    elseif (a:front =~ " ")
        let l:split = split(a:front)
        let l:back = l:split[1]
        let l:front = l:split[0]
    else
        let l:back = a:front
    endif
    "execute: concat all these strings. '.' means "concat without spaces"
    "norm means "run in normal mode and also be able to use \<C-x> characters"
    "gv means "get the previous visual selection back up"
    "c means "cut visual selection and go to insert mode"
    "\<C-R> means "insert the contents of a register. in this case, the
    "default register"
    execute 'norm! gvc' . l:front. "\<C-R>\""  . l:back
endfunction
vnoremap <C-l> :<C-u>call WrapSelect(input('Wrapping? Give both (space separated) or just the first one: '))<cr>

To use, just highlight something, hit control l, and then type a character. If it's one of the characters the function knows about, it'll provide the correct terminating character. If it's not, it'll use the same character to insert on both sides.

Surround.vim can do more than just this, but this was sufficient for my needs.

how to remove pagination in datatable

You should include "bPaginate": false, into the configuration object you pass to your constructor parameters. As seen here: http://datatables.net/release-datatables/examples/basic_init/filter_only.html

Java: Check if enum contains a given string?

public boolean contains(Choices value) {
   return EnumSet.allOf(Choices.class).contains(value);
}

How to use bluetooth to connect two iPhone?

If I remember correctly, Bluetooth defines certain roles that devices can take. Most cell phones only support a certain number of roles. For instance, I can have a Bluetooth stereo headset that connects to my phone to receive audio, but just because my cell phone has Bluetooth does mean that it supports BEING a speaker for a different device - it doesn't advertise its capabilities of having a speaker for use by other Bluetooth devices.

I assume you want to transfer files between two iPhones? Transferring files via Bluetooth does seem like functionality that I would put in the iPhone, but I'm not Apple so I don't know for sure. In fact, yes, it seems that file transfer is not supported except in jailbroken phones:

http://gizmodo.com/5138797/iphone-bluetooth-file-transfer-coming-soon-yes

You'll probably get similar answers for Bluetooth Dial-Up Networking. I'd imagine they kept the Bluetooth commands out of the SDK for various reasons and you'll have to jailbreak your phone to get the functionality back.

How to return multiple objects from a Java method?

You can utilize a HashMap<String, Object> as follows

public HashMap<String, Object> yourMethod()
{

   .... different logic here 

  HashMap<String, Object> returnHashMap = new HashMap<String, Object>();
  returnHashMap.put("objectA", objectAValue);
  returnHashMap.put("myString", myStringValue);
  returnHashMap.put("myBoolean", myBooleanValue);

  return returnHashMap;
}

Then when calling the method in a different scope, you can cast each object back to its initial type:

// call the method
HashMap<String, Object> resultMap = yourMethod();
                
// fetch the results and cast them
ObjectA objectA = (ObjectA) resultMap.get("objectA");
String myString = (String) resultMap.get("myString");
Boolean myBoolean = (Boolean) resultMap.get("myBoolean");

How to use mongoimport to import csv

I use this on mongoimport shell

mongoimport --db db_name --collection collection_name --type csv --file C:\\Your_file_path\target_file.csv --headerline

type can choose csv/tsv/json But only csv/tsv can use --headerline

You can read more on the offical doc.

In android app Toolbar.setTitle method has no effect – application name is shown as title

Though not immediately relevant to this particular setup, I found that removing "CollapsingToolbarLayout" from my XML that was wrapping my toolbar inside of an AppBarLayout made everything work.

So, this:

      <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_height="?attr/actionBarSize"
                app:layout_scrollFlags="scroll|enterAlways"
                app:navigationIcon="@drawable/ic_arrow_back_white_24dp" />

        </android.support.design.widget.AppBarLayout>

Instead of this:

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.CollapsingToolbarLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/collapsingToolbar"
                android:minHeight="?attr/actionBarSize"
                app:layout_scrollFlags="enterAlways|scroll|snap">

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_height="?attr/actionBarSize"
                    app:navigationIcon="@drawable/ic_arrow_back_white_24dp" />
            </android.support.design.widget.CollapsingToolbarLayout>

        </android.support.design.widget.AppBarLayout>

Then, I set the title in the activity's onCreate, before setSupportActionBar() is called.

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare();

runOnUiThread(new Runnable(){
   public void run() {
     Toast.makeText(getApplicationContext(), "Status = " + message.getBody() , Toast.LENGTH_LONG).show();
   }
 });

this works for me

How to select Python version in PyCharm?

Quick Answer:

  • File --> Setting
  • In left side in project section --> Project interpreter
  • Select desired Project interpreter
  • Apply + OK

[NOTE]:

Tested on Pycharm 2018 and 2017.


How to take last four characters from a varchar?

SUBSTR(column, LENGTH(column) - 3, 4)

LENGTH returns length of string and SUBSTR returns 4 characters from "the position length - 4"

Synchronization vs Lock

You can achieve everything the utilities in java.util.concurrent do with the low-level primitives like synchronized, volatile, or wait / notify

However, concurrency is tricky, and most people get at least some parts of it wrong, making their code either incorrect or inefficient (or both).

The concurrent API provides a higher-level approach, which is easier (and as such safer) to use. In a nutshell, you should not need to use synchronized, volatile, wait, notify directly anymore.

The Lock class itself is on the lower-level side of this toolbox, you may not even need to use that directly either (you can use Queues and Semaphore and stuff, etc, most of the time).

How do I write a compareTo method which compares objects?

If you using compare To method of the Comparable interface in any class. This can be used to arrange the string in Lexicographically.

public class Student() implements Comparable<Student>{

public int compareTo(Object obj){
if(this==obj){
    return 0;
}
if(obj!=null){
    String objName = ((Student)obj).getName();
    return this.name.comapreTo.(objName);
}
}

Determine function name from within that function (without using traceback)

This is actually derived from the other answers to the question.

Here's my take:

import sys

# for current func name, specify 0 or no argument.
# for name of caller of current func, specify 1.
# for name of caller of caller of current func, specify 2. etc.
currentFuncName = lambda n=0: sys._getframe(n + 1).f_code.co_name


def testFunction():
    print "You are in function:", currentFuncName()
    print "This function's caller was:", currentFuncName(1)    


def invokeTest():
    testFunction()


invokeTest()

# end of file

The likely advantage of this version over using inspect.stack() is that it should be thousands of times faster [see Alex Melihoff's post and timings regarding using sys._getframe() versus using inspect.stack() ].

Stacking DIVs on top of each other?

I had the same requirement which i have tried in below fiddle.

#container1 {
background-color:red;
position:absolute;
left:0;
top:0;
height:230px;
width:300px;
z-index:2;
}
#container2 {
background-color:blue;
position:absolute;
left:0;
top:0;
height:300px;
width:300px;
z-index:1;
}

#container {
position : relative;
height:350px;
width:350px;
background-color:yellow;
}

https://plnkr.co/edit/XnlneRFlvo1pB92UXCC6?p=preview

@Html.DropDownListFor how to set default value

SelectListItem has a Selected property. If you are creating the SelectListItems dynamically, you can just set the one you want as Selected = true and it will then be the default.

SelectListItem defaultItem = new SelectListItem()
{
   Value = 1,
   Text = "Default Item",
   Selected = true
};

HTML checkbox - allow to check only one checkbox

Checkboxes, by design, are meant to be toggled on or off. They are not dependent on other checkboxes, so you can turn as many on and off as you wish.

Radio buttons, however, are designed to only allow one element of a group to be selected at any time.

References:

Checkboxes: MDN Link

Radio Buttons: MDN Link

Redirect stderr and stdout in Bash

For tcsh, I have to use the following command :

command >& file

If use command &> file , it will give "Invalid null command" error.

build-impl.xml:1031: The module has not been deployed

One of the main reason for this error is due to permission not granted to all users. so remove this error, follow the following steps :
1) Go to the C:/Programme Files/Apache Software Foundation/Tomcat 7.0
2) Right click on the Tomcat 7.0 folder and click on properties.
3) go to Security Tab.
4) Select the User and click on Edit... button
5) Grant all the permission to the user and click on apply and ok.
Refresh the system and now try. I hope it will work

Set value to an entire column of a pandas dataframe

You can use the assign function:

df = df.assign(industry='yyy')

How to download a folder from github?

You can also just clone the repo, after cloning is done, just pick the folder or vile that you want. To clone:

git clone https://github.com/somegithubuser/somgithubrepo.git

then go to the cloned DIR and find your file or DIR you want to copy.

jQuery Datepicker localization

datepicker in Finnish (Käännös suomeksi)

$.datepicker.regional['fi'] = {
  closeText: "Valmis", // Display text for close link
  prevText: "Edel", // Display text for previous month link
  nextText: "Seur", // Display text for next month link
  currentText: "Tänään", // Display text for current month link
  monthNames: [ "Tammikuu","Helmikuu","Maaliskuu","Huhtikuu","Toukokuu","Kesäkuu",
  "Heinäkuu","Elokuu","Syyskuu","Lokakuu","Marraskuu","Joulukuu" ], // Names of months for drop-down and formatting
  monthNamesShort: [ "Tam", "Hel", "Maa", "Huh", "Tou", "Kes", "Hei", "Elo", "Syy", "Lok", "Mar", "Jou" ], // For formatting
  dayNames: [ "Sunnuntai", "Maanantai", "Tiistai", "Keskiviikko", "Torstai", "Perjantai", "Lauantai" ], // For formatting
  dayNamesShort: [ "Sun", "Maa", "Tii", "Kes", "Tor", "Per", "Lau" ], // For formatting
  dayNamesMin: [ "Su","Ma","Ti","Ke","To","Pe","La" ], // Column headings for days starting at Sunday
  weekHeader: "Vk", // Column header for week of the year
  dateFormat: "mm/dd/yy", // See format options on parseDate
  firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
  isRTL: false, // True if right-to-left language, false if left-to-right
  showMonthAfterYear: false, // True if the year select precedes month, false for month then year
  yearSuffix: "" // Additional text to append to the year in the month headers
  };

Running bash script from within python

Making sleep.sh executable and adding shell=True to the parameter list (as suggested in previous answers) works ok. Depending on the search path, you may also need to add ./ or some other appropriate path. (Ie, change "sleep.sh" to "./sleep.sh".)

The shell=True parameter is not needed (under a Posix system like Linux) if the first line of the bash script is a path to a shell; for example, #!/bin/bash.

What is time(NULL) in C?

You have to refer to the documentation for ctime. time is a function that takes one parameter of type time_t * (a pointer to a time_t object) and assigns to it the current time. Instead of passing this pointer, you can also pass NULL and then use the returned time_t value instead.

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

You can use native JS so you don't have to rely on external libraries.

(I will use some ES2015 syntax, a.k.a ES6, modern javascript) What is ES2015?

fetch('/api/rest/abc')
    .then(response => response.json())
    .then(data => {
        // Do what you want with your data
    });

You can also capture errors if any:

fetch('/api/rest/abc')
    .then(response => response.json())
    .then(data => {
        // Do what you want with your data
    })
    .catch(err => {
        console.error('An error ocurred', err);
    });

By default it uses GET and you don't have to specify headers, but you can do all that if you want. For further reference: Fetch API reference

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

I had this problem today and it didn't have anything to do with any of the other answers. Here's what I did and how I fixed it:

A repository of mine recently moved, but I had a local copy. I branched off of my local "master" branch and made some changes--and then I remembered that the repository had moved. I used git remote set-url origin https://<my_new_repository_url> to set the new URL but when I pushed it would just say "Everything up to date" instead of pushing my new branch to master.

I ended up solving it by rebasing onto origin/master and then pushing with explicit branch names, like this:

$ git rebase <my_branch> origin/master
$ git push origin <my_branch>

I hope this helps anyone who had my same problem!

React-Native: Module AppRegistry is not a registered callable module

For me just i linked with react native as this way : react-native link

Clearfix with twitter bootstrap

clearfix should contain the floating elements but in your html you have added clearfix only after floating right that is your pull-right so you should do like this:

<div class="clearfix">
  <div id="sidebar">
    <ul>
      <li>A</li>
      <li>A</li>
      <li>C</li>
      <li>D</li>
      <li>E</li>
      <li>F</li>
      <li>...</li>
      <li>Z</li>
    </ul>
  </div>
  <div id="main">
    <div>
      <div class="pull-right">
        <a>RIGHT</a>
      </div>
    </div>
  <div>MOVED BELOW Z</div>
</div>

see this demo


Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden; as you have done in your main.

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Creating .exe distributions isn't typical for Java. While such wrappers do exist, the normal mode of operation is to create a .jar file.

To create a .jar file from a Java project in Eclipse, use file->export->java->Jar file. This will create an archive with all your classes.

On the command prompt, use invocation like the following:

java -cp myapp.jar foo.bar.MyMainClass

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

Your URL should be jdbc:sqlserver://server:port;DatabaseName=dbname
and Class name should be like com.microsoft.sqlserver.jdbc.SQLServerDriver
Use MicrosoftSQL Server JDBC Driver 2.0

T-SQL CASE Clause: How to specify WHEN NULL

Jason caught an error, so this works...

Can anyone confirm the other platform versions?
SQL Server:

SELECT
CASE LEN(ISNULL(last_name,'')) 
WHEN 0 THEN '' 
ELSE ' ' + last_name
END AS newlastName

MySQL:

SELECT
CASE LENGTH(IFNULL(last_name,'')) 
WHEN 0 THEN '' 
ELSE ' ' + last_name
END AS newlastName

Oracle:

SELECT
CASE LENGTH(NVL(last_name,'')) 
WHEN 0 THEN '' 
ELSE ' ' + last_name
END AS newlastName

Add event handler for body.onload by javascript within <body> part

body.addEventListener("load", init(), false);

That init() is saying run this function now and assign whatever it returns to the load event.

What you want is to assign the reference to the function, not the result. So you need to drop the ().

body.addEventListener("load", init, false);

Also you should be using window.onload and not body.onload

addEventListener is supported in most browsers except IE 8.

Create a Date with a set timezone without using a string representation

if you want to check the difference in a time between two dates, you can simply check if second timezone is lesser or greater from your first desired timezone and subtract or add a time.

  const currTimezone = new Date().getTimezoneOffset(); // your timezone
  const newDateTimezone = date.getTimezoneOffset(); // date with unknown timezone

  if (currTimezone !== newDateTimezone) {
    // and below you are checking if difference should be - or +. It depends on if unknown timezone is lesser or greater than yours
    const newTimezone = (currTimezone - newDateTimezone) * (currTimezone > newDateTimezone ? 1 : -1);
    date.setTime(date.getTime() + (newTimezone * 60 * 1000));
  }

How to escape a single quote inside awk

This maybe what you're looking for:

awk 'BEGIN {FS=" ";} {printf "'\''%s'\'' ", $1}'

That is, with '\'' you close the opening ', then print a literal ' by escaping it and finally open the ' again.

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

This can be due to byte alignment and padding so that the structure comes out to an even number of bytes (or words) on your platform. For example in C on Linux, the following 3 structures:

#include "stdio.h"


struct oneInt {
  int x;
};

struct twoInts {
  int x;
  int y;
};

struct someBits {
  int x:2;
  int y:6;
};


int main (int argc, char** argv) {
  printf("oneInt=%zu\n",sizeof(struct oneInt));
  printf("twoInts=%zu\n",sizeof(struct twoInts));
  printf("someBits=%zu\n",sizeof(struct someBits));
  return 0;
}

Have members who's sizes (in bytes) are 4 bytes (32 bits), 8 bytes (2x 32 bits) and 1 byte (2+6 bits) respectively. The above program (on Linux using gcc) prints the sizes as 4, 8, and 4 - where the last structure is padded so that it is a single word (4 x 8 bit bytes on my 32bit platform).

oneInt=4
twoInts=8
someBits=4

Determine project root from a running node.js application

Old question, I know, however no question mention to use progress.argv. The argv array includes a full pathname and filename (with or without .js extension) that was used as parameter to be executed by node. Because this also can contain flags, you must filter this.

This is not an example you can directly use (because of using my own framework) but I think it gives you some idea how to do it. I also use a cache method to avoid that calling this function stress the system too much, especially when no extension is specified (and a file exist check is required), for example:

node myfile

or

node myfile.js

That's the reason I cache it, see also code below.


function getRootFilePath()
{
        if( !isDefined( oData.SU_ROOT_FILE_PATH ) )
        {
            var sExt = false;

            each( process.argv, function( i, v )
            {
                 // Skip invalid and provided command line options
                if( !!v && isValidString( v ) && v[0] !== '-' )
                {
                    sExt = getFileExt( v );

                    if( ( sExt === 'js' ) || ( sExt === '' && fileExists( v+'.js' )) )
                    {

                        var a = uniformPath( v ).split("/"); 

                         // Chop off last string, filename
                        a[a.length-1]='';

                         // Cache it so we don't have to do it again.
                        oData.SU_ROOT_FILE_PATH=a.join("/"); 

                         // Found, skip loop
                        return true;
                    }
                }
            }, true ); // <-- true is: each in reverse order
        }

        return oData.SU_ROOT_FILE_PATH || '';
    }
}; 

How do I get to IIS Manager?

You need to make sure the IIS Management Console is installed.

Recommended way to embed PDF in HTML?

I found this works just fine and the browser handles it in firefox. I have not checked IE...

<script>window.location='url'</script>

Why do we usually use || over |? What is the difference?

The operators || and && are called conditional operators, while | and & are called bitwise operators. They serve different purposes.

Conditional operators works only with expressions that statically evaluate to boolean on both left- and right-hand sides.

Bitwise operators works with any numeric operands.

If you want to perform a logical comparison, you should use conditional operators, since you will add some kind of type safety to your code.

"Call to undefined function mysql_connect()" after upgrade to php-7

From the PHP Manual:

Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

mysqli_connect()

PDO::__construct()

use MySQLi or PDO

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

Angular cli generate a service and include the provider in one step

Specify paths

--app
  --one
    one.module.ts
    --services

  --two
    two.module.ts
    --services

Create Service with new folder in module ONE

ng g service one/services/myNewServiceFolderName/serviceOne --module one/one

--one
  one.module.ts // service imported and added to providers.
  --services
    --myNewServiceFolderName
      serviceOne.service.ts
      serviceOne.service.spec.ts

I want to convert std::string into a const wchar_t *

If you have a std::wstring object, you can call c_str() on it to get a wchar_t*:

std::wstring name( L"Steve Nash" );
const wchar_t* szName = name.c_str();

Since you are operating on a narrow string, however, you would first need to widen it. There are various options here; one is to use Windows' built-in MultiByteToWideChar routine. That will give you an LPWSTR, which is equivalent to wchar_t*.

How do I convert special UTF-8 chars to their iso-8859-1 equivalent using javascript?

Actually, everything is typically stored as Unicode of some kind internally, but lets not go into that. I'm assuming you're getting the iconic "åäö" type strings because you're using an ISO-8859 as your character encoding. There's a trick you can do to convert those characters. The escape and unescape functions used for encoding and decoding query strings are defined for ISO characters, whereas the newer encodeURIComponent and decodeURIComponent which do the same thing, are defined for UTF8 characters.

escape encodes extended ISO-8859-1 characters (UTF code points U+0080-U+00ff) as %xx (two-digit hex) whereas it encodes UTF codepoints U+0100 and above as %uxxxx (%u followed by four-digit hex.) For example, escape("å") == "%E5" and escape("?") == "%u3042".

encodeURIComponent percent-encodes extended characters as a UTF8 byte sequence. For example, encodeURIComponent("å") == "%C3%A5" and encodeURIComponent("?") == "%E3%81%82".

So you can do:

fixedstring = decodeURIComponent(escape(utfstring));

For example, an incorrectly encoded character "å" becomes "Ã¥". The command does escape("Ã¥") == "%C3%A5" which is the two incorrect ISO characters encoded as single bytes. Then decodeURIComponent("%C3%A5") == "å", where the two percent-encoded bytes are being interpreted as a UTF8 sequence.

If you'd need to do the reverse for some reason, that works too:

utfstring = unescape(encodeURIComponent(originalstring));

Is there a way to differentiate between bad UTF8 strings and ISO strings? Turns out there is. The decodeURIComponent function used above will throw an error if given a malformed encoded sequence. We can use this to detect with a great probability whether our string is UTF8 or ISO.

var fixedstring;

try{
    // If the string is UTF-8, this will work and not throw an error.
    fixedstring=decodeURIComponent(escape(badstring));
}catch(e){
    // If it isn't, an error will be thrown, and we can assume that we have an ISO string.
    fixedstring=badstring;
}

Turn a simple socket into an SSL socket

For others like me:

There was once an example in the SSL source in the directory demos/ssl/ with example code in C++. Now it's available only via the history: https://github.com/openssl/openssl/tree/691064c47fd6a7d11189df00a0d1b94d8051cbe0/demos/ssl

You probably will have to find a working version, I originally posted this answer at Nov 6 2015. And I had to edit the source -- not much.

Certificates: .pem in demos/certs/apps/: https://github.com/openssl/openssl/tree/master/demos/certs/apps

Current Subversion revision command

REV=svn info svn://svn.code.sf.net/p/retroshare/code/trunk | grep 'Revision:' | cut -d\ -f2

Why are my CSS3 media queries not working on mobile devices?

It may also happen if the browser zoom level is not correct. Your browser window zoom should be 100%. In Chrome use Ctrl + 0 to reset the zoom level.

Update MongoDB field using value of another field

I tried the above solution but I found it unsuitable for large amounts of data. I then discovered the stream feature:

MongoClient.connect("...", function(err, db){
    var c = db.collection('yourCollection');
    var s = c.find({/* your query */}).stream();
    s.on('data', function(doc){
        c.update({_id: doc._id}, {$set: {name : doc.firstName + ' ' + doc.lastName}}, function(err, result) { /* result == true? */} }
    });
    s.on('end', function(){
        // stream can end before all your updates do if you have a lot
    })
})

When to use reinterpret_cast?

First you have some data in a specific type like int here:

int x = 0x7fffffff://==nan in binary representation

Then you want to access the same variable as an other type like float: You can decide between

float y = reinterpret_cast<float&>(x);

//this could only be used in cpp, looks like a function with template-parameters

or

float y = *(float*)&(x);

//this could be used in c and cpp

BRIEF: it means that the same memory is used as a different type. So you could convert binary representations of floats as int type like above to floats. 0x80000000 is -0 for example (the mantissa and exponent are null but the sign, the msb, is one. This also works for doubles and long doubles.

OPTIMIZE: I think reinterpret_cast would be optimized in many compilers, while the c-casting is made by pointerarithmetic (the value must be copied to the memory, cause pointers couldn't point to cpu- registers).

NOTE: In both cases you should save the casted value in a variable before cast! This macro could help:

#define asvar(x) ({decltype(x) __tmp__ = (x); __tmp__; })

How do I resolve `The following packages have unmet dependencies`

First, run

sudo apt-get install nodejs-dev node-gyp libssl1.0-dev

then run

sudo apt install npm

jquery can't get data attribute value

Changing the casing to all lowercases worked for me.

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

@fins's answer has an overflow issue on Arduio as you turn the saturation down. Here it is with some values converted to int to prevent that.

typedef struct RgbColor
{
    unsigned char r;
    unsigned char g;
    unsigned char b;
} RgbColor;

typedef struct HsvColor
{
    unsigned char h;
    unsigned char s;
    unsigned char v;
} HsvColor;

RgbColor HsvToRgb(HsvColor hsv)
{
    RgbColor rgb;
    unsigned char region, p, q, t;
    unsigned int h, s, v, remainder;

    if (hsv.s == 0)
    {
        rgb.r = hsv.v;
        rgb.g = hsv.v;
        rgb.b = hsv.v;
        return rgb;
    }

    // converting to 16 bit to prevent overflow
    h = hsv.h;
    s = hsv.s;
    v = hsv.v;

    region = h / 43;
    remainder = (h - (region * 43)) * 6; 

    p = (v * (255 - s)) >> 8;
    q = (v * (255 - ((s * remainder) >> 8))) >> 8;
    t = (v * (255 - ((s * (255 - remainder)) >> 8))) >> 8;

    switch (region)
    {
        case 0:
            rgb.r = v;
            rgb.g = t;
            rgb.b = p;
            break;
        case 1:
            rgb.r = q;
            rgb.g = v;
            rgb.b = p;
            break;
        case 2:
            rgb.r = p;
            rgb.g = v;
            rgb.b = t;
            break;
        case 3:
            rgb.r = p;
            rgb.g = q;
            rgb.b = v;
            break;
        case 4:
            rgb.r = t;
            rgb.g = p;
            rgb.b = v;
            break;
        default:
            rgb.r = v;
            rgb.g = p;
            rgb.b = q;
            break;
    }

    return rgb;
}

HsvColor RgbToHsv(RgbColor rgb)
{
    HsvColor hsv;
    unsigned char rgbMin, rgbMax;

    rgbMin = rgb.r < rgb.g ? (rgb.r < rgb.b ? rgb.r : rgb.b) : (rgb.g < rgb.b ? rgb.g : rgb.b);
    rgbMax = rgb.r > rgb.g ? (rgb.r > rgb.b ? rgb.r : rgb.b) : (rgb.g > rgb.b ? rgb.g : rgb.b);

    hsv.v = rgbMax;
    if (hsv.v == 0)
    {
        hsv.h = 0;
        hsv.s = 0;
        return hsv;
    }

    hsv.s = 255 * ((long)(rgbMax - rgbMin)) / hsv.v;
    if (hsv.s == 0)
    {
        hsv.h = 0;
        return hsv;
    }

    if (rgbMax == rgb.r)
        hsv.h = 0 + 43 * (rgb.g - rgb.b) / (rgbMax - rgbMin);
    else if (rgbMax == rgb.g)
        hsv.h = 85 + 43 * (rgb.b - rgb.r) / (rgbMax - rgbMin);
    else
        hsv.h = 171 + 43 * (rgb.r - rgb.g) / (rgbMax - rgbMin);

    return hsv;
}

Using partial views in ASP.net MVC 4

You're passing the same model to the partial view as is being passed to the main view, and they are different types. The model is a DbSet of Notes, where you need to pass in a single Note.

You can do this by adding a parameter, which I'm guessing as it's the create form would be a new Note

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

How to validate phone numbers using regex

Here's my best try so far. It handles the formats above but I'm sure I'm missing some other possible formats.

^\d?(?:(?:[\+]?(?:[\d]{1,3}(?:[ ]+|[\-.])))?[(]?(?:[\d]{3})[\-/)]?(?:[ ]+)?)?(?:[a-zA-Z2-9][a-zA-Z0-9 \-.]{6,})(?:(?:[ ]+|[xX]|(i:ext[\.]?)){1,2}(?:[\d]{1,5}))?$

How to render html with AngularJS templates

In angular 4+ we can use innerHTML property instead of ng-bind-html.

In my case, it's working and I am using angular 5.

<div class="chart-body" [innerHTML]="htmlContent"></div>

In.ts file

let htmlContent = 'This is the `<b>Bold</b>` text.';

How can I use Timer (formerly NSTimer) in Swift?

SimpleTimer (Swift 3.1)

Why?

This is a simple timer class in swift that enables you to:

  • Local scoped timer
  • Chainable
  • One liners
  • Use regular callbacks

Usage:

SimpleTimer(interval: 3,repeats: true){print("tick")}.start()//Ticks every 3 secs

Code:

class SimpleTimer {/*<--was named Timer, but since swift 3, NSTimer is now Timer*/
    typealias Tick = ()->Void
    var timer:Timer?
    var interval:TimeInterval /*in seconds*/
    var repeats:Bool
    var tick:Tick

    init( interval:TimeInterval, repeats:Bool = false, onTick:@escaping Tick){
        self.interval = interval
        self.repeats = repeats
        self.tick = onTick
    }
    func start(){
        timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(update), userInfo: nil, repeats: true)//swift 3 upgrade
    }
    func stop(){
        if(timer != nil){timer!.invalidate()}
    }
    /**
     * This method must be in the public or scope
     */
    @objc func update() {
        tick()
    }
}

Given a view, how do I get its viewController?

The fast and generic way in Swift 3:

extension UIResponder {
    func parentController<T: UIViewController>(of type: T.Type) -> T? {
        guard let next = self.next else {
            return nil
        }
        return (next as? T) ?? next.parentController(of: T.self)
    }
}

//Use:
class MyView: UIView {
    ...
    let parentController = self.parentController(of: MyViewController.self)
}

Fuzzy matching using T-SQL

Regarding de-duping things your string split and match is great first cut. If there are known items about the data that can be leveraged to reduce workload and/or produce better results, it is always good to take advantage of them. Bear in mind that often for de-duping it is impossible to entirely eliminate manual work, although you can make that much easier by catching as much as you can automatically and then generating reports of your "uncertainty cases."

Regarding name matching: SOUNDEX is horrible for quality of matching and especially bad for the type of work you are trying to do as it will match things that are too far from the target. It's better to use a combination of double metaphone results and the Levenshtein distance to perform name matching. With appropriate biasing this works really well and could probably be used for a second pass after doing a cleanup on your knowns.

You may also want to consider using an SSIS package and looking into Fuzzy Lookup and Grouping transformations (http://msdn.microsoft.com/en-us/library/ms345128(SQL.90).aspx).

Using SQL Full-Text Search (http://msdn.microsoft.com/en-us/library/cc879300.aspx) is a possibility as well, but is likely not appropriate to your specific problem domain.

Fastest method to replace all instances of a character in a string

I just coded a benchmark and tested the first 3 answers. It seems that for short strings (<500 characters)
the third most voted answer is faster than the second most voted one.

For long strings (add ".repeat(300)" to the test string) the faster is answer 1 followed by the second and the third.

Note:

The above is true for browsers using v8 engine (chrome/chromium etc).
With firefox (SpiderMonkey engine) the results are totally different
Check for yourselves!! Firefox with the third solution seems to be
more than 4.5 times faster than Chrome with the first solution... crazy :D

_x000D_
_x000D_
function log(data) {_x000D_
  document.getElementById("log").textContent += data + "\n";_x000D_
}_x000D_
_x000D_
benchmark = (() => {_x000D_
_x000D_
  time_function = function(ms, f, num) {_x000D_
    var z;_x000D_
    var t = new Date().getTime();_x000D_
    for (z = 0;_x000D_
      ((new Date().getTime() - t) < ms); z++) f(num);_x000D_
    return (z / ms)_x000D_
  } // returns how many times the function was run in "ms" milliseconds._x000D_
_x000D_
_x000D_
  function benchmark() {_x000D_
    function compare(a, b) {_x000D_
      if (a[1] > b[1]) {_x000D_
        return -1;_x000D_
      }_x000D_
      if (a[1] < b[1]) {_x000D_
        return 1;_x000D_
      }_x000D_
      return 0;_x000D_
    }_x000D_
_x000D_
    // functions_x000D_
_x000D_
    function replace1(s) {_x000D_
      s.replace(/foo/g, "bar")_x000D_
    }_x000D_
_x000D_
String.prototype.replaceAll2 = function(_f, _r){ _x000D_
_x000D_
  var o = this.toString();_x000D_
  var r = '';_x000D_
  var s = o;_x000D_
  var b = 0;_x000D_
  var e = -1;_x000D_
//      if(_c){ _f = _f.toLowerCase(); s = o.toLowerCase(); }_x000D_
_x000D_
  while((e=s.indexOf(_f)) > -1)_x000D_
  {_x000D_
    r += o.substring(b, b+e) + _r;_x000D_
    s = s.substring(e+_f.length, s.length);_x000D_
    b += e+_f.length;_x000D_
  }_x000D_
_x000D_
  // Add Leftover_x000D_
  if(s.length>0){ r+=o.substring(o.length-s.length, o.length); }_x000D_
_x000D_
  // Return New String_x000D_
  return r;_x000D_
};_x000D_
_x000D_
String.prototype.replaceAll = function(str1, str2, ignore) {_x000D_
      return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), (ignore ? "gi" : "g")), (typeof(str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2);_x000D_
    }_x000D_
_x000D_
    function replace2(s) {_x000D_
      s.replaceAll("foo", "bar")_x000D_
    }_x000D_
_x000D_
    function replace3(s) {_x000D_
      s.split('foo').join('bar');_x000D_
    }_x000D_
_x000D_
    function replace4(s) {_x000D_
      s.replaceAll2("foo", "bar")_x000D_
    }_x000D_
_x000D_
_x000D_
    funcs = [_x000D_
      [replace1, 0],_x000D_
      [replace2, 0],_x000D_
      [replace3, 0],_x000D_
      [replace4, 0]_x000D_
    ];_x000D_
_x000D_
    funcs.forEach((ff) => {_x000D_
      console.log("Benchmarking: " + ff[0].name);_x000D_
      ff[1] = time_function(2500, ff[0], "foOfoobarBaR barbarfoobarf00".repeat(10));_x000D_
      console.log("Score: " + ff[1]);_x000D_
_x000D_
    })_x000D_
    return funcs.sort(compare);_x000D_
  }_x000D_
_x000D_
  return benchmark;_x000D_
})()_x000D_
log("Starting benchmark...\n");_x000D_
res = benchmark();_x000D_
console.log("Winner: " + res[0][0].name + " !!!");_x000D_
count = 1;_x000D_
res.forEach((r) => {_x000D_
  log((count++) + ". " + r[0].name + " score: " + Math.floor(10000 * r[1] / res[0][1]) / 100 + ((count == 2) ? "% *winner*" : "% speed of winner.") + " (" + Math.round(r[1] * 100) / 100 + ")");_x000D_
});_x000D_
log("\nWinner code:\n");_x000D_
log(res[0][0].toString());
_x000D_
<textarea rows="50" cols="80" style="font-size: 16; resize:none; border: none;" id="log"></textarea>
_x000D_
_x000D_
_x000D_

The test will run for 10s (+2s) as you click the button.

My results (on the same pc):

Chrome/Linux Ubuntu 64:
1. replace1 score: 100% *winner* (766.18)
2. replace4 score: 99.07% speed of winner. (759.11)
3. replace3 score: 68.36% speed of winner. (523.83)
4. replace2 score: 59.35% speed of winner. (454.78)

Firefox/Linux Ubuntu 64
1. replace3 score: 100% *winner* (3480.1)
2. replace1 score: 13.06% speed of winner. (454.83)
3. replace4 score: 9.4% speed of winner. (327.42)
4. replace2 score: 4.81% speed of winner. (167.46)

Nice mess uh?

Took the liberty of adding more test results

Chrome/Windows 10
1. replace1 score: 100% *winner* (742.49)
2. replace4 score: 85.58% speed of winner. (635.44)
3. replace2 score: 54.42% speed of winner. (404.08)
4. replace3 score: 50.06% speed of winner. (371.73)

Firefox/Windows 10
1. replace3 score: 100% *winner* (2645.18)
2. replace1 score: 30.77% speed of winner. (814.18)
3. replace4 score: 22.3% speed of winner. (589.97)
4. replace2 score: 12.51% speed of winner. (331.13)

Edge/Windows 10
1. replace1 score: 100% *winner* (1251.24)
2. replace2 score: 46.63% speed of winner. (583.47)
3. replace3 score: 44.42% speed of winner. (555.92)
4. replace4 score: 20% speed of winner. (250.28)

Chrome on Galaxy Note 4

1. replace4 score: 100% *winner* (99.82)
2. replace1 score: 91.04% speed of winner. (90.88)
3. replace3 score: 70.27% speed of winner. (70.15)
4. replace2 score: 38.25% speed of winner. (38.18)

How to export MySQL database with triggers and procedures?

I've created the following script and it worked for me just fine.

#! /bin/sh
cd $(dirname $0)
DB=$1
DBUSER=$2
DBPASSWD=$3
FILE=$DB-$(date +%F).sql
mysqldump --routines "--user=${DBUSER}"  --password=$DBPASSWD $DB > $PWD/$FILE
gzip $FILE
echo Created $PWD/$FILE*

and you call the script using command line arguments.

backupdb.sh my_db dev_user dev_password

Adding image to JFrame

Here is a simple example of adding an image to a JFrame:

frame.add(new JLabel(new ImageIcon("Path/To/Your/Image.png")));

java.io.FileNotFoundException: (Access is denied)

Also, in some cases is important to check the target folder permissions. To give write permission for the user might be the solution. That worked for me.

How to list records with date from the last 10 days?

you can use between too:

SELECT Table.date
  FROM Table 
  WHERE date between current_date and current_date - interval '10 day';

RSpec: how to test if a method was called?

The below should work

describe "#foo"
  it "should call 'bar' with appropriate arguments" do
     subject.stub(:bar)
     subject.foo
     expect(subject).to have_received(:bar).with("Invalid number of arguments")
  end
end

Documentation: https://github.com/rspec/rspec-mocks#expecting-arguments

CGContextDrawImage draws image upside down when passed UIImage.CGImage

Swift 3 CoreGraphics Solution

If you want to use CG for whatever your reason might be, instead of UIImage, this Swift 3 construction based on previous answers did solve the issue for me:

if let cgImage = uiImage.cgImage {
    cgContext.saveGState()
    cgContext.translateBy(x: 0.0, y: cgRect.size.height)
    cgContext.scaleBy(x: 1.0, y: -1.0)
    cgContext.draw(cgImage, in: cgRect)
    cgContext.restoreGState()
}

How do I loop through a date range?

I have a Range class in MiscUtil which you could find useful. Combined with the various extension methods, you could do:

foreach (DateTime date in StartDate.To(EndDate).ExcludeEnd()
                                   .Step(DayInterval.Days())
{
    // Do something with the date
}

(You may or may not want to exclude the end - I just thought I'd provide it as an example.)

This is basically a ready-rolled (and more general-purpose) form of mquander's solution.

What is this CSS selector? [class*="span"]

It selects all elements where the class name contains the string "span" somewhere. There's also ^= for the beginning of a string, and $= for the end of a string. Here's a good reference for some CSS selectors.

I'm only familiar with the bootstrap classes spanX where X is an integer, but if there were other selectors that ended in span, it would also fall under these rules.

It just helps to apply blanket CSS rules.

Python - abs vs fabs

Edit: as @aix suggested, a better (more fair) way to compare the speed difference:

In [1]: %timeit abs(5)
10000000 loops, best of 3: 86.5 ns per loop

In [2]: from math import fabs

In [3]: %timeit fabs(5)
10000000 loops, best of 3: 115 ns per loop

In [4]: %timeit abs(-5)
10000000 loops, best of 3: 88.3 ns per loop

In [5]: %timeit fabs(-5)
10000000 loops, best of 3: 114 ns per loop

In [6]: %timeit abs(5.0)
10000000 loops, best of 3: 92.5 ns per loop

In [7]: %timeit fabs(5.0)
10000000 loops, best of 3: 93.2 ns per loop

In [8]: %timeit abs(-5.0)
10000000 loops, best of 3: 91.8 ns per loop

In [9]: %timeit fabs(-5.0)
10000000 loops, best of 3: 91 ns per loop

So it seems abs() only has slight speed advantage over fabs() for integers. For floats, abs() and fabs() demonstrate similar speed.


In addition to what @aix has said, one more thing to consider is the speed difference:

In [1]: %timeit abs(-5)
10000000 loops, best of 3: 102 ns per loop

In [2]: import math

In [3]: %timeit math.fabs(-5)
10000000 loops, best of 3: 194 ns per loop

So abs() is faster than math.fabs().

how to pass parameter from @Url.Action to controller function

public ActionResult CreatePerson(int id) //controller 

window.location.href = '@Url.Action("CreatePerson", "Person")?id=' + id;

Or

var id = 'some value';
window.location.href = '@Url.Action("CreatePerson", "Person", new {id = id})';

Html.EditorFor Set Default Value

Its not right to set default value in View. The View should perform display work, not more. This action breaks ideology of MVC pattern. So the right place to set defaults - create method of controller class.

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

This worked for me when I encountered the same issue on my KitKat. Remove your account from the device (Settings > Accounts > Google > Remove Account)

Remove the following data: Settings> Applications > All> Downloads > delete data. Settings> Applications > All> Play Store> delete data. Settings> Apps > All> Google Services Framework (or if they have it in English: Google Service Framework) > delete data.

Log in again and it was fixed for me.

HTML - how can I show tooltip ONLY when ellipsis is activated

I have CSS class, which determines where to put ellipsis. Based on that, I do the following (element set could be different, i write those, where ellipsis is used, of course it could be a separate class selector):

$(document).on('mouseover', 'input, td, th', function() {
    if ($(this).css('text-overflow') && typeof $(this).attr('title') === 'undefined') {
        $(this).attr('title', $(this).val());
    }
});

Python csv string to array

You can convert a string to a file object using io.StringIO and then pass that to the csv module:

from io import StringIO
import csv

scsv = """text,with,Polish,non-Latin,letters
1,2,3,4,5,6
a,b,c,d,e,f
ges,zólty,waz,idzie,waska,drózka,
"""

f = StringIO(scsv)
reader = csv.reader(f, delimiter=',')
for row in reader:
    print('\t'.join(row))

simpler version with split() on newlines:

reader = csv.reader(scsv.split('\n'), delimiter=',')
for row in reader:
    print('\t'.join(row))

Or you can simply split() this string into lines using \n as separator, and then split() each line into values, but this way you must be aware of quoting, so using csv module is preferred.

On Python 2 you have to import StringIO as

from StringIO import StringIO

instead.

Current date without time

String test = DateTime.Now.ToString("dd.MM.yyy");

py2exe - generate single executable file

I'm told bbfreeze will create a single file .EXE, and is newer than py2exe.

How do you run a js file using npm scripts?

You should use npm run-script build or npm build <project_folder>. More info here: https://docs.npmjs.com/cli/build.

XPath - Difference between node() and text()

For me it was a big difference when I faced this scenario (here my story:)

<?xml version="1.0" encoding="UTF-8"?>
<sentence id="S1.6">When U937 cells were infected with HIV-1, 
        
    <xcope id="X1.6.3">
        <cue ref="X1.6.3" type="negation">no</cue> 
                        
                        induction of NF-KB factor was detected
        
    </xcope>
                    
, whereas high level of progeny virions was produced, 
        
    <xcope id="X1.6.2">
        <cue ref="X1.6.2" type="speculation">suggesting</cue> that this factor was 
        <xcope id="X1.6.1">
            <cue ref="X1.6.1" type="negation">not</cue> required for viral replication
        </xcope>
    </xcope>.

</sentence>

I needed to extract text between tags and aggregate (by concat) the text including in innner tags.

/node() did the job, while /text() made half job

/text() only returned text not included in inner tags, because inner tags are not "text nodes". You may think, "just extract text included in the inner tags in an additional xpath", however, it becomes challenging to sort the text in this original order because you dont know where to place the aggregated text from the inner tags!because you dont know where to place the aggregated text from the inner nodes.

  1. When U937 cells were infected with HIV-1,
  2. no induction of NF-KB factor was detected
  3. , whereas high level of progeny virions was produced,
  4. suggesting that this factor was not required for viral replication
  5. .

Finally, /node() did exactly what I wanted, because it gets the text from inner tags too.

Automatically create an Enum based on values in a database lookup table?

One way to keep the Enums and to create a Dynamic list of values at the same time is to use the Enums that you currently have with a Dynamically created Dictionary.

Since most Enums are used in the context that they are defined to be used, and the "dynamic enums" will be supported by dynamic processes, you can distinguish the 2.

The first step is to create a table/collection that houses the IDs and References for the Dynamic Entries. In the table you will autoincrement much larger than your largest Enum value.

Now comes the part for your dynamic Enums, I am assuming that you will be using the Enums to create a set of conditions that apply a set of rules, some are dynamically generated.

Get integer from database
If Integer is in Enum -> create Enum -> then run Enum parts
If Integer is not a Enum -> create Dictionary from Table -> then run Dictionary parts.

Get changes from master into branch in Git

Either cherry-pick the relevant commits into branch aq or merge branch master into branch aq.

Custom "confirm" dialog in JavaScript?

One other way would be using colorbox

function createConfirm(message, okHandler) {
    var confirm = '<p id="confirmMessage">'+message+'</p><div class="clearfix dropbig">'+
            '<input type="button" id="confirmYes" class="alignleft ui-button ui-widget ui-state-default" value="Yes" />' +
            '<input type="button" id="confirmNo" class="ui-button ui-widget ui-state-default" value="No" /></div>';

    $.fn.colorbox({html:confirm, 
        onComplete: function(){
            $("#confirmYes").click(function(){
                okHandler();
                $.fn.colorbox.close();
            });
            $("#confirmNo").click(function(){
                $.fn.colorbox.close();
            });
    }});
}

SASS and @font-face

For those looking for an SCSS mixin instead, including woff2:

@mixin fface($path, $family, $type: '', $weight: 400, $svg: '', $style: normal) {
  @font-face {
    font-family: $family;
    @if $svg == '' {
      // with OTF without SVG and EOT
      src: url('#{$path}#{$type}.otf') format('opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype');
    } @else {
      // traditional src inclusions
      src: url('#{$path}#{$type}.eot');
      src: url('#{$path}#{$type}.eot?#iefix') format('embedded-opentype'), url('#{$path}#{$type}.woff2') format('woff2'), url('#{$path}#{$type}.woff') format('woff'), url('#{$path}#{$type}.ttf') format('truetype'), url('#{$path}#{$type}.svg##{$svg}') format('svg');
    }
    font-weight: $weight;
    font-style: $style;
  }
}
// ========================================================importing
$dir: '/assets/fonts/';
$famatic: 'AmaticSC';
@include fface('#{$dir}amatic-sc-v11-latin-regular', $famatic, '', 400, $famatic);

$finter: 'Inter';
// adding specific types of font-weights
@include fface('#{$dir}#{$finter}', $finter, '-Thin-BETA', 100);
@include fface('#{$dir}#{$finter}', $finter, '-Regular', 400);
@include fface('#{$dir}#{$finter}', $finter, '-Medium', 500);
@include fface('#{$dir}#{$finter}', $finter, '-Bold', 700);
// ========================================================usage
.title {
  font-family: Inter;
  font-weight: 700; // Inter-Bold font is loaded
}
.special-title {
  font-family: AmaticSC;
  font-weight: 700; // default font is loaded
}

The $type parameter is useful for stacking related families with different weights.

The @if is due to the need of supporting the Inter font (similar to Roboto), which has OTF but doesn't have SVG and EOT types at this time.

If you get a can't resolve error, remember to double check your fonts directory ($dir).

How to change root logging level programmatically for logback

Try this:

import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;

Logger root = (Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.INFO);

Note that you can also tell logback to periodically scan your config file like this:

<configuration scan="true" scanPeriod="30 seconds" > 
  ...
</configuration> 

Count elements with jQuery

use the .size() method or .length attribute

Assign a login to a user created without login (SQL Server)

What kind of database user is it? Run select * from sys.database_principals in the database and check columns type and type_desc for that name. If it is a Windows or SQL user, go with @gbn's answer, but if it's something else (which is my untested guess based on your error message) then you have a different problem.


Edit

So it is a SQL-authenticated login. Back when we'd use sp_change_users_login to fix such logins. SQL 2008 has it as "don't use, will be deprecated", which means that the ALTER USER command should be sufficient... but it might be worth a try in this case. Used properly (it's been a while), I believe this updates the SID of the User to match that of the login.

How to reduce the image size without losing quality in PHP

You can resize and then use imagejpeg()

Don't pass 100 as the quality for imagejpeg() - anything over 90 is generally overkill and just gets you a bigger JPEG. For a thumbnail, try 75 and work downwards until the quality/size tradeoff is acceptable.

imagejpeg($tn, $save, 75);

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

You can use these steps to import the key to an existing keystore. The instructions are combined from answers in this thread and other sites. These instructions worked for me (the java keystore):

  1. Run

openssl pkcs12 -export -in yourserver.crt -inkey yourkey.key -out server.p12 -name somename -certfile yourca.crt -caname root

(If required put the -chain option. Putting that failed for me). This will ask for the password - you must give the correct password else you will get an error (heading error or padding error etc).

  1. It will ask you to enter a new password - you must enter a password here - enter anything but remember it. (Let us assume you enter Aragorn).
  2. This will create the server.p12 file in the pkcs format.
  3. Now to import it into the *.jks file run:
    keytool -importkeystore -srckeystore server.p12 -srcstoretype PKCS12 -destkeystore yourexistingjavakeystore.jks -deststoretype JKS -deststorepass existingjavastorepassword -destkeypass existingjavastorepassword
    (Very important - do not leave out the deststorepass and the destkeypass parameters.)
  4. It will ask you for the src key store password. Enter Aragorn and hit enter. The certificate and key is now imported into your existing java keystore.

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

I ran this on MacOS /Applications/Python\ 3.6/Install\ Certificates.command

Converting JSON String to Dictionary Not List

Your JSON is an array with a single object inside, so when you read it in you get a list with a dictionary inside. You can access your dictionary by accessing item 0 in the list, as shown below:

json1_data = json.loads(json1_str)[0]

Now you can access the data stored in datapoints just as you were expecting:

datapoints = json1_data['datapoints']

I have one more question if anyone can bite: I am trying to take the average of the first elements in these datapoints(i.e. datapoints[0][0]). Just to list them, I tried doing datapoints[0:5][0] but all I get is the first datapoint with both elements as opposed to wanting to get the first 5 datapoints containing only the first element. Is there a way to do this?

datapoints[0:5][0] doesn't do what you're expecting. datapoints[0:5] returns a new list slice containing just the first 5 elements, and then adding [0] on the end of it will take just the first element from that resulting list slice. What you need to use to get the result you want is a list comprehension:

[p[0] for p in datapoints[0:5]]

Here's a simple way to calculate the mean:

sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8

If you're willing to install NumPy, then it's even easier:

import numpy
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)[0]
datapoints = numpy.array(json1_data['datapoints'])
avg = datapoints[0:5,0].mean()
# avg is now 35.8

Using the , operator with the slicing syntax for NumPy's arrays has the behavior you were originally expecting with the list slices.

Scanner only reads first word instead of line

Javadoc to the rescue :

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace

nextLine is probably the method you should use.

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

Here is a regex_subst() function. Examples:

=regex_subst("watermellon", "[aeiou]", "")
---> wtrmlln
=regex_subst("watermellon", "[^aeiou]", "")
---> aeeo

Here is the simplified code (simpler for me, anyway). I couldn't figure out how to build a suitable output pattern using the above to work like my examples:

Function regex_subst( _
     strInput As String _
   , matchPattern As String _
   , Optional ByVal replacePattern As String = "" _
) As Variant
    Dim inputRegexObj As New VBScript_RegExp_55.RegExp

    With inputRegexObj
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = matchPattern
    End With

    regex_subst = inputRegexObj.Replace(strInput, replacePattern)
End Function

What HTTP status response code should I use if the request is missing a required parameter?

I Usually go for 422 (Unprocessable entity) if something in the required parameters didn't match what the API endpoint required (like a too short password) but for a missing parameter i would go for 406 (Unacceptable).

IPC performance: Named Pipe vs Socket

For two way communication with named pipes:

  • If you have few processes, you can open two pipes for two directions (processA2ProcessB and processB2ProcessA)
  • If you have many processes, you can open in and out pipes for every process (processAin, processAout, processBin, processBout, processCin, processCout etc)
  • Or you can go hybrid as always :)

Named pipes are quite easy to implement.

E.g. I implemented a project in C with named pipes, thanks to standart file input-output based communication (fopen, fprintf, fscanf ...) it was so easy and clean (if that is also a consideration).

I even coded them with java (I was serializing and sending objects over them!)

Named pipes has one disadvantage:

  • they do not scale on multiple computers like sockets since they rely on filesystem (assuming shared filesystem is not an option)

How to get "GET" request parameters in JavaScript?

try the below code, it will help you get the GET parameters from url . for more details.

 var url_string = window.location.href; // www.test.com?filename=test
    var url = new URL(url_string);
    var paramValue = url.searchParams.get("filename");
    alert(paramValue)

How to make modal dialog in WPF?

Window.Show will show the window, and continue execution -- it's a non-blocking call.

Window.ShowDialog will block the calling thread (kinda [1]), and show the dialog. It will also block interaction with the parent/owning window. When the dialog is dismissed (for whatever reason), ShowDialog will return to the caller, and will allow you to access DialogResult (if you want it).

[1] It will keep the dispatcher pumping by pushing a dispatcher frame onto the WPF dispatcher. This will cause the message pump to keep pumping.

How do I create an empty array/matrix in NumPy?

If you absolutely don't know the final size of the array, you can increment the size of the array like this:

my_arr = numpy.zeros((0,5))
for i in range(3):
    my_arr=numpy.concatenate( ( my_arr, numpy.ones((1,5)) ) )
print(my_arr)

[[ 1.  1.  1.  1.  1.]  [ 1.  1.  1.  1.  1.]  [ 1.  1.  1.  1.  1.]]
  • Notice the 0 in the first line.
  • numpy.append is another option. It calls numpy.concatenate.

How to list containers in Docker

To show only running containers use the given command:

docker ps

To show all containers use the given command:

docker ps -a

To show the latest created container (includes all states) use the given command:

docker ps -l

To show n last created containers (includes all states) use the given command:

docker ps -n=-1

To display total file sizes use the given command:

docker ps -s

The content presented above is from docker.com.

In the new version of Docker, commands are updated, and some management commands are added:

docker container ls

It is used to list all the running containers.

docker container ls -a

And then, if you want to clean them all,

docker rm $(docker ps -aq)

It is used to list all the containers created irrespective of its state.

And to stop all the Docker containers (force)

docker rm -f $(docker ps -a -q)  

Here the container is the management command.

Sql Server equivalent of a COUNTIF aggregate function

Why not like this?

SELECT count(1)
FROM AD_CurrentView
WHERE myColumn=1

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

@article = user.articles.build(:title => "MainTitle")
@article.save

Case Function Equivalent in Excel

I know it a little late to answer but I think this short video will help you a lot.

http://www.xlninja.com/2012/07/25/excel-choose-function-explained/

Essentially it is using the choose function. He explains it very well in the video so I'll let do it instead of typing 20 pages.

Another video of his explains how to use data validation to populate a drop down which you can select from a limited range.

http://www.xlninja.com/2012/08/13/excel-data-validation-using-dependent-lists/

You could combine the two and use the value in the drop down as your index to the choose function. While he did not show how to combine them, I'm sure you could figure it out as his videos are good. If you have trouble, let me know and I'll update my answer to show you.

How to remove a file from the index in git?

Depending on your workflow, this may be the kind of thing that you need rarely enough that there's little point in trying to figure out a command-line solution (unless you happen to be working without a graphical interface for some reason).

Just use one of the GUI-based tools that support index management, for example:

  • git gui <-- uses the Tk windowing framework -- similar style to gitk
  • git cola <-- a more modern-style GUI interface

These let you move files in and out of the index by point-and-click. They even have support for selecting and moving portions of a file (individual changes) to and from the index.


How about a different perspective: If you mess up while using one of the suggested, rather cryptic, commands:

  • git rm --cached [file]
  • git reset HEAD <file>

...you stand a real chance of losing data -- or at least making it hard to find. Unless you really need to do this with very high frequency, using a GUI tool is likely to be safer.


Working without the index

Based on the comments and votes, I've come to realize that a lot of people use the index all the time. I don't. Here's how:

  • Commit my entire working copy (the typical case): git commit -a
  • Commit just a few files: git commit (list of files)
  • Commit all but a few modified files: git commit -a then amend via git gui
  • Graphically review all changes to working copy: git difftool --dir-diff --tool=meld

Two-dimensional array in Swift

Before using multidimensional arrays in Swift, consider their impact on performance. In my tests, the flattened array performed almost 2x better than the 2D version:

var table = [Int](repeating: 0, count: size * size)
let array = [Int](1...size)
for row in 0..<size {
    for column in 0..<size {
        let val = array[row] * array[column]
        // assign
        table[row * size + column] = val
    }
}

Average execution time for filling up a 50x50 Array: 82.9ms

vs.

var table = [[Int]](repeating: [Int](repeating: 0, count: size), count: size)
let array = [Int](1...size)
for row in 0..<size {
    for column in 0..<size {
        // assign
        table[row][column] = val
    }
}

Average execution time for filling up a 50x50 2D Array: 135ms

Both algorithms are O(n^2), so the difference in execution times is caused by the way we initialize the table.

Finally, the worst you can do is using append() to add new elements. That proved to be the slowest in my tests:

var table = [Int]()    
let array = [Int](1...size)
for row in 0..<size {
    for column in 0..<size {
        table.append(val)
    }
}

Average execution time for filling up a 50x50 Array using append(): 2.59s

Conclusion

Avoid multidimensional arrays and use access by index if execution speed matters. 1D arrays are more performant, but your code might be a bit harder to understand.

You can run the performance tests yourself after downloading the demo project from my GitHub repo: https://github.com/nyisztor/swift-algorithms/tree/master/big-o-src/Big-O.playground

How can I fix MySQL error #1064?

TL;DR

Error #1064 means that MySQL can't understand your command. To fix it:

  • Read the error message. It tells you exactly where in your command MySQL got confused.

  • Examine your command. If you use a programming language to create your command, use echo, console.log(), or its equivalent to show the entire command so you can see it.

  • Check the manual. By comparing against what MySQL expected at that point, the problem is often obvious.

  • Check for reserved words. If the error occurred on an object identifier, check that it isn't a reserved word (and, if it is, ensure that it's properly quoted).

  1. Aaaagh!! What does #1064 mean?

    Error messages may look like gobbledygook, but they're (often) incredibly informative and provide sufficient detail to pinpoint what went wrong. By understanding exactly what MySQL is telling you, you can arm yourself to fix any problem of this sort in the future.

    As in many programs, MySQL errors are coded according to the type of problem that occurred. Error #1064 is a syntax error.

    • What is this "syntax" of which you speak? Is it witchcraft?

      Whilst "syntax" is a word that many programmers only encounter in the context of computers, it is in fact borrowed from wider linguistics. It refers to sentence structure: i.e. the rules of grammar; or, in other words, the rules that define what constitutes a valid sentence within the language.

      For example, the following English sentence contains a syntax error (because the indefinite article "a" must always precede a noun):

      This sentence contains syntax error a.

    • What does that have to do with MySQL?

      Whenever one issues a command to a computer, one of the very first things that it must do is "parse" that command in order to make sense of it. A "syntax error" means that the parser is unable to understand what is being asked because it does not constitute a valid command within the language: in other words, the command violates the grammar of the programming language.

      It's important to note that the computer must understand the command before it can do anything with it. Because there is a syntax error, MySQL has no idea what one is after and therefore gives up before it even looks at the database and therefore the schema or table contents are not relevant.

  2. How do I fix it?

    Obviously, one needs to determine how it is that the command violates MySQL's grammar. This may sound pretty impenetrable, but MySQL is trying really hard to help us here. All we need to do is…

    • Read the message!

      MySQL not only tells us exactly where the parser encountered the syntax error, but also makes a suggestion for fixing it. For example, consider the following SQL command:

      UPDATE my_table WHERE id=101 SET name='foo'
      

      That command yields the following error message:

      ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id=101 SET name='foo'' at line 1

      MySQL is telling us that everything seemed fine up to the word WHERE, but then a problem was encountered. In other words, it wasn't expecting to encounter WHERE at that point.

      Messages that say ...near '' at line... simply mean that the end of command was encountered unexpectedly: that is, something else should appear before the command ends.

    • Examine the actual text of your command!

      Programmers often create SQL commands using a programming language. For example a php program might have a (wrong) line like this:

      $result = $mysqli->query("UPDATE " . $tablename ."SET name='foo' WHERE id=101");
      

      If you write this this in two lines

      $query = "UPDATE " . $tablename ."SET name='foo' WHERE id=101"
      $result = $mysqli->query($query);
      

      then you can add echo $query; or var_dump($query) to see that the query actually says

      UPDATE userSET name='foo' WHERE id=101
      

      Often you'll see your error immediately and be able to fix it.

    • Obey orders!

      MySQL is also recommending that we "check the manual that corresponds to our MySQL version for the right syntax to use". Let's do that.

      I'm using MySQL v5.6, so I'll turn to that version's manual entry for an UPDATE command. The very first thing on the page is the command's grammar (this is true for every command):

      UPDATE [LOW_PRIORITY] [IGNORE] table_reference
          SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
          [WHERE where_condition]
          [ORDER BY ...]
          [LIMIT row_count]
      

      The manual explains how to interpret this syntax under Typographical and Syntax Conventions, but for our purposes it's enough to recognise that: clauses contained within square brackets [ and ] are optional; vertical bars | indicate alternatives; and ellipses ... denote either an omission for brevity, or that the preceding clause may be repeated.

      We already know that the parser believed everything in our command was okay prior to the WHERE keyword, or in other words up to and including the table reference. Looking at the grammar, we see that table_reference must be followed by the SET keyword: whereas in our command it was actually followed by the WHERE keyword. This explains why the parser reports that a problem was encountered at that point.

    A note of reservation

    Of course, this was a simple example. However, by following the two steps outlined above (i.e. observing exactly where in the command the parser found the grammar to be violated and comparing against the manual's description of what was expected at that point), virtually every syntax error can be readily identified.

    I say "virtually all", because there's a small class of problems that aren't quite so easy to spot—and that is where the parser believes that the language element encountered means one thing whereas you intend it to mean another. Take the following example:

    UPDATE my_table SET where='foo'
    

    Again, the parser does not expect to encounter WHERE at this point and so will raise a similar syntax error—but you hadn't intended for that where to be an SQL keyword: you had intended for it to identify a column for updating! However, as documented under Schema Object Names:

    If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it. (Exception: A reserved word that follows a period in a qualified name must be an identifier, so it need not be quoted.) Reserved words are listed at Section 9.3, “Keywords and Reserved Words”.

    [ deletia ]

    The identifier quote character is the backtick (“`”):

    mysql> SELECT * FROM `select` WHERE `select`.id > 100;

    If the ANSI_QUOTES SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks:

    mysql> CREATE TABLE "test" (col INT);
    ERROR 1064: You have an error in your SQL syntax...
    mysql> SET sql_mode='ANSI_QUOTES';
    mysql> CREATE TABLE "test" (col INT);
    Query OK, 0 rows affected (0.00 sec)

Git submodule push

Note that since git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1 and release note, June 2012) mentions:

"git push --recurse-submodules" learned to optionally look into the histories of submodules bound to the superproject and push them out.

Probably done after this patch and the --on-demand option:

recurse-submodules=<check|on-demand>::

Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.

  • If check is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
    Otherwise the push will be aborted and exit with non-zero status.
  • If on-demand is used, all submodules that changed in the revisions to be pushed will be pushed.
    If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.

So you could push everything in one go with (from the parent repo) a:

git push --recurse-submodules=on-demand

This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.


With git 2.7 (January 2016), a simple git push will be enough to push the parent repo... and all its submodules.

See commit d34141c, commit f5c7cd9 (03 Dec 2015), commit f5c7cd9 (03 Dec 2015), and commit b33a15b (17 Nov 2015) by Mike Crowe (mikecrowe).
(Merged by Junio C Hamano -- gitster -- in commit 5d35d72, 21 Dec 2015)

push: add recurseSubmodules config option

The --recurse-submodules command line parameter has existed for some time but it has no config file equivalent.

Following the style of the corresponding parameter for git fetch, let's invent push.recurseSubmodules to provide a default for this parameter.
This also requires the addition of --recurse-submodules=no to allow the configuration to be overridden on the command line when required.

The most straightforward way to implement this appears to be to make push use code in submodule-config in a similar way to fetch.

The git config doc now include:

push.recurseSubmodules:

Make sure all submodule commits used by the revisions to be pushed are available on a remote-tracking branch.

  • If the value is 'check', then Git will verify that all submodule commits that changed in the revisions to be pushed are available on at least one remote of the submodule. If any commits are missing, the push will be aborted and exit with non-zero status.
  • If the value is 'on-demand' then all submodules that changed in the revisions to be pushed will be pushed. If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status. -
  • If the value is 'no' then default behavior of ignoring submodules when pushing is retained.

You may override this configuration at time of push by specifying '--recurse-submodules=check|on-demand|no'.

So:

git config push.recurseSubmodules on-demand
git push

Git 2.12 (Q1 2017)

git push --dry-run --recurse-submodules=on-demand will actually work.

See commit 0301c82, commit 1aa7365 (17 Nov 2016) by Brandon Williams (mbrandonw).
(Merged by Junio C Hamano -- gitster -- in commit 12cf113, 16 Dec 2016)

push run with --dry-run doesn't actually (Git 2.11 Dec. 2016 and lower/before) perform a dry-run when push is configured to push submodules on-demand.
Instead all submodules which need to be pushed are actually pushed to their remotes while any updates for the superproject are performed as a dry-run.
This is a bug and not the intended behaviour of a dry-run.

Teach push to respect the --dry-run option when configured to recursively push submodules 'on-demand'.
This is done by passing the --dry-run flag to the child process which performs a push for a submodules when performing a dry-run.


And still in Git 2.12, you now havea "--recurse-submodules=only" option to push submodules out without pushing the top-level superproject.

See commit 225e8bf, commit 6c656c3, commit 14c01bd (19 Dec 2016) by Brandon Williams (mbrandonw).
(Merged by Junio C Hamano -- gitster -- in commit 792e22e, 31 Jan 2017)

How to add an object to an ArrayList in Java

Try this one:

Data objt = new Data(name, address, contact);
Contacts.add(objt);

How can I combine two HashMap objects containing the same types?

    HashMap<Integer,String> hs1 = new HashMap<>();
    hs1.put(1,"ram");
    hs1.put(2,"sita");
    hs1.put(3,"laxman");
    hs1.put(4,"hanuman");
    hs1.put(5,"geeta");

    HashMap<Integer,String> hs2 = new HashMap<>();
    hs2.put(5,"rat");
    hs2.put(6,"lion");
    hs2.put(7,"tiger");
    hs2.put(8,"fish");
    hs2.put(9,"hen");

    HashMap<Integer,String> hs3 = new HashMap<>();//Map is which we add

    hs3.putAll(hs1);
    hs3.putAll(hs2);

    System.out.println(" hs1 : " + hs1);
    System.out.println(" hs2 : " + hs2);
    System.out.println(" hs3 : " + hs3);

Duplicate items will not be added(that is duplicate keys) as when we will print hs3 we will get only one value for key 5 which will be last value added and it will be rat. **[Set has a property of not allowing the duplicate key but values can be duplicate]

Efficiently test if a port is open on Linux?

A surprise I found out recently is that Bash natively supports tcp connections as file descriptors. To use:

exec 6<>/dev/tcp/ip.addr.of.server/445
echo -e "GET / HTTP/1.0\n" >&6
cat <&6

I'm using 6 as the file descriptor because 0,1,2 are stdin, stdout, and stderr. 5 is sometimes used by Bash for child processes, so 3,4,6,7,8, and 9 should be safe.

As per the comment below, to test for listening on a local server in a script:

exec 6<>/dev/tcp/127.0.0.1/445 || echo "No one is listening!"
exec 6>&- # close output connection
exec 6<&- # close input connection

To determine if someone is listening, attempt to connect by loopback. If it fails, then the port is closed or we aren't allowed access. Afterwards, close the connection.

Modify this for your use case, such as sending an email, exiting the script on failure, or starting the required service.

How to clear a textbox using javascript

Onfous And onblur Text box with javascript

   <input type="text" value="A new value" onfocus="if(this.value=='A new value') this.value='';" onblur="if(this.value=='') this.value='A new value';"/>

Which data type for latitude and longitude?

Use Point data type to store Longitude and Latitude in a single column:

CREATE TABLE table_name (
    id integer NOT NULL,
    name text NOT NULL,
    location point NOT NULL,
    created_on timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT table_name_pkey PRIMARY KEY (id)
)

Create an Indexing on a 'location' column :

CREATE INDEX ON table_name USING GIST(location);

GiST index is capable of optimizing “nearest-neighbor” search :

SELECT * FROM table_name ORDER BY location <-> point '(-74.013, 40.711)' LIMIT 10;

Note: The point first element is longitude and the second element is latitude.

For more info check this Query Operators.

jquery : focus to div is not working

you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">

$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');

jQuery Remove string from string

To add on nathan gonzalez answer, please note you need to assign the replaced object after calling replace function since it is not a mutator function:

myString = myString.replace('username1','');

Removing duplicate rows from table in Oracle

For best performance, here is what I wrote :
(see execution plan)

DELETE FROM your_table
WHERE rowid IN 
  (select t1.rowid from your_table  t1
      LEFT OUTER JOIN (
      SELECT MIN(rowid) as rowid, column1,column2, column3
      FROM your_table 
      GROUP BY column1, column2, column3
  )  co1 ON (t1.rowid = co1.rowid)
  WHERE co1.rowid IS NULL
);

SQL permissions for roles

SQL-Server follows the principle of "Least Privilege" -- you must (explicitly) grant permissions.

'does it mean that they wont be able to update 4 and 5 ?'

If your users in the doctor role are only in the doctor role, then yes.

However, if those users are also in other roles (namely, other roles that do have access to 4 & 5), then no.

More Information: http://msdn.microsoft.com/en-us/library/bb669084%28v=vs.110%29.aspx

How to connect from windows command prompt to mysql command line

first type cmd then the windows command prompt will appear:

PATH C:\XAMPP\MYSQL\BIN;%PATH%;
mysql -u root -p

where:

  • -u is the user id
  • -p is the password, if you will not using a password just leave it blank.

Create an empty list in python with certain size

You can .append(element) to the list, e.g.: s1.append(i). What you are currently trying to do is access an element (s1[i]) that does not exist.

Find the version of an installed npm package

Access the package.json

You can access the package.json or bower.json of the package with:

notepad ./node_modules/:packageName/package.json

This will open the package.json in notepad which has the version number of the :packageName you included in the command.

For example :

notepad ./node_modules/vue-template-compiler/package.json

Good Luck.

Rerender view on browser resize with React

It's a simple and short example of using es6 without jQuery.

import React, { Component } from 'react';

export default class CreateContact extends Component {
  state = {
    windowHeight: undefined,
    windowWidth: undefined
  }

  handleResize = () => this.setState({
    windowHeight: window.innerHeight,
    windowWidth: window.innerWidth
  });

  componentDidMount() {
    this.handleResize();
    window.addEventListener('resize', this.handleResize)
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.handleResize)
  }

  render() {
    return (
      <span>
        {this.state.windowWidth} x {this.state.windowHeight}
      </span>
    );
  }
}

hooks

import React, { useEffect, useState } from "react";

let App = () => {
  const [windowWidth, setWindowWidth] = useState(0);
  const [windowHeight, setWindowHeight] = useState(0);
  let resizeWindow = () => {
    setWindowWidth(window.innerWidth);
    setWindowHeight(window.innerHeight);
  };

  useEffect(() => {
    resizeWindow();
    window.addEventListener("resize", resizeWindow);
    return () => window.removeEventListener("resize", resizeWindow);
  }, []);

  return (
    <div>
      <span>
        {windowWidth} x {windowHeight}
      </span>
    </div>
  );
};

Why doesn't TFS get latest get the latest?

TFS, like some other source control providers, such as Perforce, do this, as the system knows what the last version you successfully got was, so get latest turns into "get changes since x". If you play by its rules and actually check things out before editing them, you don't confuse matters, and "get latest" really does as it says.

As you've seen, you can force it to reassess everything, which has a much greater bandwidth usage, but behaves closer to how SourceSafe used to.

Use of String.Format in JavaScript?

Based on @roydukkey's answer, a bit more optimized for runtime (it caches the regexes):

(function () {
    if (!String.prototype.format) {
        var regexes = {};
        String.prototype.format = function (parameters) {
            for (var formatMessage = this, args = arguments, i = args.length; --i >= 0;)
                formatMessage = formatMessage.replace(regexes[i] || (regexes[i] = RegExp("\\{" + (i) + "\\}", "gm")), args[i]);
            return formatMessage;
        };
        if (!String.format) {
            String.format = function (formatMessage, params) {
                for (var args = arguments, i = args.length; --i;)
                    formatMessage = formatMessage.replace(regexes[i - 1] || (regexes[i - 1] = RegExp("\\{" + (i - 1) + "\\}", "gm")), args[i]);
                return formatMessage;
            };
        }
    }
})();

How to open a new form from another form

Try this..

//button1 will be clicked to open a new form
private void button1_Click(object sender, EventArgs e)
{
    this.Visible = false;     // this = is the current form
    SignUp s = new SignUp();  //SignUp is the name of  my other form
    s.Visible = true;
}

Java URLConnection Timeout

You can set timeouts for all connections made from the jvm by changing the following System-properties:

System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");

Every connection will time out after 10 seconds.

Setting 'defaultReadTimeout' is not needed, but shown as an example if you need to control reading.

Open directory dialog

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Gearplay
{
    /// <summary>
    /// ?????? ?????????????? ??? OpenFolderBrows.xaml
    /// </summary>
    public partial class OpenFolderBrows : Page
    {
        internal string SelectedFolderPath { get; set; }
        public OpenFolderBrows()
        {
            InitializeComponent();
            Selectedpath();
            InputLogicalPathCollection();
             
        }

        internal void Selectedpath()
        {
            Browser.Navigate(@"C:\");
            
            Browser.Navigated += Browser_Navigated;
        }

        private void Browser_Navigated(object sender, NavigationEventArgs e)
        {
            SelectedFolderPath = e.Uri.AbsolutePath.ToString();
            //MessageBox.Show(SelectedFolderPath);
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
          
           
        }
        
        string [] testing { get; set; }
        private void InputLogicalPathCollection()
        {            // add Menu items for Cotrol 
            string[] DirectoryCollection_Path = Environment.GetLogicalDrives(); // Get Local Drives
            testing = new string[DirectoryCollection_Path.Length];
            //MessageBox.Show(DirectoryCollection_Path[0].ToString());
            MenuItem[]  menuItems = new MenuItem[DirectoryCollection_Path.Length]; // Create Empty Collection
            for(int i=0;i<menuItems.Length;i++)
            {
                // Create collection depend how much logical drives 
                menuItems[i] = new MenuItem();
                menuItems[i].Header = DirectoryCollection_Path[i];
                menuItems[i].Name = DirectoryCollection_Path[i].Substring(0,DirectoryCollection_Path.Length-1);
                DirectoryCollection.Items.Add(menuItems[i]);
                menuItems[i].Click += OpenFolderBrows_Click;
                testing[i]= DirectoryCollection_Path[i].Substring(0, DirectoryCollection_Path.Length - 1);
            }

            

        }
        
        private void OpenFolderBrows_Click(object sender, RoutedEventArgs e)
        {

            foreach (string str in testing)
            {
                if (e.OriginalSource.ToString().Contains("Header:"+str)) // Navigate to Local drive
                {
                    Browser.Navigate(str + @":\");
                   
                }


            }


        }

        private void Goback_Click(object sender, RoutedEventArgs e)
        {// Go Back
            try
            {
                Browser.GoBack();
            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Goforward_Click(object sender, RoutedEventArgs e)
        { //Go Forward
            try
            {
                Browser.GoForward();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void FolderForSave_Click(object sender, RoutedEventArgs e)
        {
            // Separate Click For Go Back same As Close App With send string var to Main Window ( Main class etc.) 
            this.NavigationService.GoBack();
        }
    }
}

CSS Outside Border

I shared two solutions depending on your needs:

<style type="text/css" ref="stylesheet">
  .border-inside-box {
    border: 1px solid black;
  }
  .border-inside-box-v1 {
    outline: 1px solid black; /* 'border-radius' not available */
  }
  .border-outside-box-v2 {
    box-shadow: 0 0 0 1px black; /* 'border-style' not available (dashed, solid, etc) */
  }
</style>

example: https://codepen.io/danieldd/pen/gObEYKj

PHP Fatal error: Using $this when not in object context

If you are invoking foobarfunc with resolution scope operator (::), then you are calling it statically, e.g. on the class level instead of the instance level, thus you are using $this when not in object context. $this does not exist in class context.

If you enable E_STRICT, PHP will raise a Notice about this:

Strict Standards: 
Non-static method foobar::foobarfunc() should not be called statically

Do this instead

$fb = new foobar;
echo $fb->foobarfunc();

On a sidenote, I suggest not to use global inside your classes. If you need something from outside inside your class, pass it through the constructor. This is called Dependency Injection and it will make your code much more maintainable and less dependant on outside things.

What is the best way to implement nested dictionaries?

You can use recursion in lambdas and defaultdict, no need to define names:

a = defaultdict((lambda f: f(f))(lambda g: lambda:defaultdict(g(g))))

Here's an example:

>>> a['new jersey']['mercer county']['plumbers']=3
>>> a['new jersey']['middlesex county']['programmers']=81
>>> a['new jersey']['mercer county']['programmers']=81
>>> a['new jersey']['middlesex county']['salesmen']=62
>>> a
defaultdict(<function __main__.<lambda>>,
        {'new jersey': defaultdict(<function __main__.<lambda>>,
                     {'mercer county': defaultdict(<function __main__.<lambda>>,
                                  {'plumbers': 3, 'programmers': 81}),
                      'middlesex county': defaultdict(<function __main__.<lambda>>,
                                  {'programmers': 81, 'salesmen': 62})})})

"401 Unauthorized" on a directory

In our case it was Windows-integrated authentication specified in the app's web.config

BUT the windows-auth module was not installed on the IIS machine at all.

Just adding another possible reason.

Change text from "Submit" on input tag

<input name="submitBnt" type="submit" value="like"/>

name is useful when using $_POST in php and also in javascript as document.getElementByName('submitBnt'). Also you can use name as a CS selector like input[name="submitBnt"]; Hope this helps

What is float in Java?

Make it

float b= 3.6f;

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

If you installed using the graphical installer by BigSQL from the official postgres site and if you installed in the default location...

You can find your uninstaller in your home directory: /Users/<yourusername/PostGreSQL/uninstall/

find vs find_by vs where

Apart from accepted answer, following is also valid

Model.find() can accept array of ids, and will return all records which matches. Model.find_by_id(123) also accept array but will only process first id value present in array

Model.find([1,2,3])
Model.find_by_id([1,2,3])

Where does PHP's error log reside in XAMPP?

\xampp\apache\logs\error.log, where xampp is your installation folder. If you haven't changed the error_log setting in PHP (check with phpinfo()), it will be logged to the Apache log.

javascript getting my textbox to display a variable

You're on the right track with using document.getElementById() as you have done for your first two text boxes. Use something like document.getElementById("textbox3") to retrieve the element. Then you can just set its value property: document.getElementById("textbox3").value = answer;

For the "Your answer is: --", I'd recommend wrapping the "--" in a <span/> (e.g. <span id="answerDisplay">--</span>). Then use document.getElementById("answerDisplay").textContent = answer; to display it.

Add column in dataframe from list

IIUC, if you make your (unfortunately named) List into an ndarray, you can simply index into it naturally.

>>> import numpy as np
>>> m = np.arange(16)*10
>>> m[df.A]
array([  0,  40,  50,  60, 150, 150, 140, 130])
>>> df["D"] = m[df.A]
>>> df
    A   B   C    D
0   0 NaN NaN    0
1   4 NaN NaN   40
2   5 NaN NaN   50
3   6 NaN NaN   60
4  15 NaN NaN  150
5  15 NaN NaN  150
6  14 NaN NaN  140
7  13 NaN NaN  130

Here I built a new m, but if you use m = np.asarray(List), the same thing should work: the values in df.A will pick out the appropriate elements of m.


Note that if you're using an old version of numpy, you might have to use m[df.A.values] instead-- in the past, numpy didn't play well with others, and some refactoring in pandas caused some headaches. Things have improved now.

What's the difference between Sender, From and Return-Path?

The official RFC which defines this specification could be found here:

http://tools.ietf.org/html/rfc4021#section-2.1.2 (look at paragraph 2.1.2. and the following)

2.1.2. Header Field: From

Description:  
    Mailbox of message author  
[...]  
Related information:
    Specifies the author(s) of the message; that is, the mailbox(es)
    of the person(s) or system(s) responsible for the writing of the
    message. Defined as standard by RFC 822.

2.1.3. Header Field: Sender

Description:  
    Mailbox of message sender  
[...]  
Related information:
    Specifies the mailbox of the agent responsible for the actual
    transmission of the message.  Defined as standard by RFC 822.

2.1.22. Header Field: Return-Path

Description:
    Message return path
[...]  
Related information:
    Return path for message response diagnostics. See also RFC 2821
    [17]. Defined as standard by RFC 822.

Simple prime number generator in Python

print [x for x in range(2,100) if not [t for t in range(2,x) if not x%t]]

How to use MySQLdb with Python and Django in OSX 10.6?

sudo apt-get install python-mysqldb works perfectly in ubuntu

pip install mysql-python raises an Environment Error

Disable Copy or Paste action for text box?

Here is the updated fiddle.

$(document).ready(function(){
    $('#confirmEmail').bind("cut copy paste",function(e) {
        e.preventDefault();
    });
});

This will prevent cut copy paste on Confirm Email text box.

Hope it helps.

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

If you know from which commit issue started, you can reset your branch to that commit and then merge them.

How to parse JSON response from Alamofire API in Swift?

I usually use Gloss library to serialize or deserialize JSON in iOS. For example, I have JSON that looks like this:

{"ABDC":[{"AB":"qwerty","CD":"uiop"}],[{"AB":"12334","CD":"asdf"}]}

First, I model the JSON array in Gloss struct:

Struct Struct_Name: Decodable {
   let IJ: String?
   let KL: String?
   init?(json: JSON){
       self.IJ = "AB" <~~ json
       self.KL = "CD" <~~ json
   }
}

And then in Alamofire responseJSON, I do this following thing:

Alamofire.request(url, method: .get, paramters: parametersURL).validate(contentType: ["application/json"]).responseJSON{ response in
 switch response.result{
   case .success (let data):
    guard let value = data as? JSON,
       let eventsArrayJSON = value["ABDC"] as? [JSON]
    else { fatalError() }
    let struct_name = [Struct_Name].from(jsonArray: eventsArrayJSON)//the JSON deserialization is done here, after this line you can do anything with your JSON
    for i in 0 ..< Int((struct_name?.count)!) {
       print((struct_name?[i].IJ!)!)
       print((struct_name?[i].KL!)!)
    }
    break

   case .failure(let error):
    print("Error: \(error)")
    break
 }
}

The output from the code above:

qwerty
uiop
1234
asdf

Getting next element while cycling through a list

As simple as this:

li = [0, 1, 2, 3]
while 1:
   for i, item in enumerate(x):
      k = i + 1 if i != len(x) - 1 else 0
      print('Current index {} : {}'.format(i,li[k]))

How to tell if browser/tab is active

In addition to Richard Simões answer you can also use the Page Visibility API.

if (!document.hidden) {
    // do what you need
}

This specification defines a means for site developers to programmatically determine the current visibility state of the page in order to develop power and CPU efficient web applications.

Learn more (2019 update)

Pass multiple complex objects to a post/put Web API method

I know this is an old question, but I had the same issue and here is what I came up with and hopefully will be useful to someone. This will allow passing JSON formatted parameters individually in request URL (GET), as one single JSON object after ? (GET) or within single JSON body object (POST). My goal was RPC-style functionality.

Created a custom attribute and parameter binding, inheriting from HttpParameterBinding:

public class JSONParamBindingAttribute : Attribute
{

}

public class JSONParamBinding : HttpParameterBinding
{

    private static JsonSerializer _serializer = JsonSerializer.Create(new JsonSerializerSettings()
    {
        DateTimeZoneHandling = DateTimeZoneHandling.Utc
    });


    public JSONParamBinding(HttpParameterDescriptor descriptor)
        : base(descriptor)
    {
    }

    public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider,
                                                HttpActionContext actionContext,
                                                CancellationToken cancellationToken)
    {
        JObject jobj = GetJSONParameters(actionContext.Request);

        object value = null;

        JToken jTokenVal = null;
        if (!jobj.TryGetValue(Descriptor.ParameterName, out jTokenVal))
        {
            if (Descriptor.IsOptional)
                value = Descriptor.DefaultValue;
            else
                throw new MissingFieldException("Missing parameter : " + Descriptor.ParameterName);
        }
        else
        {
            try
            {
                value = jTokenVal.ToObject(Descriptor.ParameterType, _serializer);
            }
            catch (Newtonsoft.Json.JsonException e)
            {
                throw new HttpParseException(String.Join("", "Unable to parse parameter: ", Descriptor.ParameterName, ". Type: ", Descriptor.ParameterType.ToString()));
            }
        }

        // Set the binding result here
        SetValue(actionContext, value);

        // now, we can return a completed task with no result
        TaskCompletionSource<AsyncVoid> tcs = new TaskCompletionSource<AsyncVoid>();
        tcs.SetResult(default(AsyncVoid));
        return tcs.Task;
    }

    public static HttpParameterBinding HookupParameterBinding(HttpParameterDescriptor descriptor)
    {
        if (descriptor.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<JSONParamBindingAttribute>().Count == 0 
            && descriptor.ActionDescriptor.GetCustomAttributes<JSONParamBindingAttribute>().Count == 0)
            return null;

        var supportedMethods = descriptor.ActionDescriptor.SupportedHttpMethods;

        if (supportedMethods.Contains(HttpMethod.Post) || supportedMethods.Contains(HttpMethod.Get))
        {
            return new JSONParamBinding(descriptor);
        }

        return null;
    }

    private JObject GetJSONParameters(HttpRequestMessage request)
    {
        JObject jobj = null;
        object result = null;
        if (!request.Properties.TryGetValue("ParamsJSObject", out result))
        {
            if (request.Method == HttpMethod.Post)
            {
                jobj = JObject.Parse(request.Content.ReadAsStringAsync().Result);
            }
            else if (request.RequestUri.Query.StartsWith("?%7B"))
            {
                jobj = JObject.Parse(HttpUtility.UrlDecode(request.RequestUri.Query).TrimStart('?'));
            }
            else
            {
                jobj = new JObject();
                foreach (var kvp in request.GetQueryNameValuePairs())
                {
                    jobj.Add(kvp.Key, JToken.Parse(kvp.Value));
                }
            }
            request.Properties.Add("ParamsJSObject", jobj);
        }
        else
        {
            jobj = (JObject)result;
        }

        return jobj;
    }



    private struct AsyncVoid
    {
    }
}

Inject binding rule inside WebApiConfig.cs's Register method:

        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.ParameterBindingRules.Insert(0, JSONParamBinding.HookupParameterBinding);

            config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        }

This allows for controller actions with default parameter values and mixed complexity, as such:

[JSONParamBinding]
    [HttpPost, HttpGet]
    public Widget DoWidgetStuff(Widget widget, int stockCount, string comment="no comment")
    {
        ... do stuff, return Widget object
    }

example post body:

{ 
    "widget": { 
        "a": 1, 
        "b": "string", 
        "c": { "other": "things" } 
    }, 
    "stockCount": 42, 
    "comment": "sample code"
} 

or GET single param (needs URL encoding)

controllerPath/DoWidgetStuff?{"widget":{..},"comment":"test","stockCount":42}

or GET multiple param (needs URL encoding)

controllerPath/DoWidgetStuff?widget={..}&comment="test"&stockCount=42

Conversion failed when converting the varchar value 'simple, ' to data type int

Given that you're only converting to ints to then perform a comparison, I'd just switch the table definition around to using varchar also:

Create table #myTempTable
(
num varchar(12)
)
insert into #myTempTable (num) values (1),(2),(3),(4),(5)

and remove all of the attempted CONVERTs from the rest of the query.

 SELECT a.name, a.value AS value, COUNT(*) AS pocet   
 FROM 
 (SELECT item.name, value.value 
  FROM mdl_feedback AS feedback 
  INNER JOIN mdl_feedback_item AS item 
       ON feedback.id = item.feedback
  INNER JOIN mdl_feedback_value AS value 
       ON item.id = value.item 
   WHERE item.typ = 'multichoicerated' AND item.feedback IN (43)
 ) AS a 
 INNER JOIN #myTempTable 
     on a.value = #myTempTable.num
 GROUP BY a.name, a.value ORDER BY a.name

Imitating a blink tag with CSS3 animations

The original Netscape <blink> had an 80% duty cycle. This comes pretty close, although the real <blink> only affects text:

_x000D_
_x000D_
.blink {_x000D_
  animation: blink-animation 1s steps(5, start) infinite;_x000D_
  -webkit-animation: blink-animation 1s steps(5, start) infinite;_x000D_
}_x000D_
@keyframes blink-animation {_x000D_
  to {_x000D_
    visibility: hidden;_x000D_
  }_x000D_
}_x000D_
@-webkit-keyframes blink-animation {_x000D_
  to {_x000D_
    visibility: hidden;_x000D_
  }_x000D_
}
_x000D_
This is <span class="blink">blinking</span> text.
_x000D_
_x000D_
_x000D_

You can find more info about Keyframe Animations here.

Angular Directive refresh on parameter change

Link function only gets called once, so it would not directly do what you are expecting. You need to use angular $watch to watch a model variable.

This watch needs to be setup in the link function.

If you use isolated scope for directive then the scope would be

scope :{typeId:'@' }

In your link function then you add a watch like

link: function(scope, element, attrs) {
    scope.$watch("typeId",function(newValue,oldValue) {
        //This gets called when data changes.
    });
 }

If you are not using isolated scope use watch on some_prop

Convert string to title case with JavaScript

Without using regex just for reference:

_x000D_
_x000D_
String.prototype.toProperCase = function() {_x000D_
  var words = this.split(' ');_x000D_
  var results = [];_x000D_
  for (var i = 0; i < words.length; i++) {_x000D_
    var letter = words[i].charAt(0).toUpperCase();_x000D_
    results.push(letter + words[i].slice(1));_x000D_
  }_x000D_
  return results.join(' ');_x000D_
};_x000D_
_x000D_
console.log(_x000D_
  'john smith'.toProperCase()_x000D_
)
_x000D_
_x000D_
_x000D_

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

Simple Solution:

import pandas as pd
df = pd.read_csv('file_name.csv', engine='python')

Rounding a number to the nearest 5 or 10 or X

For a strict Visual Basic approach, you can convert the floating-point value to an integer to round to said integer. VB is one of the rare languages that rounds on type conversion (most others simply truncate.)

Multiples of 5 or x can be done simply by dividing before and multiplying after the round.

If you want to round and keep decimal places, Math.round(n, d) would work.

use regular expression in if-condition in bash

Adding this solution with grep and basic sh builtins for those interested in a more portable solution (independent of bash version; also works with plain old sh, on non-Linux platforms etc.)

# GLOB matching
gg=svm-grid-ch    
case "$gg" in
   *grid*) echo $gg ;;
esac

# REGEXP    
if echo "$gg" | grep '^....grid*' >/dev/null ; then echo $gg ; fi    
if echo "$gg" | grep '....grid*' >/dev/null ; then echo $gg ; fi    
if echo "$gg" | grep 's...grid*' >/dev/null ; then echo $gg ; fi    

# Extended REGEXP
if echo "$gg" | egrep '(^....grid*|....grid*|s...grid*)' >/dev/null ; then
  echo $gg
fi    

Some grep incarnations also support the -q (quiet) option as an alternative to redirecting to /dev/null, but the redirect is again the most portable.

Tomcat Servlet: Error 404 - The requested resource is not available

this is may be due to the thing that you have created your .jsp or the .html file in the WEB-INF instead of the WebContent folder.

Solution: Just replace the files that are there in the WEB-INF folder to the Webcontent folder and try executing the same - You will get the appropriate output

How to get a list of programs running with nohup

If you have standart output redirect to "nohup.out" just see who use this file

lsof | grep nohup.out

What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

Disabled means that no data from that form element will be submitted when the form is submitted. Read-only means any data from within the element will be submitted, but it cannot be changed by the user.

For example:

<input type="text" name="yourname" value="Bob" readonly="readonly" />

This will submit the value "Bob" for the element "yourname".

<input type="text" name="yourname" value="Bob" disabled="disabled" />

This will submit nothing for the element "yourname".