Programs & Examples On #Entityspaces

How to Set Focus on Input Field using JQuery

Justin's answer did not work for me (Chromium 18, Firefox 43.0.1). jQuery's .focus() creates visual highlight, but text cursor does not appear in the field (jquery 3.1.0).

Inspired by https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/ , I added autofocus attribute to the input field and voila!

function addfield() {
    n=$('table tr').length;
    $('table').append('<tr><td><input name=field'+n+' autofocus></td><td><input name=value'+n+'></td></tr>');
    $('input[name="aa"'+n+']').focus();
}

How to load a model from an HDF5 file in Keras?

See the following sample code on how to Build a basic Keras Neural Net Model, save Model (JSON) & Weights (HDF5) and load them:

# create model
model = Sequential()
model.add(Dense(X.shape[1], input_dim=X.shape[1], activation='relu')) #Input Layer
model.add(Dense(X.shape[1], activation='relu')) #Hidden Layer
model.add(Dense(output_dim, activation='softmax')) #Output Layer

# Compile & Fit model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X,Y,nb_epoch=5,batch_size=100,verbose=1)    

# serialize model to JSON
model_json = model.to_json()
with open("Data/model.json", "w") as json_file:
    json_file.write(simplejson.dumps(simplejson.loads(model_json), indent=4))

# serialize weights to HDF5
model.save_weights("Data/model.h5")
print("Saved model to disk")

# load json and create model
json_file = open('Data/model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("Data/model.h5")
print("Loaded model from disk")

# evaluate loaded model on test data 
# Define X_test & Y_test data first
loaded_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
score = loaded_model.evaluate(X_test, Y_test, verbose=0)
print ("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))

Bootstrap: adding gaps between divs

I required only one instance of the vertical padding, so I inserted this line in the appropriate place to avoid adding more to the css. <div style="margin-top:5px"></div>

How to escape the % (percent) sign in C's printf?

With itself...

printf("hello%%"); /* like this */

Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'

    //source    
    public async Task<string> methodName()
            {
             return Data;
             }

    //Consumption
     methodName().Result;

Hope this helps :)

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

The acceptable verbs are controlled in web.config (found in the root of the website) in <system.web><httpHandlers> and possibly <webServices><protocols>. Web.config will be accessible to you if it exists. There is also a global server.config which probably won't. If you can get a look at either of these you may get a clue.

The acceptable verbs can differ with the content types - have you set Content-type headers in your page at all ? (i.e. if your Content-type was application/json then different verbs would be allowed)

How can I concatenate a string and a number in Python?

You would have to convert the int into a string.

# This program calculates a workers gross pay

hours = float(raw_input("Enter hours worked: \n"))

rate = float(raw_input("Enter your hourly rate of pay: \n"))

gross = hours * rate

print "Your gross pay for working " +str(hours)+ " at a rate of " + str(rate) + " hourly is $"  + str(gross)

Check existence of directory and create if doesn't exist

Here's the simple check, and creates the dir if doesn't exists:

## Provide the dir name(i.e sub dir) that you want to create under main dir:
output_dir <- file.path(main_dir, sub_dir)

if (!dir.exists(output_dir)){
dir.create(output_dir)
} else {
    print("Dir already exists!")
}

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points

Output:

Now try:

plot sin(x) with points pointtype 5

Output:

You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

Embed YouTube Video with No Ads

From the YouTube help:

You will automatically be opted into showing ads on embedded videos if you've associated your YouTube and AdSense accounts and have enabled your videos for embedding.

If you don't want to show overlay ads on your embedded videos, you can opt your videos out of showing overlay ads, though this will also disable overlay ads on your videos on YouTube.com. You may also disable your videos for embedding.

https://support.google.com/youtube/answer/132596?hl=en

Another technical solution could be to use a custom video player, and streamline the youtube video with that one. Have not tried but guess that the ads cannot be displayed in a custom player. However, could be forbidden.

How do I sort a list of dictionaries by a value of the dictionary?

If performance is a concern, I would use operator.itemgetter instead of lambda as built-in functions perform faster than hand-crafted functions. The itemgetter function seems to perform approximately 20% faster than lambda based on my testing.

From https://wiki.python.org/moin/PythonSpeed:

Likewise, the builtin functions run faster than hand-built equivalents. For example, map(operator.add, v1, v2) is faster than map(lambda x,y: x+y, v1, v2).

Here is a comparison of sorting speed using lambda vs itemgetter.

import random
import operator

# Create a list of 100 dicts with random 8-letter names and random ages from 0 to 100.
l = [{'name': ''.join(random.choices(string.ascii_lowercase, k=8)), 'age': random.randint(0, 100)} for i in range(100)]

# Test the performance with a lambda function sorting on name
%timeit sorted(l, key=lambda x: x['name'])
13 µs ± 388 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

# Test the performance with itemgetter sorting on name
%timeit sorted(l, key=operator.itemgetter('name'))
10.7 µs ± 38.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

# Check that each technique produces the same sort order
sorted(l, key=lambda x: x['name']) == sorted(l, key=operator.itemgetter('name'))
True

Both techniques sort the list in the same order (verified by execution of the final statement in the code block), but the first one is a little faster.

Determine if 2 lists have the same elements, regardless of order?

This seems to work, though possibly cumbersome for large lists.

>>> A = [0, 1]
>>> B = [1, 0]
>>> C = [0, 2]
>>> not sum([not i in A for i in B])
True
>>> not sum([not i in A for i in C])
False
>>> 

However, if each list must contain all the elements of other then the above code is problematic.

>>> A = [0, 1, 2]
>>> not sum([not i in A for i in B])
True

The problem arises when len(A) != len(B) and, in this example, len(A) > len(B). To avoid this, you can add one more statement.

>>> not sum([not i in A for i in B]) if len(A) == len(B) else False
False

One more thing, I benchmarked my solution with timeit.repeat, under the same conditions used by Aaron Hall in his post. As suspected, the results are disappointing. My method is the last one. set(x) == set(y) it is.

>>> def foocomprehend(): return not sum([not i in data for i in data2])
>>> min(timeit.repeat('fooset()', 'from __main__ import fooset, foocount, foocomprehend'))
25.2893661496
>>> min(timeit.repeat('foosort()', 'from __main__ import fooset, foocount, foocomprehend'))
94.3974742993
>>> min(timeit.repeat('foocomprehend()', 'from __main__ import fooset, foocount, foocomprehend'))
187.224562545

Max or Default?

Since .Net 3.5 you can use DefaultIfEmpty() passing the default value as an argument. Something like one of the followings ways:

int max = (from e in context.Table where e.Year == year select e.RecordNumber).DefaultIfEmpty(0).Max();
DateTime maxDate = (from e in context.Table where e.Year == year select e.StartDate ?? DateTime.MinValue).DefaultIfEmpty(DateTime.MinValue).Max();

The first one is allowed when you query a NOT NULL column and the second one is the way a used it to query a NULLABLE column. If you use DefaultIfEmpty() without arguments the default value will be that defined to the type of your output, as you can see in the Default Values Table .

The resulting SELECT will not be so elegant but it's acceptable.

Hope it helps.

Is there a way to reset IIS 7.5 to factory settings?

This link has some useful suggestions: http://forums.iis.net/t/1085990.aspx

It depends on where you have the config settings stored. By default IIS7 will have all of it's configuration settings stored in a file called "ApplicationHost.Config". If you have delegation configured then you will see site/app related config settings getting written to web.config file for the site/app. With IIS7 on vista there is an automatica backup file for master configuration is created. This file is called "application.config.backup" and it resides inside "C:\Windows\System32\inetsrv\config" You could rename this file to applicationHost.config and replace it with the applicationHost.config inside the config folder. IIS7 on server release will have better configuration back up story, but for now I recommend using APPCMD to backup/restore your configuration on regualr basis. Example: APPCMD ADD BACK "MYBACKUP" Another option (really the last option) is to uninstall/reinstall IIS along with WPAS (Windows Process activation service).

Webdriver Screenshot

I understand you are looking for an answer in python, but here is how one would do it in ruby..

http://watirwebdriver.com/screenshots/

If that only works by saving in current directory only.. I would first assign the image to a variable and then save that variable to disk as a PNG file.

eg:

 image = b.screenshot.png

 File.open("testfile.png", "w") do |file|
  file.puts "#{image}"
 end

where b is the browser variable used by webdriver. i have the flexibility to provide an absolute or relative path in "File.open" so I can save the image anywhere.

GDB: Listing all mapped memory regions for a crashed process

In GDB 7.2:

(gdb) help info proc
Show /proc process information about any running process.
Specify any process id, or use the program being debugged by default.
Specify any of the following keywords for detailed info:
  mappings -- list of mapped memory regions.
  stat     -- list a bunch of random process info.
  status   -- list a different bunch of random process info.
  all      -- list all available /proc info.

You want info proc mappings, except it doesn't work when there is no /proc (such as during pos-mortem debugging).

Try maintenance info sections instead.

How do I Search/Find and Replace in a standard string?

Why not implement your own replace?

void myReplace(std::string& str,
               const std::string& oldStr,
               const std::string& newStr)
{
  std::string::size_type pos = 0u;
  while((pos = str.find(oldStr, pos)) != std::string::npos){
     str.replace(pos, oldStr.length(), newStr);
     pos += newStr.length();
  }
}

encapsulation vs abstraction real world example

Encapsulation is to hide the variables or something inside a class, preventing unauthorized parties to use. So the public methods like getter and setter access it and the other classes call these methods for accessing

Abstraction involves the facility to define objects that represent abstract "actors" that can perform work, report on and change their state, and "communicate" with other objects in the system.

Consider the below real time example:

Encapsulation: As a driver you know how to start the car by pressing the start button and internal details of the starting operations are hidden from you. So the entire starting process is hidden from you otherwise we can tell starting operation is encapsulated from you.

OR

The driving wheel is encapsulated the process of rotating the wheel from you.

Abstraction:

Before mentioning anything about abstraction, we can take three different users here (I am calling them as entity)

1) You 2) Local Mechanic 3) Expert

You Entity: Since you know only to start the car by pressing a button and all other operations behind the scene are abstracted from you.

Local Mechanic Entity: Our local mechanic knows some of the implementation of starting the car, i.e. he can open car's bonnet and check the battery cable or chock etc. So in short Local Mechanic Entity knows some of the implementations of the car.

Expert Entity: Since our expert (Designer of the car) mechanic knows all the operations of our car, he can repair it very quickly. So in short Expert Entity knows all the implementations of the car.

The car's operation is completely abstracted from you and it is partially implemented to Local Mechanic Entity and fully implemented to Expert Entity. So you are an abstract class having only abstract methods, Local Mechanic Entity has extended You(Since he is also an ordinary user) and he implemented some of the methods and last our expert Entity extending Local Mechanic and implementing all the methods.

I think this is a good example.

Goal Seek Macro with Goal as a Formula

GoalSeek will throw an "Invalid Reference" error if the GoalSeek cell contains a value rather than a formula or if the ChangingCell contains a formula instead of a value or nothing.

The GoalSeek cell must contain a formula that refers directly or indirectly to the ChangingCell; if the formula doesn't refer to the ChangingCell in some way, GoalSeek either may not converge to an answer or may produce a nonsensical answer.

I tested your code with a different GoalSeek formula than yours (I wasn't quite clear whether some of the terms referred to cells or values).

For the test, I set:

  the GoalSeek cell  H18 = (G18^3)+(3*G18^2)+6
  the Goal cell      H32 =  11
  the ChangingCell   G18 =  0 

The code was:

Sub GSeek()
    With Worksheets("Sheet1")
        .Range("H18").GoalSeek _
        Goal:=.Range("H32").Value, _
        ChangingCell:=.Range("G18")
    End With
End Sub

And the code produced the (correct) answer of 1.1038, the value of G18 at which the formula in H18 produces the value of 11, the goal I was seeking.

What command shows all of the topics and offsets of partitions in Kafka?

We're using Kafka 2.11 and make use of this tool - kafka-consumer-groups.

$ rpm -qf /bin/kafka-consumer-groups
confluent-kafka-2.11-1.1.1-1.noarch

For example:

$ kafka-consumer-groups --describe --group logstash | grep -E "TOPIC|filebeat"
Note: This will not show information about old Zookeeper-based consumers.
TOPIC            PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                     HOST             CLIENT-ID
beats_filebeat   0          20003914484     20003914888     404             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   1          19992522286     19992522709     423             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   2          19990597254     19990597637     383             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   7          19991718707     19991719268     561             logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2   logstash-0
beats_filebeat   8          20015611981     20015612509     528             logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2   logstash-0
beats_filebeat   5          19990536340     19990541331     4991            logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3   logstash-0
beats_filebeat   6          19990728038     19990733086     5048            logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3   logstash-0
beats_filebeat   3          19994613945     19994616297     2352            logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4   logstash-0
beats_filebeat   4          19990681602     19990684038     2436            logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4   logstash-0

Random Tip

NOTE: We use an alias that overloads kafka-consumer-groups like so in our /etc/profile.d/kafka.sh:

alias kafka-consumer-groups="KAFKA_JVM_PERFORMANCE_OPTS=\"-Djava.security.auth.login.config=$HOME/.kafka_client_jaas.conf\"  kafka-consumer-groups --bootstrap-server ${KAFKA_HOSTS} --command-config /etc/kafka/security-enabler.properties"

Simplest two-way encryption using PHP

Edited:

You should really be using openssl_encrypt() & openssl_decrypt()

As Scott says, Mcrypt is not a good idea as it has not been updated since 2007.

There is even an RFC to remove Mcrypt from PHP - https://wiki.php.net/rfc/mcrypt-viking-funeral

jQuery - Follow the cursor with a DIV

You don't need jQuery for this. Here's a simple working example:

<!DOCTYPE html>
<html>
    <head>
        <title>box-shadow-experiment</title>
        <style type="text/css">
            #box-shadow-div{
                position: fixed;
                width: 1px;
                height: 1px;
                border-radius: 100%;
                background-color:black;
                box-shadow: 0 0 10px 10px black;
                top: 49%;
                left: 48.85%;
            }
        </style>
        <script type="text/javascript">
            window.onload = function(){
                var bsDiv = document.getElementById("box-shadow-div");
                var x, y;
    // On mousemove use event.clientX and event.clientY to set the location of the div to the location of the cursor:
                window.addEventListener('mousemove', function(event){
                    x = event.clientX;
                    y = event.clientY;                    
                    if ( typeof x !== 'undefined' ){
                        bsDiv.style.left = x + "px";
                        bsDiv.style.top = y + "px";
                    }
                }, false);
            }
        </script>
    </head>
    <body>
        <div id="box-shadow-div"></div>
    </body>
</html>

I chose position: fixed; so scrolling wouldn't be an issue.

How to use support FileProvider for sharing content to other apps?

just to improve answer given above: if you are getting NullPointerEx:

you can also use getApplicationContext() without context

                List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : resInfoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    grantUriPermission(packageName, photoURI, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }

Combining CSS Pseudo-elements, ":after" the ":last-child"

To have something like One, two and three you should add one more css style

li:nth-last-child(2):after {
    content: ' ';
}

This would remove the comma from the second last element.

Complete Code

_x000D_
_x000D_
li {_x000D_
  display: inline;_x000D_
  list-style-type: none;_x000D_
}_x000D_
_x000D_
li:after {_x000D_
  content: ", ";_x000D_
}_x000D_
_x000D_
li:nth-last-child(2):after {_x000D_
  content: '';_x000D_
}_x000D_
_x000D_
li:last-child:before {_x000D_
  content: " and ";_x000D_
}_x000D_
_x000D_
li:last-child:after {_x000D_
  content: ".";_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <ul>_x000D_
    <li>One</li>_x000D_
    <li>Two</li>_x000D_
    <li>Three</li>_x000D_
  </ul>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Date format Mapping to JSON Jackson

I want to point out that setting a SimpleDateFormat like described in the other answer only works for a java.util.Date which I assume is meant in the question. But for java.sql.Date the formatter does not work. In my case it was not very obvious why the formatter did not work because in the model which should be serialized the field was in fact a java.utl.Date but the actual object ended up beeing a java.sql.Date. This is possible because

public class java.sql extends java.util.Date

So this is actually valid

java.util.Date date = new java.sql.Date(1542381115815L);

So if you are wondering why your Date field is not correctly formatted make sure that the object is really a java.util.Date.

Here is also mentioned why handling java.sql.Date will not be added.

This would then be breaking change, and I don't think that is warranted. If we were starting from scratch I would agree with the change, but as things are not so much.

How can I solve a connection pool problem between ASP.NET and SQL Server?

Did you check for DataReaders that are not closed and response.redirects before closing the connection or a datareader. Connections stay open when you dont close them before a redirect.

Creating an IFRAME using JavaScript

You can use:

<script type="text/javascript">
    function prepareFrame() {
        var ifrm = document.createElement("iframe");
        ifrm.setAttribute("src", "http://google.com/");
        ifrm.style.width = "640px";
        ifrm.style.height = "480px";
        document.body.appendChild(ifrm);
    }
</script> 

also check basics of the iFrame element

How to set a value to a file input in HTML?

Actually we can do it. we can set the file value default by using webbrowser control in c# using FormToMultipartPostData Library.We have to download and include this Library in our project. Webbrowser enables the user to navigate Web pages inside form. Once the web page loaded , the script inside the webBrowser1_DocumentCompleted will be executed. So,

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
       FormToMultipartPostData postData = 
            new FormToMultipartPostData(webBrowser1, form);
        postData.SetFile("fileField", @"C:\windows\win.ini");
        postData.Submit();
    }

Refer the below link for downloading and complete reference.

https://www.codeproject.com/Articles/28917/Setting-a-file-to-upload-inside-the-WebBrowser-com

How to find day of week in php in a specific timezone

$myTimezone = date_default_timezone_get();
date_default_timezone_set($userTimezone);
$userDay = date('l', $userTimestamp);
date_default_timezone_set($myTimezone);

This should work (didn't test it, so YMMV). It works by storing the script's current timezone, changing it to the one specified by the user, getting the day of the week from the date() function at the specified timestamp, and then setting the script's timezone back to what it was to begin with.

You might have some adventures with timezone identifiers, though.

How to enable named/bind/DNS full logging?

I usually expand each log out into it's own channel and then to a separate log file, certainly makes things easier when you are trying to debug specific issues. So my logging section looks like the following:

logging {
    channel default_file {
        file "/var/log/named/default.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel general_file {
        file "/var/log/named/general.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel database_file {
        file "/var/log/named/database.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel security_file {
        file "/var/log/named/security.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel config_file {
        file "/var/log/named/config.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel resolver_file {
        file "/var/log/named/resolver.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-in_file {
        file "/var/log/named/xfer-in.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-out_file {
        file "/var/log/named/xfer-out.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel notify_file {
        file "/var/log/named/notify.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel client_file {
        file "/var/log/named/client.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel unmatched_file {
        file "/var/log/named/unmatched.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel queries_file {
        file "/var/log/named/queries.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel network_file {
        file "/var/log/named/network.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel update_file {
        file "/var/log/named/update.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dispatch_file {
        file "/var/log/named/dispatch.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dnssec_file {
        file "/var/log/named/dnssec.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel lame-servers_file {
        file "/var/log/named/lame-servers.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };

    category default { default_file; };
    category general { general_file; };
    category database { database_file; };
    category security { security_file; };
    category config { config_file; };
    category resolver { resolver_file; };
    category xfer-in { xfer-in_file; };
    category xfer-out { xfer-out_file; };
    category notify { notify_file; };
    category client { client_file; };
    category unmatched { unmatched_file; };
    category queries { queries_file; };
    category network { network_file; };
    category update { update_file; };
    category dispatch { dispatch_file; };
    category dnssec { dnssec_file; };
    category lame-servers { lame-servers_file; };
};

Hope this helps.

How to configure port for a Spring Boot application

if you are using gradle as the build tool, you can set the server port in your application.yml file as:

server:
  port: 8291

If you are using maven then the port can be set in your application.properties file as:

server.port: 8291

moment.js 24h format

Try: moment({ // Options here }).format('HHmm'). That should give you the time in a 24 hour format.

base 64 encode and decode a string in angular (2+)

For encoding to base64 in Angular2, you can use btoa() function.

Example:-

console.log(btoa("stringAngular2")); 
// Output:- c3RyaW5nQW5ndWxhcjI=

For decoding from base64 in Angular2, you can use atob() function.

Example:-

console.log(atob("c3RyaW5nQW5ndWxhcjI=")); 
// Output:- stringAngular2

Capture Signature using HTML5 and iPad

Perhaps the best two browser techs for this are Canvas, with Flash as a back up.

We tried VML on IE as backup for Canvas, but it was much slower than Flash. SVG was slower then all the rest.

With jSignature ( http://willowsystems.github.com/jSignature/ ) we used Canvas as primary, with fallback to Flash-based Canvas emulator (FlashCanvas) for IE8 and less. Id' say worked very well for us.

XAMPP - Error: MySQL shutdown unexpectedly

You must:

  • Close the xampp
  • Go to the folder where you installed it, if in (c:) may be something like C:\xampp\ , access folder C:\xampp\mysql\data
  • Delete the file ibdata1
  • Starts XAMPP again.

Android Button Onclick

There are two solutions for this are :-

(1) do not put onClick in xml

(2) remove

button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
            // TODO Auto-generated method stub
    }
});

and put

public void setLogin(View v) {
    // Your code here
}

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

How to perform Unwind segue programmatically?

Here's a complete answer with Objective C and Swift:

1) Create an IBAction unwind segue in your destination view controller (where you want to segue to). Anywhere in the implementation file.

// Objective C

    - (IBAction)unwindToContainerVC:(UIStoryboardSegue *)segue {

    }

// Swift

 @IBAction func unwindToContainerVC(segue: UIStoryboardSegue) {

    }

2) On the source view controller (the controller you're segueing from), ^ + drag from "Name of activity" to exit. You should see the unwind segue created in step 1 in the popup. (If you don't see it, review step one). Pick unwindToContainerVC: from the popup, or whatever you named your method to connect your source controller to the unwind IBAction.

enter image description here

3) Select the segue in the source view controller's document outline of the storyboard (it will be listed near the bottom), and give it an identifier.

enter image description here

4) Call the unwind segue using this method from source view controller, substituting your unwind segue name.

// Objective C

[self performSegueWithIdentifier:@"unwindToContainerVC" sender:self];

// Swift

self.performSegueWithIdentifier("unwindToContainerVC", sender: self)

NB. Use the sourceViewController property of the segue parameter on the unwind method to access any exposed properties on the source controller. Also, notice that the framework handles dismissing the source controller. If you'd like to confirm this add a dealloc method to the source controller with a log message that should fire once it has been killed. If dealloc doesn't fire you may have a retain cycle.

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

Getting time difference between two times in PHP

<?php
$start = strtotime("12:00");
$end = // Run query to get datetime value from db
$elapsed = $end - $start;
echo date("H:i", $elapsed);
?>

Android WebView Cookie Problem

After some time researching I've gathered some pieces that made me get to this solution. Once that CookieSyncManager is deprecated, this may be the best way to set a specific cookie for a webview in Kotlin nowadays, you shouldn't need anything else.

private fun setCookie(){
    val webView = WebView(this) // this = context
    val cookieManager = CookieManager.getInstance()
    cookieManager.acceptCookie()

    val domain = "https://www.yourdomain.com/"

    webView.webViewClient = WebViewClient()
    webView.settings.javaScriptEnabled = true

    cookieManager.setCookie(domain,"$cookieKey=$cookieValue")
    cookieManager.setAcceptThirdPartyCookies(webView, true)

    webView.loadUrl(domain)
}

Swift programmatically navigate to another view controller/scene

So If you present a view controller it will not show in navigation controller. It will just take complete screen. For this case you have to create another navigation controller and add your nextViewController as root for this and present this new navigationController.

Another way is to just push the view controller.

self.presentViewController(nextViewController, animated:true, completion:nil)

For more info check Apple documentation:- https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/doc/uid/TP40006926-CH3-SW96

Eclipse : Maven search dependencies doesn't work

Use https://search.maven.org/ manually with the prefix fc: to search for class names. Both Netbeans and Eclipse seem to be too stupid to use that search interface and the gigabytes of downloaded repository indexes seem to not contain any class information. Total waste of disk space. Those IDE projects are so badly maintained lately, I wish they would move development to GitHub.

ln (Natural Log) in Python

math.log is the natural logarithm:

From the documentation:

math.log(x[, base]) With one argument, return the natural logarithm of x (to base e).

Your equation is therefore:

n = math.log((1 + (FV * r) / p) / math.log(1 + r)))

Note that in your code you convert n to a str twice which is unnecessary

How do you stylize a font in Swift?

You can set custom font in two ways : design time and run-time.

  1. First you need to download required font (.ttf file format). Then, double click on the file to install it.

  2. This will show a pop-up. Click on 'install font' button.

Screenshot 1

  1. This will install the font and will appear in 'Fonts' window.

Screenshot 2

  1. Now, the font is installed successfully. Drag and drop the custom font in your project. While doing this make sure that 'Add to targets' is checked.

Screenshot 3

  1. You need to make sure that this file is also added into 'Copy Bundle Resources' present in Build Phases of Targets of your project.

Screenshot 4

  1. After this you need to add this font in Info.plist of your project. Create a new key with 'Font Provided by application' with type as Array. Add a the font as an element with type String in Array.

Screenshot 5

A. Design mode :

  1. Select the label from Storyboard file. Goto Font attribute present in Attribute inspector of Utilities.

Screenshot 6

  1. Click on Font and select 'Custom font'

Screenshot 7

  1. From Family section select the custom font you have installed.

Screenshot 8

  1. Now you can see that font of label is set to custom font.

Screenshot 9

B. Run-time mode :

 self.lblWelcome.font = UIFont(name: "BananaYeti-Extrabold Trial", size: 16)

It seems that run-time mode doesn't work for dynamically formed string like

self.lblWelcome.text = "Welcome, " + fullname + "!"

Note that in above case only design-time approach worked correctly for me.

How to submit http form using C#

Your HTML file is not going to interact with C# directly, but you can write some C# to behave as if it were the HTML file.

For example: there is a class called System.Net.WebClient with simple methods:

using System.Net;
using System.Collections.Specialized;

...
using(WebClient client = new WebClient()) {

    NameValueCollection vals = new NameValueCollection();
    vals.Add("test", "test string");
    client.UploadValues("http://www.someurl.com/page.php", vals);
}

For more documentation and features, refer to the MSDN page.

Sort Go map values by keys

According to the Go spec, the order of iteration over a map is undefined, and may vary between runs of the program. In practice, not only is it undefined, it's actually intentionally randomized. This is because it used to be predictable, and the Go language developers didn't want people relying on unspecified behavior, so they intentionally randomized it so that relying on this behavior was impossible.

What you'll have to do, then, is pull the keys into a slice, sort them, and then range over the slice like this:

var m map[keyType]valueType
keys := sliceOfKeys(m) // you'll have to implement this
for _, k := range keys {
    v := m[k]
    // k is the key and v is the value; do your computation here
}

Best way to do a split pane in HTML

I found a working splitter, http://www.dreamchain.com/split-pane/, which works with jQuery v1.9. Note I had to add the following CSS code to get it working with a fixed bootstrap navigation bar.

fixed-left {
    position: absolute !important; /* to override relative */
    height: auto !important;
    top: 55px; /* Fixed navbar height */
    bottom: 0px;
}

SELECT query with CASE condition and SUM()

Use an "Or"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where (CPaymentType='Check' Or CPaymentType='Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

or an "IN"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where CPaymentType IN ('Check', 'Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

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

success only fires if the AJAX call is successful, i.e. ultimately returns a HTTP 200 status. error fires if it fails and complete when the request finishes, regardless of success.

In jQuery 1.8 on the jqXHR object (returned by $.ajax) success was replaced with done, error with fail and complete with always.

However you should still be able to initialise the AJAX request with the old syntax. So these do similar things:

// set success action before making the request
$.ajax({
  url: '...',
  success: function(){
    alert('AJAX successful');
  }
});

// set success action just after starting the request
var jqxhr = $.ajax( "..." )
  .done(function() { alert("success"); });

This change is for compatibility with jQuery 1.5's deferred object. Deferred (and now Promise, which has full native browser support in Chrome and FX) allow you to chain asynchronous actions:

$.ajax("parent").
    done(function(p) { return $.ajax("child/" + p.id); }).
    done(someOtherDeferredFunction).
    done(function(c) { alert("success: " + c.name); });

This chain of functions is easier to maintain than a nested pyramid of callbacks you get with success.

However, please note that done is now deprecated in favour of the Promise syntax that uses then instead:

$.ajax("parent").
    then(function(p) { return $.ajax("child/" + p.id); }).
    then(someOtherDeferredFunction).
    then(function(c) { alert("success: " + c.name); }).
    catch(function(err) { alert("error: " + err.message); });

This is worth adopting because async and await extend promises improved syntax (and error handling):

try {
    var p = await $.ajax("parent");
    var x = await $.ajax("child/" + p.id);
    var c = await someOtherDeferredFunction(x);
    alert("success: " + c.name);
}
catch(err) { 
    alert("error: " + err.message); 
}

Date Conversion from String to sql Date in Java giving different output?

You need to use MM as mm stands for minutes.

There are two ways of producing month pattern.

SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); //outputs month in numeric way, 2013-02-01

SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy"); // Outputs months as follows, 2013-Feb-01

Full coding snippet:

        String startDate="01-Feb-2013"; // Input String
        SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); // New Pattern
        java.util.Date date = sdf1.parse(startDate); // Returns a Date format object with the pattern
        java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());
        System.out.println(sqlStartDate); // Outputs : 2013-02-01

Can I do Android Programming in C++, C?

Yes, you can program Android apps in C++ (for the most part), using the Native Development Kit (NDK), although Java is the primary/preferred language for programming Android, and your C++ code will likely have to interface with Java components, and you'll likely need to read and understand the documentation for Java components, as well. Therefore, I'd advise you to use Java unless you have some existing C++ code base that you need to port and that isn't practical to rewrite in Java.

Java is very similar to C++, I don't think you will have any problems picking it up... going from C++ to Java is incredibly easy; going from Java to C++ is a little more difficult, though not terrible. Java for C++ Programmers does a pretty good job at explaining the differences. Writing your Android code in Java will be more idiomatic and will also make the development process easier for you (as the tooling for the Java Android SDK is significantly better than the corresponding NDK tooling)

In terms of setup, Google provides the Android Studio IDE for both Java and C++ Android development (with Gradle as the build system), but you are free to use whatever IDE or build system you want so long as, under the hood, you are using the Android SDK / NDK to produce the final outputs.

jQuery: how to change title of document during .ready()?

Like this:

$(document).ready(function ()
{
    document.title = "Hello World!";
});

Be sure to set a default-title if you want your site to be properly indexed by search-engines.

A little tip:

$(function ()
{
    // this is a shorthand for the whole document-ready thing
    // In my opinion, it's more readable 
});

How do you check current view controller class in Swift?

Try this

if self is MyViewController {        

}

How to display an alert box from C# in ASP.NET?

Response.Write("<script>alert('Data inserted successfully')</script>");

Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues

To anyone else who tried most of the solutions and still having problems.

My solution is different from the others, which is located at the bottom of this post, but before you try it make sure you have exhausted the following lists. To be sure, I have tried all of them but to no avail.

  1. Recompile and redeploy from scratch, don't update the existing app. SO Answer

  2. Grant IIS_IUSRS full access to the directory "C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files"

    Keep in mind the framework version you are using. If your app is using impersonation, use that identity instead of IIS_IUSRS

  3. Delete all contents of the directory "C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files".

    Keep in mind the framework version you are using

  4. Change the identity of the AppPool that your app is using, from ApplicatonPoolIdentity to NetworkService.

    IIS > Application Pools > Select current app pool > Advance Settings > Identity.

    SO Answer (please restore to default if it doesn't work)

  5. Verify IIS Version and AppPool .NET version compatibility with your app. Highly applicable to first time deployments. SO Answer

  6. Verify impersonation configuration if applicable. SO Answer

My Solution:

I found out that certain anti-virus softwares are actively blocking compilations of DLLs within the directory "Temporary ASP.NET Files", mine was McAfee, the IT people failed to notify me of the installation.

As per advice by both McAfee experts and Microsoft, you need to exclude the directory "Temporary ASP.NET Files" in the real time scanning.

Sources:

Don't disable the Anti-Virus because it is only doing its job. Don't manually copy missing DLL files in the directory \Temporary ASP.NET Files{project name} because thats duct taping.

How to enable scrolling of content inside a modal?

.modal-body {
    max-height: 80vh;
    overflow-y: scroll;
}

it's works for me

jQuery textbox change event doesn't fire until textbox loses focus?

$(this).bind('input propertychange', function() {
        //your code here
    });

This is works for typing, paste, right click mouse paste etc.

Pointers, smart pointers or shared pointers?

Sydius outlined the types fairly well:

  • Normal pointers are just that - they point to some thing in memory somewhere. Who owns it? Only the comments will let you know. Who frees it? Hopefully the owner at some point.
  • Smart pointers are a blanket term that cover many types; I'll assume you meant scoped pointer which uses the RAII pattern. It is a stack-allocated object that wraps a pointer; when it goes out of scope, it calls delete on the pointer it wraps. It "owns" the contained pointer in that it is in charge of deleteing it at some point. They allow you to get a raw reference to the pointer they wrap for passing to other methods, as well as releasing the pointer, allowing someone else to own it. Copying them does not make sense.
  • Shared pointers is a stack-allocated object that wraps a pointer so that you don't have to know who owns it. When the last shared pointer for an object in memory is destructed, the wrapped pointer will also be deleted.

How about when you should use them? You will either make heavy use of scoped pointers or shared pointers. How many threads are running in your application? If the answer is "potentially a lot", shared pointers can turn out to be a performance bottleneck if used everywhere. The reason being that creating/copying/destructing a shared pointer needs to be an atomic operation, and this can hinder performance if you have many threads running. However, it won't always be the case - only testing will tell you for sure.

There is an argument (that I like) against shared pointers - by using them, you are allowing programmers to ignore who owns a pointer. This can lead to tricky situations with circular references (Java will detect these, but shared pointers cannot) or general programmer laziness in a large code base.

There are two reasons to use scoped pointers. The first is for simple exception safety and cleanup operations - if you want to guarantee that an object is cleaned up no matter what in the face of exceptions, and you don't want to stack allocate that object, put it in a scoped pointer. If the operation is a success, you can feel free to transfer it over to a shared pointer, but in the meantime save the overhead with a scoped pointer.

The other case is when you want clear object ownership. Some teams prefer this, some do not. For instance, a data structure may return pointers to internal objects. Under a scoped pointer, it would return a raw pointer or reference that should be treated as a weak reference - it is an error to access that pointer after the data structure that owns it is destructed, and it is an error to delete it. Under a shared pointer, the owning object can't destruct the internal data it returned if someone still holds a handle on it - this could leave resources open for much longer than necessary, or much worse depending on the code.

How do I append one string to another in Python?

If you need to do many append operations to build a large string, you can use StringIO or cStringIO. The interface is like a file. ie: you write to append text to it.

If you're just appending two strings then just use +.

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

This type of warnings are usually flagged because of the request HTTP headers. Specifically the Accept request header. The MDN documentation for HTTP headers states

The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the Content-Type response header. Browsers set adequate values for this header depending of the context where the request is done....

application/json is probably not on the list of MIME types in the Accept header sent by the browser hence the warning.

Solution

Custom HTTP headers can only be sent programmatically via XMLHttpRequest or any of the js library wrappers implementing it.

Simple argparse example wanted: 1 argument, 3 results

To add to what others have stated:

I usually like to use the 'dest' parameter to specify a variable name and then use 'globals().update()' to put those variables in the global namespace.

Usage:

$ python script.py -i "Hello, World!"

Code:

...
parser.add_argument('-i', '--input', ..., dest='inputted_variable',...)
globals().update(vars(parser.parse_args()))
...
print(inputted_variable) # Prints "Hello, World!"

How can I get dict from sqlite query?

Fastest on my tests:

conn.row_factory = lambda c, r: dict(zip([col[0] for col in c.description], r))
c = conn.cursor()

%timeit c.execute('SELECT * FROM table').fetchall()
19.8 µs ± 1.05 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)

vs:

conn.row_factory = lambda c, r: dict([(col[0], r[idx]) for idx, col in enumerate(c.description)])
c = conn.cursor()

%timeit c.execute('SELECT * FROM table').fetchall()
19.4 µs ± 75.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

You decide :)

SQL Error with Order By in Subquery

Besides the fact that order by doesn't seem to make sense in your query.... To use order by in a sub select you will need to use TOP 2147483647.

SELECT (
  SELECT TOP 2147483647
  COUNT(1) FROM Seanslar WHERE MONTH(tarihi) = 4
  GROUP BY refKlinik_id
  ORDER BY refKlinik_id
) as dorduncuay

My understanding is that "TOP 100 PERCENT" doesn't gurantee ordering anymore starting with SQL 2005:

In SQL Server 2005, the ORDER BY clause in a view definition is used only to determine the rows that are returned by the TOP clause. The ORDER BY clause does not guarantee ordered results when the view is queried, unless ORDER BY is also specified in the query itself.

See SQL Server 2005 breaking changes

Hope this helps, Patrick

phpMyAdmin mbstring error

Please uncomment the following lines at php.ini

;extension=php_mbstring.dll ;extension=php_exif.dll ; Must be after mbstring as it depends on it ;extension=php_mysql.dll ;extension=php_mysqli.dll

This will help to solve.

The type arguments for method cannot be inferred from the usage

For those who are wondering why this works in Java but not C#, consider what happens if some doof wrote this class:

public class Trololol : ISignatur<bool>, ISignatur<int>{
    Type ISignatur<bool>.Type => typeof(bool);
    Type ISignatur<int>.Type => typeof(int);
}

How is the compiler supposed to resolve var access = service.Get(new Trololol())? Both int and bool are valid.

The reason this implicit resolution works in Java likely has to do with Erasure and how Java will throw a fit if you try to implement an interface with two or more different type arguments. Such a class is simply not allowed in Java, but is just fine in C#.

Find all paths between two graph nodes

I've implemented a version where it basically finds all possible paths from one node to the other, but it doesn't count any possible 'cycles' (the graph I'm using is cyclical). So basically, no one node will appear twice within the same path. And if the graph were acyclical, then I suppose you could say it seems to find all the possible paths between the two nodes. It seems to be working just fine, and for my graph size of ~150, it runs almost instantly on my machine, though I'm sure the running time must be something like exponential and so it'll start to get slow quickly as the graph gets bigger.

Here is some Java code that demonstrates what I'd implemented. I'm sure there must be more efficient or elegant ways to do it as well.

Stack connectionPath = new Stack();
List<Stack> connectionPaths = new ArrayList<>();
// Push to connectionsPath the object that would be passed as the parameter 'node' into the method below
void findAllPaths(Object node, Object targetNode) {
    for (Object nextNode : nextNodes(node)) {
       if (nextNode.equals(targetNode)) {
           Stack temp = new Stack();
           for (Object node1 : connectionPath)
               temp.add(node1);
           connectionPaths.add(temp);
       } else if (!connectionPath.contains(nextNode)) {
           connectionPath.push(nextNode);
           findAllPaths(nextNode, targetNode);
           connectionPath.pop();
        }
    }
}

Formatting dates on X axis in ggplot2

To show months as Jan 2017 Feb 2017 etc:

scale_x_date(date_breaks = "1 month", date_labels =  "%b %Y") 

Angle the dates if they take up too much space:

theme(axis.text.x=element_text(angle=60, hjust=1))

How does jQuery work when there are multiple elements with the same ID value?

There should only be one element with a given id. If you're stuck with that situation, see the 2nd half of my answer for options.

How a browser behaves when you have multiple elements with the same id (illegal HTML) is not defined by specification. You could test all the browsers and find out how they behave, but it's unwise to use this configuration or rely on any particular behavior.

Use classes if you want multiple objects to have the same identifier.

<div>
    <span class="a">1</span>
    <span class="a">2</span>
    <span>3</span>
</div>

$(function() {
    var w = $("div");
    console.log($(".a").length);            // 2
    console.log($("body .a").length);       // 2
    console.log($(".a", w).length);         // 2
});

If you want to reliably look at elements with IDs that are the same because you can't fix the document, then you will have to do your own iteration as you cannot rely on any of the built in DOM functions.

You could do so like this:

function findMultiID(id) {
    var results = [];
    var children = $("div").get(0).children;
    for (var i = 0; i < children.length; i++) {
        if (children[i].id == id) {
            results.push(children[i]);
        }
    }
    return(results);
}

Or, using jQuery:

$("div *").filter(function() {return(this.id == "a");});

jQuery working example: http://jsfiddle.net/jfriend00/XY2tX/.

As to Why you get different results, that would have to do with the internal implementation of whatever piece of code was carrying out the actual selector operation. In jQuery, you could study the code to find out what any given version was doing, but since this is illegal HTML, there is no guarantee that it will stay the same over time. From what I've seen in jQuery, it first checks to see if the selector is a simple id like #a and if so, just used document.getElementById("a"). If the selector is more complex than that and querySelectorAll() exists, jQuery will often pass the selector off to the built in browser function which will have an implementation specific to that browser. If querySelectorAll() does not exist, then it will use the Sizzle selector engine to manually find the selector which will have it's own implementation. So, you can have at least three different implementations all in the same browser family depending upon the exact selector and how new the browser is. Then, individual browsers will all have their own querySelectorAll() implementations. If you want to reliably deal with this situation, you will probably have to use your own iteration code as I've illustrated above.

linux shell script: split string, put them in an array then loop through them

sentence="one;two;three"
a="${sentence};"
while [ -n "${a}" ]
do
    echo ${a%%;*}
    a=${a#*;}
done

Get current value selected in dropdown using jQuery

Check it Out-->

For getting text

$("#selme").change(function(){
 $(this[this.selectedIndex]).text();
});

For getting value

$("#selme").change(function(){
 $(this[this.selectedIndex]).val();
});

How do I read a specified line in a text file?

.NET 4.0 edit

Since .NET 4.0, it is possible to access a single line of a file directly. For instance, to access line 15:

string line = File.ReadLines(FileName).Skip(14).Take(1).First();

This will return only the line required


Since you can't predict the location (can you?) of the i-th line in the file, you'll have to read all previous lines too. If the line number is small, this can be more efficient than the ReadAllLines method.

string GetLine(string fileName, int line)
{
   using (var sr = new StreamReader(fileName)) {
       for (int i = 1; i < line; i++)
          sr.ReadLine();
       return sr.ReadLine();
   }
}

phpinfo() is not working on my CentOS server

Another possible answer for Windows 10:

The command httpd -k restart does not work on my machine somehow.

Try to use the Windows 10 Service to restart the relative service.

java.nio.file.Path for a classpath resource

You need to define the Filesystem to read resource from jar file as mentioned in https://docs.oracle.com/javase/8/docs/technotes/guides/io/fsp/zipfilesystemprovider.html. I success to read resource from jar file with below codes:

Map<String, Object> env = new HashMap<>();
try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {

        Path path = fs.getPath("/path/myResource");

        try (Stream<String> lines = Files.lines(path)) {
            ....
        }
    }

How to get image height and width using java?

You can load jpeg binary data as a file and parse the jpeg headers yourself. The one you are looking for is the 0xFFC0 or Start of Frame header:

Start of frame marker (FFC0)

* the first two bytes, the length, after the marker indicate the number of bytes, including the two length bytes, that this header contains
* P -- one byte: sample precision in bits (usually 8, for baseline JPEG)
* Y -- two bytes
* X -- two bytes
* Nf -- one byte: the number of components in the image
      o 3 for color baseline JPEG images
      o 1 for grayscale baseline JPEG images

* Nf times:
      o Component ID -- one byte
      o H and V sampling factors -- one byte: H is first four bits and V is second four bits
      o Quantization table number-- one byte

The H and V sampling factors dictate the final size of the component they are associated with. For instance, the color space defaults to YCbCr and the H and V sampling factors for each component, Y, Cb, and Cr, default to 2, 1, and 1, respectively (2 for both H and V of the Y component, etc.) in the Jpeg-6a library by the Independent Jpeg Group. While this does mean that the Y component will be twice the size of the other two components--giving it a higher resolution, the lower resolution components are quartered in size during compression in order to achieve this difference. Thus, the Cb and Cr components must be quadrupled in size during decompression.

For more info about the headers check out wikipedia's jpeg entry or I got the above info here.

I used a method similar to the code below which I got from this post at the sun forums:

import java.awt.Dimension;
import java.io.*;

public class JPEGDim {

public static Dimension getJPEGDimension(File f) throws IOException {
    FileInputStream fis = new FileInputStream(f);

    // check for SOI marker
    if (fis.read() != 255 || fis.read() != 216)
        throw new RuntimeException("SOI (Start Of Image) marker 0xff 0xd8 missing");

    Dimension d = null;

    while (fis.read() == 255) {
        int marker = fis.read();
        int len = fis.read() << 8 | fis.read();

        if (marker == 192) {
            fis.skip(1);

            int height = fis.read() << 8 | fis.read();
            int width = fis.read() << 8 | fis.read();

            d = new Dimension(width, height);
            break;
        }

        fis.skip(len - 2);
    }

    fis.close();

    return d;
}

public static void main(String[] args) throws IOException {
    System.out.println(getJPEGDimension(new File(args[0])));
}

}

How to make inline functions in C#

Yes.

You can create anonymous methods or lambda expressions:

Func<string, string> PrefixTrimmer = delegate(string x) {
    return x ?? "";
};
Func<string, string> PrefixTrimmer = x => x ?? "";

How to present popover properly in iOS 8

I made an Objective-C version of Imagine Digitals swift answer above. I don't think I missed anything as it seems to work under preliminary testing, if you spot something let me know, and I'll update it

-(void) presentPopover
{
    YourViewController* popoverContent = [[YourViewController alloc] init]; //this will be a subclass of UIViewController
    UINavigationController* nav =  [[UINavigationController alloc] initWithRootViewController:popoverContent];
    nav.modalPresentationStyle = UIModalPresentationPopover;
    UIPopoverPresentationController* popover = nav.popoverPresentationController;
    popoverContent.preferredContentSize = CGSizeMake(500,600);
    popover.delegate = self;
    popover.sourceRect = CGRectMake(100,100,0,0); //I actually used popover.barButtonItem = self.myBarButton;

    [self presentViewController:nav animated:YES completion:nil];
}

Text that shows an underline on hover

<span class="txt">Some Text</span>

.txt:hover {
    text-decoration: underline;
}

How does one add keyboard languages and switch between them in Linux Mint 16?

Mint 18.2 (Cinnamon)
Menu > Keyboard Preferences > Layouts > Options > Switching to another layout:

Menu > Keyboard Preferences > Layouts > Options > Switching to another layout

How do I convert a TimeSpan to a formatted string?

Thanks to Peter for the extension method. I modified it to work with longer time spans better:

namespace ExtensionMethods
{
    public static class TimeSpanExtensionMethods
    {
        public static string ToReadableString(this TimeSpan span)
        {
            string formatted = string.Format("{0}{1}{2}",
                (span.Days / 7) > 0 ? string.Format("{0:0} weeks, ", span.Days / 7) : string.Empty,
                span.Days % 7 > 0 ? string.Format("{0:0} days, ", span.Days % 7) : string.Empty,
                span.Hours > 0 ? string.Format("{0:0} hours, ", span.Hours) : string.Empty);

            if (formatted.EndsWith(", ")) formatted = formatted.Substring(0, formatted.Length - 2);

            return formatted;
        }
    }
}

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

when reimporting your keys from the old keyring, you need to specify the command:

gpg --allow-secret-key-import --import <keyring>

otherwise it will only import the public keys, not the private keys.

SQL Server SELECT INTO @variable?

If you wanted to simply assign some variables for later use, you can do them in one shot with something along these lines:

declare @var1 int,@var2 int,@var3 int;

select 
    @var1 = field1,
    @var2 = field2,
    @var3 = field3
from
    table
where
    condition

If that's the type of thing you're after

How can I use getSystemService in a non-activity class (LocationManager)?

You can go for this :

getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

How to check if a column exists in Pandas

This will work:

if 'A' in df:

But for clarity, I'd probably write it as:

if 'A' in df.columns:

PHP compare two arrays and get the matched values not the difference

OK.. We needed to compare a dynamic number of product names...

There's probably a better way... but this works for me...

... because....Strings are just Arrays of characters.... :>}

//  Compare Strings ...  Return Matching Text and Differences with Product IDs...

//  From MySql...
$productID1 = 'abc123';
$productName1 = "EcoPlus Premio Jet 600";   

$productID2 = 'xyz789';
$productName2 = "EcoPlus Premio Jet 800";   

$ProductNames = array(
    $productID1 => $productName1,
    $productID2 => $productName2
);


function compareNames($ProductNames){   

    //  Convert NameStrings to Arrays...    
    foreach($ProductNames as $id => $product_name){
        $Package1[$id] = explode(" ",$product_name);    
    }

    // Get Matching Text...
    $Matching = call_user_func_array('array_intersect', $Package1 );
    $MatchingText = implode(" ",$Matching);

    //  Get Different Text...
    foreach($Package1 as $id => $product_name_chunks){
        $Package2 = array($product_name_chunks,$Matching);
        $diff = call_user_func_array('array_diff', $Package2 );
        $DifferentText[$id] = trim(implode(" ", $diff));
    }

    $results[$MatchingText]  = $DifferentText;              
    return $results;    
}

$Results =  compareNames($ProductNames);

print_r($Results);

// Gives us this...
[EcoPlus Premio Jet] 
        [abc123] => 600
        [xyz789] => 800

How can I use an http proxy with node.js http.Client?

You can use request, I just found it's unbelievably easy to use proxy on node.js, just with one external "proxy" parameter, even more it supports HTTPS through a http proxy.

var request = require('request');

request({
  'url':'https://anysite.you.want/sub/sub',
  'method': "GET",
  'proxy':'http://yourproxy:8087'
},function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body);
  }
})

Array.sort() doesn't sort numbers correctly

You can use a sort function :

var myarray=[25, 8, 7, 41]
myarray.sort( function(a,b) { return b - a; } );
// 7 8 25 41

Look at http://www.javascriptkit.com/javatutors/arraysort.shtml

How do I use arrays in cURL POST requests

    $ch = curl_init();

    $data = array(
        'client_id' => 'xx',
        'client_secret' => 'xx',
        'redirect_uri' => $x,
        'grant_type' => 'xxx',
        'code' => $xx,
    );

    $data = http_build_query($data);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_URL, "https://example.com");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);

    $output = curl_exec($ch);

how to use jQuery ajax calls with node.js

I suppose your html page is hosted on a different port. Same origin policy requires in most browsers that the loaded file be on the same port than the loading file.

Get Date in YYYYMMDD format in windows batch file

You can try this ! This should work on windows machines.

for /F "usebackq tokens=1,2,3 delims=-" %%I IN (`echo %date%`) do echo "%%I" "%%J" "%%K"

add item to dropdown list in html using javascript

Try to use appendChild method:

select.appendChild(option);

How do I break a string in YAML over multiple lines?

1. Block Notation(plain, flow-style, scalar): Newlines become spaces and extra newlines after the block are removed

---
# Note: It has 1 new line after the string
content:
    Arbitrary free text
    over multiple lines stopping
    after indentation changes...

...

Equivalent JSON

{
 "content": "Arbitrary free text over multiple lines stopping after indentation changes..."
}

2. Literal Block Scalar: A Literal Block Scalar | will include the newlines and any trailing spaces. but removes extra

newlines after the block.

---
# After string we have 2 spaces and 2 new lines
content1: |
 Arbitrary free text
 over "multiple lines" stopping
 after indentation changes...  


...

Equivalent JSON

{
 "content1": "Arbitrary free text\nover \"multiple lines\" stopping\nafter indentation changes...  \n"
}

3. + indicator with Literal Block Scalar: keep extra newlines after block

---
# After string we have 2 new lines
plain: |+
 This unquoted scalar
 spans many lines.


...

Equivalent JSON

{
 "plain": "This unquoted scalar\nspans many lines.\n\n\n"
}

4. – indicator with Literal Block Scalar: means that the newline at the end of the string is removed.

---
# After string we have 2 new lines
plain: |-
 This unquoted scalar
 spans many lines.


...

Equivalent JSON

{
 "plain": "This unquoted scalar\nspans many lines."
}

5. Folded Block Scalar(>):

will fold newlines to spaces and but removes extra newlines after the block.

---
folded_newlines: >
 this is really a
 single line of text
 despite appearances


...

Equivalent JSON

{
 "fold_newlines": "this is really a single line of text despite appearances\n"
}

for more you can visit my Blog

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

The following steps are to reset the password for a user in case you forgot, this would also solve your mentioned error.

First, stop your MySQL:

sudo /etc/init.d/mysql stop

Now start up MySQL in safe mode and skip the privileges table:

sudo mysqld_safe --skip-grant-tables &

Login with root:

mysql -uroot

And assign the DB that needs to be used:

use mysql;

Now all you have to do is reset your root password of the MySQL user and restart the MySQL service:

update user set password=PASSWORD("YOURPASSWORDHERE") where User='root';

flush privileges;

quit and restart MySQL:

quit

sudo /etc/init.d/mysql stop sudo /etc/init.d/mysql start Now your root password should be working with the one you just set, check it with:

mysql -u root -p

How to install requests module in Python 3.4, instead of 2.7

i just reinstalled the pip and it works, but I still wanna know why it happened...

i used the apt-get remove --purge python-pip after I just apt-get install pyhton-pip and it works, but don't ask me why...

Add new attribute (element) to JSON object using JavaScript

You can also add new json objects into your json, using the extend function,

var newJson = $.extend({}, {my:"json"}, {other:"json"});
// result -> {my: "json", other: "json"}

A very good option for the extend function is the recursive merge. Just add the true value as the first parameter (read the documentation for more options). Example,

var newJson = $.extend(true, {}, {
    my:"json",
    nestedJson: {a1:1, a2:2}
}, {
    other:"json",
    nestedJson: {b1:1, b2:2}
});
// result -> {my: "json", other: "json", nestedJson: {a1:1, a2:2, b1:1, b2:2}}

How can I calculate an md5 checksum of a directory?

Checksum all files, including both content and their filenames

grep -ar -e . /your/dir | md5sum | cut -c-32

Same as above, but only including *.py files

grep -ar -e . --include="*.py" /your/dir | md5sum | cut -c-32

You can also follow symlinks if you want

grep -aR -e . /your/dir | md5sum | cut -c-32

Other options you could consider using with grep

-s, --no-messages         suppress error messages
-D, --devices=ACTION      how to handle devices, FIFOs and sockets;
-Z, --null                print 0 byte after FILE name
-U, --binary              do not strip CR characters at EOL (MSDOS/Windows)

Difference between id and name attributes in HTML

The id will give an element a id, so once you write real code, (like JavaScript) you can use the id to read elements. The name is just a name so the user can see the name of the element, I guess.

Example:

<h1 id="heading">text</h1>
<script>
  document.getElementById("heading"); //Reads the element that has the id "heading".
</script>
//You can also use something like this:
document.getElementById("heading").value; //Reads the value of the selected element.

Is it helpful? Let me know if there is some problems.

Root password inside a Docker container

To create/change a root password in a running container

docker exec -itu root {containerName} passwd

"This operation requires IIS integrated pipeline mode."

I resolved this problem by following steps:

  1. Right click on root folder of project.
  2. Goto properties
  3. Click web in left menu
  4. change current port http://localhost:####/
  5. click create virtual directory
  6. Save the changes (ctrl+s)
  7. Run

may be it help you to.

Best way to use PHP to encrypt and decrypt passwords?

Security warning: This code is not secure.

working example

define('SALT', 'whateveryouwant'); 

function encrypt($text) 
{ 
    return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SALT, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)))); 
} 

function decrypt($text) 
{ 
    return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SALT, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); 
} 

$encryptedmessage = encrypt("your message"); 
echo decrypt($encryptedmessage); 

Ruby on Rails: Where to define global constants?

I typically have a 'lookup' model/table in my rails program and use it for the constants. It is very useful if the constants are going to be different for different environments. In addition, if you have a plan to extend them, say you want to add 'yellow' on a later date, you could simply add a new row to the lookup table and be done with it.

If you give the admin permissions to modify this table, they will not come to you for maintenance. :) DRY.

Here is how my migration code looks like:

class CreateLookups < ActiveRecord::Migration
  def change
    create_table :lookups do |t|
      t.string :group_key
      t.string :lookup_key
      t.string :lookup_value
      t.timestamps
    end
  end
end

I use seeds.rb to pre-populate it.

Lookup.find_or_create_by_group_key_and_lookup_key_and_lookup_value!(group_key: 'development_COLORS', lookup_key: 'color1', lookup_value: 'red');

C++ multiline string literal

Since an ounce of experience is worth a ton of theory, I tried a little test program for MULTILINE:

#define MULTILINE(...) #__VA_ARGS__

const char *mstr[] =
{
    MULTILINE(1, 2, 3),       // "1, 2, 3"
    MULTILINE(1,2,3),         // "1,2,3"
    MULTILINE(1 , 2 , 3),     // "1 , 2 , 3"
    MULTILINE( 1 , 2 , 3 ),   // "1 , 2 , 3"
    MULTILINE((1,  2,  3)),   // "(1,  2,  3)"
    MULTILINE(1
              2
              3),             // "1 2 3"
    MULTILINE(1\n2\n3\n),     // "1\n2\n3\n"
    MULTILINE(1\n
              2\n
              3\n),           // "1\n 2\n 3\n"
    MULTILINE(1, "2" \3)      // "1, \"2\" \3"
};

Compile this fragment with cpp -P -std=c++11 filename to reproduce.

The trick behind #__VA_ARGS__ is that __VA_ARGS__ does not process the comma separator. So you can pass it to the stringizing operator. Leading and trailing spaces are trimmed, and spaces (including newlines) between words are compressed to a single space then. Parentheses need to be balanced. I think these shortcomings explain why the designers of C++11, despite #__VA_ARGS__, saw the need for raw string literals.

JavaScript string encryption and decryption?

The existing answers which leverage SJCL, CryptoJS, and/or WebCrypto aren't necessarily wrong but they're not as safe as you might initially suspect. Generally you want to use libsodium. First I'll explain why, then how.

Why Not SJCL, CryptoJS, WebCrypto, etc.?

Short answer: In order for your encryption to actually be secure, these libraries expect you to make too many choices e.g. the block cipher mode (CBC, CTR, GCM; if you can't tell which of the three I just listed is secure to use and under what constraints, you shouldn't be burdened with this sort of choice at all).

Unless your job title is cryptography engineer, the odds are stacked against you implementing it securely.

Why to Avoid CryptoJS?

CryptoJS offers a handful of building blocks and expects you to know how to use them securely. It even defaults to CBC mode (archived).

Why is CBC mode bad?

Read this write-up on AES-CBC vulnerabilities.

Why to Avoid WebCrypto?

WebCrypto is a potluck standard, designed by committee, for purposes that are orthogonal to cryptography engineering. Specifically, WebCrypto was meant to replace Flash, not provide security.

Why to Avoid SJCL?

SJCL's public API and documentation begs users to encrypt data with a human-remembered password. This is rarely, if ever, what you want to do in the real world.

Additionally: Its default PBKDF2 round count is roughly 86 times as small as you want it to be. AES-128-CCM is probably fine.

Out of the three options above, SJCL is the least likely to end in tears. But there are better options available.

Why is Libsodium Better?

You don't need to choose between a menu of cipher modes, hash functions, and other needless options. You'll never risk screwing up your parameters and removing all security from your protocol.

Instead, libsodium just gives you simple options tuned for maximum security and minimalistic APIs.

  • crypto_box() / crypto_box_open() offer authenticated public-key encryption.
    • The algorithm in question combines X25519 (ECDH over Curve25519) and XSalsa20-Poly1305, but you don't need to know (or even care) about that to use it securely
  • crypto_secretbox() / crypto_secretbox_open() offer shared-key authenticated encryption.
    • The algorithm in question is XSalsa20-Poly1305, but you don't need to know/care

Additionally, libsodium has bindings in dozens of popular programming languages, so it's very likely that libsodium will just work when trying to interoperate with another programming stack. Also, libsodium tends to be very fast without sacrificing security.

How to Use Libsodium in JavaScript?

First, you need to decide one thing:

  1. Do you just want to encrypt/decrypt data (and maybe still somehow use the plaintext in database queries securely) and not worry about the details? Or...
  2. Do you need to implement a specific protocol?

If you selected the first option, get CipherSweet.js.

The documentation is available online. EncryptedField is sufficient for most use cases, but the EncryptedRow and EncryptedMultiRows APIs may be easier if you have a lot of distinct fields you want to encrypt.

With CipherSweet, you don't need to even know what a nonce/IV is to use it securely.

Additionally, this handles int/float encryption without leaking facts about the contents through ciphertext size.

Otherwise, you'll want sodium-plus, which is a user-friendly frontend to various libsodium wrappers. Sodium-Plus allows you to write performant, asynchronous, cross-platform code that's easy to audit and reason about.

To install sodium-plus, simply run...

npm install sodium-plus

There is currently no public CDN for browser support. This will change soon. However, you can grab sodium-plus.min.js from the latest Github release if you need it.

_x000D_
_x000D_
const { SodiumPlus } = require('sodium-plus');_x000D_
let sodium;_x000D_
_x000D_
(async function () {_x000D_
    if (!sodium) sodium = await SodiumPlus.auto();_x000D_
    let plaintext = 'Your message goes here';_x000D_
    let key = await sodium.crypto_secretbox_keygen();_x000D_
    let nonce = await sodium.randombytes_buf(24);_x000D_
    let ciphertext = await sodium.crypto_secretbox(_x000D_
        plaintext,_x000D_
        nonce,_x000D_
        key    _x000D_
    );_x000D_
    console.log(ciphertext.toString('hex'));_x000D_
_x000D_
    let decrypted = await sodium.crypto_secretbox_open(_x000D_
        ciphertext,_x000D_
        nonce,_x000D_
        key_x000D_
    );_x000D_
_x000D_
    console.log(decrypted.toString());_x000D_
})();
_x000D_
_x000D_
_x000D_

The documentation for sodium-plus is available on Github.

If you'd like a step-by-step tutorial, this dev.to article has what you're looking for.

Export to xls using angularjs

You can try Alasql JavaScript library which can work together with XLSX.js library for easy export of Angular.js data. This is an example of controller with exportData() function:

function myCtrl($scope) {
  $scope.exportData = function () {
    alasql('SELECT * INTO XLSX("john.xlsx",{headers:true}) FROM ?',[$scope.items]);
  };

  $scope.items = [{
    name: "John Smith",
    email: "[email protected]",
    dob: "1985-10-10"
  }, {
    name: "Jane Smith",
    email: "[email protected]",
    dob: "1988-12-22"
  }];
}

See full HTML and JavaScript code for this example in jsFiddle.

UPDATED Another example with coloring cells.

Also you need to include two libraries:

Run ScrollTop with offset of element by ID

No magic involved, just subtract from the offset top of the element

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

Animate a custom Dialog

I meet the same problem,but ,at last I solve the problem by followed way

((ViewGroup)dialog.getWindow().getDecorView())
.getChildAt(0).startAnimation(AnimationUtils.loadAnimation(
context,android.R.anim.slide_in_left));

Stripping non printable characters from a string in python

Iterating over strings is unfortunately rather slow in Python. Regular expressions are over an order of magnitude faster for this kind of thing. You just have to build the character class yourself. The unicodedata module is quite helpful for this, especially the unicodedata.category() function. See Unicode Character Database for descriptions of the categories.

import unicodedata, re, itertools, sys

all_chars = (chr(i) for i in range(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(chr, itertools.chain(range(0x00,0x20), range(0x7f,0xa0))))

control_char_re = re.compile('[%s]' % re.escape(control_chars))

def remove_control_chars(s):
    return control_char_re.sub('', s)

For Python2

import unicodedata, re, sys

all_chars = (unichr(i) for i in xrange(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(unichr, range(0x00,0x20) + range(0x7f,0xa0)))

control_char_re = re.compile('[%s]' % re.escape(control_chars))

def remove_control_chars(s):
    return control_char_re.sub('', s)

For some use-cases, additional categories (e.g. all from the control group might be preferable, although this might slow down the processing time and increase memory usage significantly. Number of characters per category:

  • Cc (control): 65
  • Cf (format): 161
  • Cs (surrogate): 2048
  • Co (private-use): 137468
  • Cn (unassigned): 836601

Edit Adding suggestions from the comments.

Macro to Auto Fill Down to last adjacent cell

ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

Convert Json string to Json object in Swift 4

The problem is that you thought your jsonString is a dictionary. It's not.

It's an array of dictionaries. In raw json strings, arrays begin with [ and dictionaries begin with {.


I used your json string with below code :

let string = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]"
let data = string.data(using: .utf8)!
do {
    if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
    {
       print(jsonArray) // use the json here     
    } else {
        print("bad json")
    }
} catch let error as NSError {
    print(error)
}

and I am getting the output :

[["form_desc": <null>, "form_name": Activity 4 with Images, "canonical_name": df_SAWERQ, "form_id": 3465]]

Copy folder recursively, excluding some folders

Use rsync:

rsync -av --exclude='path1/to/exclude' --exclude='path2/to/exclude' source destination

Note that using source and source/ are different. A trailing slash means to copy the contents of the folder source into destination. Without the trailing slash, it means copy the folder source into destination.

Alternatively, if you have lots of directories (or files) to exclude, you can use --exclude-from=FILE, where FILE is the name of a file containing files or directories to exclude.

--exclude may also contain wildcards, such as --exclude=*/.svn*

create table with sequence.nextval in oracle

In Oracle 12c you can also declare an identity column

CREATE TABLE identity_test_tab (
  id          NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
  description VARCHAR2(30)
);

examples & performance tests here ... where, is shorts, the conclusion is that the direct use of the sequence or the new identity column are much faster than the triggers.

In oracle, how do I change my session to display UTF8?

Therefore, before starting '$ sqlplus' on OS, run the followings:

  • On Windows

    set NLS_LANG=AMERICAN_AMERICA.UTF8

  • On Unix (Solaris and Linux, centos etc)

    export NLS_LANG=AMERICAN_AMERICA.UTF8

It would also be advisable to set env variable in your '.bash_profile' [on start up script]

This is the place where other ORACLE env variables (ORACLE_SID, ORACLE_HOME) are usually set.

just fyi - SQL Developer is good at displaying/handling non-English UTF8 characters.

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

Try this:

net use * /delete /y

The /y key makes it select Yes in prompt silently

How do you find the row count for all your tables in Postgres

To get estimates, see Greg Smith's answer.

To get exact counts, the other answers so far are plagued with some issues, some of them serious (see below). Here's a version that's hopefully better:

CREATE FUNCTION rowcount_all(schema_name text default 'public')
  RETURNS table(table_name text, cnt bigint) as
$$
declare
 table_name text;
begin
  for table_name in SELECT c.relname FROM pg_class c
    JOIN pg_namespace s ON (c.relnamespace=s.oid)
    WHERE c.relkind = 'r' AND s.nspname=schema_name
  LOOP
    RETURN QUERY EXECUTE format('select cast(%L as text),count(*) from %I.%I',
       table_name, schema_name, table_name);
  END LOOP;
end
$$ language plpgsql;

It takes a schema name as parameter, or public if no parameter is given.

To work with a specific list of schemas or a list coming from a query without modifying the function, it can be called from within a query like this:

WITH rc(schema_name,tbl) AS (
  select s.n,rowcount_all(s.n) from (values ('schema1'),('schema2')) as s(n)
)
SELECT schema_name,(tbl).* FROM rc;

This produces a 3-columns output with the schema, the table and the rows count.

Now here are some issues in the other answers that this function avoids:

  • Table and schema names shouldn't be injected into executable SQL without being quoted, either with quote_ident or with the more modern format() function with its %I format string. Otherwise some malicious person may name their table tablename;DROP TABLE other_table which is perfectly valid as a table name.

  • Even without the SQL injection and funny characters problems, table name may exist in variants differing by case. If a table is named ABCD and another one abcd, the SELECT count(*) FROM... must use a quoted name otherwise it will skip ABCD and count abcd twice. The %I of format does this automatically.

  • information_schema.tables lists custom composite types in addition to tables, even when table_type is 'BASE TABLE' (!). As a consequence, we can't iterate oninformation_schema.tables, otherwise we risk having select count(*) from name_of_composite_type and that would fail. OTOH pg_class where relkind='r' should always work fine.

  • The type of COUNT() is bigint, not int. Tables with more than 2.15 billion rows may exist (running a count(*) on them is a bad idea, though).

  • A permanent type need not to be created for a function to return a resultset with several columns. RETURNS TABLE(definition...) is a better alternative.

Can't clone a github repo on Linux via HTTPS

As JERC said, make sure you have an updated version of git. If you are only using the default settings, when you try to install git you will get version 1.7.1. Other than manually downloading and installing the latest version of get, you can also accomplish this by adding a new repository to yum.

From tecadmin.net:

Download and install the rpmforge repository:

# use this for 64-bit
rpm -i 'http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm'
# use this for 32-bit
rpm -i 'http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.i686.rpm'

# then run this in either case
rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt

Then you need to enable the rpmforge-extras. Edit /etc/yum.repos.d/rpmforge.repo and change enabled = 0 to enabled = 1 under [rpmforge-extras]. The file looks like this:

### Name: RPMforge RPM Repository for RHEL 6 - dag
### URL: http://rpmforge.net/
[rpmforge]
name = RHEL $releasever - RPMforge.net - dag
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/rpmforge
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge
enabled = 1
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1

[rpmforge-extras]
name = RHEL $releasever - RPMforge.net - extras
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/extras
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge-extras
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge-extras
enabled = 0 ####### CHANGE THIS LINE TO "enabled = 1" #############
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1

[rpmforge-testing]
name = RHEL $releasever - RPMforge.net - testing
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/testing
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge-testing
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge-testing
enabled = 0
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1

Once you've done this, then you can update git with

yum update git

I'm not sure why, but they then suggest disabling rpmforge-extras (change back to enabled = 0) and then running yum clean all.

Most likely you'll need to use sudo for these commands.

ReactJS Two components communicating

Oddly nobody mentioned mobx. The idea is similar to redux. If I have a piece of data that multiple components are subscribed to it, then I can use this data to drive multiple components.

How to make EditText not editable through XML in Android?

Kotlin extension option:

fun AppCompatAutoCompleteTextView.setEditable(editable: Boolean) {
    if (!editable) {
        this.tag = this.keyListener
        this.keyListener = null
    } else {
        if(this.tag is KeyListener) {
            [email protected] = [email protected] as KeyListener
        }
    }
}

How can I make a link from a <td> table cell

Yes, that's possible, albeit not literally the <td>, but what's in it. The simple trick is, to make sure that the content extends to the borders of the cell (it won't include the borders itself though).

As already explained, this isn't semantically correct. An a element is an inline element and should not be used as block-level element. However, here's an example (but JavaScript plus a td:hover CSS style will be much neater) that works in most browsers:

<td>
  <a href="http://example.com">
    <div style="height:100%;width:100%">
      hello world
    </div>
  </a>
</td>

PS: it's actually neater to change a in a block-level element using CSS as explained in another solution in this thread. it won't work well in IE6 though, but that's no news ;)

Alternative (non-advised) solution

If your world is only Internet Explorer (rare, nowadays), you can violate the HTML standard and write this, it will work as expected, but will be highly frowned upon and be considered ill-advised (you haven't heard this from me). Any other browser than IE will not render the link, but will show the table correctly.

<table>
    <tr>
        <a href="http://example.com"><td  width="200">hello world</td></a>
    </tr>
</table>

Inserting the same value multiple times when formatting a string

You can use advanced string formatting, available in Python 2.6 and Python 3.x:

incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)

CFNetwork SSLHandshake failed iOS 9

For more info Configuring App Transport Security Exceptions in iOS 9 and OSX 10.11

Curiously, you’ll notice that the connection attempts to change the http protocol to https to protect against mistakes in your code where you may have accidentally misconfigured the URL. In some cases, this might actually work, but it’s also confusing.

This Shipping an App With App Transport Security covers some good debugging tips

ATS Failure

Most ATS failures will present as CFErrors with a code in the -9800 series. These are defined in the Security/SecureTransport.h header

2015-08-23 06:34:42.700 SelfSignedServerATSTest[3792:683731] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)

CFNETWORK_DIAGNOSTICS

Set the environment variable CFNETWORK_DIAGNOSTICS to 1 in order to get more information on the console about the failure

nscurl

The tool will run through several different combinations of ATS exceptions, trying a secure connection to the given host under each ATS configuration and reporting the result.

nscurl --ats-diagnostics https://example.com

Grep regex NOT containing string

(?<!1\.2\.3\.4).*Has exploded

You need to run this with -P to have negative lookbehind (Perl regular expression), so the command is:

grep -P '(?<!1\.2\.3\.4).*Has exploded' test.log

Try this. It uses negative lookbehind to ignore the line if it is preceeded by 1.2.3.4. Hope that helps!

How to replace all special character into a string using C#

Yes, you can use regular expressions in C#.

Using regular expressions with C#:

using System.Text.RegularExpressions;

string your_String = "Hello@Hello&Hello(Hello)";
string my_String =  Regex.Replace(your_String, @"[^0-9a-zA-Z]+", ",");

How to convert signed to unsigned integer in python

To get the value equivalent to your C cast, just bitwise and with the appropriate mask. e.g. if unsigned long is 32 bit:

>>> i = -6884376
>>> i & 0xffffffff
4288082920

or if it is 64 bit:

>>> i & 0xffffffffffffffff
18446744073702667240

Do be aware though that although that gives you the value you would have in C, it is still a signed value, so any subsequent calculations may give a negative result and you'll have to continue to apply the mask to simulate a 32 or 64 bit calculation.

This works because although Python looks like it stores all numbers as sign and magnitude, the bitwise operations are defined as working on two's complement values. C stores integers in twos complement but with a fixed number of bits. Python bitwise operators act on twos complement values but as though they had an infinite number of bits: for positive numbers they extend leftwards to infinity with zeros, but negative numbers extend left with ones. The & operator will change that leftward string of ones into zeros and leave you with just the bits that would have fit into the C value.

Displaying the values in hex may make this clearer (and I rewrote to string of f's as an expression to show we are interested in either 32 or 64 bits):

>>> hex(i)
'-0x690c18'
>>> hex (i & ((1 << 32) - 1))
'0xff96f3e8'
>>> hex (i & ((1 << 64) - 1)
'0xffffffffff96f3e8L'

For a 32 bit value in C, positive numbers go up to 2147483647 (0x7fffffff), and negative numbers have the top bit set going from -1 (0xffffffff) down to -2147483648 (0x80000000). For values that fit entirely in the mask, we can reverse the process in Python by using a smaller mask to remove the sign bit and then subtracting the sign bit:

>>> u = i & ((1 << 32) - 1)
>>> (u & ((1 << 31) - 1)) - (u & (1 << 31))
-6884376

Or for the 64 bit version:

>>> u = 18446744073702667240
>>> (u & ((1 << 63) - 1)) - (u & (1 << 63))
-6884376

This inverse process will leave the value unchanged if the sign bit is 0, but obviously it isn't a true inverse because if you started with a value that wouldn't fit within the mask size then those bits are gone.

Create new XML file and write data to it?

DOMDocument is a great choice. It's a module specifically designed for creating and manipulating XML documents. You can create a document from scratch, or open existing documents (or strings) and navigate and modify their structures.

$xml = new DOMDocument();
$xml_album = $xml->createElement("Album");
$xml_track = $xml->createElement("Track");
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );

$xml->save("/tmp/test.xml");

To re-open and write:

$xml = new DOMDocument();
$xml->load('/tmp/test.xml');
$nodes = $xml->getElementsByTagName('Album') ;
if ($nodes->length > 0) {
   //insert some stuff using appendChild()
}

//re-save
$xml->save("/tmp/test.xml");

Override intranet compatibility mode IE8

If you pull down the "Tools" menu and choose "Compatibility View Settings" On that dialog at the bottom is a setting "Display intranet sites in compatibility mode". If you uncheck this that should resolve the problem and IE will use the mode based on the DOCTYPE.

Log record changes in SQL server in an audit table

This is the code with two bug fixes. The first bug fix was mentioned by Royi Namir in the comment on the accepted answer to this question. The bug is described on StackOverflow at Bug in Trigger Code. The second one was found by @Fandango68 and fixes columns with multiples words for their names.

ALTER TRIGGER [dbo].[TR_person_AUDIT]
ON [dbo].[person]
FOR UPDATE
AS
           DECLARE @bit            INT,
                   @field          INT,
                   @maxfield       INT,
                   @char           INT,
                   @fieldname      VARCHAR(128),
                   @TableName      VARCHAR(128),
                   @PKCols         VARCHAR(1000),
                   @sql            VARCHAR(2000),
                   @UpdateDate     VARCHAR(21),
                   @UserName       VARCHAR(128),
                   @Type           CHAR(1),
                   @PKSelect       VARCHAR(1000)


           --You will need to change @TableName to match the table to be audited.
           -- Here we made GUESTS for your example.
           SELECT @TableName = 'PERSON'

           SELECT @UserName = SYSTEM_USER,
                  @UpdateDate = CONVERT(NVARCHAR(30), GETDATE(), 126)

           -- Action
           IF EXISTS (
                  SELECT *
                  FROM   INSERTED
              )
               IF EXISTS (
                      SELECT *
                      FROM   DELETED
                  )
                   SELECT @Type = 'U'
               ELSE
                   SELECT @Type = 'I'
           ELSE
               SELECT @Type = 'D'

           -- get list of columns
           SELECT * INTO #ins
           FROM   INSERTED

           SELECT * INTO #del
           FROM   DELETED

           -- Get primary key columns for full outer join
           SELECT @PKCols = COALESCE(@PKCols + ' and', ' on') 
                  + ' i.[' + c.COLUMN_NAME + '] = d.[' + c.COLUMN_NAME + ']'
           FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
                  INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
           WHERE  pk.TABLE_NAME = @TableName
                  AND CONSTRAINT_TYPE = 'PRIMARY KEY'
                  AND c.TABLE_NAME = pk.TABLE_NAME
                  AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

           -- Get primary key select for insert
           SELECT @PKSelect = COALESCE(@PKSelect + '+', '') 
                  + '''<[' + COLUMN_NAME 
                  + ']=''+convert(varchar(100),
           coalesce(i.[' + COLUMN_NAME + '],d.[' + COLUMN_NAME + ']))+''>'''
           FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
                  INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
           WHERE  pk.TABLE_NAME = @TableName
                  AND CONSTRAINT_TYPE = 'PRIMARY KEY'
                  AND c.TABLE_NAME = pk.TABLE_NAME
                  AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

           IF @PKCols IS NULL
           BEGIN
               RAISERROR('no PK on table %s', 16, -1, @TableName)

               RETURN
           END

           SELECT @field = 0,
                  -- @maxfield = MAX(COLUMN_NAME) 
                  @maxfield = -- FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName


                  MAX(
                      COLUMNPROPERTY(
                          OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                          COLUMN_NAME,
                          'ColumnID'
                      )
                  )
           FROM   INFORMATION_SCHEMA.COLUMNS
           WHERE  TABLE_NAME = @TableName






           WHILE @field < @maxfield
           BEGIN
               SELECT @field = MIN(
                          COLUMNPROPERTY(
                              OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                              COLUMN_NAME,
                              'ColumnID'
                          )
                      )
               FROM   INFORMATION_SCHEMA.COLUMNS
               WHERE  TABLE_NAME = @TableName
                      AND COLUMNPROPERTY(
                              OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                              COLUMN_NAME,
                              'ColumnID'
                          ) > @field

               SELECT @bit = (@field - 1)% 8 + 1

               SELECT @bit = POWER(2, @bit - 1)

               SELECT @char = ((@field - 1) / 8) + 1





               IF SUBSTRING(COLUMNS_UPDATED(), @char, 1) & @bit > 0
                  OR @Type IN ('I', 'D')
               BEGIN
                   SELECT @fieldname = COLUMN_NAME
                   FROM   INFORMATION_SCHEMA.COLUMNS
                   WHERE  TABLE_NAME = @TableName
                          AND COLUMNPROPERTY(
                                  OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                                  COLUMN_NAME,
                                  'ColumnID'
                              ) = @field



                   SELECT @sql = 
                          '
           insert into Audit (    Type, 
           TableName, 
           PK, 
           FieldName, 
           OldValue, 
           NewValue, 
           UpdateDate, 
           UserName)
           select ''' + @Type + ''',''' 
                          + @TableName + ''',' + @PKSelect
                          + ',''' + @fieldname + ''''
                          + ',convert(varchar(1000),d.' + @fieldname + ')'
                          + ',convert(varchar(1000),i.' + @fieldname + ')'
                          + ',''' + @UpdateDate + ''''
                          + ',''' + @UserName + ''''
                          + ' from #ins i full outer join #del d'
                          + @PKCols
                          + ' where i.' + @fieldname + ' <> d.' + @fieldname 
                          + ' or (i.' + @fieldname + ' is null and  d.'
                          + @fieldname
                          + ' is not null)' 
                          + ' or (i.' + @fieldname + ' is not null and  d.' 
                          + @fieldname
                          + ' is null)' 



                   EXEC (@sql)
               END
           END

Catch checked change event of a checkbox

The click will affect a label if we have one attached to the input checkbox?

I think that is better to use the .change() function

<input type="checkbox" id="something" />

$("#something").change( function(){
  alert("state changed");
});

Ajax post request in laravel 5 return error 500 (Internal Server Error)

for me this error cause of different stuff. i have two ajax call in my page. first one for save comment and another one for save like. in my routes.php i had this:

Route::post('posts/show','PostController@save_comment');
Route::post('posts/show','PostController@save_like');

and i got 500 internal server error for my save like ajax call. so i change second line http request type to PUT and error goes away. you can use PATCH too. maybe it helps.

Removing address bar from browser (to view on Android)

If you've loaded jQuery, you can see if the height of the content is greater than the viewport height. If not, then you can make it that height (or a little less). I ran the following code in WVGA800 mode in the Android emulator, and then ran it on my Samsung Galaxy Tab, and in both cases it hid the addressbar.

$(document).ready(function() {

  if (navigator.userAgent.match(/Android/i)) {
    window.scrollTo(0,0); // reset in case prev not scrolled  
    var nPageH = $(document).height();
    var nViewH = window.outerHeight;
    if (nViewH > nPageH) {
      nViewH -= 250;
      $('BODY').css('height',nViewH + 'px');
    }
    window.scrollTo(0,1);
  }

});

Adjust UILabel height depending on the text

Adding to the above answers:

This can be easily achieved via storyboard.

  1. Set constraint for UILabel.(In my case I did top, left and fixed width)
  2. Set Number of line to 0 in Attribute Inspector
  3. Set Line Break to WordWrap in Attribute Inspector.

UILabel Height Adjust

Merge two HTML table cells

Set the colspan attribute to 2.

...but please don't use tables for layout.

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

For me, IIS Express was not accessible when I added iplisten on DOS Prompt like this: netsh http add iplisten MyIPAddress. I fixed it by deleting the iplisten like this: netsh http delete iplisten MyIPAddress.

How to make a dropdown readonly using jquery?

To simplify things here's a jQuery plugin that does that without the hassle: https://github.com/haggen/readonly

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

For me, this problem went away on Windows when I moved my project to a shallower parent directory, i.e. to:

C:\Users\spenc\Desktop\MyProjectDirectory

instead of

C:\Users\spenc\Desktop\...\MyProjectDirectory.

I think the source of the problem was that MSBuild has a file path length restriction to 260 characters. This causes the basic compiler test CMake performs to build a project called CompilerIdCXX.vcxproj to fail with the error:

C1083: Cannot open source file: 'CMakeCXXCompilerId.cpp'

because the length of the file's path e.g.

C:\Users\spenc\Desktop\...\MyProjectDirectory\build\CMakeFiles\...\CMakeCXXCompilerId.cpp

exceeds the MAX_PATH restriction.

CMake then concludes there is no CXX compiler.

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

I got the same error, but when i did as below, it resolved the issue.
Instead of writing like this:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

use the below one:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

How do you transfer or export SQL Server 2005 data to Excel

SSIS is a no-brainer for doing stuff like this and is very straight forward (and this is just the kind of thing it is for).

  1. Right-click the database in SQL Management Studio
  2. Go to Tasks and then Export data, you'll then see an easy to use wizard.
  3. Your database will be the source, you can enter your SQL query
  4. Choose Excel as the target
  5. Run it at end of wizard

If you wanted, you could save the SSIS package as well (there's an option at the end of the wizard) so that you can do it on a schedule or something (and even open and modify to add more functionality if needed).

Changing the background color of a drop down list transparent in html

Or maybe

 background: transparent !important;
 color: #ffffff;

Using .htaccess to make all .html pages to run as .php files?

None of the answers posted here worked for me.

In my case the problem was, by the one hand, that the .conf file (/etc/apache2/sites-available/default-ssl.conf or /etc/apache2/sites-available/000-default.conf) did not contain the directive AllowOverride All for the site directory, which caused the .htaccess to not been processed. To solve this, add:

<Directory /var/www/html/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>

On the other hand, the problem was that the .htaccess was created by the root user, and therefore the apache user could not read it. So, changing the file owner solved definitely the problem:

chown www-data:www-data .htaccess

Connect different Windows User in SQL Server Management Studio (2005 or later)

A bit of powershell magic will do the trick:

cmdkey /add:"SERVER:1433" /user:"DOMAIN\USERNAME" /pass:"PASSWORD"

Then just select windows authentication

how to define ssh private key for servers fetched by dynamic inventory in files

I had a similar issue and solved it with a patch to ec2.py and adding some configuration parameters to ec2.ini. The patch takes the value of ec2_key_name, prefixes it with the ssh_key_path, and adds the ssh_key_suffix to the end, and writes out ansible_ssh_private_key_file as this value.

The following variables have to be added to ec2.ini in a new 'ssh' section (this is optional if the defaults match your environment):

[ssh]
# Set the path and suffix for the ssh keys
ssh_key_path = ~/.ssh
ssh_key_suffix = .pem

Here is the patch for ec2.py:

204a205,206
>     'ssh_key_path': '~/.ssh',
>     'ssh_key_suffix': '.pem',
422a425,428
>         # SSH key setup
>         self.ssh_key_path = os.path.expanduser(config.get('ssh', 'ssh_key_path'))
>         self.ssh_key_suffix = config.get('ssh', 'ssh_key_suffix')
> 
1490a1497
>         instance_vars["ansible_ssh_private_key_file"] = os.path.join(self.ssh_key_path, instance_vars["ec2_key_name"] + self.ssh_key_suffix)

Move to another EditText when Soft Keyboard Next is clicked on Android

<AutoCompleteTextView
                android:id="@+id/email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:drawableLeft="@drawable/user"
                android:hint="@string/username"
                android:inputType="text"
                android:maxLines="1"
                android:imeOptions="actionNext"
                android:singleLine="true" />

These three lines do the magic

            android:maxLines="1"
            android:imeOptions="actionNext"
            android:singleLine="true"

Datanode process not running in Hadoop

Delete the datanode under your hadoop folder then rerun start-all.sh

Remove an element from a Bash array

If anyone finds themselves in a position where they need to remember set -e or set -x values and be able to restore them, please check out this gist which uses the first array deletion solution to manage it's own stack:

https://gist.github.com/kigster/94799325e39d2a227ef89676eed44cc6

Avoid browser popup blockers

The general rule is that popup blockers will engage if window.open or similar is invoked from javascript that is not invoked by direct user action. That is, you can call window.open in response to a button click without getting hit by the popup blocker, but if you put the same code in a timer event it will be blocked. Depth of call chain is also a factor - some older browsers only look at the immediate caller, newer browsers can backtrack a little to see if the caller's caller was a mouse click etc. Keep it as shallow as you can to avoid the popup blockers.

c++ bool question

Yes that is correct. "Boolean variables only have two possible values: true (1) and false (0)." cpp tutorial on boolean values

Get first element of Series without knowing the index

Use iloc to access by position (rather than label):

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]: 
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]: 
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Your code is in the <head> => runs before the elements are rendered, so document.getElementById('compute'); returns null, as MDN promise...

element = document.getElementById(id);
element is a reference to an Element object, or null if an element with the specified ID is not in the document.

MDN

Solutions:

  1. Put the scripts in the bottom of the page.
  2. Call the attach code in the load event.
  3. Use jQuery library and it's DOM ready event.

What is the jQuery ready event and why is it needed?
(why no just JavaScript's load event):

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers...
...

ready docs

How to write dynamic variable in Ansible playbook

I am sure there is a smarter way for doing what you want but this should work:

- name         : Test var
  hosts        : all
  gather_facts : no
  vars:
    myvariable : false
  tasks:
    - name: param1
      set_fact:
        myvariable: "{{param1}}"
      when: param1 is defined

    - name: param2
      set_fact:
        myvariable: "{{ param2 if not myvariable else myvariable + ',' + param2 }}"
      when: param2 is defined

    - name: param3
      set_fact:
        myvariable: "{{ param3 if not myvariable else myvariable + ',' + param3 }}"
      when: param3 is defined

    - name: default
      set_fact:
        myvariable: "default"
      when: not myvariable

    - debug:
       var=myvariable

Hope that helps. I am not sure if you can construct variables dynamically and do this in an iterator. But you could also write a small python code or any other language and plug it into ansible

how to print a string to console in c++

yes it's possible to print a string to the console.

#include "stdafx.h"
#include <string>
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    string strMytestString("hello world");
    cout << strMytestString;
    return 0;
}

stdafx.h isn't pertinent to the solution, everything else is.

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.

However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.

In that case, you can use

jekyll serve --host 0.0.0.0

This binds your application to the host & next use following to connect to it from some other host

http://host's IP adress/4000 

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

LINQ Group By into a Dictionary Object

The following worked for me.

var temp = ctx.Set<DbTable>()
  .GroupBy(g => new { g.id })
  .ToDictionary(d => d.Key.id);

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

I ran into this issue recently and figured out a cheeky way of doing it without stringing together additional IN clauses

You could make use of Tuples

SELECT field1, field2, field3
FROM table1
WHERE (1, name) IN ((1, value1), (1, value2), (1, value3),.....(1, value5000));

Oracle does allow >1000 Tuples but not simple values. More on this here,

https://community.oracle.com/message/3515498#3515498
and
https://community.oracle.com/thread/958612

This is of course if you don't have the option of using a subquery inside IN to get the values you need from a temp table.

Add error bars to show standard deviation on a plot in R

You can use arrows:

arrows(x,y-sd,x,y+sd, code=3, length=0.02, angle = 90)

Remove unused imports in Android Studio

Sorry for the late answer.. For mac users command + option + o Try this.. It is working for me..

Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

In my case I cloned a git-project where both Java and Kotlin included. Then checked another branch and pressed "Sync Project with Gradle Files". Android Studio 3.0.1.

Splitting a dataframe string column into multiple different columns

Is this what you are trying to do?

# Our data
text <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
"F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
"F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)

#  Split into individual elements by the '.' character
#  Remember to escape it, because '.' by itself matches any single character
elems <- unlist( strsplit( text , "\\." ) )

#  We know the dataframe should have 4 columns, so make a matrix
m <- matrix( elems , ncol = 4 , byrow = TRUE )

#  Coerce to data.frame - head() is just to illustrate the top portion
head( as.data.frame( m ) )
#  V1 V2  V3  V4
#1  F US CLE V13
#2  F US CA6 U13
#3  F US CA6 U13
#4  F US CA6 U13
#5  F US CA6 U13
#6  F US CA6 U13

How to emulate a do-while loop in Python?

I am not sure what you are trying to do. You can implement a do-while loop like this:

while True:
  stuff()
  if fail_condition:
    break

Or:

stuff()
while not fail_condition:
  stuff()

What are you doing trying to use a do while loop to print the stuff in the list? Why not just use:

for i in l:
  print i
print "done"

Update:

So do you have a list of lines? And you want to keep iterating through it? How about:

for s in l: 
  while True: 
    stuff() 
    # use a "break" instead of s = i.next()

Does that seem like something close to what you would want? With your code example, it would be:

for s in some_list:
  while True:
    if state is STATE_CODE:
      if "//" in s:
        tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
        state = STATE_COMMENT
      else :
        tokens.add( TOKEN_CODE, s )
    if state is STATE_COMMENT:
      if "//" in s:
        tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )
        break # get next s
      else:
        state = STATE_CODE
        # re-evaluate same line
        # continues automatically

npm not working - "read ECONNRESET"

I had the problem with npm throwing this error.

So basically whenever error was thrown i either used manual install
from git or waited and installed specified version like:

npm install resolve@^1.1.6

when running alone:

npm install resolve

didn't worked.

I updated node.js from 7 to 8 and npm install goes smoothly.

I think that maybe the version 7 caused this problem since @luschn downgraded to 6 so he didn't use 7 too.

Maybe the registry itself is returning errors without showing problems on their status pages because after some time i could install this one breaking package and then proceed with npm install to install the rest.

How can I remove a character from a string using JavaScript?

If you just want to remove single character and If you know index of a character you want to remove, you can use following function:

/**
 * Remove single character at particular index from string
 * @param {*} index index of character you want to remove
 * @param {*} str string from which character should be removed
 */
function removeCharAtIndex(index, str) {
    var maxIndex=index==0?0:index;
    return str.substring(0, maxIndex) + str.substring(index, str.length)
}

cvc-elt.1: Cannot find the declaration of element 'MyElement'

After making the change suggested above by Martin, I was still getting the same error. I had to make an additional change to my parsing code. I was parsing the XML file via a DocumentBuilder as shown in the oracle docs: https://docs.oracle.com/javase/7/docs/api/javax/xml/validation/package-summary.html

// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

The problem was that DocumentBuilder is not namespace aware by default. The following additional change resolved the issue:

// parse an XML document into a DOM tree
DocumentBuilderFactory dmfactory = DocumentBuilderFactory.newInstance();
dmfactory.setNamespaceAware(true);

DocumentBuilder parser = dmfactory.newDocumentBuilder();
Document document = parser.parse(new File("example.xml"));

How to Edit a row in the datatable

If your data set is too large first select required rows by Select(). it will stop further looping.

DataRow[] selected = table.Select("Product_id = 2")

Then loop through subset and update

    foreach (DataRow row in selected)
    {
        row["Product_price"] = "<new price>";
    }

How to get the background color of an HTML element?

As with all css properties that contain hyphens, their corresponding names in JS is to remove the hyphen and make the following letter capital: backgroundColor

alert(myDiv.style.backgroundColor);

How to do a simple file search in cmd

dir *.txt /s /p will give more detailed information.

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

AS per point 1, your PEAR path is c:\xampplite\php\pear\

However, your path is pointing to \xampplite\php\pear\PEAR

Putting the two one above the other you can clearly see one is too long:

c:\xampplite\php\pear\

\xampplite\php\pear\PEAR

Your include path is set to go one PEAR too deep into the pear tree. The PEAR subfolder of the pear folder includes the PEAR component. You need to adjust your include path up one level.

(you don't need the c: by the way, your path is fine as is, just too deep)

How to execute raw queries with Laravel 5.1?

you can run raw query like this way too.

DB::table('setting_colleges')->first();

How to loop through all but the last item of a list?

for x in y[:-1]

If y is a generator, then the above will not work.

How do you get the contextPath from JavaScript, the right way?

A Spring Boot with Thymeleaf solution could look like:

Lets say my context-path is /app/

In Thymeleaf you can get it via:

<script th:inline="javascript">
    /*<![CDATA[*/
        let contextPath    = /*[[@{/}]]*/
    /*]]>*/
</script>

Javascript logical "!==" operator?

You can find === and !== operators in several other dynamically-typed languages as well. It always means that the two values are not only compared by their "implied" value (i.e. either or both values might get converted to make them comparable), but also by their original type.

That basically means that if 0 == "0" returns true, 0 === "0" will return false because you are comparing a number and a string. Similarly, while 0 != "0" returns false, 0 !== "0" returns true.

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

The fact that the same number of rows is returned is an after fact, the query optimizer cannot know in advance that every row in Accepts has a matching row in Marker, can it?

If you join two tables A and B, say A has 1 million rows and B has 1 row. If you say A LEFT INNER JOIN B it means only rows that match both A and B can result, so the query plan is free to scan B first, then use an index to do a range scan in A, and perhaps return 10 rows. But if you say A LEFT OUTER JOIN B then at least all rows in A have to be returned, so the plan must scan everything in A no matter what it finds in B. By using an OUTER join you are eliminating one possible optimization.

If you do know that every row in Accepts will have a match in Marker, then why not declare a foreign key to enforce this? The optimizer will see the constraint, and if is trusted, will take it into account in the plan.

Methods vs Constructors in Java

The Major difference is Given Below -

1: Constructor must have same name as the class name while this is not the case of methods

class Calendar{
    int year = 0;
    int month= 0;

    //constructor
    public Calendar(int year, int month){
        this.year = year;
        this.month = month;
        System.out.println("Demo Constructor");
    }

    //Method
    public void Display(){

        System.out.println("Demo method");
    }
} 

2: Constructor initializes objects of a class whereas method does not. Methods performs operations on objects that already exist. In other words, to call a method we need an object of the class.

public class Program {

    public static void main(String[] args) {

        //constructor will be called on object creation
        Calendar ins =  new Calendar(25, 5);

        //Methods will be called on object created
        ins.Display();

    }

}

3: Constructor does not have return type but a method must have a return type

class Calendar{

    //constructor – no return type
    public Calendar(int year, int month){

    }

    //Method have void return type
    public void Display(){

        System.out.println("Demo method");
    }
} 

Is it possible to insert multiple rows at a time in an SQLite database?

As of version 3.7.11 SQLite does support multi-row-insert. Richard Hipp comments:

I'm using 3.6.13

I command like this:

insert into xtable(f1,f2,f3) select v1 as f1, v2 as f2, v3 as f3 
union select nextV1+, nextV2+, nextV3+

With 50 records inserted at a time, it takes only a second or less.

It's true using sqlite to insert multiple rows at a time is very possible. By @Andy wrote.

thanks Andy +1

How to list branches that contain a given commit?

From the git-branch manual page:

 git branch --contains <commit>

Only list branches which contain the specified commit (HEAD if not specified). Implies --list.


 git branch -r --contains <commit>

Lists remote tracking branches as well (as mentioned in user3941992's answer below) that is "local branches that have a direct relationship to a remote branch".


As noted by Carl Walsh, this applies only to the default refspec

fetch = +refs/heads/*:refs/remotes/origin/*

If you need to include other ref namespace (pull request, Gerrit, ...), you need to add that new refspec, and fetch again:

git config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"
git fetch
git branch -r --contains <commit>

See also this git ready article.

The --contains tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you’ve got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.

$ git log -1 tests
commit d590f2ac0635ec0053c4a7377bd929943d475297
Author: Nick Quaranto <[email protected]>
Date:   Wed Apr 1 20:38:59 2009 -0400

    Green all around, finally.

$ git branch --contains d590f2
  tests
* master

Note: if the commit is on a remote tracking branch, add the -a option.
(as MichielB comments below)

git branch -a --contains <commit>

MatrixFrog comments that it only shows which branches contain that exact commit.
If you want to know which branches contain an "equivalent" commit (i.e. which branches have cherry-picked that commit) that's git cherry:

Because git cherry compares the changeset rather than the commit id (sha1), you can use git cherry to find out if a commit you made locally has been applied <upstream> under a different commit id.
For example, this will happen if you’re feeding patches <upstream> via email rather than pushing or pulling commits directly.

           __*__*__*__*__> <upstream>
          /
fork-point
          \__+__+__-__+__+__-__+__> <head>

(Here, the commits marked '-' wouldn't show up with git cherry, meaning they are already present in <upstream>.)

<!--[if !IE]> not working

Conditional comment is a comment starts with <!--[if IE]> which couldn't be read by any browser except IE.

from 2011 Conditional comment isn't supported starting form IE 10 as announced by Microsoft in that time https://msdn.microsoft.com/en-us/library/hh801214(v=vs.85).aspx

The only option to use the Conditional comments is to request IE to run your site as IE 9 which supports the Conditional comments.

you can write your own css and/or js files for ie only and other browsers won't load or execute it.

this code snippet shows how to make IE 10 or 11 run ie-only.css and ie-only.js which contains custom codes to solve IE compatibility issues.

    <html>
      <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9">
      <!--[if IE]>
            <meta http-equiv="Content-Type" content="text/html; charset=Unicode">
            <link rel="stylesheet" type="text/css" href='/css/ie-only.css' />
            <script src="/js/ie-only.js"></script>
      <![endif]-->
    </html>

jQuery .val change doesn't change input value

For me the problem was that changing the value for this field didn`t work:

$('#cardNumber').val(maskNumber);

None of the solutions above worked for me so I investigated further and found:

According to DOM Level 2 Event Specification: The change event occurs when a control loses the input focus and its value has been modified since gaining focus. That means that change event is designed to fire on change by user interaction. Programmatic changes do not cause this event to be fired.

The solution was to add the trigger function and cause it to trigger change event like this:

$('#cardNumber').val(maskNumber).trigger('change');

How do I increase the RAM and set up host-only networking in Vagrant?

You can easily increase your VM's RAM by modifying the memory property of config.vm.provider section in your vagrant file.

config.vm.provider "virtualbox" do |vb|
 vb.memory = "4096"
end

This allocates about 4GB of RAM to your VM. You can change this according to your requirement. For example, following setting would allocate 2GB of RAM to your VM.

config.vm.provider "virtualbox" do |vb|
 vb.memory = "2048"
end

Try removing the config.vm.customize ["modifyvm", :id, "--memory", 1024] in your file, and adding the above code.

For the network configuration, try modifying the config.vm.network :hostonly, "199.188.44.20" in your file toconfig.vm.network "private_network", ip: "199.188.44.20"

How to find an object in an ArrayList by property

For finding objects which are meaningfully equal, you need to override equals and hashcode methods for the class. You can find a good tutorial here.

http://www.thejavageek.com/2013/06/28/significance-of-equals-and-hashcode/

ant build.xml file doesn't exist

There may be two situations.

  1. No build.xml is present in the current directory
  2. Your ant configuration file has diffrent name.

Please see and confim the same. In the case one you have to find where your build file is located and in the case 2, You will have to run command ant -f <your build file name>.

jQuery how to find an element based on a data-attribute value?

I improved upon psycho brm's filterByData extension to jQuery.

Where the former extension searched on a key-value pair, with this extension you can additionally search for the presence of a data attribute, irrespective of its value.

(function ($) {

    $.fn.filterByData = function (prop, val) {
        var $self = this;
        if (typeof val === 'undefined') {
            return $self.filter(
                function () { return typeof $(this).data(prop) !== 'undefined'; }
            );
        }
        return $self.filter(
            function () { return $(this).data(prop) == val; }
        );
    };

})(window.jQuery);

Usage:

$('<b>').data('x', 1).filterByData('x', 1).length    // output: 1
$('<b>').data('x', 1).filterByData('x').length       // output: 1

_x000D_
_x000D_
// test data_x000D_
function extractData() {_x000D_
  log('data-prop=val ...... ' + $('div').filterByData('prop', 'val').length);_x000D_
  log('data-prop .......... ' + $('div').filterByData('prop').length);_x000D_
  log('data-random ........ ' + $('div').filterByData('random').length);_x000D_
  log('data-test .......... ' + $('div').filterByData('test').length);_x000D_
  log('data-test=anyval ... ' + $('div').filterByData('test', 'anyval').length);_x000D_
}_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#b5').data('test', 'anyval');_x000D_
});_x000D_
_x000D_
// the actual extension_x000D_
(function($) {_x000D_
_x000D_
  $.fn.filterByData = function(prop, val) {_x000D_
    var $self = this;_x000D_
    if (typeof val === 'undefined') {_x000D_
      return $self.filter(_x000D_
_x000D_
        function() {_x000D_
          return typeof $(this).data(prop) !== 'undefined';_x000D_
        });_x000D_
    }_x000D_
    return $self.filter(_x000D_
_x000D_
      function() {_x000D_
        return $(this).data(prop) == val;_x000D_
      });_x000D_
  };_x000D_
_x000D_
})(window.jQuery);_x000D_
_x000D_
_x000D_
//just to quickly log_x000D_
function log(txt) {_x000D_
  if (window.console && console.log) {_x000D_
    console.log(txt);_x000D_
    //} else {_x000D_
    //  alert('You need a console to check the results');_x000D_
  }_x000D_
  $("#result").append(txt + "<br />");_x000D_
}
_x000D_
#bPratik {_x000D_
  font-family: monospace;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="bPratik">_x000D_
  <h2>Setup</h2>_x000D_
  <div id="b1" data-prop="val">Data added inline :: data-prop="val"</div>_x000D_
  <div id="b2" data-prop="val">Data added inline :: data-prop="val"</div>_x000D_
  <div id="b3" data-prop="diffval">Data added inline :: data-prop="diffval"</div>_x000D_
  <div id="b4" data-test="val">Data added inline :: data-test="val"</div>_x000D_
  <div id="b5">Data will be added via jQuery</div>_x000D_
  <h2>Output</h2>_x000D_
  <div id="result"></div>_x000D_
_x000D_
  <hr />_x000D_
  <button onclick="extractData()">Reveal</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or the fiddle: http://jsfiddle.net/PTqmE/46/

What's NSLocalizedString equivalent in Swift?

Localization with default language:

extension String {
func localized() -> String {
       let defaultLanguage = "en"
       let path = Bundle.main.path(forResource: defaultLanguage, ofType: "lproj")
       let bundle = Bundle(path: path!)

       return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
    }
}

How can I generate an apk that can run without server with react-native?

for React Native 0.49 and over

you should go to project directory on terminal and run that command

1 - mkdir android/app/src/main/assets
2 - react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

if under 0.49

  1 - mkdir android/app/src/main/assets
  2 - react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

Then Use android studio to open the 'android' folder in you react native app directory, it will ask to upgrade gradle and some other stuff. go to build-> Generate signed APK and follow the instructions from there. That okey.

Difference between nVidia Quadro and Geforce cards?

Surfing the web, you will find many technical justifications for Quadro price. Real answer is in "demand for reliable and task specific graphic cards".

Imagine you have an architectural firm with many fat projects on deadline. Your computers are only used in working with one specific CAD software. If foundation of your business is supposed to rely on these computers, you would want to make sure this foundation is strong.

For such clients, Nvidia engineered cards like Quadro, providing what they call "Professional Solution". And if you are among the targeted clients, you would really appreciate reliability of these graphic cards.

Many believe Geforce have become powerful and reliable enough to take Quadro's place. But in the end, it depends on the software you are mostly going to use and importance of reliability in what you do.

Lodash .clone and .cloneDeep behaviors

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

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

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

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

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

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

Checking if a variable exists in javascript

If you want to check if a variable (say v) has been defined and is not null:

if (typeof v !== 'undefined' && v !== null) {
    // Do some operation  
}

If you want to check for all falsy values such as: undefined, null, '', 0, false:

if (v) {
   // Do some operation
}

Remove blank values from array using C#

If you are using .NET 3.5+ you could use LINQ (Language INtegrated Query).

test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();

HTML5 Video tag not working in Safari , iPhone and iPad

I have faced same issue. Because my video frame size was too big. ie.2248 px apple support H.264 Baseline Profile Level 3.0 video, up to 640 x 480 at 30 fps. Note that B frames are not supported in the Baseline profile. check this for more info

How do I get the last character of a string using an Excel function?

Just another way to do this:

=MID(A1, LEN(A1), 1)

RegEx pattern any two letters followed by six numbers

You could try something like this:

[a-zA-Z]{2}[0-9]{6}

Here is a break down of the expression:

[a-zA-Z]    # Match a single character present in the list below
               # A character in the range between “a” and “z”
               # A character in the range between “A” and “Z”
   {2}         # Exactly 2 times
[0-9]       # Match a single character in the range between “0” and “9”
   {6}         # Exactly 6 times

This will match anywhere in a subject. If you need boundaries around the subject then you could do either of the following:

^[a-zA-Z]{2}[0-9]{6}$

Which ensures that the whole subject matches. I.e there is nothing before or after the subject.

or

\b[a-zA-Z]{2}[0-9]{6}\b

which ensures there is a word boundary on each side of the subject.

As pointed out by @Phrogz, you could make the expression more terse by replacing the [0-9] for a \d as in some of the other answers.

[a-zA-Z]{2}\d{6}

How to initailize byte array of 100 bytes in java with all 0's

Actually the default value of byte is 0.

Where can I find jenkins restful api reference?

Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.

You can additionally use some wrapper, like I do, in Python, using http://jenkinsapi.readthedocs.io/en/latest/

Here is their website: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API

Increasing Google Chrome's max-connections-per-server limit to more than 6

BTW, HTTP 1/1 specification (RFC2616) suggests no more than 2 connections per server.

Clients that use persistent connections SHOULD limit the number of simultaneous connections that they maintain to a given server. A single-user client SHOULD NOT maintain more than 2 connections with any server or proxy. A proxy SHOULD use up to 2*N connections to another server or proxy, where N is the number of simultaneously active users. These guidelines are intended to improve HTTP response times and avoid congestion.

Gradle version 2.2 is required. Current version is 2.10

The android studio and Gradle version looks like very bad managed. And there's tons of version in-capability issues. And the error message is mostly clueless. For this particular issue. The closest answer is from "Jitendra Singh". Change the version to:

 classpath 'com.android.tools.build:gradle:2.0.0'

But in my case: Android studio 2.2 RC, I still get another error:

Could not find matching constructor for: com.android.build.gradle.internal.LibraryTaskManager(org.gradle.api.internal.project.DefaultProject_Decorated, com.android.builder.core.AndroidBuilder, android.databinding.tool.DataBindingBuilder, com.android.build.gradle.LibraryExtension_Decorated, com.android.build.gradle.internal.SdkHandler, com.android.build.gradle.internal.DependencyManager, org.gradle.tooling.provider.model.internal.DefaultToolingModelBuilderRegistry)

So I went to the maven central to find the latest com.android.tools.build:gradle version which is 2.1.3 for now. So after change to

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.3'
    }
}

Solved my problem eventually.

SVN repository backup strategies

Basically it's safe to copy the repository folder if the svn server is stopped. (source: https://groups.google.com/forum/?fromgroups#!topic/visualsvn/i_55khUBrys%5B1-25%5D )

So if you're allowed to stop the server, do it and just copy the repository, either with some script or a backup tool. Cobian Backup fits here nicely as it can stop and start services automatically, and it can do incremental backups so you're only backing up parts of repository that have changed recently (useful if the repository is large and you're backing up to remote location).

Example:

  1. Install Cobian Backup
  2. Add a backup task:

    • Set source to repository folder (e.g. C:\Repositories\),

    • Add pre-backup event "STOP_SERVICE" VisualSVN,

    • Add post-backup event, "START_SERVICE" VisualSVN,

    • Set other options as needed. We've set up incremental backups including removal of old ones, backup schedule, destination, compression incl. archive splitting etc.

  3. Profit!

Copy Paste Values only( xlPasteValues )

selection=selection.values

this do things at a very fast way.

How to add System.Windows.Interactivity to project?

The official package for behaviors is Microsoft.Xaml.Behaviors.Wpf.

It used to be in the Blend SDK (deprecated).
See Jan's answer for more details if you need to migrate.

How can I pipe stderr, and not stdout?

First redirect stderr to stdout — the pipe; then redirect stdout to /dev/null (without changing where stderr is going):

command 2>&1 >/dev/null | grep 'something'

For the details of I/O redirection in all its variety, see the chapter on Redirections in the Bash reference manual.

Note that the sequence of I/O redirections is interpreted left-to-right, but pipes are set up before the I/O redirections are interpreted. File descriptors such as 1 and 2 are references to open file descriptions. The operation 2>&1 makes file descriptor 2 aka stderr refer to the same open file description as file descriptor 1 aka stdout is currently referring to (see dup2() and open()). The operation >/dev/null then changes file descriptor 1 so that it refers to an open file description for /dev/null, but that doesn't change the fact that file descriptor 2 refers to the open file description which file descriptor 1 was originally pointing to — namely, the pipe.

Git pull command from different user

This command will help to pull from the repository as the different user:

git pull https://[email protected]/projectfolder/projectname.git master

It is a workaround, when you are using same machine that someone else used before you, and had saved credentials

How to display a confirmation dialog when clicking an <a> link?

This method is slightly different than either of the above answers if you attach your event handler using addEventListener (or attachEvent).

function myClickHandler(evt) {
  var allowLink = confirm('Continue with link?');
  if (!allowLink) {
    evt.returnValue = false; //for older Internet Explorer
    if (evt.preventDefault) {
      evt.preventDefault();
    }
    return false;
  }
}

You can attach this handler with either:

document.getElementById('mylinkid').addEventListener('click', myClickHandler, false);

Or for older versions of internet explorer:

document.getElementById('mylinkid').attachEvent('onclick', myClickHandler);

What is polymorphism, what is it for, and how is it used?

(I was browsing another article on something entirely different.. and polymorphism popped up... Now I thought that I knew what Polymorphism was.... but apparently not in this beautiful way explained.. Wanted to write it down somewhere.. better still will share it... )

http://www.eioba.com/a/1htn/how-i-explained-rest-to-my-wife

read on from this part:

..... polymorphism. That's a geeky way of saying that different nouns can have the same verb applied to them.