Programs & Examples On #Remote debugging

Remote debugging is the process of running a debug session in a local development environment attached to a remotely deployed application.

Accessing localhost (xampp) from another computer over LAN network - how to?

I am Fully agree With BugFinder.

In simple Words, just put ip address 192.168.1.56 in your browser running on 192.168.1.2!

if it does not work then there are following possible reasons for that :

  1. Network Connectivity Issue :

    • First of all Check your network Connectivity using ping 192.168.1.56 command in command prompt/terminal on 192.168.1.2 computer.
  2. Firewall Problem : Your windows firewall setting do not have allowing rule for XAMPP(apache). (Most probable problem)

    • (solution) go to advanced firewall settings and add inbound and outbound rules for Apache executable file.
  3. Apache Configuration problem. : Your apache is configured to listen only local requests.

    • (Solution) you can it by opening httpd.conf file and replace Listen 127.0.0.1:80 to Listen 80 or *Listen :80
  4. Port Conflict with other Servers(IIS etc.)

    • (Solution) Turn off apache server and then open local host in browser. if any response is obtained then turnoff that server then start Apache.

if all above does not work then probably there is some configuration problem on your apache server.try to find it out otherwise just reinstall it and transfer all php files(htdocs) to new installation of XAMPP/WAMP.

Remote debugging a Java application

Edit: I noticed that some people are cutting and pasting the invocation here. The answer I originally gave was relevant for the OP only. Here's a more modern invocation style (including using the more conventional port of 8000):

java -agentlib:jdwp=transport=dt_socket,server=y,address=8000,suspend=n <other arguments>

Original answer follows.


Try this:

java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n myapp

Two points here:

  1. No spaces in the runjdwp option.
  2. Options come before the class name. Any arguments you have after the class name are arguments to your program!

Running java with JAVA_OPTS env variable has no effect

You can setup _JAVA_OPTIONS instead of JAVA_OPTS. This should work without $_JAVA_OPTIONS.

Debug JavaScript in Eclipse

For Node.js there is Nodeclipse 0.2 with some bug fixes for chromedevtools

Work on a remote project with Eclipse via SSH

Try the Remote System Explorer (RSE). It's a set of plug-ins to do exactly what you want.

RSE may already be included in your current Eclipse installation. To check in Eclipse Indigo go to Window > Open Perspective > Other... and choose Remote System Explorer from the Open Perspective dialog to open the RSE perspective.

To create an SSH remote project from the RSE perspective in Eclipse:

  1. Define a new connection and choose SSH Only from the Select Remote System Type screen in the New Connection dialog.
  2. Enter the connection information then choose Finish.
  3. Connect to the new host. (Assumes SSH keys are already setup.)
  4. Once connected, drill down into the host's Sftp Files, choose a folder and select Create Remote Project from the item's context menu. (Wait as the remote project is created.)

If done correctly, there should now be a new remote project accessible from the Project Explorer and other perspectives within eclipse. With the SSH connection set-up correctly passwords can be made an optional part of the normal SSH authentication process. A remote project with Eclipse via SSH is now created.

Adb over wireless without usb cable at all for not rooted phones

This might help:

If the adb connection is ever lost:

Make sure that your host is still connected to the same Wi-Fi network your Android device is. Reconnect by executing the "adb connect IP" step. (IP is obviously different when you change location.) Or if that doesn't work, reset your adb host: adb kill-server and then start over from the beginning.

Eclipse : Failed to connect to remote VM. Connection refused.

I ran into this problem debugging play framework version 2.x, turned out the server hadn't been started even though the play debug run command was issued. After a first request to the webserver which caused the play framework to really start the application at port 9000, I was able to connect properly to the debug port 9999 from eclipse.

[info] play - Application started (Dev)

The text above was shown in the console when the message above appeared, indicating why eclipse couldn't connect before first http request.

Run local python script on remote server

I've had to do this before using Paramiko in a case where I wanted to run a dynamic, local PyQt4 script on a host running an ssh server that has connected my OpenVPN server and ask for their routing preference (split tunneling).

So long as the ssh server you are connecting to has all of the required dependencies of your script (PyQt4 in my case), you can easily encapsulate the data by encoding it in base64 and use the exec() built-in function on the decoded message. If I remember correctly my one-liner for this was:

stdout = client.exec_command('python -c "exec(\\"' + open('hello.py','r').read().encode('base64').strip('\n') + '\\".decode(\\"base64\\"))"' )[1]

It is hard to read and you have to escape the escape sequences because they are interpreted twice (once by the sender and then again by the receiver). It also may need some debugging, I've packed up my server to PCS or I'd just reference my OpenVPN routing script.

The difference in doing it this way as opposed to sending a file is that it never touches the disk on the server and is run straight from memory (unless of course they log the command). You'll find that encapsulating information this way (although inefficient) can help you package data into a single file.

For instance, you can use this method to include raw data from external dependencies (i.e. an image) in your main script.

Are static methods inherited in Java?

If that's what the book really says, it's wrong.[1]

The Java Language Specification #8.4.8 states:

8.4.8 Inheritance, Overriding, and Hiding

A class C inherits from its direct superclass all concrete methods m (both static and instance) of the superclass for which all of the following are true:

  • m is a member of the direct superclass of C.

  • m is public, protected, or declared with package access in the same package as C.

  • No method declared in C has a signature that is a subsignature (§8.4.2) of the signature of m.

[1] It doesn't say that in my copy, 1st edition, 2000.

How to get current time with jQuery

Using JavaScript native Date functions you can get hours, minutes and seconds as you want. If you wish to format date and time in particular way you may want to implement a method extending JavaScript Date prototype.

Here is one already implemented: https://github.com/jacwright/date.format

Can I replace groups in Java regex?

replace the password fields from the input:

{"_csrf":["9d90c85f-ac73-4b15-ad08-ebaa3fa4a005"],"originPassword":["uaas"],"newPassword":["uaas"],"confirmPassword":["uaas"]}



  private static final Pattern PATTERN = Pattern.compile(".*?password.*?\":\\[\"(.*?)\"\\](,\"|}$)", Pattern.CASE_INSENSITIVE);

  private static String replacePassword(String input, String replacement) {
    Matcher m = PATTERN.matcher(input);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
      Matcher m2 = PATTERN.matcher(m.group(0));
      if (m2.find()) {
        StringBuilder stringBuilder = new StringBuilder(m2.group(0));
        String result = stringBuilder.replace(m2.start(1), m2.end(1), replacement).toString();
        m.appendReplacement(sb, result);
      }
    }
    m.appendTail(sb);
    return sb.toString();
  }

  @Test
  public void test1() {
    String input = "{\"_csrf\":[\"9d90c85f-ac73-4b15-ad08-ebaa3fa4a005\"],\"originPassword\":[\"123\"],\"newPassword\":[\"456\"],\"confirmPassword\":[\"456\"]}";
    String expected = "{\"_csrf\":[\"9d90c85f-ac73-4b15-ad08-ebaa3fa4a005\"],\"originPassword\":[\"**\"],\"newPassword\":[\"**\"],\"confirmPassword\":[\"**\"]}";
    Assert.assertEquals(expected, replacePassword(input, "**"));
  }

Hibernate Annotations - Which is better, field or property access?

Are we there yet

That's an old presentation but Rod suggests that annotation on property access encourages anemic domain models and should not be the "default" way to annotate.

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

What is the most efficient string concatenation method in python?

Python 3.6 changed the game for string concatenation of known components with Literal String Interpolation.

Given the test case from mkoistinen's answer, having strings

domain = 'some_really_long_example.com'
lang = 'en'
path = 'some/really/long/path/'

The contenders are

  • f'http://{domain}/{lang}/{path}' - 0.151 µs

  • 'http://%s/%s/%s' % (domain, lang, path) - 0.321 µs

  • 'http://' + domain + '/' + lang + '/' + path - 0.356 µs

  • ''.join(('http://', domain, '/', lang, '/', path)) - 0.249 µs (notice that building a constant-length tuple is slightly faster than building a constant-length list).

Thus currently the shortest and the most beautiful code possible is also fastest.

In alpha versions of Python 3.6 the implementation of f'' strings was the slowest possible - actually the generated byte code is pretty much equivalent to the ''.join() case with unnecessary calls to str.__format__ which without arguments would just return self unchanged. These inefficiencies were addressed before 3.6 final.

The speed can be contrasted with the fastest method for Python 2, which is + concatenation on my computer; and that takes 0.203 µs with 8-bit strings, and 0.259 µs if the strings are all Unicode.

Python list iterator behavior and next(iterator)

What you see is the interpreter echoing back the return value of next() in addition to i being printed each iteration:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    next(a)
... 
0
1
2
3
4
5
6
7
8
9

So 0 is the output of print(i), 1 the return value from next(), echoed by the interactive interpreter, etc. There are just 5 iterations, each iteration resulting in 2 lines being written to the terminal.

If you assign the output of next() things work as expected:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    _ = next(a)
... 
0
2
4
6
8

or print extra information to differentiate the print() output from the interactive interpreter echo:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print('Printing: {}'.format(i))
...    next(a)
... 
Printing: 0
1
Printing: 2
3
Printing: 4
5
Printing: 6
7
Printing: 8
9

In other words, next() is working as expected, but because it returns the next value from the iterator, echoed by the interactive interpreter, you are led to believe that the loop has its own iterator copy somehow.

how to create a login page when username and password is equal in html

<html>
    <head>
        <title>Login page</title>
    </head>
    <body>
        <h1>Simple Login Page</h1>
        <form name="login">
            Username<input type="text" name="userid"/>
            Password<input type="password" name="pswrd"/>
            <input type="button" onclick="check(this.form)" value="Login"/>
            <input type="reset" value="Cancel"/>
        </form>
        <script language="javascript">
            function check(form) { /*function to check userid & password*/
                /*the following code checkes whether the entered userid and password are matching*/
                if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
                    window.open('target.html')/*opens the target page while Id & password matches*/
                }
                else {
                    alert("Error Password or Username")/*displays error message*/
                }
            }
        </script>
    </body>
</html>

Eclipse executable launcher error: Unable to locate companion shared library

I also faced ths problem, I just deleted the extracted file and extracted it again.

I have a .rar file.

This problem occurs when the file is not extracted completely.

Set selected radio from radio group with a value

Or you can just write value attribute to it:

$(':radio[value=<yourvalue>]').attr('checked',true);

This works for me.

Launch programs whose path contains spaces

Copy the folder, firefox.exe is in and place in the c:\ only. The script is having a hard time climbing your file tree. I found that when I placed the *.exe file in the c:\ it eliminated the error message " file not found."

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

Python SQL query string formatting

This is slightly modified version of @aandis answer. When it comes to raw string, prefix 'r' character before the string. For example:

sql = r"""
    SELECT field1, field2, field3, field4
      FROM table
     WHERE condition1 = 1
       AND condition2 = 2;
"""

This is recommended when your query has any special character like '\' which requires escaping and lint tools like flake8 reports it as error.

Access 2010 VBA query a table and iterate through results

DAO is native to Access and by far the best for general use. ADO has its place, but it is unlikely that this is it.

 Dim rs As DAO.Recordset
 Dim db As Database
 Dim strSQL as String

 Set db=CurrentDB

 strSQL = "select * from table where some condition"

 Set rs = db.OpenRecordset(strSQL)

 Do While Not rs.EOF

    rs.Edit
    rs!SomeField = "Abc"
    rs!OtherField = 2
    rs!ADate = Date()
    rs.Update

    rs.MoveNext
Loop

Recursively looping through an object to build a property list

With a little help from lodash...

/**
 * For object (or array) `obj`, recursively search all keys
 * and generate unique paths for every key in the tree.
 * @param {Object} obj
 * @param {String} prev
 */
export const getUniqueKeyPaths = (obj, prev = '') => _.flatten(
  Object
  .entries(obj)
  .map(entry => {
    const [k, v] = entry
    if (v !== null && typeof v === 'object') {
      const newK = prev ? `${prev}.${k}` : `${k}`
      // Must include the prev and current k before going recursive so we don't lose keys whose values are arrays or objects
      return [newK, ...getUniqueKeyPaths(v, newK)]
    }
    return `${prev}.${k}`
  })
)

Java SE 6 vs. JRE 1.6 vs. JDK 1.6 - What do these mean?

A Brief and Maybe Incorrect History of Java Versions

  • Java is a platform. It consists of two products - the software development kit, and the runtime environment.

  • When Java was first released, it was apparently just called Java. If you were a developer, you also knew the version, which was a normal "1.0" and later a "1.1". The two products that were part of the platform were also given names:

    • JDK - "Java Development Kit"
    • JRE - "Java Runtime Environment"
  • Apparently the changes in version 1.2 so significant that they started calling the platform as Java 2.

    • The default "distribution" of the platform was given the moniker "standard" to contrast it with its siblings. So you had three platforms:

      • "Java 2 Standard Edition (J2SE)"
      • "Java 2 Enterprise Edition (J2EE)"
      • "Java 2 Mobile Edition (J2ME)"
    • The JDK was officially renamed to "Java 2 Software Development Kit".

  • When version 1.5 came out, the suits decided that they needed to "rebrand" the product. So the Java platform got two versions - the product version "5" and the developer version "1.5" (Yes, the rule is explicitly mentioned -- "drop the '1.'). However, the "2" was retained in the name. So now the platform is officially called "Java 2 Platform Standard Edition 5.0 (J2SE 5.0)".

    • The suits also realized that the development community was not picking up their renaming of the JDK. But instead of reverting their change, they just decide to drop the "2" from the name of the individual products, which now get be "J2SE Development Kit 5.0 (JDK 5.0)" and "J2SE Runtime Environment 5.0 (JRE 5.0)".
  • When version 1.6 come out, someone realized that having two numbers in the name was weird. So they decide to completely drop the 2 (and the ".0" suffix), and we end up with the "Java Platform, Standard Edition 6 (Java SE 6)" containing the "Java SE Development Kit 6 (JDK 6)" and the "Java SE Runtime Environment 6 (JRE 6)".

  • Version 1.7 did not do anything stupid. If I had to guess, the next big change would be dropping the "SE", so that the cycle completes and the JDK again gets to be called the "Java Development Kit".

Notes

  • For simplicity, a bunch of trademark signs were omitted. So assume Java™, JDK™ and JRE™.

  • SO seems to have trouble rendering nested lists.

References

Epilogue

Just drop the "1." from versions printed by javac -version and java -version and you're good to go.

Windows task scheduler error 101 launch failure code 2147943785

The user that is configured to run this scheduled task must have "Log on as a batch job" rights on the computer that hosts the exe you are launching. This can be configured on the local security policy of the computer that hosts the exe. You can change the policy (on the server hosting the exe) under

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log On As Batch Job

Add your user to this list (you could also make the user account a local admin on the machine hosting the exe).

Finally, you could also simply copy your exe from the network location to your local computer and run it from there instead.

Note also that a domain policy could be restricting "Log on as a batch job" rights at your organization.

How to configure postgresql for the first time?

In MacOS, I followed the below steps to make it work.

For the first time, after installation, get the username of the system.

$ cd ~
$ pwd
/Users/someuser
$ psql -d postgres -U someuser

Now that you have logged into the system, and you can create the DB.

postgres=# create database mydb;
CREATE DATABASE
postgres=# create user myuser with encrypted password 'pass123';
CREATE ROLE
postgres=# grant all privileges on database mydb to myuser;
GRANT

How to remove Firefox's dotted outline on BUTTONS as well as links?

The CSS code below works to remove this:

a:focus, a:active, 
button::-moz-focus-inner,
input[type="reset"]::-moz-focus-inner,
input[type="button"]::-moz-focus-inner,
input[type="submit"]::-moz-focus-inner,
select::-moz-focus-inner,
input[type="file"] > input[type="button"]::-moz-focus-inner {
    border: 0;
    outline : 0;
}

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

Here is the solution step-by-step:

  1. Open up httpd-ssl.conf in path2xampp\apache\conf\extra
  2. Look for the line Listen 443
  3. Change port number to anything you want. I use 4430. ex. Listen 4430.
  4. Replace every 443 string in that file with 4430.
  5. Save the file.

How do I serialize a C# anonymous type to a JSON string?

public static class JsonSerializer
{
    public static string Serialize<T>(this T data)
    {
        try
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            var stream = new MemoryStream();
            serializer.WriteObject(stream, data);
            string jsonData = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length);
            stream.Close();
            return jsonData;
        }
        catch
        {
            return "";
        }
    }
    public static T Deserialize<T>(this string jsonData)
    {
        try
        {
            DataContractJsonSerializer slzr = new DataContractJsonSerializer(typeof(T));
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
            T data = (T)slzr.ReadObject(stream);
            stream.Close();
            return data;
        }
        catch
        {
            return default(T);
        }
    }
}

How to print a date in a regular format?

Since the print today returns what you want this means that the today object's __str__ function returns the string you are looking for.

So you can do mylist.append(today.__str__()) as well.

The simplest way to comma-delimit a list?

public String toString(List<Item> items)
{
    StringBuilder sb = new StringBuilder("[");

    for (Item item : items)
    {
        sb.append(item).append(", ");
    }

    if (sb.length() >= 2)
    {
        //looks cleaner in C# sb.Length -= 2;
        sb.setLength(sb.length() - 2);
    }

    sb.append("]");

    return sb.toString();
}

Proper way to assert type of variable in Python

The isinstance built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:

def my_print(text, begin, end):
    "Print 'text' in UPPER between 'begin' and 'end' in lower"
    try:
      print begin.lower() + text.upper() + end.lower()
    except (AttributeError, TypeError):
      raise AssertionError('Input variables should be strings')

This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)

jQuery removeClass wildcard

The removeClass function takes a function argument since jQuery 1.4.

$("#hello").removeClass (function (index, className) {
    return (className.match (/(^|\s)color-\S+/g) || []).join(' ');
});

Live example: http://jsfiddle.net/xa9xS/1409/

Setting up enviromental variables in Windows 10 to use java and javac

Its still the same concept, you'll need to setup path variable so that windows is aware of the java executable and u can run it from command prompt conveniently

Details from the java's own page: https://java.com/en/download/help/path.xml That article applies to: •Platform(s): Solaris SPARC, Solaris x86, Red Hat Linux, SUSE Linux, Windows 8, Windows 7, Vista, Windows XP, Windows 10

Remove the newline character in a list read from a file

You want the String.strip(s[, chars]) function, which will strip out whitespace characters or whatever characters (such as '\n') you specify in the chars argument.

See http://docs.python.org/release/2.3/lib/module-string.html

Windows batch - concatenate multiple text files into one

At its most basic, concatenating files from a batch file is done with 'copy'.

copy file1.txt + file2.txt + file3.txt concattedfile.txt

How to get substring in C

#include <stdio.h>
#include <string.h>

int main() {
    char src[] = "SexDrugsRocknroll";
    char dest[5] = { 0 }; // 4 chars + terminator */
    int len = strlen(src);
    int i = 0;

    while (i*4 < len) {
        strncpy(dest, src+(i*4), 4);
        i++;

        printf("loop %d : %s\n", i, dest);
    }
}

Socket.IO handling disconnect event

Ok, instead of identifying players by name track with sockets through which they have connected. You can have a implementation like

Server

var allClients = [];
io.sockets.on('connection', function(socket) {
   allClients.push(socket);

   socket.on('disconnect', function() {
      console.log('Got disconnect!');

      var i = allClients.indexOf(socket);
      allClients.splice(i, 1);
   });
});

Hope this will help you to think in another way

CSS table column autowidth

use auto and min or max width like this:

td {
max-width:50px;
width:auto;
min-width:10px;
}

Difference between a virtual function and a pure virtual function

You can actually provide implementations of pure virtual functions in C++. The only difference is all pure virtual functions must be implemented by derived classes before the class can be instantiated.

What is wrong with my SQL here? #1089 - Incorrect prefix key

It works for me:

CREATE TABLE `users`(
    `user_id` INT(10) NOT NULL AUTO_INCREMENT,
    `username` VARCHAR(255) NOT NULL,
    `password` VARCHAR(255) NOT NULL,
    PRIMARY KEY (`user_id`)
) ENGINE = MyISAM;       

Decreasing height of bootstrap 3.0 navbar

if you are using the less source, there should be a variable for the navbar height in the variables.less file. If you are not using the source, then you can customize it using the customize utilty that bootstrap's site provides. And then you can downloaded it and include it in your project. The variable you are looking for is: @navbar-height

Regular expression \p{L} and \p{N}

\p{L} matches a single code point in the category "letter".
\p{N} matches any kind of numeric character in any script.

Source: regular-expressions.info

If you're going to work with regular expressions a lot, I'd suggest bookmarking that site, it's very useful.

How to style dt and dd so they are on the same line?

You can use CSS Grid:

_x000D_
_x000D_
dl {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
_x000D_
<dl>
<dt>Title 1</dt>
<dd>Description 1</dd>
<dt>Title 2</dt>
<dd>Description 2</dd>
<dt>Title 3</dt>
<dd>Description 3</dd>
<dt>Title 4</dt>
<dd>Description 4</dd>
<dt>Title 5</dt>
<dd>Description 5</dd>
</dl>
_x000D_
_x000D_
_x000D_

Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?

To execute more Maven builds from one script you shall use the Windows call function in the following way:

call mvn install:install-file -DgroupId=gdata -DartifactId=base -Dversion=1.0 -Dfile=gdata-base-1.0.jar  -Dpackaging=jar -DgeneratePom=true
call mvn install:install-file -DgroupId=gdata -DartifactId=blogger -Dversion=2.0 -Dfile=gdata-blogger-2.0.jar  -Dpackaging=jar -DgeneratePom=true
call mvn install:install-file -DgroupId=gdata -DartifactId=blogger-meta -Dversion=2.0 -Dfile=gdata-blogger-meta-2.0.jar  -Dpackaging=jar -DgeneratePom=true

How to calculate a mod b in Python?

A = [3, 1, 2, 4]
for a in A:
    print(a % 2)

output:

1
1
0
0

How to open Console window in Eclipse?

The only reliable way to open it is Window -> Show View -> Other -> Search "console". There was a handful suggestions in this post and none of them works! Apparently Eclipse likes to change their logic every other second.

Also, resetting the view is the most horrible suggestion, because that way you will lose everything you have ever done to change the layout, so it will probably not work for the most of the readers.

What is the difference between Html.Hidden and Html.HiddenFor

Html.Hidden and Html.HiddenFor used to generate name-value pairs which waited by action method in controller. Sample Usage(*):

@using (Html.BeginForm("RemoveFromCart", "Cart")) {
                    @Html.Hidden("ProductId", line.Product.ProductID)
                    @Html.HiddenFor(x => x.ReturnUrl)
                    <input class="btn btn-sm btn-warning"
                           type="submit" value="Remove" />
                }

If your action method wait for "ProductId" you have to generate this name in form via using (Html.Hidden or Html.HiddenFor) For the case it is not possible to generate this name with strongly typed model you simple write this name with a string thats "ProductId".

public ViewResult RemoveFromCart(int productId, string returnUrl){...}

If I had written Html.HiddenFor(x => line.Product.ProductID), the helper would render a hidden field with the name "line.Product.ProductID". The name of the field would not match the names of the parameters for the "RemoveFromCart" action method which waiting the name of "ProductId". This would prevent the default model binders from working, so the MVC Framework would not be able to call the method.

*Adam Freeman (Apress - Pro ASP.Net MVC 5)

how to increase MaxReceivedMessageSize when calling a WCF from C#

Change the customBinding in the web.config to use larger defaults. I picked 2MB as it is a reasonable size. Of course setting it to 2GB (as your code suggests) will work but it does leave you more vulnerable to attacks. Pick a size that is larger than your largest request but isn't overly large.

Check this : Using Large Message Requests in Silverlight with WCF

<system.serviceModel>
   <behaviors>
     <serviceBehaviors>
       <behavior name="TestLargeWCF.Web.MyServiceBehavior">
         <serviceMetadata httpGetEnabled="true"/>
         <serviceDebug includeExceptionDetailInFaults="false"/>
       </behavior>
     </serviceBehaviors>
   </behaviors>
   <bindings>
     <customBinding>
       <binding name="customBinding0">
         <binaryMessageEncoding />
         <!-- Start change -->
         <httpTransport maxReceivedMessageSize="2097152"
                        maxBufferSize="2097152"
                        maxBufferPoolSize="2097152"/>
         <!-- Stop change -->
       </binding>
     </customBinding>
   </bindings>
   <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
   <services>
     <service behaviorConfiguration="Web.MyServiceBehavior" name="TestLargeWCF.Web.MyService">
       <endpoint address=""
                binding="customBinding"
                bindingConfiguration="customBinding0"
                contract="TestLargeWCF.Web.MyService"/>
       <endpoint address="mex"
                binding="mexHttpBinding"
                contract="IMetadataExchange"/>
     </service>
   </services>
 </system.serviceModel> 

How to write a caption under an image?

For responsive images. You can add the picture and source tags within the figure tag.

<figure>
  <picture>
    <source media="(min-width: 750px)" srcset="images/image_2x.jpg"/>
    <source media="(min-width: 500px)" srcset="images/image.jpg" />
    <img src="images.jpg" alt="An image">
  </picture>
  <figcaption>Caption goes here</figcaption>
</figure>

Create own colormap using matplotlib and plot color scale

This seems to work for me.

def make_Ramp( ramp_colors ): 
    from colour import Color
    from matplotlib.colors import LinearSegmentedColormap

    color_ramp = LinearSegmentedColormap.from_list( 'my_list', [ Color( c1 ).rgb for c1 in ramp_colors ] )
    plt.figure( figsize = (15,3))
    plt.imshow( [list(np.arange(0, len( ramp_colors ) , 0.1)) ] , interpolation='nearest', origin='lower', cmap= color_ramp )
    plt.xticks([])
    plt.yticks([])
    return color_ramp

custom_ramp = make_Ramp( ['#754a28','#893584','#68ad45','#0080a5' ] ) 

custom color ramp

What are the differences between a program and an application?

i guess you mean System Programs and Application programs

System Programs makes the hardware run , Applications are for specific tasks

an Example for System Programs are Device Drivers

as for the Applications you can say web browsers , word porcessros etc

How can I get terminal output in python?

The recommended way in Python 3.5 and above is to use subprocess.run():

from subprocess import run
output = run("pwd", capture_output=True).stdout

fatal error: mpi.h: No such file or directory #include <mpi.h>

Debian appears to include the following:

  • mpiCC.openmpi
  • mpic++.openmpi
  • mpicc.openmpi
  • mpicxx.openmpi
  • mpif77.openmpi
  • mpif90.openmpi

I'll test symlinks of each for mpic, etc., and see if that helps the likes of HDF5-openmpi enabled find mpi.h.

Take that back Debian includes symlinks via their alternatives system and it still cannot find the proper paths between HDF5 openmpi packages and mpi.h referenced in the H5public.h header.

Colorized grep -- viewing the entire file with highlighted matches

another dirty way:

grep -A80 -B80 --color FIND_THIS IN_FILE

I did an

alias grepa='grep -A80 -B80 --color'

in bashrc.

NPM clean modules

In a word no.

In two, not yet.

There is, however, an open issue for a --no-build flag to npm install to perform an installation without building, which could be used to do what you're asking.

See this open issue.

"Content is not allowed in prolog" when parsing perfectly valid XML on GAE

I catched the same error message today. The solution was to change the document from UTF-8 with BOM to UTF-8 without BOM

How to extract numbers from string in c?

Or you can make a simple function like this:

// Provided 'c' is only a numeric character
int parseInt (char c) {
    return c - '0';
}

How to prevent form from being submitted?

You can use inline event onsubmit like this

<form onsubmit="alert('stop submit'); return false;" >

Or

<script>
   function toSubmit(){
      alert('I will not submit');
      return false;
   }
</script>

<form onsubmit="return toSubmit();" >

Demo

Now, this may be not a good idea when making big projects. You may need to use Event Listeners.

Please read more about Inline Events vs Event Listeners (addEventListener and IE's attachEvent) here. For I can not explain it more than Chris Baker did.

Both are correct, but none of them are "best" per se, and there may be a reason the developer chose to use both approaches.

How many characters can a Java String have?

Have you considered using BigDecimal instead of String to hold your numbers?

Cannot change version of project facet Dynamic Web Module to 3.0?

For a maven eclipse web project, changing dynamic web module version needs to check three places. If one uses eclipse, and after you have checked the following: 1) web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

2) maven:

<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>   ## ensure you have tomcat 7 not other version
</dependency>

<plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.0</version>
      <configuration>
            <source>1.7</source> ## at least 6
            <target>1.7</target>
      </configuration>
</plugin>

3) eclipse build path and compiler version is 1.7

you still have an error marker at maven:

cannot change version of project facet dynamic web module to 3.0 one or more constrants have not been satisfied

Then you can: uncheck the dynamic web module, and recheck it. I think it is because .settings of eclipse file is corrupted somehow. About the second tip tomcat which version is a good note.

Initializing select with AngularJS and ng-repeat

If you are using md-select and ng-repeat ing md-option from angular material then you can add ng-model-options="{trackBy: '$value.id'}" to the md-select tag ash shown in this pen

Code:

_x000D_
_x000D_
<md-select ng-model="user" style="min-width: 200px;" ng-model-options="{trackBy: '$value.id'}">_x000D_
  <md-select-label>{{ user ? user.name : 'Assign to user' }}</md-select-label>_x000D_
  <md-option ng-value="user" ng-repeat="user in users">{{user.name}}</md-option>_x000D_
</md-select>
_x000D_
_x000D_
_x000D_

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

That is because you are not fully qualifying your cells object. Try this

With Worksheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

Notice the DOT before Cells?

Convert string[] to int[] in one line of code using LINQ

EDIT: to convert to array

int[] asIntegers = arr.Select(s => int.Parse(s)).ToArray();

This should do the trick:

var asIntegers = arr.Select(s => int.Parse(s));

How to use HTTP GET in PowerShell?

Downloading Wget is not necessary; the .NET Framework has web client classes built in.

$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

I was having the same problem so I decided to download the source kit and install it according to how you posted above...

  1. Downloaded Source Kit
  2. Opened command prompt on that folder and typed python setup.py build
  3. Then I typed python setup.py install

It worked perfectly!

Now, some notes: when I typed python setup.py build, I saw that Microsoft Visual Studio v9.0 C compiler was being used to build everything.

So probably it's something with your compiler not correctly configured or something...

Anyways, that worked with me so thank you!

How to select all instances of a variable and edit variable name in Sublime

The Magic is, you have to start with an empty selection, so put your cursor in front of the word/character you want to multi-select and press Ctrl+D .

MySQL "Or" Condition

Wrap your AND logic in parenthesis, like this:

mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo' OR date='$Date_FiveDaysAgo' OR date='$Date_SixDaysAgo' OR date='$Date_SevenDaysAgo')");

Unsupported major.minor version 52.0 in my app

Gradle Scripts >> build.gradle (Module app)

Change buildToolsVersion "24.0.0" to buildToolsVersion "23.0.3"

source : experience

node.js http 'get' request with query string parameters

If you don't want use external package , Just add the following function in your utilities :

var params=function(req){
  let q=req.url.split('?'),result={};
  if(q.length>=2){
      q[1].split('&').forEach((item)=>{
           try {
             result[item.split('=')[0]]=item.split('=')[1];
           } catch (e) {
             result[item.split('=')[0]]='';
           }
      })
  }
  return result;
}

Then , in createServer call back , add attribute params to request object :

 http.createServer(function(req,res){
     req.params=params(req); // call the function above ;
      /**
       * http://mysite/add?name=Ahmed
       */
     console.log(req.params.name) ; // display : "Ahmed"

})

Generating Random Passwords

I'll add another ill-advised answer to the pot.

I have a use case where I need random passwords for machine-machine communication, so I don't have any requirement for human readability. I also don't have access to Membership.GeneratePassword in my project, and don't want to add the dependency.

I am fairly certain Membership.GeneratePassword is doing something similar to this, but here you can tune the pools of characters to draw from.

public static class PasswordGenerator
{
    private readonly static Random _rand = new Random();

    public static string Generate(int length = 24)
    {
        const string lower = "abcdefghijklmnopqrstuvwxyz";
        const string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        const string number = "1234567890";
        const string special = "!@#$%^&*_-=+";

        // Get cryptographically random sequence of bytes
        var bytes = new byte[length];
        new RNGCryptoServiceProvider().GetBytes(bytes);

        // Build up a string using random bytes and character classes
        var res = new StringBuilder();
        foreach(byte b in bytes)
        {
            // Randomly select a character class for each byte
            switch (_rand.Next(4))
            {
                // In each case use mod to project byte b to the correct range
                case 0:
                    res.Append(lower[b % lower.Count()]);
                    break;
                case 1:
                    res.Append(upper[b % upper.Count()]);
                    break;
                case 2:
                    res.Append(number[b % number.Count()]);
                    break;
                case 3:
                    res.Append(special[b % special.Count()]);
                    break;
            }
        }
        return res.ToString();
    }
}

And some example output:

PasswordGenerator.Generate(12)
"pzY=64@-ChS$"
"BG0OsyLbYnI_"
"l9#5^2&adj_i"
"#++Ws9d$%O%X"
"IWhdIN-#&O^s"

To preempt complaints about the use of Random: The primary source of randomness is still the crypto RNG. Even if you could deterministically preordain the sequence coming out of Random (say it only produced 1) you still wouldn't know the next char that would be picked (though that would limit the range of possibilities).

One simple extension would be to add weighting to the different character sets, which could be as simple as upping the max value and adding fall-through cases to increase weight.

switch (_rand.Next(6))
{
    // Prefer letters 2:1
    case 0:
    case 1:
        res.Append(lower[b % lower.Count()]);
        break;
    case 2:
    case 3:
        res.Append(upper[b % upper.Count()]);
        break;
    case 4:
        res.Append(number[b % number.Count()]);
        break;
    case 5:
        res.Append(special[b % special.Count()]);
        break;
}

For a more humanistic random password generator I once implemented a prompt system using the EFF dice-word list.

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

Edited my eclipse.ini file to update the newly updated JDK. Previously I had jdk1.7.0_09 and updated now to jdk1.7.0_80 and eclipse threw this error.

A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be available in order to run Eclipse. No Java virtual machine was found after searching the following locations: C:/Program Files/Java/jdk1.7.0_09/bin/javaw

After updating eclipse.ini from,

-vm
C:/Program Files/Java/jdk1.7.0_09/bin/javaw

to

-vm
C:/Program Files/Java/jdk1.7.0_80/bin/javaw

Eclipse works fine.

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

How to check if a textbox is empty using javascript

You can also check it using jQuery.. It's quite easy:

<html>
    <head>
        <title>jQuery: Check if Textbox is empty</title>
        <script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
    </head>
    <body>
        <form name="form1" method="post" action="">
            <label for="city">City:</label>
            <input type="text" name="city" id="city">
        </form>
        <button id="check">Check</button>
        <script type="text/javascript">
             $('#check').click(function () {
                 if ($('#city').val() == '') {
                     alert('Empty!!!');
                 } else {
                     alert('Contains: ' + $('#city').val());
                 }
             });                
        </script>
    </body>
</html>

Which MySQL data type to use for storing boolean values

After reading the answers here I decided to use bit(1) and yes, it is somehow better in space/time, BUT after a while I changed my mind and I will never use it again. It complicated my development a lot, when using prepared statements, libraries etc (php).

Since then, I always use tinyint(1), seems good enough.

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

A problem I had on my Mac using rbenv was that when I first set it up, it loaded a bunch of ruby executables in /usr/local/bin - these executables loaded the system ruby, rather than the current version.

If you run

which bundle

And it shows /usr/local/bin/bundle you may have this issue.

Search through /usr/local/bin and delete any files that start with #!/user/bin ruby

Then run

rbenv rehash

Create table in SQLite only if it doesn't exist already

Am going to try and add value to this very good question and to build on @BrittonKerin's question in one of the comments under @David Wolever's fantastic answer. Wanted to share here because I had the same challenge as @BrittonKerin and I got something working (i.e. just want to run a piece of code only IF the table doesn't exist).

        # for completeness lets do the routine thing of connections and cursors
        conn = sqlite3.connect(db_file, timeout=1000) 

        cursor = conn.cursor() 

        # get the count of tables with the name  
        tablename = 'KABOOM' 
        cursor.execute("SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? ", (tablename, ))

        print(cursor.fetchone()) # this SHOULD BE in a tuple containing count(name) integer.

        # check if the db has existing table named KABOOM
        # if the count is 1, then table exists 
        if cursor.fetchone()[0] ==1 : 
            print('Table exists. I can do my custom stuff here now.... ')
            pass
        else: 
           # then table doesn't exist. 
           custRET = myCustFunc(foo,bar) # replace this with your custom logic

Commenting in a Bash script inside a multiline command

Here is a bash script that combines the ideas and idioms of several previous comments to provide, with examples, inline comments having the general form ${__+ <comment text>}.

In particular

  • <comment text> can be multi-line
  • <comment text> is not parameter-expanded
  • no subprocesses are spawned (so comments are efficient)

There is one restriction on the <comment text>, namely, unbalanced braces '}' and parentheses ')' must be protected (i.e., '\}' and '\)').

There is one requirement on the local bash environment:

  • the parameter name __ must be unset

Any other syntactically valid bash parameter-name will serve in place of __, provided that the name has no set value.

An example script follows

# provide bash inline comments having the form
#     <code> ${__+ <comment>} <code> 
#     <code> ${__+ <multiline
#                   comment>} <code>

# utility routines that obviate "useless use of cat"
function bashcat { printf '%s\n' "$(</dev/stdin)"; }
function scat { 1>&2 bashcat; exit 1; }

# ensure that '__' is unset && remains unset
[[ -z ${__+x} ]] &&  # if '__' is unset
  declare -r __ ||   # then ensure that '__' remains unset 
  scat <<EOF         # else exit with an error
Error: the parameter __='${__}' is set, hence the
  comment-idiom '\${__+ <comment text>}' will fail
EOF

${__+ (example of inline comments)
------------------------------------------------
the following inline comment-idiom is supported
    <code> ${__+ <comment>} <code> 
    <code> ${__+ <multiline
                  comment>} <code> 
(advisory) the parameter '__' must NOT be set;
  even the null declaration __='' will fail
(advisory) protect unbalanced delimiters \} and \) 
(advisory) NO parameter-expansion of <comment> 
(advisory) NO subprocesses are spawned
(advisory) a functionally equivalent idiom is 
    <code> `# <comment>` <code> 
    <code> `# <multiline
               comment>` <code>
however each comment spawns a bash subprocess
that inelegantly requires ~1ms of computation 
------------------------------------------------}

Setting Java heap space under Maven 2 on Windows

On windows:

Add an environmental variable (in both system and user's variables, I have some weird problem, that it gets the var from various places, so I add them in both of them).

Name it MAVEN_OPTS.

Value will be: -Xms1024m -Xmx3000m -XX:MaxPermSize=1024m -XX:+CMSClassUnloadingEnabled

The numbers can be different, make them relative to your mem size.

I had that problem and this fixed it, nothing else!

How Do I 'git fetch' and 'git merge' from a Remote Tracking Branch (like 'git pull')

Are you sure you are on the local an-other-branch when you merge?

git fetch origin an-other-branch
git checkout an-other-branch
git merge origin/an-other-branch

The other explanation:

all the changes from the branch you’re trying to merge have already been merged to the branch you’re currently on.
More specifically it means that the branch you’re trying to merge is a parent of your current branch

if you're ahead of the remote repo by one commit, it's the remote repo that's out of date, not you.

But in your case, if git pull works, that just means you are not on the right branch.

Is it a good practice to use try-except-else in Python?

Python doesn't subscribe to the idea that exceptions should only be used for exceptional cases, in fact the idiom is 'ask for forgiveness, not permission'. This means that using exceptions as a routine part of your flow control is perfectly acceptable, and in fact, encouraged.

This is generally a good thing, as working this way helps avoid some issues (as an obvious example, race conditions are often avoided), and it tends to make code a little more readable.

Imagine you have a situation where you take some user input which needs to be processed, but have a default which is already processed. The try: ... except: ... else: ... structure makes for very readable code:

try:
   raw_value = int(input())
except ValueError:
   value = some_processed_value
else: # no error occured
   value = process_value(raw_value)

Compare to how it might work in other languages:

raw_value = input()
if valid_number(raw_value):
    value = process_value(int(raw_value))
else:
    value = some_processed_value

Note the advantages. There is no need to check the value is valid and parse it separately, they are done once. The code also follows a more logical progression, the main code path is first, followed by 'if it doesn't work, do this'.

The example is naturally a little contrived, but it shows there are cases for this structure.

Virtualbox "port forward" from Guest to Host

That's not possible. localhost always defaults to the loopback device on the local operating system.
As your virtual machine runs its own operating system it has its own loopback device which you cannot access from the outside.

If you want to access it e.g. in a browser, connect to it using the local IP instead:

http://192.168.180.1:8000

This is just an example of course, you can find out the actual IP by issuing an ifconfig command on a shell in the guest operating system.

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

I had the experienced the same issue in different context of my project and there are different scenarios like

 - object is accessed from various source like (server side and client)
 - without any interval accessing the same object from a different place

In the first case

When I issue a server cal, before save the that object their one call from js and trying to save and another place, I got like, js call is going two, three times(I thing that call binding thing cause the issue)

I solved by

e.preventDefault()

The second case,

object.lock()

Simulate delayed and dropped packets on Linux

Haven't tried it myself, but this page has a list of plugin modules that run in Linux' built in iptables IP filtering system. One of the modules is called "nth", and allows you to set up a rule that will drop a configurable rate of the packets. Might be a good place to start, at least.

LIKE vs CONTAINS on SQL Server

The second (assuming you means CONTAINS, and actually put it in a valid query) should be faster, because it can use some form of index (in this case, a full text index). Of course, this form of query is only available if the column is in a full text index. If it isn't, then only the first form is available.

The first query, using LIKE, will be unable to use an index, since it starts with a wildcard, so will always require a full table scan.


The CONTAINS query should be:

SELECT * FROM table WHERE CONTAINS(Column, 'test');

Php header location redirect not working

Make Sure that you don't leave a space before <?php when you start <?php tag at the top of the page.

How to change Maven local repository in eclipse

Here is settings.xml --> C:\maven\conf\settings.xml

Releasing memory in Python

First, you may want to install glances:

sudo apt-get install python-pip build-essential python-dev lm-sensors 
sudo pip install psutil logutils bottle batinfo https://bitbucket.org/gleb_zhulik/py3sensors/get/tip.tar.gz zeroconf netifaces pymdstat influxdb elasticsearch potsdb statsd pystache docker-py pysnmp pika py-cpuinfo bernhard
sudo pip install glances

Then run it in the terminal!

glances

In your Python code, add at the begin of the file, the following:

import os
import gc # Garbage Collector

After using the "Big" variable (for example: myBigVar) for which, you would like to release memory, write in your python code the following:

del myBigVar
gc.collect()

In another terminal, run your python code and observe in the "glances" terminal, how the memory is managed in your system!

Good luck!

P.S. I assume you are working on a Debian or Ubuntu system

How to get diff between all files inside 2 folders that are on the web?

Once you have the source trees, e.g.

diff -ENwbur repos1/ repos2/ 

Even better

diff -ENwbur repos1/ repos2/  | kompare -o -

and have a crack at it in a good gui tool :)

  • -Ewb ignore the bulk of whitespace changes
  • -N detect new files
  • -u unified
  • -r recurse

IOS: verify if a point is inside a rect

In Swift that would look like this:

let point = CGPointMake(20,20)
let someFrame = CGRectMake(10,10,100,100)
let isPointInFrame = CGRectContainsPoint(someFrame, point)

Swift 3 version:

let point = CGPointMake(20,20)
let someFrame = CGRectMake(10,10,100,100)
let isPointInFrame = someFrame.contains(point)

Link to documentation . Please remember to check containment if both are in the same coordinate system if not then conversions are required (some example)

How to break long string to multiple lines

you may simply create your string in multiple steps, a bit redundant but it keeps the code readable and maintain sanity while debugging or editing

SqlQueryString = "Insert into Employee values(" 
SqlQueryString = SqlQueryString & txtEmployeeNo.Value & " ,"
SqlQueryString = SqlQueryString & " '" & txtEmployeeNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtContractStartDate.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtSeatNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtContractStartDate.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtSeatNo.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtFloor.Value & "',"
SqlQueryString = SqlQueryString & " '" & txtLeaves.Value & "' )"

Remove quotes from String in Python

Just use string methods .replace() if they occur throughout, or .strip() if they only occur at the start and/or finish:

a = '"sajdkasjdsak" "asdasdasds"' 

a = a.replace('"', '')
'sajdkasjdsak asdasdasds'

# or, if they only occur at start and end...
a = a.strip('\"')
'sajdkasjdsak" "asdasdasds'

# or, if they only occur at start...
a = a.lstrip('\"')

# or, if they only occur at end...
a = a.rstrip('\"')

error: Unable to find vcvarsall.bat

I had this problem using Python 3.4.1 on Windows 7 x64, and unfortunately the packages I needed didn't have suitable exe or wheels that I could use. This system requires a few 'workarounds', which are detailed below (and TLDR at bottom).

Using the info in Jaxrtech's answer above, I determined I needed Visual Studio C++ 2010 (sys.version return MSC v.1600), so I installed Visual C++ 2010 Express from the link in his answer, which is http://go.microsoft.com/?linkid=9709949. I installed everything with updates, but as you can read below, this was a mistake. Only the original version of Express should be installed at this time (no updated anything).

vcvarsall.bat was now present, but there was a new error when installing the package, query_vcvarsall raise ValueError(str(list(result.keys())))ValueError: [u'path']. There are other stackoverflow questions with this error, such as Errors while building/installing C module for Python 2.7

I determined from that answer that 2010 Express only installs 32-bit compilers. To get 64-bit (and other) compilers, you need to install Windows 7.1 SDK. See http://msdn.microsoft.com/en-us/windowsserver/bb980924.aspx

This would not install for me though, and the installer returned the error installation failed with return code 5100. I found the solution at the following link: http://support.microsoft.com/kb/2717426. In short, if newer versions of x86 and x64 Microsoft Visual C++ 2010 Redistributable's are installed, they conflict with the ones in SDK installer, and need uninstalling first.

The SDK then installed, but I noticed vcvars64.bat still did not exist in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin, nor its subfolders. vcvarsall.bat runs the vcvars64 batch file, so without it, the python package still wouldn't install (I forgot the error that was shown at this time).

I then found some instructions here: http://www.cryptohaze.com/wiki/index.php/Windows_7_Build_Setup#Download_VS_2010_and_Windows_SDK_7.1 Following the instructions, I had already installed Express and 7.1 SDK, so installed SDK 7.1 SP1, and did the missing header file fix. I then manually created vcvars64.bat with the content CALL setenv /x64. I will paste all those instructions here, so they don't get lost.

Step 1 is to download Visual Studio Express 2010.

http://www.microsoft.com/visualstudio/en-us/products/2010-editions/express is a good place to start. Download the installer, and run it (vc_web.exe). You don't need the SQL 2008 additional download.

You'll also need the Windows SDK (currently 7.1) for the 64-bit compilers - unless you want to do 32-bit only builds, which are not fully supported...

http://www.microsoft.com/en-us/download/details.aspx?id=8279 is a good starting point to download this - you'll want to run winsdk_web.exe when downloaded!

The default install here is just fine.

Finally, download and install the Windows SDK 7.1 SP1 update: http://www.microsoft.com/en-us/download/details.aspx?id=4422

And, to fix missing header file, VS2010 SP1. http://www.microsoft.com/downloads/en/confirmation.aspx?FamilyID=75568aa6-8107-475d-948a-ef22627e57a5

And, bloody hell, fix the missing batch file for VS2010 Express. This is getting downright absurd.

In C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64, create "vcvars64.bat" with the following (you will need to be running as administrator):

CALL setenv /x64

My python package still did not install (can't recall error). I then found some instructions (copied below) to use the special SDK 7.1 Command Prompt, see: https://mail.python.org/pipermail/distutils-sig/2012-February/018300.html

Never mind this question. Somebody here noticed this item on the menu: Start->All Programs->Microsoft Windows SDK v7.1 ->Windows SDK 7.1 Command Prompt

This runs a batch job that appears to set up a working environment for the compiler. From that prompt, you can type "setup.py build" or "setup.py install".

I opened the Windows SDK 7.1 Command Prompt as instructed, and used it to run easy_install on the python package. And at last, success!


TLDR;

  1. Install Visual Studio Express 2010 (preferably without updated redistributables or SQL server).
  2. Install Windows 7.1 SDK
  3. Instal SDK 7.1 SP1 update, and VS2010 SP1 header file fix (this step may not be required).
  4. Manually create C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64\vcvars64.bat with content CALL setenv /x64
  5. Start->All Programs->Microsoft Windows SDK v7.1 ->Windows SDK 7.1 Command Prompt to open special x64 command prompt, which can then be used with python/easy_install/pip/etc (including those in virtual_envs).

How to state in requirements.txt a direct github source

requirements.txt allows the following ways of specifying a dependency on a package in a git repository as of pip 7.0:1

[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e [email protected]:SomeProject#egg=SomeProject (deprecated as of Jan 2020)

For Github that means you can do (notice the omitted -e):

git+git://github.com/mozilla/elasticutils.git#egg=elasticutils

Why the extra answer?
I got somewhat confused by the -e flag in the other answers so here's my clarification:

The -e or --editable flag means that the package is installed in <venv path>/src/SomeProject and thus not in the deeply buried <venv path>/lib/pythonX.X/site-packages/SomeProject it would otherwise be placed in.2

Documentation

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

For anyone going through these issues and uneasy about disabling a whole set of checks, there is a way to pass your own custom signatures to Intelephense.

Copied from Intelephese repo's comment (by @KapitanOczywisty):
https://github.com/bmewburn/vscode-intelephense/issues/892#issuecomment-565852100

For single workspace it is very simple, you have to create .php file with all signatures and intelephense will index them.

If you want add stubs globally, you still can, but I'm not sure if it's intended feature. Even if intelephense.stubs throws warning about incorrect value you can in fact put there any folder name.

{   
   "intelephense.stubs": [
       // ...
       "/path/to/your/stub"   
   ] 
} 

Note: stubs are refreshed with this setting change.

You can take a look at build-in stubs here: https://github.com/JetBrains/phpstorm-stubs

In my case, I needed dspec's describe, beforeEach, it... to don't be highlighted as errors, so I just included the file with the signatures /directories_and_paths/app/vendor/bin/dspec in my VSCode's workspace settings, which had the function declarations I needed:

function describe($description = null, \Closure $closure = null) {
}

function it($description, \Closure $closure) {
}

// ... and so on

Python DNS module import error

This issue can be generated by Symantec End Point Protection (SEP). And I suspect most EPP products could potentially impact your running of scripts.

If SEP is disabled, the script will run instantly.

Therefore you may need to update the SEP policy to not block python scripts accessing stuff.

Batch file. Delete all files and folders in a directory

set "DIR_TO_DELETE=your_path_to_the_folder"

IF EXIST %DIR_TO_DELETE% (
    FOR /D %%p IN ("%DIR_TO_DELETE%\*.*") DO rmdir "%%p" /S /Q
    del %DIR_TO_DELETE%\*.* /F /Q
)

How to store JSON object in SQLite database

Convert JSONObject into String and save as TEXT/ VARCHAR. While retrieving the same column convert the String into JSONObject.

For example

Write into DB

String stringToBeInserted = jsonObject.toString();
//and insert this string into DB

Read from DB

String json = Read_column_value_logic_here
JSONObject jsonObject = new JSONObject(json);

Change background of LinearLayout in Android

If your using a background resource and wish to change the resource out you can use setBackgroundResource() function.

ui_item.setBackgroundResource(R.drawable.myResource)

A background resource in XML would look like:

<LinearLayout
                android:id="@+id/ui_item"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/background_01"
                android:orientation="vertical">

Effectively use async/await with ASP.NET Web API

I am not very sure whether it will make any difference in performance of my API.

Bear in mind that the primary benefit of asynchronous code on the server side is scalability. It won't magically make your requests run faster. I cover several "should I use async" considerations in my article on async ASP.NET.

I think your use case (calling other APIs) is well-suited for asynchronous code, just bear in mind that "asynchronous" does not mean "faster". The best approach is to first make your UI responsive and asynchronous; this will make your app feel faster even if it's slightly slower.

As far as the code goes, this is not asynchronous:

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
  var response = _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
  return Task.FromResult(response);
}

You'd need a truly asynchronous implementation to get the scalability benefits of async:

public async Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
  return await _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}

Or (if your logic in this method really is just a pass-through):

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
  return _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}

Note that it's easier to work from the "inside out" rather than the "outside in" like this. In other words, don't start with an asynchronous controller action and then force downstream methods to be asynchronous. Instead, identify the naturally asynchronous operations (calling external APIs, database queries, etc), and make those asynchronous at the lowest level first (Service.ProcessAsync). Then let the async trickle up, making your controller actions asynchronous as the last step.

And under no circumstances should you use Task.Run in this scenario.

How can I make a checkbox readonly? not disabled?

You may simply add onclick="return false" - this will stop browser executing default action (checkbox checked/not checked will not be changed)

How to kill all processes with a given partial name?

If you judge pkill -f PATTERN a bit too dangerous, I wrote ezkill a bash script that prompt you to choose which processes amongst those that match the PATTERN you want to kill.

Converting string to Date and DateTime

$d = new DateTime('10-16-2003');

$timestamp = $d->getTimestamp(); // Unix timestamp
$formatted_date = $d->format('Y-m-d'); // 2003-10-16

Edit: you can also pass a DateTimeZone to DateTime() constructor to ensure the creation of the date for the desired time zone, not the server default one.

AWS EFS vs EBS vs S3 (differences & when to use?)

AWS EFS, EBS and S3. From Functional Standpoint, here is the difference

EFS:

  1. Network filesystem :can be shared across several Servers; even between regions. The same is not available for EBS case. This can be used esp for storing the ETL programs without the risk of security

  2. Highly available, scalable service.

  3. Running any application that has a high workload, requires scalable storage, and must produce output quickly.

  4. It can provide higher throughput. It match sudden file system growth, even for workloads up to 500,000 IOPS or 10 GB per second.

  5. Lift-and-shift application support: EFS is elastic, available, and scalable, and enables you to move enterprise applications easily and quickly without needing to re-architect them.

  6. Analytics for big data: It has the ability to run big data applications, which demand significant node throughput, low-latency file access, and read-after-write operations.

EBS:

  1. for NoSQL databases, EBS offers NoSQL databases the low-latency performance and dependability they need for peak performance.

S3:

Robust performance, scalability, and availability: Amazon S3 scales storage resources free from resource procurement cycles or investments upfront.

2)Data lake and big data analytics: Create a data lake to hold raw data in its native format, then using machine learning tools, analytics to draw insights.

  1. Backup and restoration: Secure, robust backup and restoration solutions
  2. Data archiving
  3. S3 is an object store good at storing vast numbers of backups or user files. Unlike EBS or EFS, S3 is not limited to EC2. Files stored within an S3 bucket can be accessed programmatically or directly from services such as AWS CloudFront. Many websites use it to hold their content and media files, which may be served efficiently via AWS CloudFront.

Can I Set "android:layout_below" at Runtime Programmatically?

Yes:

RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); 
params.addRule(RelativeLayout.BELOW, R.id.below_id);
viewToLayout.setLayoutParams(params);

First, the code creates a new layout params by specifying the height and width. The addRule method adds the equivalent of the xml properly android:layout_below. Then you just call View#setLayoutParams on the view you want to have those params.

Android: Create a toggle button with image and no text

I know this is a little late, however for anyone interested, I've created a custom component that is basically a toggle image button, the drawable can have states as well as the background

https://gist.github.com/akshaydashrath/9662072

Delete last N characters from field in a SQL Server database

UPDATE mytable SET column=LEFT(column, LEN(column)-5)

Removes the last 5 characters from the column (every row in mytable)

jQuery change input text value

Just adding to Jason's answer, the . selector is only for classes. If you want to select something other than the element, id, or class, you need to wrap it in square brackets.

e.g.

$('element[attr=val]')

Python Progress Bar

I like Brian Khuu's answer for its simplicity and not needing external packages. I changed it a bit so I'm adding my version here:

import sys
import time


def updt(total, progress):
    """
    Displays or updates a console progress bar.

    Original source: https://stackoverflow.com/a/15860757/1391441
    """
    barLength, status = 20, ""
    progress = float(progress) / float(total)
    if progress >= 1.:
        progress, status = 1, "\r\n"
    block = int(round(barLength * progress))
    text = "\r[{}] {:.0f}% {}".format(
        "#" * block + "-" * (barLength - block), round(progress * 100, 0),
        status)
    sys.stdout.write(text)
    sys.stdout.flush()


runs = 300
for run_num in range(runs):
    time.sleep(.1)
    updt(runs, run_num + 1)

It takes the total number of runs (total) and the number of runs processed so far (progress) assuming total >= progress. The result looks like this:

[#####---------------] 27%

How to extract file name from path?

Dim sFilePath$, sFileName$
sFileName = Split(sFilePath, "\")(UBound(Split(sFilePath, "\")))

How do I get the value of text input field using JavaScript?

If you are using jQuery then by using plugin formInteract, you just need to do this:

// Just keep the HTML as it is.

<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>

At bottom of the page just include this plugin file and write this code:

// Initialize one time at the bottom of the page.
var search= $("#searchTxt).formInteract();

search.getAjax("http://www.myurl.com/search/", function(rsp){
    // Now do whatever you want to with your response
});

Or if using a parameterized URL then use this:

$.get("http://www.myurl.com/search/"+search.get().searchTxt, {}, function(rsp){
    // Now do work with your response;
})

Here is the link to project https://bitbucket.org/ranjeet1985/forminteract

You can use this plugin for many purposes like getting the value of a form, putting values into a form, validation of forms and many more. You can see some example of code in the index.html file of the project.

Of course I am the author of this project and all are welcome to make it better.

Java: get greatest common divisor

If you are using Java 1.5 or later then this is an iterative binary GCD algorithm which uses Integer.numberOfTrailingZeros() to reduce the number of checks and iterations required.

public class Utils {
    public static final int gcd( int a, int b ){
        // Deal with the degenerate case where values are Integer.MIN_VALUE
        // since -Integer.MIN_VALUE = Integer.MAX_VALUE+1
        if ( a == Integer.MIN_VALUE )
        {
            if ( b == Integer.MIN_VALUE )
                throw new IllegalArgumentException( "gcd() is greater than Integer.MAX_VALUE" );
            return 1 << Integer.numberOfTrailingZeros( Math.abs(b) );
        }
        if ( b == Integer.MIN_VALUE )
            return 1 << Integer.numberOfTrailingZeros( Math.abs(a) );

        a = Math.abs(a);
        b = Math.abs(b);
        if ( a == 0 ) return b;
        if ( b == 0 ) return a;
        int factorsOfTwoInA = Integer.numberOfTrailingZeros(a),
            factorsOfTwoInB = Integer.numberOfTrailingZeros(b),
            commonFactorsOfTwo = Math.min(factorsOfTwoInA,factorsOfTwoInB);
        a >>= factorsOfTwoInA;
        b >>= factorsOfTwoInB;
        while(a != b){
            if ( a > b ) {
                a = (a - b);
                a >>= Integer.numberOfTrailingZeros( a );
            } else {
                b = (b - a);
                b >>= Integer.numberOfTrailingZeros( b );
            }
        }
        return a << commonFactorsOfTwo;
    }
}

Unit test:

import java.math.BigInteger;
import org.junit.Test;
import static org.junit.Assert.*;

public class UtilsTest {
    @Test
    public void gcdUpToOneThousand(){
        for ( int x = -1000; x <= 1000; ++x )
            for ( int y = -1000; y <= 1000; ++y )
            {
                int gcd = Utils.gcd(x, y);
                int expected = BigInteger.valueOf(x).gcd(BigInteger.valueOf(y)).intValue();
                assertEquals( expected, gcd );
            }
    }

    @Test
    public void gcdMinValue(){
        for ( int x = 0; x < Integer.SIZE-1; x++ ){
            int gcd = Utils.gcd(Integer.MIN_VALUE,1<<x);
            int expected = BigInteger.valueOf(Integer.MIN_VALUE).gcd(BigInteger.valueOf(1<<x)).intValue();
            assertEquals( expected, gcd );
        }
    }
}

How to set iPhone UIView z index?

We can use zPosition in ios

if we have a view named salonDetailView eg : @IBOutlet weak var salonDetailView: UIView!

In my case see the image

and have UIView for GMSMapView eg : @IBOutlet weak var mapViewUI: GMSMapView!

To show the View salonDetailView upper of the mapViewUI

use zPosition as below

salonDetailView.layer.zPosition = 1

invalid use of non-static member function

You must make Foo::comparator static or wrap it in a std::mem_fun class object. This is because lower_bounds() expects the comparer to be a class of object that has a call operator, like a function pointer or a functor object. Also, if you are using C++11 or later, you can also do as dwcanillas suggests and use a lambda function. C++11 also has std::bind too.

Examples:

// Binding:
std::lower_bounds(first, last, value, std::bind(&Foo::comparitor, this, _1, _2));
// Lambda:
std::lower_bounds(first, last, value, [](const Bar & first, const Bar & second) { return ...; });

Using Sockets to send and receive data

the easiest way to do this is to wrap your sockets in ObjectInput/OutputStreams and send serialized java objects. you can create classes which contain the relevant data, and then you don't need to worry about the nitty gritty details of handling binary protocols. just make sure that you flush your object streams after you write each object "message".

Tar error: Unexpected EOF in archive

May be you have ftped the file in ascii mode instead of binary mode ? If not, this might help.

$ gunzip myarchive.tar.gz

And then untar the resulting tar file using

$ tar xvf myarchive.tar

Hope this helps.

Mac zip compress without __MACOSX folder?

When I had this problem I've done it from command line:

zip file.zip uncompressed

EDIT, after many downvotes: I was using this option for some time ago and I don't know where I learnt it, so I can't give you a better explanation. Chris Johnson's answer is correct, but I won't delete mine. As one comment says, it's more accurate to what OP is asking, as it compress without those files, instead of removing them from a compressed file. I find it easier to remember, too.

Deserialize from string instead TextReader

public static string XmlSerializeToString(this object objectInstance)
{
    var serializer = new XmlSerializer(objectInstance.GetType());
    var sb = new StringBuilder();

    using (TextWriter writer = new StringWriter(sb))
    {
        serializer.Serialize(writer, objectInstance);
    }

    return sb.ToString();
}

public static T XmlDeserializeFromString<T>(this string objectData)
{
    return (T)XmlDeserializeFromString(objectData, typeof(T));
}

public static object XmlDeserializeFromString(this string objectData, Type type)
{
    var serializer = new XmlSerializer(type);
    object result;

    using (TextReader reader = new StringReader(objectData))
    {
        result = serializer.Deserialize(reader);
    }

    return result;
}

To use it:

//Make XML
var settings = new ObjectCustomerSettings();
var xmlString = settings.XmlSerializeToString();

//Make Object
var settings = xmlString.XmlDeserializeFromString<ObjectCustomerSettings>(); 

Is there a CSS parent selector?

It's now 2019, and the latest draft of the CSS Nesting Module actually has something like this. Introducing @nest at-rules.

3.2. The Nesting At-Rule: @nest

While direct nesting looks nice, it is somewhat fragile. Some valid nesting selectors, like .foo &, are disallowed, and editing the selector in certain ways can make the rule invalid unexpectedly. As well, some people find the nesting challenging to distinguish visually from the surrounding declarations.

To aid in all these issues, this specification defines the @nest rule, which imposes fewer restrictions on how to validly nest style rules. Its syntax is:

@nest = @nest <selector> { <declaration-list> }

The @nest rule functions identically to a style rule: it starts with a selector, and contains declarations that apply to the elements the selector matches. The only difference is that the selector used in a @nest rule must be nest-containing, which means it contains a nesting selector in it somewhere. A list of selectors is nest-containing if all of its individual complex selectors are nest-containing.

(Copy and pasted from the URL above).

Example of valid selectors under this specification:

.foo {
  color: red;
  @nest & > .bar {
    color: blue;
  }
}
/* Equivalent to:
   .foo { color: red; }
   .foo > .bar { color: blue; }
 */

.foo {
  color: red;
  @nest .parent & {
    color: blue;
  }
}
/* Equivalent to:
   .foo { color: red; }
   .parent .foo { color: blue; }
 */

.foo {
  color: red;
  @nest :not(&) {
    color: blue;
  }
}
/* Equivalent to:
   .foo { color: red; }
   :not(.foo) { color: blue; }
 */

Javascript Debugging line by line using Google Chrome

Assuming you're running on a Windows machine...

  1. Hit the F12 key
  2. Select the Scripts, or Sources, tab in the developer tools
  3. Click the little folder icon in the top level
  4. Select your JavaScript file
  5. Add a breakpoint by clicking on the line number on the left (adds a little blue marker)
  6. Execute your JavaScript

Then during execution debugging you can do a handful of stepping motions...

  • F8 Continue: Will continue until the next breakpoint
  • F10 Step over: Steps over next function call (won't enter the library)
  • F11 Step into: Steps into the next function call (will enter the library)
  • Shift + F11 Step out: Steps out of the current function

Update

After reading your updated post; to debug your code I would recommend temporarily using the jQuery Development Source Code. Although this doesn't directly solve your problem, it will allow you to debug more easily. For what you're trying to achieve I believe you'll need to step-in to the library, so hopefully the production code should help you decipher what's happening.

Searching in a ArrayList with custom objects for certain strings

Probably something like:

ArrayList<DataPoint> myList = new ArrayList<DataPoint>();
//Fill up myList with your Data Points

//Traversal
for(DataPoint myPoint : myList) {
    if(myPoint.getName() != null && myPoint.getName().equals("Michael Hoffmann")) {
        //Process data do whatever you want
        System.out.println("Found it!");
     }
}

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Print a variable in hexadecimal in Python

Use

print " ".join("0x%s"%my_string[i:i+2] for i in range(0, len(my_string), 2))

like this:

>>> my_string = "deadbeef"
>>> print " ".join("0x%s"%my_string[i:i+2] for i in range(0, len(my_string), 2))
0xde 0xad 0xbe 0xef
>>>

On an unrelated side note ... using string as a variable name even as an example variable name is very bad practice.

How to read multiple Integer values from a single line of input in Java?

There is more than one way to do that but simple one is using String.split(" ") this is a method of String class that separate words by a spacial character(s) like " " (space)


All we need to do is save this word in an Array of Strings.

Warning : you have to use scan.nextLine(); other ways its not going to work(Do not use scan.next();

String user_input = scan.nextLine();
String[] stringsArray = user_input.split(" ");

now we need to convert these strings to Integers. create a for loop and convert every single index of stringArray :

for (int i = 0; i < stringsArray.length; i++) {
    int x = Integer.parseInt(stringsArray[i]);
    // Do what you want to do with these int value here
}

Best way is converting the whole stringArray to an intArray :

 int[] intArray = new int[stringsArray.length];
 for (int i = 0; i < stringsArray.length; i++) {
    intArray[i] = Integer.parseInt(stringsArray[i]);
 }

now do any proses you want like print or sum or... on intArray


The whole code will be like this :

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        String user_input = scan.nextLine();
        String[] stringsArray = user_input.split(" ");

        int[] intArray = new int[stringsArray.length];
        for (int i = 0; i < stringsArray.length; i++) {
            intArray[i] = Integer.parseInt(stringsArray[i]);
        }
    }
}

How to vertically align elements in a div?

By default h1 is a block element and will render on the line after the first img, and will cause the second img to appear on the line following the block.

To stop this from occurring you can set the h1 to have inline flow behaviour:

#header > h1 { display: inline; }

As for absolutely positioning the img inside the div, you need to set the containing div to have a "known size" before this will work properly. In my experience, you also need to change the position attribute away from the default - position: relative works for me:

#header { position: relative; width: 20em; height: 20em; }
#img-for-abs-positioning { position: absolute; top: 0; left: 0; }

If you can get that to work, you might want to try progressively removing the height, width, position attributes from div.header to get the minimal required attributes to get the effect you want.

UPDATE:

Here is a complete example that works on Firefox 3:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <title>Example of vertical positioning inside a div</title>
        <style type="text/css">
            #header > h1 { display: inline; }
            #header { border: solid 1px red; 
                      position: relative; }
            #img-for-abs-positioning { position: absolute;
                                       bottom: -1em; right: 2em; }
        </style>
    </head>

    <body>
        <div id="header">
            <img src="#" alt="Image 1" width="40" height="40" />
            <h1>Header</h1>
            <img src="#" alt="Image 2" width="40" height="40" 
                 id="img-for-abs-positioning" />
        </div>
    </body>
</html>

How do I create a basic UIButton programmatically?

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
       action:@selector(aMethod:)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];

How to listen to route changes in react router v4?

With hooks:

import { useEffect } from 'react'
import { withRouter } from 'react-router-dom'
import { history as historyShape } from 'react-router-prop-types'

const DebugHistory = ({ history }) => {
  useEffect(() => {
    console.log('> Router', history.action, history.location])
  }, [history.location.key])

  return null
}

DebugHistory.propTypes = { history: historyShape }

export default withRouter(DebugHistory)

Import and render as <DebugHistory> component

ERROR 1064 (42000): You have an error in your SQL syntax;

It is varchar and not var_char

CREATE DATABASE IF NOT EXISTS courses;

USE courses;

CREATE TABLE IF NOT EXISTS teachers(
    id INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
    name VARCHAR(50) NOT NULL,
    addr VARCHAR(255) NOT NULL,
    phone INT NOT NULL
);

You should use a SQL tool to visualize possbile errors like MySQL Workbench.

Save file to specific folder with curl command

This option comes in curl 7.73.0:

curl --create-dirs -O --output-dir /tmp/receipes https://example.com/pancakes.jpg

JavaScript for handling Tab Key press

Given this piece of HTML code:

<a href='https://facebook.com/'>Facebook</a>
<a href='https://google.ca/'>Google</a>
<input type='text' placeholder='an input box'>

We can use this JavaScript:

function checkTabPress(e) {
    'use strict';
    var ele = document.activeElement;

    if (e.keyCode === 9 && ele.nodeName.toLowerCase() === 'a') {
        console.log(ele.href);
    }
}

document.addEventListener('keyup', function (e) {
    checkTabPress(e);
}, false);

I have bound an event listener to the document element for the keyUp event, which triggers a function to check if the Tab key was pressed (or technically, released).

The function checks the currently focused element and whether the NodeName is a. If so, it enters the if block and, in my case, writes the value of the href property to the JavaScript console.

Here's a jsFiddle

Convert hex string to int in Python

For any given string s:

int(s, 16)

Is it possible to get an Excel document's row count without loading the entire document into memory?

Adding on to what Hubro said, apparently get_highest_row() has been deprecated. Using the max_row and max_column properties returns the row and column count. For example:

    wb = load_workbook(path, use_iterators=True)
    sheet = wb.worksheets[0]

    row_count = sheet.max_row
    column_count = sheet.max_column

Custom pagination view in Laravel 5

Here is an easy solution of customized Laravel pagination both server and client side code is included.

Assuming using Laravel 5.2 and the following included view:

@include('pagination.default', ['pager' => $data])

Features

  • Showing Previous and Next buttons and disable them when not applicable.
  • Showing First and Last page buttons.
  • Example: ( Previous|First|...|10|11|12|13|14|15|16|17|18|...|Last|Next )

default.blade.php

@if ($paginator->last_page > 1)
<ul class="pagination pg-blue">
    <li class="page-item {{($paginator->current_page == 1)?'disabled':''}}">
        <a class="page-link" tabindex="-1" href="{{ '/locate-vendor/'}}{{ substr($paginator->prev_page_url,7) }}">
            Previous
        </a>
    </li>

    <li class="page-item {{($paginator->current_page == 1)?'disabled':''}}">
        <a class="page-link" tabindex="-1" href="{{ '/locate-vendor/1'}}">
            First
        </a>
    </li>

    @if ( $paginator->current_page > 5 )
    <li class="page-item">
        <a class="page-link" tabindex="-1">...</a>
    </li>
    @endif

    @for ($i = 1; $i <= $paginator->last_page; $i++)
        @if ( ($i > ($paginator->current_page - 5)) && ($i < ($paginator->current_page + 5)) )
        <li class="page-item {{($paginator->current_page == $i)?'active':''}}">
            <a class="page-link" href="{{'/locate-vendor/'}}{{$i}}">{{$i}}</a>
        </li>
        @endif
    @endfor

    @if ( $paginator->current_page < ($paginator->last_page - 4) )
    <li class="page-item">
        <a class="page-link" tabindex="-1">...</a>
    </li>
    @endif

    <li class="page-item {{($paginator->current_page==$paginator->last_page)?'disabled':''}}">
        <a class="page-link" href="{{'/locate-vendor/'}}{{$paginator->last_page}}">
            Last
        </a>
    </li>

    <li class="page-item {{($paginator->current_page==$paginator->last_page)?'disabled':''}}">
        <a class="page-link" href="{{'/locate-vendor/'}}{{substr($paginator->next_page_url,7)}}">
            Next
        </a>
    </li>
</ul>
@endif

Server Side Controller Function

public function getVendors (Request $request)
    {
        $inputs = $request->except('token');
        $perPage  = (isset($inputs['per_page']) && $inputs['per_page']>0)?$inputs['per_page']:$this->perPage;   
        $currentPage = (isset($inputs['page']) && $inputs['page']>0)?$inputs['page']:$this->page;   
        $slice_init = ($currentPage == 1)?0:(($currentPage*$perPage)-$perPage);

        $totalVendors = DB::table('client_broker')
                           ->whereIn('client_broker_type_id', [1, 2])
                           ->where('status_id', '1')
                           ->whereNotNull('client_broker_company_name')
                           ->whereNotNull('client_broker_email')
                           ->select('client_broker_id', 'client_broker_company_name','client_broker_email')
                           ->distinct()
                           ->count();

        $vendors = DB::table('client_broker')
                           ->whereIn('client_broker_type_id', [1, 2])
                           ->where('status_id', '1')
                           ->whereNotNull('client_broker_company_name')
                           ->whereNotNull('client_broker_email')
                           ->select('client_broker_id', 'client_broker_company_name','client_broker_email')
                           ->distinct()
                           ->skip($slice_init)
                           ->take($perPage)
                           ->get();

        $vendors = new LengthAwarePaginator($vendors, $totalVendors, $perPage, $currentPage);

        if ($totalVendors) {
            $response = ['status' => 1, 'totalVendors' => $totalVendors, 'pageLimit'=>$perPage, 'data' => $vendors,  'Message' => 'Vendors Details Found.'];
        } else {
            $response = ['status' => 0, 'totalVendors' => 0, 'data' => [], 'pageLimit'=>'',  'Message' => 'Vendors Details not Found.'];
        }
        return response()->json($response, 200);

    }

How can I loop through all rows of a table? (MySQL)

Mr Purple's example I used in mysql trigger like that,

begin
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
Select COUNT(*) from user where deleted_at is null INTO n;
SET i=0;
WHILE i<n DO 
  INSERT INTO user_notification(notification_id,status,userId)values(new.notification_id,1,(Select userId FROM user LIMIT i,1)) ;
  SET i = i + 1;
END WHILE;
end

How to generate a random number between a and b in Ruby?

rand(3..10)

Kernel#rand

When max is a Range, rand returns a random number where range.member?(number) == true.

do <something> N times (declarative syntax)

Given a function something:

function something() { console.log("did something") }

And a new method times added to the Array prototype:

Array.prototype.times = function(f){
  for(v of this) 
    for(var _ of Array(v))
      f();
}

This code:

[1,2,3].times(something)

Outputs this:

did something
did something
did something
did something
did something
did something

Which I think answers your updated question (5 years later) but I wonder how useful it is to have this work on an array? Wouldn't the effect be the same as calling [6].times(something), which in turn could be written as:

for(_ of Array(6)) something();

(although the use of _ as a junk variable will probably clobber lodash or underscore if you're using it)

Renaming columns in Pandas

One line or Pipeline solutions

I'll focus on two things:

  1. OP clearly states

    I have the edited column names stored it in a list, but I don't know how to replace the column names.

    I do not want to solve the problem of how to replace '$' or strip the first character off of each column header. OP has already done this step. Instead I want to focus on replacing the existing columns object with a new one given a list of replacement column names.

  2. df.columns = new where new is the list of new columns names is as simple as it gets. The drawback of this approach is that it requires editing the existing dataframe's columns attribute and it isn't done inline. I'll show a few ways to perform this via pipelining without editing the existing dataframe.


Setup 1
To focus on the need to rename of replace column names with a pre-existing list, I'll create a new sample dataframe df with initial column names and unrelated new column names.

df = pd.DataFrame({'Jack': [1, 2], 'Mahesh': [3, 4], 'Xin': [5, 6]})
new = ['x098', 'y765', 'z432']

df

   Jack  Mahesh  Xin
0     1       3    5
1     2       4    6

Solution 1
pd.DataFrame.rename

It has been said already that if you had a dictionary mapping the old column names to new column names, you could use pd.DataFrame.rename.

d = {'Jack': 'x098', 'Mahesh': 'y765', 'Xin': 'z432'}
df.rename(columns=d)

   x098  y765  z432
0     1     3     5
1     2     4     6

However, you can easily create that dictionary and include it in the call to rename. The following takes advantage of the fact that when iterating over df, we iterate over each column name.

# Given just a list of new column names
df.rename(columns=dict(zip(df, new)))

   x098  y765  z432
0     1     3     5
1     2     4     6

This works great if your original column names are unique. But if they are not, then this breaks down.


Setup 2
Non-unique columns

df = pd.DataFrame(
    [[1, 3, 5], [2, 4, 6]],
    columns=['Mahesh', 'Mahesh', 'Xin']
)
new = ['x098', 'y765', 'z432']

df

   Mahesh  Mahesh  Xin
0       1       3    5
1       2       4    6

Solution 2
pd.concat using the keys argument

First, notice what happens when we attempt to use solution 1:

df.rename(columns=dict(zip(df, new)))

   y765  y765  z432
0     1     3     5
1     2     4     6

We didn't map the new list as the column names. We ended up repeating y765. Instead, we can use the keys argument of the pd.concat function while iterating through the columns of df.

pd.concat([c for _, c in df.items()], axis=1, keys=new) 

   x098  y765  z432
0     1     3     5
1     2     4     6

Solution 3
Reconstruct. This should only be used if you have a single dtype for all columns. Otherwise, you'll end up with dtype object for all columns and converting them back requires more dictionary work.

Single dtype

pd.DataFrame(df.values, df.index, new)

   x098  y765  z432
0     1     3     5
1     2     4     6

Mixed dtype

pd.DataFrame(df.values, df.index, new).astype(dict(zip(new, df.dtypes)))

   x098  y765  z432
0     1     3     5
1     2     4     6

Solution 4
This is a gimmicky trick with transpose and set_index. pd.DataFrame.set_index allows us to set an index inline, but there is no corresponding set_columns. So we can transpose, then set_index, and transpose back. However, the same single dtype versus mixed dtype caveat from solution 3 applies here.

Single dtype

df.T.set_index(np.asarray(new)).T

   x098  y765  z432
0     1     3     5
1     2     4     6

Mixed dtype

df.T.set_index(np.asarray(new)).T.astype(dict(zip(new, df.dtypes)))

   x098  y765  z432
0     1     3     5
1     2     4     6

Solution 5
Use a lambda in pd.DataFrame.rename that cycles through each element of new.
In this solution, we pass a lambda that takes x but then ignores it. It also takes a y but doesn't expect it. Instead, an iterator is given as a default value and I can then use that to cycle through one at a time without regard to what the value of x is.

df.rename(columns=lambda x, y=iter(new): next(y))

   x098  y765  z432
0     1     3     5
1     2     4     6

And as pointed out to me by the folks in sopython chat, if I add a * in between x and y, I can protect my y variable. Though, in this context I don't believe it needs protecting. It is still worth mentioning.

df.rename(columns=lambda x, *, y=iter(new): next(y))

   x098  y765  z432
0     1     3     5
1     2     4     6

how to bind img src in angular 2 in ngFor?

Angular 2.x to 8 Compatible!

You can directly give the source property of the current object in the img src attribute. Please see my code below:

<div *ngFor="let brochure of brochureList">
    <img class="brochure-poster" [src]="brochure.imageUrl" />
</div>

NOTE: You can as well use string interpolation but that is not a legit way to do it. Property binding was created for this very purpose hence better use this.

NOT RECOMMENDED :

<img class="brochure-poster" src="{{brochure.imageUrl}}"/>

Its because that defeats the purpose of property binding. It is more meaningful to use that for setting the properties. {{}} is a normal string interpolation expression, that does not reveal to anyone reading the code that it makes special meaning. Using [] makes it easily to spot the properties that are set dynamically.

Here is my brochureList contains the following json received from service(you can assign it to any variable):

[ {
            "productId":1,
            "productName":"Beauty Products",
            "productCode": "XXXXXX",            
            "description":  "Skin Care",           
            "imageUrl":"app/Images/c1.jpg"
         },
        {
             "productId":2,
            "productName":"Samsung Galaxy J5",
            "productCode": "MOB-124",      
            "description":  "8GB, Gold",
            "imageUrl":"app/Images/c8.jpg"
         }]

AngularJS : Difference between the $observe and $watch methods

If I understand your question right you are asking what is difference if you register listener callback with $watch or if you do it with $observe.

Callback registerd with $watch is fired when $digest is executed.

Callback registered with $observe are called when value changes of attributes that contain interpolation (e.g. attr="{{notJetInterpolated}}").


Inside directive you can use both of them on very similar way:

    attrs.$observe('attrYouWatch', function() {
         // body
    });

or

    scope.$watch(attrs['attrYouWatch'], function() {
         // body
    });

List and kill at jobs on UNIX

at -l to list jobs, which gives return like this:

age2%> at -l
11      2014-10-21 10:11 a hoppent
10      2014-10-19 13:28 a hoppent

atrm 10 kills job 10

Or so my sysadmin told me, and it

'POCO' definition

POCO stands for "Plain Old CLR Object".

How to create a css rule for all elements except one class?

Wouldn't setting a css rule for all tables, and then a subsequent one for tables where class="dojoxGrid" work? Or am I missing something?

How do I update zsh to the latest version?

If you have Homebrew installed, you can do this.

# check the zsh info
brew info zsh

# install zsh
brew install --without-etcdir zsh

# add shell path
sudo vim /etc/shells

# add the following line into the very end of the file(/etc/shells)
/usr/local/bin/zsh

# change default shell
chsh -s /usr/local/bin/zsh

Hope it helps, thanks.

C++ cast to derived class

First of all - prerequisite for downcast is that object you are casting is of the type you are casting to. Casting with dynamic_cast will check this condition in runtime (provided that casted object has some virtual functions) and throw bad_cast or return NULL pointer on failure. Compile-time casts will not check anything and will just lead tu undefined behaviour if this prerequisite does not hold.
Now analyzing your code:

DerivedType m_derivedType = m_baseType;

Here there is no casting. You are creating a new object of type DerivedType and try to initialize it with value of m_baseType variable.

Next line is not much better:

DerivedType m_derivedType = (DerivedType)m_baseType;

Here you are creating a temporary of DerivedType type initialized with m_baseType value.

The last line

DerivedType * m_derivedType = (DerivedType*) & m_baseType;

should compile provided that BaseType is a direct or indirect public base class of DerivedType. It has two flaws anyway:

  1. You use deprecated C-style cast. The proper way for such casts is
    static_cast<DerivedType *>(&m_baseType)
  2. The actual type of casted object is not of DerivedType (as it was defined as BaseType m_baseType; so any use of m_derivedType pointer will result in undefined behaviour.

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript. Just use CSS3. Please take a look at

carousel.carousel-fade

in the CSS of the following examples:

How to create a new database after initally installing oracle database 11g Express Edition?

This link: Creating the Sample Database in Oracle 11g Release 2 is a good example of creating a sample database.

This link: Newbie Guide to Oracle 11g Database Common Problems should help you if you come across some common problems creating your database.

Best of luck!

EDIT: As you are using XE, you should have a DB already created, to connect using SQL*Plus and SQL Developer etc. the info is here: Connecting to Oracle Database Express Edition and Exploring It.

Extract:

Connecting to Oracle Database XE from SQL Developer SQL Developer is a client program with which you can access Oracle Database XE. With Oracle Database XE 11g Release 2 (11.2), you must use SQL Developer version 3.0. This section assumes that SQL Developer is installed on your system, and shows how to start it and connect to Oracle Database XE. If SQL Developer is not installed on your system, see Oracle Database SQL Developer User's Guide for installation instructions.

Note:

For the following procedure: The first time you start SQL Developer on your system, you must provide the full path to java.exe in step 1.

For step 4, you need a user name and password.

For step 6, you need a host name and port.

To connect to Oracle Database XE from SQL Developer:

Start SQL Developer.

For instructions, see Oracle Database SQL Developer User's Guide.

If this is the first time you have started SQL Developer on your system, you are prompted to enter the full path to java.exe (for example, C:\jdk1.5.0\bin\java.exe). Either type the full path after the prompt or browse to it, and then press the key Enter.

The Oracle SQL Developer window opens.

In the navigation frame of the window, click Connections.

The Connections pane appears.

In the Connections pane, click the icon New Connection.

The New/Select Database Connection window opens.

In the New/Select Database Connection window, type the appropriate values in the fields Connection Name, Username, and Password.

For security, the password characters that you type appear as asterisks.

Near the Password field is the check box Save Password. By default, it is deselected. Oracle recommends accepting the default.

In the New/Select Database Connection window, click the tab Oracle.

The Oracle pane appears.

In the Oracle pane:

For Connection Type, accept the default (Basic).

For Role, accept the default.

In the fields Hostname and Port, either accept the defaults or type the appropriate values.

Select the option SID.

In the SID field, type accept the default (xe).

In the New/Select Database Connection window, click the button Test.

The connection is tested. If the connection succeeds, the Status indicator changes from blank to Success.

Description of the illustration success.gif

If the test succeeded, click the button Connect.

The New/Select Database Connection window closes. The Connections pane shows the connection whose name you entered in the Connection Name field in step 4.

You are in the SQL Developer environment.

To exit SQL Developer, select Exit from the File menu.

How to take complete backup of mysql database using mysqldump command line utility

Use '-R' to backup stored procedures, but also keep in mind that if you want a consistent dump of your database while its being modified you need to use --single-transaction (if you only backup innodb) or --lock-all-tables (if you also need myisam tables)

how to get the last character of a string?

Use substr with parameter -1:

"linto.yahoo.com.".substr(-1);

equals "."

Note:

To extract characters from the end of the string, use a negative start number (This does not work in IE 8 and earlier).

How to add a single item to a Pandas Series

Here is another thought n for appending multiple items in one line without changing the name of series. However, this may be not as efficient as the other answer.

>>> df = pd.Series(np.random.random(5), name='random')
>>> df

0    0.363885
1    0.402623
2    0.450449
3    0.172917
4    0.983481
Name: random, dtype: float64


>>> df.to_frame().T.assign(a=3, b=2, c=5).squeeze()

0    0.363885
1    0.402623
2    0.450449
3    0.172917
4    0.983481
a    3.000000
b    2.000000
c    5.000000
Name: random, dtype: float64

Instagram: Share photo from webpage

The short answer is: No. The only way to post images is through the mobile app.

From the Instagram API documentation: http://instagram.com/developer/endpoints/media/

At this time, uploading via the API is not possible. We made a conscious choice not to add this for the following reasons:

  • Instagram is about your life on the go – we hope to encourage photos from within the app. However, in the future we may give whitelist access to individual apps on a case by case basis.
  • We want to fight spam & low quality photos. Once we allow uploading from other sources, it's harder to control what comes into the Instagram ecosystem.

All this being said, we're working on ways to ensure users have a consistent and high-quality experience on our platform.

How to add a button to UINavigationBar?

swift 3

    let cancelBarButton = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(cancelPressed(_:)))
    cancelBarButton.setTitleTextAttributes( [NSFontAttributeName : UIFont.cancelBarButtonFont(),
                                                          NSForegroundColorAttributeName : UIColor.white], for: .normal)
    self.navigationItem.leftBarButtonItem = cancelBarButton


    func cancelPressed(_ sender: UIBarButtonItem ) {
        self.dismiss(animated: true, completion: nil)
    }

How do you delete an ActiveRecord object?

It's destroy and destroy_all methods, like

user.destroy
User.find(15).destroy
User.destroy(15)
User.where(age: 20).destroy_all
User.destroy_all(age: 20)

Alternatively you can use delete and delete_all which won't enforce :before_destroy and :after_destroy callbacks or any dependent association options.

User.delete_all(condition: 'value') will allow you to delete records without a primary key

Note: from @hammady's comment, user.destroy won't work if User model has no primary key.

Note 2: From @pavel-chuchuva's comment, destroy_all with conditions and delete_all with conditions has been deprecated in Rails 5.1 - see guides.rubyonrails.org/5_1_release_notes.html

Is it possible to change the content HTML5 alert messages?

Yes:

<input required title="Enter something OR ELSE." /> 

The title attribute will be used to notify the user of a problem.

Find the PID of a process that uses a port on Windows

Command:

netstat -aon | findstr 4723

Output:

TCP    0.0.0.0:4723           0.0.0.0:0                LISTENING       10396

Now cut the process ID, "10396", using the for command in Windows.

Command:

for /f "tokens=5" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa

Output:

10396

If you want to cut the 4th number of the value means "LISTENING" then command in Windows.

Command:

for /f "tokens=4" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa

Output:

LISTENING

Subtract one day from datetime

SELECT DATEDIFF (
    DAY, 
    DATEDIFF(DAY, @CreatedDate, -1), 
    GETDATE())

Generate a unique id

We can do something like this

string TransactionID = "BTRF"+DateTime.Now.Ticks.ToString().Substring(0, 10);

no debugging symbols found when using gdb

Some Linux distributions don't use the gdb style debugging symbols. (IIRC they prefer dwarf2.)

In general, gcc and gdb will be in sync as to what kind of debugging symbols they use, and forcing a particular style will just cause problems; unless you know that you need something else, use just -g.

Good tool for testing socket connections?

I would go with netcat too , but since you can't use it , here is an alternative : netcat :). You can find netcat implemented in three languages ( python/ruby/perl ) . All you need to do is install the interpreters for the language you choose . Surely , that won't be viewed as a hacking tool .

Here are the links :

Perl implementation

Python implementation

Ruby Implementation

How to invoke function from external .c file in C?

 write main.c like this - 
 caution : while linking both main.0 and ClasseAusiliaria.o should be 
 available to linker.

 #include <stdlib.h>
 #include <stdio.h>
 extern int addizione(int a, int b)

 int main(void)
 {
     int risultato;
     risultato = addizione(5,6);
     printf("%d\n",risultato);
 }

Python: TypeError: cannot concatenate 'str' and 'int' objects

The easiest and least confusing solution:

a = raw_input("Enter a: ")
b = raw_input("Enter b: ")
print "a + b as strings: %s" % a  + b
a = int(a)
b = int(b)
c = a + b
print "a + b as integers: %d" % c

I found this on http://freecodeszone.blogspot.com/

Node.js Web Application examples/tutorials

The closest thing is likely Dav Glass's experimental work using node.js, express and YUI3. Basically, he explains how YUI3 is used to render markup on the server side, then sent to the client where binding to event and data occurs. The beauty is YUI3 is used as-is on both the client and the server. Makes a lot of sense. The one big issue is there is not yet a production ready server-side DOM library.

screencast

DB query builder toArray() laravel 4

try this one

DB::table('user')->where('name','Jhon')->get();

just remove the "=" sign . . . .because you are trying to array just the name 'jhon' . . . . . . . .I hope it's help you . .

Git - What is the difference between push.default "matching" and "simple"

git push can push all branches or a single one dependent on this configuration:

Push all branches

git config --global push.default matching

It will push all the branches to the remote branch and would merge them. If you don't want to push all branches, you can push the current branch if you fully specify its name, but this is much is not different from default.

Push only the current branch if its named upstream is identical

git config --global push.default simple

So, it's better, in my opinion, to use this option and push your code branch by branch. It's better to push branches manually and individually.

Round a divided number in Bash

If you have integer division of positive numbers which rounds toward zero, then you can add one less than the divisor to the dividend to make it round up.

That is to say, replace X / Y with (X + Y - 1) / Y.

Proof:

  • Case 1: X = k * Y (X is integer multiple of Y): In this case, we have (k * Y + Y - 1) / Y, which splits into (k * Y) / Y + (Y - 1) / Y. The (Y - 1)/Y part rounds to zero, and we are left with a quotient of k. This is exactly what we want: when the inputs are divisible, we want the adjusted calculation to still produce the correct exact quotient.

  • Case 2: X = k * Y + m where 0 < m < Y (X is not a multiple of Y). In this case we have a numerator of k * Y + m + Y - 1, or k * Y + Y + m - 1, and we can write the division out as (k * Y)/Y + Y/Y + (m - 1)/Y. Since 0 < m < Y, 0 <= m - 1 < Y - 1, and so the last term (m - 1)/Y goes to zero. We are left with (k * Y)/Y + Y/Y which work out to k + 1. This shows that the behavior rounds up. If we have an X which is a k multiple of Y, if we add just 1 to it, the division rounds up to k + 1.

But this rounding is extremely opposite; all inexact divisions go away from zero. How about something in between?

That can be achieved by "priming" the numerator with Y/2. Instead of X/Y, calculate (X+Y/2)/Y. Instead of proof, let's go empirical on this one:

$ round()
> {
>   echo $((($1 + $2/2) / $2))
> }
$ round 4 10
0
$ round 5 10
1
$ round 6 10
1
$ round 9 10
1
$ round 10 10
1
$ round 14 10
1
$ round 15 10
2

Whenever the divisor is an even, positive number, if the numerator is congruent to half that number, it rounds up, and rounds down if it is one less than that.

For instance, round 6 12 goes to 1, as do all values which are equal to 6, modulo 12, like 18 (which goes to 2) and so on. round 5 12 goes down to 0.

For odd numbers, the behavior is correct. None of the exact rational numbers are midway between two consecutive multiples. For instance, with a denominator of 11 we have 5/11 < 5.5/11 (exact middle) < 6/11; and round 5 11 rounds down, whereas round 6 11 rounds up.

How to fix HTTP 404 on Github Pages?

I also faced this issue, my pages getting 404. And then I added README.md on my repository, and the 404 was gone.

How do I use Join-Path to combine more than two strings into a file path?

Here's something that will do what you'd want when using a string array for the ChildPath.

$path = "C:"
@( "Program Files", "Microsoft Office" ) | %{ $path = Join-Path $path $_ }
Write-Host $path

Which outputs

C:\Program Files\Microsoft Office

The only caveat I found is that the initial value for $path must have a value (cannot be null or empty).

ASP.NET Core Web API Authentication

I have implemented BasicAuthenticationHandler for basic authentication so you can use it with standart attributes Authorize and AllowAnonymous.

public class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOptions>
{
    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var authHeader = (string)this.Request.Headers["Authorization"];

        if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
        {
            //Extract credentials
            string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
            Encoding encoding = Encoding.GetEncoding("iso-8859-1");
            string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));

            int seperatorIndex = usernamePassword.IndexOf(':', StringComparison.OrdinalIgnoreCase);

            var username = usernamePassword.Substring(0, seperatorIndex);
            var password = usernamePassword.Substring(seperatorIndex + 1);

            //you also can use this.Context.Authentication here
            if (username == "test" && password == "test")
            {
                var user = new GenericPrincipal(new GenericIdentity("User"), null);
                var ticket = new AuthenticationTicket(user, new AuthenticationProperties(), Options.AuthenticationScheme);
                return Task.FromResult(AuthenticateResult.Success(ticket));
            }
            else
            {
                return Task.FromResult(AuthenticateResult.Fail("No valid user."));
            }
        }

        this.Response.Headers["WWW-Authenticate"]= "Basic realm=\"yourawesomesite.net\"";
        return Task.FromResult(AuthenticateResult.Fail("No credentials."));
    }
}

public class BasicAuthenticationMiddleware : AuthenticationMiddleware<BasicAuthenticationOptions>
{
    public BasicAuthenticationMiddleware(
       RequestDelegate next,
       IOptions<BasicAuthenticationOptions> options,
       ILoggerFactory loggerFactory,
       UrlEncoder encoder)
       : base(next, options, loggerFactory, encoder)
    {
    }

    protected override AuthenticationHandler<BasicAuthenticationOptions> CreateHandler()
    {
        return new BasicAuthenticationHandler();
    }
}

public class BasicAuthenticationOptions : AuthenticationOptions
{
    public BasicAuthenticationOptions()
    {
        AuthenticationScheme = "Basic";
        AutomaticAuthenticate = true;
    }
}

Registration at Startup.cs - app.UseMiddleware<BasicAuthenticationMiddleware>();. With this code, you can restrict any controller with standart attribute Autorize:

[Authorize(ActiveAuthenticationSchemes = "Basic")]
[Route("api/[controller]")]
public class ValuesController : Controller

and use attribute AllowAnonymous if you apply authorize filter on application level.

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, which allows using aggregation operators such as $addFields, which outputs all existing fields from the input documents and newly added fields:

var new_info = { param2: "val2_new", param3: "val3_new" }

// { some_key: { param1: "val1", param2: "val2", param3: "val3" } }
// { some_key: { param1: "val1", param2: "val2"                 } }
db.collection.update({}, [{ $addFields: { some_key: new_info } }], { multi: true })
// { some_key: { param1: "val1", param2: "val2_new", param3: "val3_new" } }
// { some_key: { param1: "val1", param2: "val2_new", param3: "val3_new" } }
  • The first part {} is the match query, filtering which documents to update (in this case all documents).

  • The second part [{ $addFields: { some_key: new_info } }] is the update aggregation pipeline:

    • Note the squared brackets signifying the use of an aggregation pipeline.
    • Since this is an aggregation pipeline, we can use $addFields.
    • $addFields performs exactly what you need: updating the object so that the new object will overlay / merge with the existing one:
    • In this case, { param2: "val2_new", param3: "val3_new" } will be merged into the existing some_key by keeping param1 untouched and either add or replace both param2 and param3.
  • Don't forget { multi: true }, otherwise only the first matching document will be updated.

How to check if input date is equal to today's date?

There is a simpler solution

if (inputDate.getDate() === todayDate.getDate()) {
   // do stuff
}

like that you don't loose the time attached to inputDate if any

Explicitly calling return in a function or not

Question was: Why is not (explicitly) calling return faster or better, and thus preferable?

There is no statement in R documentation making such an assumption.
The main page ?'function' says:

function( arglist ) expr
return(value)

Is it faster without calling return?

Both function() and return() are primitive functions and the function() itself returns last evaluated value even without including return() function.

Calling return() as .Primitive('return') with that last value as an argument will do the same job but needs one call more. So that this (often) unnecessary .Primitive('return') call can draw additional resources. Simple measurement however shows that the resulting difference is very small and thus can not be the reason for not using explicit return. The following plot is created from data selected this way:

bench_nor2 <- function(x,repeats) { system.time(rep(
# without explicit return
(function(x) vector(length=x,mode="numeric"))(x)
,repeats)) }

bench_ret2 <- function(x,repeats) { system.time(rep(
# with explicit return
(function(x) return(vector(length=x,mode="numeric")))(x)
,repeats)) }

maxlen <- 1000
reps <- 10000
along <- seq(from=1,to=maxlen,by=5)
ret <- sapply(along,FUN=bench_ret2,repeats=reps)
nor <- sapply(along,FUN=bench_nor2,repeats=reps)
res <- data.frame(N=along,ELAPSED_RET=ret["elapsed",],ELAPSED_NOR=nor["elapsed",])

# res object is then visualized
# R version 2.15

Function elapsed time comparison

The picture above may slightly difffer on your platform. Based on measured data, the size of returned object is not causing any difference, the number of repeats (even if scaled up) makes just a very small difference, which in real word with real data and real algorithm could not be counted or make your script run faster.

Is it better without calling return?

Return is good tool for clearly designing "leaves" of code where the routine should end, jump out of the function and return value.

# here without calling .Primitive('return')
> (function() {10;20;30;40})()
[1] 40
# here with .Primitive('return')
> (function() {10;20;30;40;return(40)})()
[1] 40
# here return terminates flow
> (function() {10;20;return();30;40})()
NULL
> (function() {10;20;return(25);30;40})()
[1] 25
> 

It depends on strategy and programming style of the programmer what style he use, he can use no return() as it is not required.

R core programmers uses both approaches ie. with and without explicit return() as it is possible to find in sources of 'base' functions.

Many times only return() is used (no argument) returning NULL in cases to conditially stop the function.

It is not clear if it is better or not as standard user or analyst using R can not see the real difference.

My opinion is that the question should be: Is there any danger in using explicit return coming from R implementation?

Or, maybe better, user writing function code should always ask: What is the effect in not using explicit return (or placing object to be returned as last leaf of code branch) in the function code?

Why are there two ways to unstage a file in Git?

In the newer version that is > 2.2 you can use git restore --staged <file_name>. Note here If you want to unstage (move to changes) your files one at a time you use above command with your file name. eg

git restore --staged abc.html

Now if you want unstage all your file at once, you can do something like this

git restore --staged .

Please note space and dot (.) which means consider staged all files.

How to set a value for a span using jQuery

You're looking for the wrong selector id:

 $("#submitter").text(submitter_name);

should be

 $("#submittername").text(submitter_name);

a tag as a submit button?

in my opinion the easiest way would be somthing like this:

<?php>
echo '<a href="link.php?submit='.$value.'">Submit</a>';
</?>

within the "link.php" you can request the value like this:

$_REQUEST['submit']

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

I was able to fix this issue by matching my build version to the .NET version on the server.

I double clicked the .exe just to see what would happen and it told me to install 4.5....

So I downgraded to 4.0 and it worked!

So make sure your versions match. It ran on my dev box fine, but server had older .NET version.

C++ equivalent of StringBuffer/StringBuilder?

I wanted to add something new because of the following:

At a first attemp I failed to beat

std::ostringstream 's operator<<

efficiency, but with more attemps I was able to make a StringBuilder that is faster in some cases.

Everytime I append a string I just store a reference to it somewhere and increase the counter of the total size.

The real way I finally implemented it (Horror!) is to use a opaque buffer(std::vector < char > ):

  • 1 byte header (2 bits to tell if following data is :moved string, string or byte[])
  • 6 bits to tell lenght of byte[]

for byte [ ]

  • I store directly bytes of short strings (for sequential memory access)

for moved strings (strings appended with std::move)

  • The pointer to a std::string object (we have ownership)
  • set a flag in the class if there are unused reserved bytes there

for strings

  • The pointer to a std::string object (no ownership)

There's also one small optimization, if last inserted string was mov'd in, it checks for free reserved but unused bytes and store further bytes in there instead of using the opaque buffer (this is to save some memory, it actually make it slightly slower, maybe depend also on the CPU, and it is rare to see strings with extra reserved space anyway)

This was finally slightly faster than std::ostringstream but it has few downsides:

  • I assumed fixed lenght char types (so 1,2 or 4 bytes, not good for UTF8), I'm not saying it will not work for UTF8, Just I don't checked it for laziness.
  • I used bad coding practise (opaque buffer, easy to make it not portable, I believe mine is portable by the way)
  • Lacks all features of ostringstream
  • If some referenced string is deleted before mergin all the strings: undefined behaviour.

conclusion? use std::ostringstream

It already fix the biggest bottleneck while ganing few % points in speed with mine implementation is not worth the downsides.

MySQL Data Source not appearing in Visual Studio

Uninstall later version and install mysql-connector 6.3.9 for visual studio 2010.

After installing add the dll files and restart the visual studio.

It works fine.

Converting a double to an int in C#

ToInt32 rounds. Casting to int just throws away the non-integer component.

What's a clean way to stop mongod on Mac OS X?

If you installed mongodb with homebrew, there's an easier way:

List mongo job with launchctl:

launchctl list | grep mongo

Stop mongo job:

launchctl stop <job label>

(For me this is launchctl stop homebrew.mxcl.mongodb)

Start mongo job:

launchctl start <job label>

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

I have solved as plist file.

  1. Add a NSAppTransportSecurity : Dictionary.
  2. Add Subkey named " NSAllowsArbitraryLoads " as Boolean : YES

enter image description here

Convert object to JSON in Android

Might be better choice:

@Override
public String toString() {
    return new GsonBuilder().create().toJson(this, Producto.class);
}

What is the default initialization of an array in Java?

Everything in a Java program not explicitly set to something by the programmer, is initialized to a zero value.

  • For references (anything that holds an object) that is null.
  • For int/short/byte/long that is a 0.
  • For float/double that is a 0.0
  • For booleans that is a false.
  • For char that is the null character '\u0000' (whose decimal equivalent is 0).

When you create an array of something, all entries are also zeroed. So your array contains five zeros right after it is created by new.

Note (based on comments): The Java Virtual Machine is not required to zero out the underlying memory when allocating local variables (this allows efficient stack operations if needed) so to avoid random values the Java Language Specification requires local variables to be initialized.

ImportError: No module named 'selenium'

If you have pip installed you can install selenium like so.

pip install selenium

or depending on your permissions:

sudo pip install selenium

For python3:

sudo pip3 install selenium

As you can see from this question pip vs easy_install pip is a more reliable package installer as it was built to improve easy_install.

I would also suggest that when creating new projects you do so in virtual environments, even a simple selenium project. You can read more about virtual environments here. In fact pip is included out of the box with virtualenv!

remote: repository not found fatal: not found

Your username shouldn't be an email address, but your GitHub user account: pete.
And your password should be your GitHub account password.

You actually can set your username directly in the remote url, in order for Git to request only your password:

cd C:\Users\petey_000\rails_projects\first_app
git remote set-url origin https://[email protected]/pete/first_app

And you need to create the fist_app repo on GitHub first: make sure to create it completely empty, or, if you create it with an initial commit (including a README.md, a license file and a .gitignore file), then do a git pull first, before making your git push.

How to set DataGrid's row Background, based on a property value using data bindings

In XAML, add and define a RowStyle Property for the DataGrid with a goal to set the Background of the Row, to the Color defined in my Employee Object.

<DataGrid AutoGenerateColumns="False" ItemsSource="EmployeeList">
   <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
             <Setter Property="Background" Value="{Binding ColorSet}"/>
        </Style>
   </DataGrid.RowStyle>

And in my Employee Class

public class Employee {

    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public string ColorSet { get; set; }

    public Employee() { }

    public Employee(int id, string name, int age)
    {
        Id = id;
        Name = name;
        Age = age;
        if (Age > 50)
        {
            ColorSet = "Green";
        }
        else if (Age > 100)
        {
            ColorSet = "Red";
        }
        else
        {
            ColorSet = "White";
        }
    }
}

This way every Row of the DataGrid has the BackGround Color of the ColorSet Property of my Object.

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

in HQL query, Don't write the Table name, write your Entity class name in your query like

String s = "from Entity_class name";
query qry = session.createUqery(s);

Count if two criteria match - EXCEL formula

Add the sheet name infront of the cell, e.g.:

=COUNTIFS(stock!A:A,"M",stock!C:C,"Yes")

Assumes the sheet name is "stock"

Check if an element is present in a Bash array

You could do:

if [[ " ${arr[*]} " == *" d "* ]]; then
    echo "arr contains d"
fi

This will give false positives for example if you look for "a b" -- that substring is in the joined string but not as an array element. This dilemma will occur for whatever delimiter you choose.

The safest way is to loop over the array until you find the element:

array_contains () {
    local seeking=$1; shift
    local in=1
    for element; do
        if [[ $element == "$seeking" ]]; then
            in=0
            break
        fi
    done
    return $in
}

arr=(a b c "d e" f g)
array_contains "a b" "${arr[@]}" && echo yes || echo no    # no
array_contains "d e" "${arr[@]}" && echo yes || echo no    # yes

Here's a "cleaner" version where you just pass the array name, not all its elements

array_contains2 () { 
    local array="$1[@]"
    local seeking=$2
    local in=1
    for element in "${!array}"; do
        if [[ $element == "$seeking" ]]; then
            in=0
            break
        fi
    done
    return $in
}

array_contains2 arr "a b"  && echo yes || echo no    # no
array_contains2 arr "d e"  && echo yes || echo no    # yes

For associative arrays, there's a very tidy way to test if the array contains a given key: The -v operator

$ declare -A arr=( [foo]=bar [baz]=qux )
$ [[ -v arr[foo] ]] && echo yes || echo no
yes
$ [[ -v arr[bar] ]] && echo yes || echo no
no

See 6.4 Bash Conditional Expressions in the manual.

Python assigning multiple variables to same value? list behavior

Simply put, in the first case, you are assigning multiple names to a list. Only one copy of list is created in memory and all names refer to that location. So changing the list using any of the names will actually modify the list in memory.

In the second case, multiple copies of same value are created in memory. So each copy is independent of one another.

codeigniter, result() vs. result_array()

in my experince the problem using result() and result_array() in my JSON if using result() there no problem its works but if using result_array() i got error "Trying to get property of non-object" so im not search into deep the problem so i just using result() if using JSON and using result_array() if not using JSON

Convert array to JSON

Wow, seems it got a lot easier nowadays... 3 ways you can do it:

json = { ...array };

json = Object.assign({}, array);

json = array.reduce((json, value, key) => { json[key] = value; return json; }, {});

How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

ASP.NET always generate asp:Button as an input type=submit.
If you want a button which doesn't do a post, but need some control for the element on the server side, create a simple HTML input with attributes type=button and runat=server.

If you disable click actions doing OnClientClick=return false, it won't do anything on click, unless you create a function like:

function btnClick() {
    // do stuff
    return false;
}

How might I force a floating DIV to match the height of another floating DIV?

You can always use a background image to do it too. I tend to vote for this option 100% of the time as the only other perfect solution is the Jquery option.

As with using the outer div with a background color you'll end up having to have the content in both divs reaching the same height.

Passing in class names to react components

In React, when you want to pass an interpreted expression, you have to open a pair of curly braces. Try:

render () {
  return (
    <button className={`pill ${ this.props.styleName }`}>
      {this.props.children}
    </button>
  );
}

Using the classnames npm package

import classnames from 'classnames';

render() {
  return (
    <button className={classnames('pill', this.props.styleName)}>
      {this.props.children}
    </button>
  );
}

Entity Framework Query for inner join

from s in db.Services
join sa in db.ServiceAssignments on s.Id equals sa.ServiceId
where sa.LocationId == 1
select s

Where db is your DbContext. Generated query will look like (sample for EF6):

SELECT [Extent1].[Id] AS [Id]
       -- other fields from Services table
FROM [dbo].[Services] AS [Extent1]
INNER JOIN [dbo].[ServiceAssignments] AS [Extent2]
    ON [Extent1].[Id] = [Extent2].[ServiceId]
WHERE [Extent2].[LocationId] = 1

Does JSON syntax allow duplicate keys in an object?

The JSON spec says this:

An object is an unordered set of name/value pairs.

The important part here is "unordered": it implies uniqueness of keys, because the only thing you can use to refer to a specific pair is its key.

In addition, most JSON libs will deserialize JSON objects to hash maps/dictionaries, where keys are guaranteed unique. What happens when you deserialize a JSON object with duplicate keys depends on the library: in most cases, you'll either get an error, or only the last value for each duplicate key will be taken into account.

For example, in Python, json.loads('{"a": 1, "a": 2}') returns {"a": 2}.

rake assets:precompile RAILS_ENV=production not working as required

Have you added this gem to your gemfile?

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

move that gem out of assets group and then run bundle again, I hope that would help!

Angular ReactiveForms: Producing an array of checkbox values?

TL;DR

  1. I prefer to use FormGroup to populate the list of checkbox
  2. Write a custom validator for check at least one checkbox was selected
  3. Working example https://stackblitz.com/edit/angular-validate-at-least-one-checkbox-was-selected

This also struck me for sometimes so I did try both FormArray and FormGroup approaches.

Most of the time, the list of checkbox was populated on the server and I received it through API. But sometimes you will have a static set of checkbox with your predefined value. With each use case, the corresponding FormArray or FormGroup will be used.

Basically FormArray is a variant of FormGroup. The key difference is that its data gets serialized as an array (as opposed to being serialized as an object in case of FormGroup). This might be especially useful when you don’t know how many controls will be present within the group, like dynamic forms.

For the sake of simplicity, imagine you have a simple create product form with

  • One required product name textbox.
  • A list of category to select from, required at least one to be checked. Assume the list will be retrieved from the server.

First, I set up a form with only product name formControl. It is a required field.

this.form = this.formBuilder.group({
    name: ["", Validators.required]
});

Since the category is dynamically rendering, I will have to add these data into the form later after the data was ready.

this.getCategories().subscribe(categories => {
    this.form.addControl("categoriesFormArr", this.buildCategoryFormArr(categories));
    this.form.addControl("categoriesFormGroup", this.buildCategoryFormGroup(categories));
})

There are two approaches to build up the category list.

1. Form Array

  buildCategoryFormArr(categories: ProductCategory[], selectedCategoryIds: string[] = []): FormArray {
    const controlArr = categories.map(category => {
      let isSelected = selectedCategoryIds.some(id => id === category.id);
      return this.formBuilder.control(isSelected);
    })
    return this.formBuilder.array(controlArr, atLeastOneCheckboxCheckedValidator())
  }
<div *ngFor="let control of categoriesFormArr?.controls; let i = index" class="checkbox">
  <label><input type="checkbox" [formControl]="control" />
    {{ categories[i]?.title }}
  </label>
</div>

This buildCategoryFormGroup will return me a FormArray. It also take a list of selected value as an argument so If you want to reuse the form for edit data, it could be helpful. For the purpose of create a new product form, it is not be applicable yet.

Noted that when you try to access the formArray values. It will looks like [false, true, true]. To get a list of selected id, it required a bit more work to check from the list but based on the array index. Doesn't sound good to me but it works.

get categoriesFormArraySelectedIds(): string[] {
  return this.categories
  .filter((cat, catIdx) => this.categoriesFormArr.controls.some((control, controlIdx) => catIdx === controlIdx && control.value))
  .map(cat => cat.id);
}

That's why I came up using FormGroup for that matter

2. Form Group

The different of the formGroup is it will store the form data as the object, which required a key and a form control. So it is the good idea to set the key as the categoryId and then we can retrieve it later.

buildCategoryFormGroup(categories: ProductCategory[], selectedCategoryIds: string[] = []): FormGroup {
  let group = this.formBuilder.group({}, {
    validators: atLeastOneCheckboxCheckedValidator()
  });
  categories.forEach(category => {
    let isSelected = selectedCategoryIds.some(id => id === category.id);
    group.addControl(category.id, this.formBuilder.control(isSelected));
  })
  return group;
}
<div *ngFor="let item of categories; let i = index" class="checkbox">
  <label><input type="checkbox" [formControl]="categoriesFormGroup?.controls[item.id]" /> {{ categories[i]?.title }}
  </label>
</div>

The value of the form group will look like:

{
    "category1": false,
    "category2": true,
    "category3": true,
}

But most often we want to get only the list of categoryIds as ["category2", "category3"]. I also have to write a get to take these data. I like this approach better comparing to the formArray, because I could actually take the value from the form itself.

  get categoriesFormGroupSelectedIds(): string[] {
    let ids: string[] = [];
    for (var key in this.categoriesFormGroup.controls) {
      if (this.categoriesFormGroup.controls[key].value) {
        ids.push(key);
      }
      else {
        ids = ids.filter(id => id !== key);
      }
    }
    return ids;
  }

3. Custom validator to check at least one checkbox was selected

I made the validator to check at least X checkbox was selected, by default it will check against one checkbox only.

export function atLeastOneCheckboxCheckedValidator(minRequired = 1): ValidatorFn {
  return function validate(formGroup: FormGroup) {
    let checked = 0;

    Object.keys(formGroup.controls).forEach(key => {
      const control = formGroup.controls[key];

      if (control.value === true) {
        checked++;
      }
    });

    if (checked < minRequired) {
      return {
        requireCheckboxToBeChecked: true,
      };
    }

    return null;
  };
}

How to get exit code when using Python subprocess communicate method?

Popen.communicate will set the returncode attribute when it's done(*). Here's the relevant documentation section:

Popen.returncode 
  The child return code, set by poll() and wait() (and indirectly by communicate()). 
  A None value indicates that the process hasn’t terminated yet.

  A negative value -N indicates that the child was terminated by signal N (Unix only).

So you can just do (I didn't test it but it should work):

import subprocess as sp
child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
streamdata = child.communicate()[0]
rc = child.returncode

(*) This happens because of the way it's implemented: after setting up threads to read the child's streams, it just calls wait.

javascript setTimeout() not working

Use:

setTimeout(startTimer,startInterval); 

You're calling startTimer() and feed it's result (which is undefined) as an argument to setTimeout().

Resetting a setTimeout

$(function() {

    (function(){

        var pthis = this;
        this.mseg = 115000;
        this.href = 'file.php'

        this.setTimer = function() { 
            return (window.setTimeout( function() {window.location.href = this.href;}, this.mseg));
        };
        this.timer = pthis.setTimer();

        this.clear = function(ref) { clearTimeout(ref.timer); ref.setTimer(); };
        $(window.document).click( function(){pthis.clear.apply(pthis, [pthis])} );

    })();

});

Click events on Pie Charts in Chart.js

I have an elegant solution to this problem. If you have multiple dataset, identifying which dataset was clicked gets tricky. The _datasetIndex always returns zero. But this should do the trick. It will get you the label and the dataset label as well. Please note ** this.getElementAtEvent** is without the s in getElement

options: {
   onClick: function (e, items) {
    var firstPoint = this.getElementAtEvent(e)[0];
    if (firstPoint) {
      var label = firstPoint._model.label;
      var val = firstPoint._model.datasetLabel;
      console.log(label+" - "+val);
    }
    
  }
}

Convert a space delimited string to list

try

states.split()

it returns the list

['Alaska',
 'Alabama',
 'Arkansas',
 'American',
 'Samoa',
 'Arizona',
 'California',
 'Colorado']

and this returns the random element of the list

import random
random.choice(states.split())

split statement parses the string and returns the list, by default it's divided into the list by spaces, if you specify the string it's divided by this string, so for example

states.split('Ari')

returns

['Alaska Alabama Arkansas American Samoa ', 'zona California Colorado']

Btw, list is in python interpretated with [] brackets instead of {} brackets, {} brackets are used for dictionaries, you can read more on this here

I see you are probably new to python, so I'd give you some advice how to use python's great documentation

Almost everything you need can be found here You can use also python included documentation, open python console and write help() If you don't know what to do with some object, I'd install ipython, write statement and press Tab, great tool which helps you with interacting with the language

I just wrote this here to show that python is great tool also because it's great documentation and it's really powerful to know this

How to know function return type and argument types?

Well things have changed a little bit since 2011! Now there's type hints in Python 3.5 which you can use to annotate arguments and return the type of your function. For example this:

def greeting(name):
  return 'Hello, {}'.format(name)

can now be written as this:

def greeting(name: str) -> str:
  return 'Hello, {}'.format(name)

As you can now see types, there's some sort of optional static type checking which will help you and your type checker to investigate your code.

for more explanation I suggest to take a look at the blog post on type hints in PyCharm blog.

Resizing an image in an HTML5 canvas

For resizing to image with width less that original, i use:

    function resize2(i) {
      var cc = document.createElement("canvas");
      cc.width = i.width / 2;
      cc.height = i.height / 2;
      var ctx = cc.getContext("2d");
      ctx.drawImage(i, 0, 0, cc.width, cc.height);
      return cc;
    }
    var cc = img;
    while (cc.width > 64 * 2) {
      cc = resize2(cc);
    }
    // .. than drawImage(cc, .... )

and it works =).

How to index into a dictionary?

If anybody still looking at this question, the currently accepted answer is now outdated:

Since Python 3.7* the dictionaries are order-preserving, that is they now behave exactly as collections.OrderedDicts used to. Unfortunately, there is still no dedicated method to index into keys() / values() of the dictionary, so getting the first key / value in the dictionary can be done as

first_key = list(colors)[0]
first_val = list(colors.values())[0]

or alternatively (this avoids instantiating the keys view into a list):

def get_first_key(dictionary):
    for key in dictionary:
        return key
    raise IndexError

first_key = get_first_key(colors)
first_val = colors[first_key]

If you need an n-th key, then similarly

def get_nth_key(dictionary, n=0):
    if n < 0:
        n += len(dictionary)
    for i, key in enumerate(dictionary.keys()):
        if i == n:
            return key
    raise IndexError("dictionary index out of range") 

(*CPython 3.6 already included ordered dicts, but this was only an implementation detail. The language specification includes ordered dicts from 3.7 onwards.)