Programs & Examples On #Color codes

What is a quick way to force CRLF in C# / .NET?

It depends on exactly what the requirements are. In particular, how do you want to handle "\r" on its own? Should that count as a line break or not? As an example, how should "a\n\rb" be treated? Is that one very odd line break, one "\n" break and then a rogue "\r", or two separate linebreaks? If "\r" and "\n" can both be linebreaks on their own, why should "\r\n" not be treated as two linebreaks?

Here's some code which I suspect is reasonably efficient.

using System;
using System.Text;

class LineBreaks
{    
    static void Main()
    {
        Test("a\nb");
        Test("a\nb\r\nc");
        Test("a\r\nb\r\nc");
        Test("a\rb\nc");
        Test("a\r");
        Test("a\n");
        Test("a\r\n");
    }

    static void Test(string input)
    {
        string normalized = NormalizeLineBreaks(input);
        string debug = normalized.Replace("\r", "\\r")
                                 .Replace("\n", "\\n");
        Console.WriteLine(debug);
    }

    static string NormalizeLineBreaks(string input)
    {
        // Allow 10% as a rough guess of how much the string may grow.
        // If we're wrong we'll either waste space or have extra copies -
        // it will still work
        StringBuilder builder = new StringBuilder((int) (input.Length * 1.1));

        bool lastWasCR = false;

        foreach (char c in input)
        {
            if (lastWasCR)
            {
                lastWasCR = false;
                if (c == '\n')
                {
                    continue; // Already written \r\n
                }
            }
            switch (c)
            {
                case '\r':
                    builder.Append("\r\n");
                    lastWasCR = true;
                    break;
                case '\n':
                    builder.Append("\r\n");
                    break;
                default:
                    builder.Append(c);
                    break;
            }
        }
        return builder.ToString();
    }
}

How do I print the percent sign(%) in c

Use "%%". The man page describes this requirement:

% A '%' is written. No argument is converted. The complete conversion specification is '%%'.

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

You probably have a forward declaration of the class, but haven't included the header:

#include <sstream>

//...
QString Stats_Manager::convertInt(int num)
{
    std::stringstream ss;   // <-- also note namespace qualification
    ss << num;
    return ss.str();
}

How to set the locale inside a Debian/Ubuntu Docker container?

I dislike having Docker environment variables when I do not expect user of a Docker image to change them.

Just put it somewhere in one RUN. If you do not have UTF-8 locales generated, then you can do the following set of commands:

export DEBIAN_FRONTEND=noninteractive
apt-get update -q -q
apt-get install --yes locales
locale-gen --no-purge en_US.UTF-8
update-locale LANG=en_US.UTF-8
echo locales locales/locales_to_be_generated multiselect en_US.UTF-8 UTF-8 | debconf-set-selections
echo locales locales/default_environment_locale select en_US.UTF-8 | debconf-set-selections
dpkg-reconfigure locales

Any way to write a Windows .bat file to kill processes?

Use Powershell! Built in cmdlets for managing processes. Examples here (hard way), here(built in) and here (more).

Warning: Cannot modify header information - headers already sent by ERROR

Check something with echo, print() or printr() in the include file, header.php.

It might be that this is the problem OR if any MVC file, then check the number of spaces after ?>. This could also make a problem.

"java.lang.OutOfMemoryError: PermGen space" in Maven build

Increase the size of your perm space, of course. Use the -XX:MaxPermSize=128m option. Set the value to something appropriate.

Subversion stuck due to "previous operation has not finished"?

There is often no need for a new checkout or copying.

I have just solved a similar issue relating to the error "previous operation has not finished" with help from this (Link)

It seems that svn sometimes gets stuck while processing commands/operations. All of these operations are stored in the database file wc.db in the .svn folder.

By downloading SQLite to my checkout directory and running

sqlite3.exe .svn/wc.db "select * from work_queue"

you can get a list of all pending operations. These operations are the ones the error is referring to as "not finished".

By running

sqlite3.exe .svn/wc.db "delete from work_queue"

all of the old operations are deleted from the work queue and the error disapears. No need for a new checkout or anything

Delete worksheet in Excel using VBA

Worksheets("Sheet1").Delete
Worksheets("Sheet2").Delete

What does the M stand for in C# Decimal literal notation?

A real literal suffixed by M or m is of type decimal (money). For example, the literals 1m, 1.5m, 1e10m, and 123.456M are all of type decimal. This literal is converted to a decimal value by taking the exact value, and, if necessary, rounding to the nearest representable value using banker's rounding. Any scale apparent in the literal is preserved unless the value is rounded or the value is zero (in which latter case the sign and scale will be 0). Hence, the literal 2.900m will be parsed to form the decimal with sign 0, coefficient 2900, and scale 3.

Read more about real literals

Capture screenshot of active window?

Here is a snippet to capture either the desktop or the active window. It has no reference to Windows Forms.

public class ScreenCapture
{
    [DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern IntPtr GetDesktopWindow();

    [StructLayout(LayoutKind.Sequential)]
    private struct Rect
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }   

    [DllImport("user32.dll")]
    private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);

    public static Image CaptureDesktop()
    {
        return CaptureWindow(GetDesktopWindow());
    }

    public static Bitmap CaptureActiveWindow()
    {
        return CaptureWindow(GetForegroundWindow());
    }

    public static Bitmap CaptureWindow(IntPtr handle)
    {
        var rect = new Rect();
        GetWindowRect(handle, ref rect);
        var bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
        var result = new Bitmap(bounds.Width, bounds.Height);

        using (var graphics = Graphics.FromImage(result))
        {
            graphics.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
        }

        return result;
    }
}

How to capture the whole screen:

var image = ScreenCapture.CaptureDesktop();
image.Save(@"C:\temp\snippetsource.jpg", ImageFormat.Jpeg);

How to capture the active window:

var image = ScreenCapture.CaptureActiveWindow();
image.Save(@"C:\temp\snippetsource.jpg", ImageFormat.Jpeg);

Originally found here: http://www.snippetsource.net/Snippet/158/capture-screenshot-in-c

Dynamically fill in form values with jQuery

If you need to hit the database, you need to hit the web server again (for the most part).

What you can do is use AJAX, which makes a request to another script on your site to retrieve data, gets the data, and then updates the input fields you want.

AJAX calls can be made in jquery with the $.ajax() function call, so this will happen

User's browser enters input that fires a trigger that makes an AJAX call

$('input .callAjax').bind('change', function() { 
  $.ajax({ url: 'script/ajax', 
           type: json
           data: $foo,  
           success: function(data) {
             $('input .targetAjax').val(data.newValue);
           });
  );

Now you will need to point that AJAX call at script (sounds like you're working PHP) that will do the query you want and send back data.

You will probably want to use the JSON object call so you can pass back a javascript object, that will be easier to use than return XML etc.

The php function json_encode($phpobj); will be useful.

postgreSQL - psql \i : how to execute script in a given path

i did try this and its working in windows machine to run a sql file on a specific schema.

psql -h localhost -p 5432 -U username -d databasename -v schema=schemaname < e:\Table.sql

Class has no member named

I had similar problem. My header file which included the definition of the class wasn't working. I wasn't able to use the member functions of that class. So i simply copied my class to another header file. Now its working all ok.

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

Let's get a canonical answer here. I will reference the HTML5 spec.

First of all, 12.1.2.4 Optional tags:

A head element's start tag may be omitted if the element is empty, or if the first thing inside the head element is an element.

A head element's end tag may be omitted if the head element is not immediately followed by a space character or a comment.

A body element's start tag may be omitted if the element is empty, or if the first thing inside the body element is not a space character or a comment, except if the first thing inside the body element is a script or style element.

A body element's end tag may be omitted if the body element is not immediately followed by a comment.

Then, the 4.1.1 The html element:

Content model: A head element followed by a body element.

Having the cited restrictions and strictly defined element order, we can easily work out what are the rules for placing implicit <body> tag.

Since <head/> must come first, and it can contain elements only (and not direct text), all elements suitable for <head/> will become the part of implicit <head/>, up to the first stray text or <body/>-specific element. At that moment, all remaining elements and text nodes will be placed in <body/>.


Now let's consider your second snippet:

<html>
  <header>...</header>
  <body>
    <section>...</section>
    <section>...</section>
    <section>...</section>
  </body>
  <footer>...</footer>
</html>

Here, the <header/> element is not suitable for <head/> (it's flow content), the <body> tag will be placed immediately before it. In other words, the document will be understood by browser as following:

<html>
  <head/>
  <body>
    <header>...</header>
    <body>
      <section>...</section>
      <section>...</section>
      <section>...</section>
    </body>
    <footer>...</footer>
  </body>
</html>

And that's certainly not what you were expecting. And as a note, it is invalid as well; see 4.4.1 The body element:

Contexts in which this element can be used: As the second element in an html element.

[...]

In conforming documents, there is only one body element.


Thus, the <header/> or <footer/> will be correctly used in this context. Well, they will be practically equivalent to the first snippet. But this will cause an additional <body/> element in middle of a <body/> which is invalid.


As a side note, you're probably confusing <body/> here with the main part of the content which has no specific element. You could look up that page for other solutions on getting what you want.

Quoting 4.4.1 The body element once again:

The body element represents the main content of the document.

which means all the content. And both header and footer are part of this content.

Set specific precision of a BigDecimal

Try this code ...

    Integer perc = 5;
    BigDecimal spread = BigDecimal.ZERO; 
    BigDecimal perc = spread.setScale(perc,BigDecimal.ROUND_HALF_UP);
    System.out.println(perc);

Result: 0.00000

Creating a BLOB from a Base64 string in JavaScript

The method with fetch is the best solution, but if anyone needs to use a method without fetch then here it is, as the ones mentioned previously didn't work for me:

function makeblob(dataURL) {
    const BASE64_MARKER = ';base64,';
    const parts = dataURL.split(BASE64_MARKER);
    const contentType = parts[0].split(':')[1];
    const raw = window.atob(parts[1]);
    const rawLength = raw.length;
    const uInt8Array = new Uint8Array(rawLength);

    for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }

    return new Blob([uInt8Array], { type: contentType });
}

How to convert DateTime to VarChar

You did not say which database, but with mysql here is an easy way to get a date from a timestamp (and the varchar type conversion should happen automatically):

mysql> select date(now());
+-------------+
| date(now()) |
+-------------+
| 2008-09-16  | 
+-------------+
1 row in set (0.00 sec)

git with development, staging and production branches

We do it differently. IMHO we do it in an easier way: in master we are working on the next major version.

Each larger feature gets its own branch (derived from master) and will be rebased (+ force pushed) on top of master regularly by the developer. Rebasing only works fine if a single developer works on this feature. If the feature is finished, it will be freshly rebased onto master and then the master fast-forwarded to the latest feature commit.

To avoid the rebasing/forced push one also can merge master changes regularly to the feature branch and if it's finished merge the feature branch into master (normal merge or squash merge). But IMHO this makes the feature branch less clear and makes it much more difficult to reorder/cleanup the commits.

If a new release is coming, we create a side-branch out of master, e.g. release-5 where only bugs get fixed.

Is there a way to ignore a single FindBugs warning?

At the time of writing this (May 2018), FindBugs seems to have been replaced by SpotBugs. Using the SuppressFBWarnings annotation requires your code to be compiled with Java 8 or later and introduces a compile time dependency on spotbugs-annotations.jar.

Using a filter file to filter SpotBugs rules has no such issues. The documentation is here.

TestNG ERROR Cannot find class in classpath

If none of the above answers work, you can run the test in IDE, get the class path and use it in your command. Ex: If you are using Intellij IDEA, you can find it at the top of the console(screenshot below). Intellij Console

Clicking on the highlighted part expands and displays the complete class path.

you need to remove the references to jars inside the folder: JetBrains\IntelliJ IDEA Community Edition VERSION

java -cp "path_copied" org.testng.TestNG testng.xml

If the project is a Maven project, you can add maven surefire plugin and provide testng suite XML file path, navigate to the project directory and run the command: mvn clean install test

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12</version>
                <configuration>
                    <suiteXmlFiles>
                        <suiteXmlFile>config/testrun_config.xml</suiteXmlFile>
                    </suiteXmlFiles>
                </configuration>
            </plugin>

How to process a file in PowerShell line-by-line as a stream

If you want to use straight PowerShell check out the below code.

$content = Get-Content C:\Users\You\Documents\test.txt
foreach ($line in $content)
{
    Write-Host $line
}

How to initialize private static members in C++?

For a variable:

foo.h:

class foo
{
private:
    static int i;
};

foo.cpp:

int foo::i = 0;

This is because there can only be one instance of foo::i in your program. It's sort of the equivalent of extern int i in a header file and int i in a source file.

For a constant you can put the value straight in the class declaration:

class foo
{
private:
    static int i;
    const static int a = 42;
};

How do I get class name in PHP?

Now, I have answer for my problem. Thanks to Brad for the link, I find the answer here. And thanks to J.Money for the idea. My solution:

<?php

class Model
{
    public static function getClassName() {
        return get_called_class();
    }
}

class Product extends Model {}

class User extends Model {}

echo Product::getClassName(); // "Product" 
echo User::getClassName(); // "User" 

what is the most efficient way of counting occurrences in pandas?

I think df['word'].value_counts() should serve. By skipping the groupby machinery, you'll save some time. I'm not sure why count should be much slower than max. Both take some time to avoid missing values. (Compare with size.)

In any case, value_counts has been specifically optimized to handle object type, like your words, so I doubt you'll do much better than that.

How to access property of anonymous type in C#?

The accepted answer correctly describes how the list should be declared and is highly recommended for most scenarios.

But I came across a different scenario, which also covers the question asked. What if you have to use an existing object list, like ViewData["htmlAttributes"] in MVC? How can you access its properties (they are usually created via new { @style="width: 100px", ... })?

For this slightly different scenario I want to share with you what I found out. In the solutions below, I am assuming the following declaration for nodes:

List<object> nodes = new List<object>();

nodes.Add(
new
{
    Checked = false,
    depth = 1,
    id = "div_1" 
});

1. Solution with dynamic

In C# 4.0 and higher versions, you can simply cast to dynamic and write:

if (nodes.Any(n => ((dynamic)n).Checked == false))
    Console.WriteLine("found a  not checked  element!");

Note: This is using late binding, which means it will recognize only at runtime if the object doesn't have a Checked property and throws a RuntimeBinderException in this case - so if you try to use a non-existing Checked2 property you would get the following message at runtime: "'<>f__AnonymousType0<bool,int,string>' does not contain a definition for 'Checked2'".

2. Solution with reflection

The solution with reflection works both with old and new C# compiler versions. For old C# versions please regard the hint at the end of this answer.

Background

As a starting point, I found a good answer here. The idea is to convert the anonymous data type into a dictionary by using reflection. The dictionary makes it easy to access the properties, since their names are stored as keys (you can access them like myDict["myProperty"]).

Inspired by the code in the link above, I created an extension class providing GetProp, UnanonymizeProperties and UnanonymizeListItems as extension methods, which simplify access to anonymous properties. With this class you can simply do the query as follows:

if (nodes.UnanonymizeListItems().Any(n => (bool)n["Checked"] == false))
{
    Console.WriteLine("found a  not checked  element!");
}

or you can use the expression nodes.UnanonymizeListItems(x => (bool)x["Checked"] == false).Any() as if condition, which filters implicitly and then checks if there are any elements returned.

To get the first object containing "Checked" property and return its property "depth", you can use:

var depth = nodes.UnanonymizeListItems()
             ?.FirstOrDefault(n => n.Contains("Checked")).GetProp("depth");

or shorter: nodes.UnanonymizeListItems()?.FirstOrDefault(n => n.Contains("Checked"))?["depth"];

Note: If you have a list of objects which don't necessarily contain all properties (for example, some do not contain the "Checked" property), and you still want to build up a query based on "Checked" values, you can do this:

if (nodes.UnanonymizeListItems(x => { var y = ((bool?)x.GetProp("Checked", true)); 
                                      return y.HasValue && y.Value == false;}).Any())
{
    Console.WriteLine("found a  not checked   element!");
}

This prevents, that a KeyNotFoundException occurs if the "Checked" property does not exist.


The class below contains the following extension methods:

  • UnanonymizeProperties: Is used to de-anonymize the properties contained in an object. This method uses reflection. It converts the object into a dictionary containing the properties and its values.
  • UnanonymizeListItems: Is used to convert a list of objects into a list of dictionaries containing the properties. It may optionally contain a lambda expression to filter beforehand.
  • GetProp: Is used to return a single value matching the given property name. Allows to treat not-existing properties as null values (true) rather than as KeyNotFoundException (false)

For the examples above, all that is required is that you add the extension class below:

public static class AnonymousTypeExtensions
{
    // makes properties of object accessible 
    public static IDictionary UnanonymizeProperties(this object obj)
    {
        Type type = obj?.GetType();
        var properties = type?.GetProperties()
               ?.Select(n => n.Name)
               ?.ToDictionary(k => k, k => type.GetProperty(k).GetValue(obj, null));
        return properties;
    }
    
    // converts object list into list of properties that meet the filterCriteria
    public static List<IDictionary> UnanonymizeListItems(this List<object> objectList, 
                    Func<IDictionary<string, object>, bool> filterCriteria=default)
    {
        var accessibleList = new List<IDictionary>();
        foreach (object obj in objectList)
        {
            var props = obj.UnanonymizeProperties();
            if (filterCriteria == default
               || filterCriteria((IDictionary<string, object>)props) == true)
            { accessibleList.Add(props); }
        }
        return accessibleList;
    }

    // returns specific property, i.e. obj.GetProp(propertyName)
    // requires prior usage of AccessListItems and selection of one element, because
    // object needs to be a IDictionary<string, object>
    public static object GetProp(this object obj, string propertyName, 
                                 bool treatNotFoundAsNull = false)
    {
        try 
        {
            return ((System.Collections.Generic.IDictionary<string, object>)obj)
                   ?[propertyName];
        }
        catch (KeyNotFoundException)
        {
            if (treatNotFoundAsNull) return default(object); else throw;
        }
    }
}

Hint: The code above is using the null-conditional operators, available since C# version 6.0 - if you're working with older C# compilers (e.g. C# 3.0), simply replace ?. by . and ?[ by [ everywhere (and do the null-handling traditionally by using if statements or catch NullReferenceExceptions), e.g.

var depth = nodes.UnanonymizeListItems()
            .FirstOrDefault(n => n.Contains("Checked"))["depth"];

As you can see, the null-handling without the null-conditional operators would be cumbersome here, because everywhere you removed them you have to add a null check - or use catch statements where it is not so easy to find the root cause of the exception resulting in much more - and hard to read - code.

If you're not forced to use an older C# compiler, keep it as is, because using null-conditionals makes null handling much easier.

Note: Like the other solution with dynamic, this solution is also using late binding, but in this case you're not getting an exception - it will simply not find the element if you're referring to a non-existing property, as long as you keep the null-conditional operators.

What might be useful for some applications is that the property is referred to via a string in solution 2, hence it can be parameterized.

What is the use of hashCode in Java?

From the Javadoc:

Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java programming language.)

How do I reset a jquery-chosen select option with jQuery?

HTML:

<select id="autoship_option" data-placeholder="Choose Option..." 
        style="width: 175px;" class="chzn-select">
    <option value=""></option>
    <option value="active">Active Autoship</option>
</select>
<button id="rs">Click to reset</button>

JS:

$('#rs').on('click', function(){
    $('autoship_option').find('option:selected').removeAttr('selected');
});

Fiddle: http://jsfiddle.net/Z8nE8/

How to uninstall a Windows Service when there is no executable for it left on the system?

My favourite way of doing this is to use Sysinternals Autoruns application. Just select the service and press delete.

Using CSS how to change only the 2nd column of a table

You can use the :nth-child pseudo class like this:

.countTable table table td:nth-child(2)

Note though, this won't work in older browsers (or IE), you'll need to give the cells a class or use javascript in that case.

Convert hex string (char []) to int?

Something like this could be useful:

char str[] = "0x1800785";
int num;

sscanf(str, "%x", &num);
printf("0x%x %i\n", num, num); 

Read man sscanf

Fastest way to check a string is alphanumeric in Java

A regex will probably be quite efficient, because you would specify ranges: [0-9a-zA-Z]. Assuming the implementation code for regexes is efficient, this would simply require an upper and lower bound comparison for each range. Here's basically what a compiled regex should do:

boolean isAlphanumeric(String str) {
    for (int i=0; i<str.length(); i++) {
        char c = str.charAt(i);
        if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
            return false;
    }

    return true;
}

I don't see how your code could be more efficient than this, because every character will need to be checked, and the comparisons couldn't really be any simpler.

Connection refused to MongoDB errno 111

In my case previous version was 3.2. I have upgraded to 3.6 but data files was not compatible to new version so I removed all data files as it was not usable for me and its works.

You can check logs using /var/log/mongodb

Pass a local file in to URL in Java

I tried it with Java on Linux. The following possibilities are OK:

file:///home/userId/aaaa.html
file:/home/userId/aaaa.html
file:aaaa.html  (if current directory is /home/userId)

not working is:

file://aaaa.html

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

It's in the app.config file.

<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceDebug includeExceptionDetailInFaults="true"/>

Handling a timeout error in python sockets

Here is a solution I use in one of my project.

network_utils.telnet

import socket
from timeit import default_timer as timer

def telnet(hostname, port=23, timeout=1):
    start = timer()
    connection = socket.socket()
    connection.settimeout(timeout)
    try:
        connection.connect((hostname, port))
        end = timer()
        delta = end - start
    except (socket.timeout, socket.gaierror) as error:
        logger.debug('telnet error: ', error)
        delta = None
    finally:
        connection.close()

    return {
        hostname: delta
    }

Tests

def test_telnet_is_null_when_host_unreachable(self):
    hostname = 'unreachable'

    response = network_utils.telnet(hostname)

    self.assertDictEqual(response, {'unreachable': None})

def test_telnet_give_time_when_reachable(self):
    hostname = '127.0.0.1'

    response = network_utils.telnet(hostname, port=22)

    self.assertGreater(response[hostname], 0)

How to run .APK file on emulator

Start an Android Emulator (make sure that all supported APIs are included when you created the emulator, we needed to have the Google APIs for instance).

Then simply email yourself a link to the .apk file, and download it directly in the emulator, and click the downloaded file to install it.

Reading string from input with space character?

Use:

fgets (name, 100, stdin);

100 is the max length of the buffer. You should adjust it as per your need.

Use:

scanf ("%[^\n]%*c", name);

The [] is the scanset character. [^\n] tells that while the input is not a newline ('\n') take input. Then with the %*c it reads the newline character from the input buffer (which is not read), and the * indicates that this read in input is discarded (assignment suppression), as you do not need it, and this newline in the buffer does not create any problem for next inputs that you might take.

Read here about the scanset and the assignment suppression operators.

Note you can also use gets but ....

Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.

Speed tradeoff of Java's -Xms and -Xmx options

It depends on the GC your java is using. Parallel GCs might work better on larger memory settings - I'm no expert on that though.

In general, if you have larger memory the less frequent it needs to be GC-ed - there is lots of room for garbage. However, when it comes to a GC, the GC has to work on more memory - which in turn might be slower.

Pass row number as variable in excel sheet

An alternative is to use OFFSET:

Assuming the column value is stored in B1, you can use the following

C1 = OFFSET(A1, 0, B1 - 1)

This works by:

a) taking a base cell (A1)
b) adding 0 to the row (keeping it as A)
c) adding (A5 - 1) to the column

You can also use another value instead of 0 if you want to change the row value too.

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

Set variable with multiple values and use IN

Use a Temp Table or a Table variable, e.g.

select 'A' as [value]
into #tmp
union
select 'B'
union 
select 'C'

and then

SELECT   
blah 
FROM    foo 
WHERE   myField IN (select [value] from #tmp) 

or

SELECT   
f.blah 
FROM foo f INNER JOIN #tmp t ON f.myField = t.[value]

What is the standard way to add N seconds to datetime.time in Python?

As others here have stated, you can just use full datetime objects throughout:

from datetime import datetime, date, time, timedelta
sometime = time(8,00) # 8am
later = (datetime.combine(date.today(), sometime) + timedelta(seconds=3)).time()

However, I think it's worth explaining why full datetime objects are required. Consider what would happen if I added 2 hours to 11pm. What's the correct behavior? An exception, because you can't have a time larger than 11:59pm? Should it wrap back around?

Different programmers will expect different things, so whichever result they picked would surprise a lot of people. Worse yet, programmers would write code that worked just fine when they tested it initially, and then have it break later by doing something unexpected. This is very bad, which is why you're not allowed to add timedelta objects to time objects.

java: run a function after a specific number of seconds

My code is as follows:

new java.util.Timer().schedule(

    new java.util.TimerTask() {
        @Override
        public void run() {
            // your code here, and if you have to refresh UI put this code: 
           runOnUiThread(new   Runnable() {
                  public void run() {
                            //your code

                        }
                   });
        }
    }, 
    5000 
);

Insert some string into given string at given index in Python

line='Name Age Group Class Profession'
arr = line.split()
for i in range(3):
    arr.insert(2, arr[2])
print(' '.join(arr))

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

Both times when you write the package name : 1. When you create a new project in Android Studio and 2. When you create a Configuration File

YOU should write it with lowercase letters - after changing to lowercase it works. If you don't want to waste time just go to you .json file and replace com.myname.MyAPPlicationnamE with com.myname.myapplicationname (for every match in the json file).

How do you clear the console screen in C?

just type clrscr(); function in void main().

as example:

void main()
{
clrscr();
printf("Hello m fresher in programming c.");
getch();
}

clrscr();

function easy to clear screen.

Using "Object.create" instead of "new"

Object.create is not yet standard on several browsers, for example IE8, Opera v11.5, Konq 4.3 do not have it. You can use Douglas Crockford's version of Object.create for those browsers but this doesn't include the second 'initialisation object' parameter used in CMS's answer.

For cross browser code one way to get object initialisation in the meantime is to customise Crockford's Object.create. Here is one method:-

Object.build = function(o) {
   var initArgs = Array.prototype.slice.call(arguments,1)
   function F() {
      if((typeof o.init === 'function') && initArgs.length) {
         o.init.apply(this,initArgs)
      }
   }
   F.prototype = o
   return new F()
}

This maintains Crockford prototypal inheritance, and also checks for any init method in the object, then runs it with your parameter(s), like say new man('John','Smith'). Your code then becomes:-

MY_GLOBAL = {i: 1, nextId: function(){return this.i++}}  // For example

var userB = {
    init: function(nameParam) {
        this.id = MY_GLOBAL.nextId();
        this.name = nameParam;
    },
    sayHello: function() {
        console.log('Hello '+ this.name);
    }
};
var bob = Object.build(userB, 'Bob');  // Different from your code
bob.sayHello();

So bob inherits the sayHello method and now has own properties id=1 and name='Bob'. These properties are both writable and enumerable of course. This is also a much simpler way to initialise than for ECMA Object.create especially if you aren't concerned about the writable, enumerable and configurable attributes.

For initialisation without an init method the following Crockford mod could be used:-

Object.gen = function(o) {
   var makeArgs = arguments 
   function F() {
      var prop, i=1, arg, val
      for(prop in o) {
         if(!o.hasOwnProperty(prop)) continue
         val = o[prop]
         arg = makeArgs[i++]
         if(typeof arg === 'undefined') break
         this[prop] = arg
      }
   }
   F.prototype = o
   return new F()
}

This fills the userB own properties, in the order they are defined, using the Object.gen parameters from left to right after the userB parameter. It uses the for(prop in o) loop so, by ECMA standards, the order of property enumeration cannot be guaranteed the same as the order of property definition. However, several code examples tested on (4) major browsers show they are the same, provided the hasOwnProperty filter is used, and sometimes even if not.

MY_GLOBAL = {i: 1, nextId: function(){return this.i++}};  // For example

var userB = {
   name: null,
   id: null,
   sayHello: function() {
      console.log('Hello '+ this.name);
   }
}

var bob = Object.gen(userB, 'Bob', MY_GLOBAL.nextId());

Somewhat simpler I would say than Object.build since userB does not need an init method. Also userB is not specifically a constructor but looks like a normal singleton object. So with this method you can construct and initialise from normal plain objects.

Fill DataTable from SQL Server database

If the variable table contains invalid characters (like a space) you should add square brackets around the variable.

public DataTable fillDataTable(string table)
{
    string query = "SELECT * FROM dstut.dbo.[" + table + "]";

    using(SqlConnection sqlConn = new SqlConnection(conSTR))
    using(SqlCommand cmd = new SqlCommand(query, sqlConn))
    {
        sqlConn.Open();
        DataTable dt = new DataTable();
        dt.Load(cmd.ExecuteReader());
        return dt;
    }
}

By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input

What are the differences between Pandas and NumPy+SciPy in Python?

Numpy is required by pandas (and by virtually all numerical tools for Python). Scipy is not strictly required for pandas but is listed as an "optional dependency". I wouldn't say that pandas is an alternative to Numpy and/or Scipy. Rather, it's an extra tool that provides a more streamlined way of working with numerical and tabular data in Python. You can use pandas data structures but freely draw on Numpy and Scipy functions to manipulate them.

String.format() to format double in java

String.format("%4.3f" , x) ;

It means that we need total 4 digits in ans , of which 3 should be after decimal . And f is the format specifier of double . x means the variable for which we want to find it . Worked for me . . .

Changing minDate and maxDate on the fly using jQuery DatePicker

You have a couple of options...

1) You need to call the destroy() method not remove() so...

$('#date').datepicker('destroy');

Then call your method to recreate the datepicker object.

2) You can update the property of the existing object via

$('#date').datepicker('option', 'minDate', new Date(startDate));
$('#date').datepicker('option', 'maxDate', new Date(endDate));

or...

$('#date').datepicker('option', { minDate: new Date(startDate),
                                  maxDate: new Date(endDate) });

Can't bind to 'formGroup' since it isn't a known property of 'form'

if this is just a typescript error but everything on your form works,you may just have to restart your IDE

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

Determine if char is a num or letter

chars are just integers, so you can actually do a straight comparison of your character against literals:

if( c >= '0' && c <= '9' ){

This applies to all characters. See your ascii table.

ctype.h also provides functions to do this for you.

How to change letter spacing in a Textview?

For embedding HTML text in your textview you can use Html.fromHTML() syntax. More information you will get from http://developer.android.com/reference/android/text/Html.html#fromHtml%28java.lang.String%29

How to dynamically change a web page's title?

for those looking of the npm version of it, there is an entire library for this:

npm install --save react-document-meta


import React from 'react';
import DocumentMeta from 'react-document-meta';

class Example extends React.Component {
  render() {
    const meta = {
      title: 'Some Meta Title',
      description: 'I am a description, and I can create multiple tags',
      canonical: 'http://example.com/path/to/page',
      meta: {
        charset: 'utf-8',
        name: {
          keywords: 'react,meta,document,html,tags'
        }
      }
    };

    return (
      <div>
        <DocumentMeta {...meta} />
        <h1>Hello World!</h1>
      </div>
    );
  }
}

React.render(<Example />, document.getElementById('root'));

Is there a difference between PhoneGap and Cordova commands?

they re both identical, except that phonegap cli can help you build your application on PhoneGap Build. My suggestion is to use the cordova CLI if you don't use the PhoneGap build service.

Prevent cell numbers from incrementing in a formula in Excel

TL:DR
row lock = A$5
column lock = $A5
Both = $A$5

Below are examples of how to use the Excel lock reference $ when creating your formulas

To prevent increments when moving from one row to another put the $ after the column letter and before the row number. e.g. A$5

To prevent increments when moving from one column to another put the $ before the row number. e.g. $A5

To prevent increments when moving from one column to another or from one row to another put the $ before the row number and before the column letter. e.g. $A$5

Using the lock reference will also prevent increments when dragging cells over to duplicate calculations.

How to render a DateTime in a specific format in ASP.NET MVC 3?

Only View File Adjust like this. You may try this.

@Html.FormatValue( (object)Convert.ChangeType(item.transdate, typeof(object)), 
                            "{0: yyyy-MM-dd}")

item.transdate it is your DateTime type data.

Cannot connect to MySQL 4.1+ using old authentication

Had the same issue, but executing the queries alone will not help. To fix this I did the following,

  1. Set old_passwords=0 in my.cnf file
  2. Restart mysql
  3. Login to mysql as root user
  4. Execute FLUSH PRIVILEGES;

How to get a list of installed android applications and pick one to run

I had a requirement to filter out the system apps which user do not really use(eg. "com.qualcomm.service", "update services", etc). Ultimately I added another condition to filter down the app list. I just checked whether the app has 'launcher intent'.

So, the resultant code looks like...

PackageManager pm = getPackageManager();
        List<ApplicationInfo> apps = pm.getInstalledApplications(PackageManager.GET_GIDS);

        for (ApplicationInfo app : apps) {
            if(pm.getLaunchIntentForPackage(app.packageName) != null) {
                // apps with launcher intent
                if((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
                    // updated system apps

                } else if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                    // system apps

                } else {
                    // user installed apps

                }
                appsList.add(app);
            }

        }

How do you remove columns from a data.frame?

Use read.table with colClasses instances of "NULL" to avoid creating them in the first place:

## example data and temp file
x <- data.frame(x = 1:10, y = rnorm(10), z = runif(10), a = letters[1:10], stringsAsFactors = FALSE)
tmp <- tempfile()
write.table(x, tmp, row.names = FALSE)


(y <- read.table(tmp, colClasses = c("numeric", rep("NULL", 2), "character"), header = TRUE))

x a
1   1 a
2   2 b
3   3 c
4   4 d
5   5 e
6   6 f
7   7 g
8   8 h
9   9 i
10 10 j

unlink(tmp)

Floating point inaccuracy examples

In python:

>>> 1.0 / 10
0.10000000000000001

Explain how some fractions cannot be represented precisely in binary. Just like some fractions (like 1/3) cannot be represented precisely in base 10.

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

You need to add dynamically created components to entryComponents inside your @NgModule

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    DashboardComponent,
    HomeComponent,
    DialogResultExampleDialog        
  ],
  entryComponents: [DialogResultExampleDialog]

Note: In some cases entryComponents under lazy loaded modules will not work, as a workaround put them in your app.module (root)

Import Android volley to Android Studio

Add this in your "build.gradle" of you app.

implementation 'com.android.volley:volley:1.1.1'

How to check if an user is logged in Symfony2 inside a controller?

Warning: Checking for 'IS_AUTHENTICATED_FULLY' alone will return false if the user has logged in using "Remember me" functionality.

According to Symfony 2 documentation, there are 3 possibilities:

IS_AUTHENTICATED_ANONYMOUSLY - automatically assigned to a user who is in a firewall protected part of the site but who has not actually logged in. This is only possible if anonymous access has been allowed.

IS_AUTHENTICATED_REMEMBERED - automatically assigned to a user who was authenticated via a remember me cookie.

IS_AUTHENTICATED_FULLY - automatically assigned to a user that has provided their login details during the current session.

Those roles represent three levels of authentication:

If you have the IS_AUTHENTICATED_REMEMBERED role, then you also have the IS_AUTHENTICATED_ANONYMOUSLY role. If you have the IS_AUTHENTICATED_FULLY role, then you also have the other two roles. In other words, these roles represent three levels of increasing "strength" of authentication.

I ran into an issue where users of our system that had used "Remember Me" functionality were being treated as if they had not logged in at all on pages that only checked for 'IS_AUTHENTICATED_FULLY'.

The answer then is to require them to re-login if they are not authenticated fully, or to check for the remembered role:

$securityContext = $this->container->get('security.authorization_checker');
if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
    // authenticated REMEMBERED, FULLY will imply REMEMBERED (NON anonymous)
}

Hopefully, this will save someone out there from making the same mistake I made. I used this very post as a reference when looking up how to check if someone was logged in or not on Symfony 2.

Source: http://symfony.com/doc/2.3/cookbook/security/remember_me.html#forcing-the-user-to-re-authenticate-before-accessing-certain-resources

Python: printing a file to stdout

If it's a large file and you don't want to consume a ton of memory as might happen with Ben's solution, the extra code in

>>> import shutil
>>> import sys
>>> with open("test.txt", "r") as f:
...    shutil.copyfileobj(f, sys.stdout)

also works.

Play infinitely looping video on-load in HTML5

As of April 2018, Chrome (along with several other major browsers) now require the muted attribute too.

Therefore, you should use

<video width="320" height="240" autoplay loop muted>
  <source src="movie.mp4" type="video/mp4" />
</video>

Why doesn't git recognize that my file has been changed, therefore git add not working

It happend to me as well, I tried the above mentioned methods and nothing helped. Then the solution was to change the file via terminal, not GUI. I do not know why this worked but worked. After I edited the file via nano from terminal git recognized it as changed and i was able to add it and commit.

How do I add Git version control (Bitbucket) to an existing source code folder?

User johannes told you how to do add existing files to a Git repository in a general situation. Because you talk about Bitbucket, I suggest you do the following:

  1. Create a new repository on Bitbucket (you can see a Create button on the top of your profile page) and you will go to this page:

    Create repository on Bitbucket

  2. Fill in the form, click next and then you automatically go to this page:

    Create repository from scratch or add existing files

  3. Choose to add existing files and you go to this page:

    Enter image description here

  4. You use those commands and you upload the existing files to Bitbucket. After that, the files are online.

Convert bytes to a string

I made a function to clean a list

def cleanLists(self, lista):
    lista = [x.strip() for x in lista]
    lista = [x.replace('\n', '') for x in lista]
    lista = [x.replace('\b', '') for x in lista]
    lista = [x.encode('utf8') for x in lista]
    lista = [x.decode('utf8') for x in lista]

    return lista

Removing spaces from string

I also had this problem. To sort out the problem of spaces in the middle of the string this line of code always works:

String field = field.replaceAll("\\s+", "");

e.printStackTrace equivalent in python

import traceback
traceback.print_exc()

When doing this inside an except ...: block it will automatically use the current exception. See http://docs.python.org/library/traceback.html for more information.

Excel VBA - Sum up a column

I have a label on my form receiving the sum of numbers from Column D in Sheet1. I am only interested in rows 2 to 50, you can use a row counter if your row count is dynamic. I have some blank entries as well in column D and they are ignored.

Me.lblRangeTotal = Application.WorksheetFunction.Sum(ThisWorkbook.Sheets("Sheet1").Range("D2:D50"))

Prevent direct access to a php include file

1: Checking the count of included files

if( count(get_included_files()) == ((version_compare(PHP_VERSION, '5.0.0', '>='))?1:0) )
{
    exit('Restricted Access');
}

Logic: PHP exits if the minimum include count isn't met. Note that prior to PHP5, the base page is not considered an include.


2: Defining and verifying a global constant

// In the base page (directly accessed):
define('_DEFVAR', 1);

// In the include files (where direct access isn't permitted):
defined('_DEFVAR') or exit('Restricted Access');

Logic: If the constant isn't defined, then the execution didn't start from the base page, and PHP would stop executing.

Note that for the sake of portability across upgrades and future changes, making this authentication method modular would significantly reduce the coding overhead as the changes won't need to be hard-coded to every single file.

// Put the code in a separate file instead, say 'checkdefined.php':
defined('_DEFVAR') or exit('Restricted Access');

// Replace the same code in the include files with:
require_once('checkdefined.php');

This way additional code can be added to checkdefined.php for logging and analytical purposes, as well as for generating appropriate responses.

Credit where credit is due: The brilliant idea of portability came from this answer.


3: Remote address authorisation

// Call the include from the base page(directly accessed):
$includeData = file_get_contents("http://127.0.0.1/component.php?auth=token");

// In the include files (where direct access isn't permitted):
$src = $_SERVER['REMOTE_ADDR']; // Get the source address
$auth = authoriseIP($src); // Authorisation algorithm
if( !$auth ) exit('Restricted Access');

The drawback with this method is isolated execution, unless a session-token provided with the internal request. Verify via the loop-back address in case of a single server configuration, or an address white-list for a multi-server or load-balanced server infrastructure.


4: Token authorisation

Similar to the previous method, one can use GET or POST to pass an authorization token to the include file:

if($key!="serv97602"){header("Location: ".$dart);exit();}

A very messy method, but also perhaps the most secure and versatile at the same time, when used in the right way.


5: Webserver specific configuration

Most servers allow you to assign permissions for individual files or directories. You could place all your includes in such restricted directories, and have the server configured to deny them.

For example in APACHE, the configuration is stored in the .htaccess file. Tutorial here.

Note however that server-specific configurations are not recommended by me because they are bad for portability across different web-servers. In cases like Content Management Systems where the deny-algorithm is complex or the list of denied directories is rather big, it might only make reconfiguration sessions rather gruesome. In the end it's best to handle this in code.


6: Placing includes in a secure directory OUTSIDE the site root

Least preferred because of access limitations in server environments, but a rather powerful method if you have access to the file-system.

//Your secure dir path based on server file-system
$secure_dir=dirname($_SERVER['DOCUMENT_ROOT']).DIRECTORY_SEPARATOR."secure".DIRECTORY_SEPARATOR;
include($secure_dir."securepage.php");

Logic:

  • The user cannot request any file outside the htdocs folder as the links would be outside the scope of the website's address system.
  • The php server accesses the file-system natively, and hence can access files on a computer just like how a normal program with required privileges can.
  • By placing the include files in this directory, you can ensure that the php server gets to access them, while hotlinking is denied to the user.
  • Even if the webserver's filesystem access configuration wasn't done properly, this method would prevent those files from becoming public accidentally.

Please excuse my unorthodox coding conventions. Any feedback is appreciated.

How do I call an Angular 2 pipe with multiple arguments?

In your component's template you can use multiple arguments by separating them with colons:

{{ myData | myPipe: 'arg1':'arg2':'arg3'... }}

From your code it will look like this:

new MyPipe().transform(myData, arg1, arg2, arg3)

And in your transform function inside your pipe you can use the arguments like this:

export class MyPipe implements PipeTransform { 
    // specify every argument individually   
    transform(value: any, arg1: any, arg2: any, arg3: any): any { }
    // or use a rest parameter
    transform(value: any, ...args: any[]): any { }
}

Beta 16 and before (2016-04-26)

Pipes take an array that contains all arguments, so you need to call them like this:

new MyPipe().transform(myData, [arg1, arg2, arg3...])

And your transform function will look like this:

export class MyPipe implements PipeTransform {    
    transform(value:any, args:any[]):any {
        var arg1 = args[0];
        var arg2 = args[1];
        ...
    }
}

Using subprocess to run Python script on Windows

Just found sys.executable - the full path to the current Python executable, which can be used to run the script (instead of relying on the shbang, which obviously doesn't work on Windows)

import sys
import subprocess

theproc = subprocess.Popen([sys.executable, "myscript.py"])
theproc.communicate()

How to determine when a Git branch was created?

very simple

In the address bar of your web browser, type the following URL and press the Enter key to retrieve information of a GitHub repository.

https://api.github.com/repos/{:owner}/{:repository}

Note! In the URL above, replace the {:owner} and {:repository} parts with the values that can be found in the URL of the GitHub repository for which you want to know the creation date. For example, if the URL of the repository is https://github.com/ArthurGareginyan/batch-rename/, then the URL of it’s information will be https://api.github.com/repos/ArthurGareginyan/batch-rename.

output:

image

How to convert data.frame column from Factor to numeric

This is FAQ 7.10. Others have shown how to apply this to a single column in a data frame, or to multiple columns in a data frame. But this is really treating the symptom, not curing the cause.

A better approach is to use the colClasses argument to read.table and related functions to tell R that the column should be numeric so that it never creates a factor and creates numeric. This will put in NA for any values that do not convert to numeric.

Another better option is to figure out why R does not recognize the column as numeric (usually a non numeric character somewhere in that column) and fix the original data so that it is read in properly without needing to create NAs.

Best is a combination of the last 2, make sure the data is correct before reading it in and specify colClasses so R does not need to guess (this can speed up reading as well).

Declaring an HTMLElement Typescript

Note that const declarations are block-scoped.

const el: HTMLElement | null = document.getElementById('content');

if (el) {
  const definitelyAnElement: HTMLElement = el;
}

So the value of definitelyAnElement is not accessible outside of the {}.

(I would have commented above, but I do not have enough Reputation apparently.)

Row count on the Filtered data

Simply put this in your code:

Application.WorksheetFunction.Subtotal(3, Range("A2:A500000"))

Make sure you apply the correct range, but just keep it to ONE column

What is the syntax of the enhanced for loop in Java?

  1. Enhanced For Loop (Java)
for (Object obj : list);
  1. Enhanced For Each in arraylist (Java)
ArrayList<Integer> list = new ArrayList<Integer>(); 
list.forEach((n) -> System.out.println(n)); 

How to convert Base64 String to javascript file object like as from file input form?

Way 1: only works for dataURL, not for other types of url.

_x000D_
_x000D_
 function dataURLtoFile(dataurl, filename) {_x000D_
 _x000D_
        var arr = dataurl.split(','),_x000D_
            mime = arr[0].match(/:(.*?);/)[1],_x000D_
            bstr = atob(arr[1]), _x000D_
            n = bstr.length, _x000D_
            u8arr = new Uint8Array(n);_x000D_
            _x000D_
        while(n--){_x000D_
            u8arr[n] = bstr.charCodeAt(n);_x000D_
        }_x000D_
        _x000D_
        return new File([u8arr], filename, {type:mime});_x000D_
    }_x000D_
    _x000D_
    //Usage example:_x000D_
    var file = dataURLtoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=','hello.txt');_x000D_
    console.log(file);
_x000D_
_x000D_
_x000D_

Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)

_x000D_
_x000D_
 //return a promise that resolves with a File instance_x000D_
    function urltoFile(url, filename, mimeType){_x000D_
        return (fetch(url)_x000D_
            .then(function(res){return res.arrayBuffer();})_x000D_
            .then(function(buf){return new File([buf], filename,{type:mimeType});})_x000D_
        );_x000D_
    }_x000D_
    _x000D_
    //Usage example:_x000D_
    urltoFile('data:text/plain;base64,aGVsbG8gd29ybGQ=', 'hello.txt','text/plain')_x000D_
    .then(function(file){ console.log(file);});
_x000D_
_x000D_
_x000D_

RuntimeWarning: DateTimeField received a naive datetime

You can also override settings, particularly useful in tests:

from django.test import override_settings

with override_settings(USE_TZ=False):
    # Insert your code that causes the warning here
    pass

This will prevent you from seeing the warning, at the same time anything in your code that requires a timezone aware datetime may give you problems. If this is the case, see kravietz answer.

Cannot implicitly convert type from Task<>

The main issue with your example that you can't implicitly convert Task<T> return types to the base T type. You need to use the Task.Result property. Note that Task.Result will block async code, and should be used carefully.

Try this instead:

public List<int> TestGetMethod()  
{  
    return GetIdList().Result;  
}

How to access a mobile's camera from a web app?

I don't know of any way to access a mobile phone's camera from the web browser without some additional mechanism (i.e. Flash or some type of container that allows access to the hardware API)

For the latter have a look at PhoneGap: http://docs.phonegap.com/phonegap_camera_camera.md.html

With this you should be able to access the camera at least on iOS and Android-based devices.

How do I calculate a point on a circle’s circumference?

The parametric equation for a circle is

x = cx + r * cos(a)
y = cy + r * sin(a)

Where r is the radius, cx,cy the origin, and a the angle.

That's pretty easy to adapt into any language with basic trig functions. Note that most languages will use radians for the angle in trig functions, so rather than cycling through 0..360 degrees, you're cycling through 0..2PI radians.

How to set environment variable or system property in spring tests?

You can set the System properties as VM arguments.

If your project is a maven project then you can execute following command while running the test class:

mvn test -Dapp.url="https://stackoverflow.com"

Test class:

public class AppTest  {
@Test
public void testUrl() {
    System.out.println(System.getProperty("app.url"));
    }
}

If you want to run individual test class or method in eclipse then :

1) Go to Run -> Run Configuration

2) On left side select your Test class under the Junit section.

3) do the following :

enter image description here

jQuery append() - return appended elements

I think you could do something like this:

var $child = $("#parentId").append("<div></div>").children("div:last-child");

The parent #parentId is returned from the append, so add a jquery children query to it to get the last div child inserted.

$child is then the jquery wrapped child div that was added.

Sorting a Dictionary in place with respect to keys

The correct answer is already stated (just use SortedDictionary).

However, if by chance you have some need to retain your collection as Dictionary, it is possible to access the Dictionary keys in an ordered way, by, for example, ordering the keys in a List, then using this list to access the Dictionary. An example...

Dictionary<string, int> dupcheck = new Dictionary<string, int>();

...some code that fills in "dupcheck", then...

if (dupcheck.Count > 0) {
  Console.WriteLine("\ndupcheck (count: {0})\n----", dupcheck.Count);
  var keys_sorted = dupcheck.Keys.ToList();
    keys_sorted.Sort();
  foreach (var k in keys_sorted) {
    Console.WriteLine("{0} = {1}", k, dupcheck[k]);
  }
}

Don't forget using System.Linq; for this.

how to write value into cell with vba code without auto type conversion?

This is probably too late, but I had a similar problem with dates that I wanted entered into cells from a text variable. Inevitably, it converted my variable text value to a date. What I finally had to do was concatentate a ' to the string variable and then put it in the cell like this:

prvt_rng_WrkSht.Cells(prvt_rng_WrkSht.Rows.Count, cnst_int_Col_Start_Date).Formula = "'" & _ 
    param_cls_shift.Start_Date (string property of my class) 

Difference between 'struct' and 'typedef struct' in C++?

In C++, there is only a subtle difference. It's a holdover from C, in which it makes a difference.

The C language standard (C89 §3.1.2.3, C99 §6.2.3, and C11 §6.2.3) mandates separate namespaces for different categories of identifiers, including tag identifiers (for struct/union/enum) and ordinary identifiers (for typedef and other identifiers).

If you just said:

struct Foo { ... };
Foo x;

you would get a compiler error, because Foo is only defined in the tag namespace.

You'd have to declare it as:

struct Foo x;

Any time you want to refer to a Foo, you'd always have to call it a struct Foo. This gets annoying fast, so you can add a typedef:

struct Foo { ... };
typedef struct Foo Foo;

Now struct Foo (in the tag namespace) and just plain Foo (in the ordinary identifier namespace) both refer to the same thing, and you can freely declare objects of type Foo without the struct keyword.


The construct:

typedef struct Foo { ... } Foo;

is just an abbreviation for the declaration and typedef.


Finally,

typedef struct { ... } Foo;

declares an anonymous structure and creates a typedef for it. Thus, with this construct, it doesn't have a name in the tag namespace, only a name in the typedef namespace. This means it also cannot be forward-declared. If you want to make a forward declaration, you have to give it a name in the tag namespace.


In C++, all struct/union/enum/class declarations act like they are implicitly typedef'ed, as long as the name is not hidden by another declaration with the same name. See Michael Burr's answer for the full details.

What does jQuery.fn mean?

In the jQuery source code we have jQuery.fn = jQuery.prototype = {...} since jQuery.prototype is an object the value of jQuery.fn will simply be a reference to the same object that jQuery.prototype already references.

To confirm this you can check jQuery.fn === jQuery.prototype if that evaluates true (which it does) then they reference the same object

Convert txt to csv python script

This is how I do it:

 with open(txtfile, 'r') as infile, open(csvfile, 'w') as outfile:
        stripped = (line.strip() for line in infile)
        lines = (line.split(",") for line in stripped if line)
        writer = csv.writer(outfile)
        writer.writerows(lines)

Hope it helps!

Delete last char of string

As an alternate to adding a comma for each item you could just using String.Join:

var strgroupids = String.Join(",",  groupIds);

This will add the seperator ("," in this instance) between each element in the array.

@UniqueConstraint and @Column(unique = true) in hibernate annotation

In addition to @Boaz's and @vegemite4me's answers....

By implementing ImplicitNamingStrategy you may create rules for automatically naming the constraints. Note you add your naming strategy to the metadataBuilder during Hibernate's initialization:

metadataBuilder.applyImplicitNamingStrategy(new MyImplicitNamingStrategy());

It works for @UniqueConstraint, but not for @Column(unique = true), which always generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq).

There is a bug report to solve this issue, so if you can, please vote there to have this implemented. Here: https://hibernate.atlassian.net/browse/HHH-11586

Thanks.

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

How do Python's any and all functions work?

>>> any([False, False, False])
False
>>> any([False, True, False])
True
>>> all([False, True, True])
False
>>> all([True, True, True])
True

Dealing with float precision in Javascript

You could do something like this:

> +(Math.floor(y/x)*x).toFixed(15);
1.2

What is the HTML5 equivalent to the align attribute in table cells?

If they're block level elements they won't be affected by text-align: center;. Someone may have set img { display: block; } and that's throwing it out of whack. You can try:

td { text-align: center; }
td * { display: inline; }

and if it looks as desired you should definitely replace * with the desired elements like:

td img, td foo { display: inline; }

PHP write file from input to txt

Your form should look like this :

<form action="myprocessingscript.php" method="POST">
    <input name="field1" type="text" />
    <input name="field2" type="text" />
    <input type="submit" name="submit" value="Save Data">
</form>

and the PHP

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n";
    $ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
    if($ret === false) {
        die('There was an error writing this file');
    }
    else {
        echo "$ret bytes written to file";
    }
}
else {
   die('no post data to process');
}

I wrote to /tmp/mydata.txt because this way I know exactly where it is. using data.txt writes to that file in the current working directory which I know nothing of in your example.

file_put_contents opens, writes and closes files for you. Don't mess with it.

Further reading: file_put_contents

Best way to increase heap size in catalina.bat file

If you look in your installation's bin directory you will see catalina.sh or .bat scripts. If you look in these you will see that they run a setenv.sh or setenv.bat script respectively, if it exists, to set environment variables. The relevant environment variables are described in the comments at the top of catalina.sh/bat. To use them create, for example, a file $CATALINA_HOME/bin/setenv.sh with contents

export JAVA_OPTS="-server -Xmx512m"

For Windows you will need, in setenv.bat, something like

set JAVA_OPTS=-server -Xmx768m

Original answer here

After you run startup.bat, you can easily confirm the correct settings have been applied provided you have turned @echo on somewhere in your catatlina.bat file (a good place could be immediately after echo Using CLASSPATH: "%CLASSPATH%"):

enter image description here

Using Html.ActionLink to call action on different controller

I would recommend writing these helpers using named parameters for the sake of clarity as follows:

@Html.ActionLink(
    linkText: "Details",
    actionName: "Details",
    controllerName: "Product",
    routeValues: new {
        id = item.ID
    },
    htmlAttributes: null
)

What's the difference between integer class and numeric class in R

To my understanding - we do not declare a variable with a data type so by default R has set any number without L to be a numeric. If you wrote:

> x <- c(4L, 5L, 6L, 6L)
> class(x)
>"integer" #it would be correct

Example of Integer:

> x<- 2L
> print(x)

Example of Numeric (kind of like double/float from other programming languages)

> x<-3.4
> print(x)

How do I select a sibling element using jQuery?

you can select a sibling element using jQuery

 <script type="text/javascript">
    $(document).ready(function(){
        $("selector").siblings().addClass("classname");
    });
 </script>

Demo here

Val and Var in Kotlin

Lets try this way.

Val is a Immutable constant 
    val change="Unchange" println(change)
    //It will throw error because val is constant variable
    // change="Change" 
    // println(change)
Var is a Mutable constant
    var name: String="Dummy"
    println(name)
    name="Funny"
    println(name)

How to use <DllImport> in VB.NET?

I saw in getwindowtext (user32) on pinvoke.net that you can place a MarshalAs statement to state that the StringBuffer is equivalent to LPSTR.

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
Public Function GetWindowText(hwnd As IntPtr, <MarshalAs(UnManagedType.LPStr)>lpString As System.Text.StringBuilder, cch As Integer) As Integer
End Function

Format datetime in asp.net mvc 4

Ahhhh, now it is clear. You seem to have problems binding back the value. Not with displaying it on the view. Indeed, that's the fault of the default model binder. You could write and use a custom one that will take into consideration the [DisplayFormat] attribute on your model. I have illustrated such a custom model binder here: https://stackoverflow.com/a/7836093/29407


Apparently some problems still persist. Here's my full setup working perfectly fine on both ASP.NET MVC 3 & 4 RC.

Model:

public class MyViewModel
{
    [DisplayName("date of birth")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? Birth { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            Birth = DateTime.Now
        });
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

View:

@model MyViewModel

@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Birth)
    @Html.EditorFor(x => x.Birth)
    @Html.ValidationMessageFor(x => x.Birth)
    <button type="submit">OK</button>
}

Registration of the custom model binder in Application_Start:

ModelBinders.Binders.Add(typeof(DateTime?), new MyDateTimeModelBinder());

And the custom model binder itself:

public class MyDateTimeModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (!string.IsNullOrEmpty(displayFormat) && value != null)
        {
            DateTime date;
            displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
            // use the format specified in the DisplayFormat attribute to parse the date
            if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            {
                return date;
            }
            else
            {
                bindingContext.ModelState.AddModelError(
                    bindingContext.ModelName,
                    string.Format("{0} is an invalid date format", value.AttemptedValue)
                );
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}

Now, no matter what culture you have setup in your web.config (<globalization> element) or the current thread culture, the custom model binder will use the DisplayFormat attribute's date format when parsing nullable dates.

HtmlEncode from Class Library

Just reference the System.Web assembly and then call: HttpServerUtility.HtmlEncode

http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.htmlencode.aspx

Array versus List<T>: When to use which?

If I know exactly how many elements I'm going to need, say I need 5 elements and only ever 5 elements then I use an array. Otherwise I just use a List<T>.

What process is listening on a certain port on Solaris?

I think the first answer is the best I wrote my own shell script developing this idea :

#!/bin/sh
if [ $# -ne 1 ]
then
    echo "Sintaxis:\n\t"
    echo " $0 {port to search in process }"
    exit
else
    MYPORT=$1
    for i in `ls /proc`
    do

       pfiles $i | grep port | grep "port: $MYPORT" > /dev/null
       if [ $? -eq 0 ]
         then
           echo " Port $MYPORT founded in $i proccess !!!\n\n"
           echo "Details\n\t"
           pfiles $i | grep port | grep "port: $MYPORT"
           echo "\n\t"
           echo "Process detail: \n\t"
           ps -ef | grep $i  | grep -v grep
       fi
    done
fi

How do you create optional arguments in php?

Give the optional argument a default value.

function date ($format, $timestamp='') {
}

How can I get all sequences in an Oracle database?

select sequence_owner, sequence_name from dba_sequences;


DBA_SEQUENCES -- all sequences that exist 
ALL_SEQUENCES  -- all sequences that you have permission to see 
USER_SEQUENCES  -- all sequences that you own

Note that since you are, by definition, the owner of all the sequences returned from USER_SEQUENCES, there is no SEQUENCE_OWNER column in USER_SEQUENCES.

How to invert a grep expression

As stated multiple times, inversion is achieved by the -v option to grep. Let me add the (hopefully amusing) note that you could have figured this out yourself by grepping through the grep help text:

grep --help | grep invert

-v, --invert-match select non-matching lines

How to add results of two select commands in same query

If you want to make multiple operation use

select (sel1.s1+sel2+s2)

(select sum(hours) s1 from resource) sel1
join 
(select sum(hours) s2 from projects-time)sel2
on sel1.s1=sel2.s2

How do I find out which process is locking a file using .NET?

One of the good things about handle.exe is that you can run it as a subprocess and parse the output.

We do this in our deployment script - works like a charm.

CSS for grabbing cursors (drag & drop)

The closed hand cursor is not 16x16. If you would need them in the same dimensions, here you have both of them in 16x16 px

opened hand closed hand

Or if you need original cursors:

https://www.google.com/intl/en_ALL/mapfiles/openhand.cur https://www.google.com/intl/en_ALL/mapfiles/closedhand.cur

Set div height to fit to the browser using CSS

I think the fastest way is to use grid system with fractions. So your container have 100vw, which is 100% of the window width and 100vh which is 100% of the window height.

Using fractions or 'fr' you can choose the width you like. the sum of the fractions equals to 100%, in this example 4fr. So the first part will be 1fr (25%) and the seconf is 3fr (75%)

More about fr units here.

_x000D_
_x000D_
.container{
  width: 100vw;
  height:100vh; 
  display: grid;
  grid-template-columns: 1fr 3fr;
}

/*You don't need this*/
.div1{
  background-color: yellow;
}

.div2{
  background-color: red;
}
_x000D_
<div class='container'>
  <div class='div1'>This is div 1</div>
  <div class='div2'>This is div 2</div>
</div>
_x000D_
_x000D_
_x000D_

How to set entire application in portrait mode only?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    //setting screen orientation locked so it will be acting as potrait
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
}

Content-Disposition:What are the differences between "inline" and "attachment"?

Because when I use one or another I get a window prompt asking me to download the file for both of them.

This behavior depends on the browser and the file you are trying to serve. With inline, the browser will try to open the file within the browser.

For example, if you have a PDF file and Firefox/Adobe Reader, an inline disposition will open the PDF within Firefox, whereas attachment will force it to download.

If you're serving a .ZIP file, browsers won't be able to display it inline, so for inline and attachment dispositions, the file will be downloaded.

JavaScript error (Uncaught SyntaxError: Unexpected end of input)

This error is mainly caused by empty returned ajax calls, when trying to parse an empty JSON.

To solve this test if the returned data is empty

$.ajax({
    url: url,
    type: "get",
    dataType: "json",
    success: function (response) {

        if(response.data.length == 0){
            // EMPTY
        }else{
            var obj =jQuery.parseJSON(response.data);
            console.log(obj);
        }
    }
});

How to dynamically insert a <script> tag via jQuery after page load?

There is one workaround that sounds more like a hack and I agree it's not the most elegant way of doing it, but works 100%:

Say your AJAX response is something like

<b>some html</b>
<script>alert("and some javscript")

Note that I've skipped the closing tag on purpose. Then in the script that loads the above, do the following:

$.ajax({
    url: "path/to/return/the-above-js+html.php",
    success: function(newhtml){
        newhtml += "<";
        newhtml += "/script>";
        $("head").append(newhtml);
    }
});

Just don't ask me why :-) This is one of those things I've come to as a result of desperate almost random trials and fails.

I have no complete suggestions on how it works, but interestingly enough, it will NOT work if you append the closing tag in one line.

In times like these, I feel like I've successfully divided by zero.

Convert SVG to image (JPEG, PNG, etc.) in the browser

There are several ways to convert SVG to PNG using the Canvg library.

In my case, I needed to get the PNG blob from inline SVG.

The library documentation provides an example (see OffscreenCanvas example).

But this method does not work at the moment in Firefox. Yes, you can enable the gfx.offscreencanvas.enabled option in the settings. But will every user on the site do this? :)

However, there is another way that will work in Firefox too.

const el = document.getElementById("some-svg"); //this is our inline SVG

var canvas = document.createElement('canvas'); //create a canvas for the SVG render
canvas.width = el.clientWidth; //set canvas sizes
canvas.height = el.clientHeight;

const svg = new XMLSerializer().serializeToString(el); //convert SVG to string

//render SVG inside canvas
const ctx = canvas.getContext('2d');
const v = await Canvg.fromString(ctx, svg);
await v.render();

let canvasBlob = await new Promise(resolve => canvas.toBlob(resolve));

For the last line thanks to this answer

Disable a Maven plugin defined in a parent POM

I know this thread is really old but the solution from @Ivan Bondarenko helped me in my situation.

I had the following in my pom.xml.

<build>
    ...
    <plugins>
         <plugin>
                <groupId>com.consol.citrus</groupId>
                <artifactId>citrus-remote-maven-plugin</artifactId>
                <version>${citrus.version}</version>
                <executions>
                    <execution>
                        <id>generate-citrus-war</id>
                        <goals>
                            <goal>test-war</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
    </plugins>
</build>

What I wanted, was to disable the execution of generate-citrus-war for a specific profile and this was the solution:

<profile>
    <id>it</id>
    <build>
        <plugins>
            <plugin>
                <groupId>com.consol.citrus</groupId>
                <artifactId>citrus-remote-maven-plugin</artifactId>
                <version>${citrus.version}</version>
                <executions>
                    <!-- disable generating the war for this profile -->
                    <execution>
                        <id>generate-citrus-war</id>
                        <phase/>
                    </execution>

                    <!-- do something else -->
                    <execution>
                        ...
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</profile>

Xcode Simulator: how to remove older unneeded devices?

Run this command in terminal to remove simulators that can't be accessed from the current version of Xcode (8+?) in use on your machine.

xcrun simctl delete unavailable

Also if you're looking to reclaim simulator related space Michael Tsai found that deleting sim logs saved him 30 GB.

~/Library/Logs/CoreSimulator

Cutting the videos based on start and end time using ffmpeg

Use -to instead of -t: -to specifies the end time, -t specifies the duration

Unix command to check the filesize

ls -l --block-size=M 

will give you a long format listing (needed to actually see the file size) and round file sizes up to the nearest MiB. If you want MB (10^6 bytes) rather than MiB (2^20 bytes) units, use --block-size=MB instead.

Or

ls -lah 

-h When used with the -l option, use unit suffixes: Byte, Kilobyte, Megabyte, Gigabyte, Terabyte and Petabyte in order to reduce the number of digits to three or less using base 2 for sizes.

man ls

http://unixhelp.ed.ac.uk/CGI/man-cgi?ls

Find length (size) of an array in jquery

obj={};

$.each(obj, function (key, value) {
    console.log(key+ ' : ' + value); //push the object value
});

for (var i in obj) {
    nameList += "" + obj[i] + "";//display the object value
}

$("id/class").html($(nameList).length);//display the length of object.

Comparison between Corona, Phonegap, Titanium

From what I've gathered, here are some differences between the two:

  • PhoneGap basically generates native wrappers for what are still web apps. It spits out a WhateverYourPlatformIs project, you build it, and deploy. If we're talking about the iPhone (which is where I spend my time), it doesn't seem much different from creating a web app launcher (a shortcut that gets its own Springboard icon, so you can launch it like (like) a native app). The "app" itself is still html/js/etc., and runs inside a hosted browser control. What PhoneGap provides beyond that is a bridge between JavaScript and native device APIs. So, you write JavaScript against PhoneGap APIs, and PhoneGap then makes the appropriate corresponding native call. In that respect, it is different from deploying a plain old web app.

  • Titanium source gets compiled down to native bits. That is, your html/js/etc. aren't simply attached to a project and then hosted inside a web browser control - they're turned into native apps. That means, for example, that your app's interface will be composed of native UI components. There are ways of getting native look-and-feel without having a native app, but... well... what a nightmare that usually turns out to be.

The two are similar in that you write all your stuff using typical web technologies (html/js/css/blah blah blah), and that you get access to native functionality through custom JavaScript APIs.

But, again, PhoneGap apps (PhonGapps? I don't know... is that a stupid name? It's easier to say - I know that much) start their lives as web apps and end their lives as web apps. On the iPhone, your html/js/etc. is just executed inside a UIWebView control, and the PhoneGap JavaScript APIs your js calls are routed to native APIs.

Titanium apps become native apps - they're just developed using web dev tech.

What does this actually mean?

  1. A Titanium app will look like a "real" app because, ultimately, it is a "real" app.

  2. A PhoneGap app will look like a web app being hosted in a browser control because, ultimately, it is a web app being hosted in a browser control.

Which is right for you?

  • If you want to write native apps using web dev skills, Titanium is your best bet.

  • If you want to write an app using web dev skills that you could realistically deploy to multiple platforms (iPhone, Android, Blackberry, and whatever else they decide to include), and if you want access to a subset of native platform features (GPS, accelerometer, etc.) through a unified JavaScript API, PhoneGap is probably what you want.

You might be asking: Why would I want to write a PhoneGapp (I've decided to use the name) rather than a web app that's hosted on the web? Can't I still access some native device features that way, but also have the convenience of true web deployment rather than forcing the user to download my "native" app and install it?

The answer is: Because you can submit your PhoneGapp to the App Store and charge for it. You also get that launcher icon, which makes it harder for the user to forget about your app (I'm far more likely to forget about a bookmark than an app icon).

You could certainly charge for access to your web-hosted web app, but how many people are really going to go through the process to do that? With the App Store, I pick an app, tap the "Buy" button, enter a password, and I'm done. It installs. Seconds later, I'm using it. If I had to use someone else's one-off mobile web transaction interface, which likely means having to tap out my name, address, phone number, CC number, and other things I don't want to tap out, I almost certainly wouldn't go through with it. Also, I trust Apple - I'm confident Steve Jobs isn't going to log my info and then charge a bunch of naughty magazine subscriptions to my CC for kicks.

Anyway, except for the fact that web dev tech is involved, PhoneGap and Titanium are very different - to the point of being only superficially comparable.

I hate web apps, by the by, and if you read iTunes App Store reviews, users are pretty good at spotting them. I won't name any names, but I have a couple "apps" on my phone that look and run like garbage, and it's because they're web apps that are hosted inside UIWebView instances. If I wanted to use a web app, I'd open Safari and, you know, navigate to one. I bought an iPhone because I want things that are iPhone-y. I have no problem using, say, a snazzy Google web app inside Safari, but I'd feel cheated if Google just snuck a bookmark onto Springboard by presenting a web app as a native one.

Have to go now. My girlfriend has that could-you-please-stop-using-that-computer-for-three-seconds look on her face.

How do I compare a value to a backslash?

Escape the backslash:

if message.value[0] == "/" or message.value[0] == "\\":

From the documentation:

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

Printing the correct number of decimal points with cout

Just a minor point; put the following in the header

using namespace std;

then

std::cout << std::fixed << std::setprecision(2) << d;

becomes simplified to

cout << fixed << setprecision(2) << d;

How to check a boolean condition in EL?

You can check this way too

<c:if test="${theBooleanVariable ne true}">It's false!</c:if>

How to measure elapsed time in Python?

To get insight on every function calls recursively, do:

%load_ext snakeviz
%%snakeviz

It just takes those 2 lines of code in a Jupyter notebook, and it generates a nice interactive diagram. For example:

enter image description here

Here is the code. Again, the 2 lines starting with % are the only extra lines of code needed to use snakeviz:

# !pip install snakeviz
%load_ext snakeviz
import glob
import hashlib

%%snakeviz

files = glob.glob('*.txt')
def print_files_hashed(files):
    for file in files:
        with open(file) as f:
            print(hashlib.md5(f.read().encode('utf-8')).hexdigest())
print_files_hashed(files)

It also seems possible to run snakeviz outside notebooks. More info on the snakeviz website.

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

What is the reason behind "non-static method cannot be referenced from a static context"?

So you are asking for a very core reason?

Well, since you are developing in Java, the compiler generates an object code that the Java Virtual Machine can interpret. The JVM anyway is a binary program that run in machine language (probably the JVM’s version specific for your operating system and hardware was previously compiled by another programming language like C in order to get a machine code that can run in your processor). At the end, any code is translated to machine code. So, create an object (an instance of a class) is equivalent to reserve a memory space (memory registers that will be processor registers when the CPU scheduler of the operating system put your program at the top of the queue in order to execute it) to have a data storage place that can be able to read and write data. If you don’t have an instance of a class (which happens on a static context), then you don’t have that memory space to read or write the data. In fact, like other people had said, the data don’t exist (because from the begin you never had written neither had reserved the memory space to store it).

Sorry for my english! I'm latin!

Why is sed not recognizing \t as a tab?

I used this on Mac:

sed -i '' $'$i\\\n\\\thello\n' filename

Used this link for reference

Why did my Git repo enter a detached HEAD state?

Detached HEAD means that what's currently checked out is not a local branch.

Some scenarios that will result in a Detached HEAD state:

  • If you checkout a remote branch, say origin/master. This is a read-only branch. Thus, when creating a commit from origin/master it will be free-floating, i.e. not connected to any branch.

  • If you checkout a specific tag or commit. When doing a new commit from here, it will again be free-floating, i.e. not connected to any branch. Note that when a branch is checked out, new commits always gets automatically placed at the tip.

    When you want to go back and checkout a specific commit or tag to start working from there, you could create a new branch originating from that commit and switch to it by git checkout -b new_branch_name. This will prevent the Detached HEAD state as you now have a branch checked out and not a commit.

How to count the frequency of the elements in an unordered list?

Counting the frequency of elements is probably best done with a dictionary:

b = {}
for item in a:
    b[item] = b.get(item, 0) + 1

To remove the duplicates, use a set:

a = list(set(a))

CSS Selector "(A or B) and C"?

I found success using the :is() selector:

*:is(.a, .b).c{...}

Force sidebar height 100% using CSS (with a sticky bottom image)?

I would use css tables to achieve a 100% sidebar height.

The basic idea is to wrap the sidebar and main divs in a container.

Give the container a display:table

And give the 2 child divs (sidebar and main) a display: table-cell

Like so..

#container {
display: table;
}
#main {
display: table-cell;
vertical-align: top;
}
#sidebar {
display: table-cell;
vertical-align: top;
} 

Take a look at this LIVE DEMO where I have modified your initial markup using the above technique (I have used background colors for the different divs so that you can see which ones are which)

Sending images using Http Post

I struggled a lot trying to implement posting a image from Android client to servlet using httpclient-4.3.5.jar, httpcore-4.3.2.jar, httpmime-4.3.5.jar. I always got a runtime error. I found out that basically you cannot use these jars with Android as Google is using older version of HttpClient in Android. The explanation is here http://hc.apache.org/httpcomponents-client-4.3.x/android-port.html. You need to get the httpclientandroidlib-1.2.1 jar from android http-client library. Then change your imports from or.apache.http.client to ch.boye.httpclientandroidlib. Hope this helps.

Fatal error: Class 'Illuminate\Foundation\Application' not found

I just fixed this problem (Different Case with same error),
The answer above I tried may not work because My case were different but produced the same error.
I think my vendor libraries were jumbled,
I get this error by:
1. Pull from remote git, master branch is codeigniter then I do composer update on master branch, I wanted to work on laravel branch then I checkout and do composer update so I get the error,

Fatal error: Class 'Illuminate\Foundation\Application' not found in C:\cms\bootstrap\app.php on line 14

Solution: I delete the project on local and do a clone again, after that I checkout to my laravel file work's branch and do composer update then it is fixed.

Error:(23, 17) Failed to resolve: junit:junit:4.12

Simply try to compile and run you project while having active internet connection.

it worked for me in Android studio 1.5 Ubuntu 15.04

Column count doesn't match value count at row 1

  1. you missed the comma between two values or column name
  2. you put extra values or an extra column name

How to make Bootstrap Panel body with fixed height

You can use max-height in an inline style attribute, as below:

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>

To use scrolling with content that overflows a given max-height, you can alternatively try the following:

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="max-height: 10;overflow-y: scroll;">fdoinfds sdofjohisdfj</div>
</div>

To restrict the height to a fixed value you can use something like this.

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="min-height: 10; max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>

Specify the same value for both max-height and min-height (either in pixels or in points – as long as it’s consistent).

You can also put the same styles in css class in a stylesheet (or a style tag as shown below) and then include the same in your tag. See below:

Style Code:

.fixed-panel {
  min-height: 10;
  max-height: 10;
  overflow-y: scroll;
}

Apply Style :

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body fixed-panel">fdoinfds sdofjohisdfj</div>
</div>

Hope this helps with your need.

convert ArrayList<MyCustomClass> to JSONArray

Add to your gradle:

implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

Convert ArrayList to JsonArray

JsonArray jsonElements = (JsonArray) new Gson().toJsonTree(itemsArrayList);

What is the use of DesiredCapabilities in Selenium WebDriver?

  1. It is a class in org.openqa.selenium.remote.DesiredCapabilities package.
  2. It gives facility to set the properties of browser. Such as to set BrowserName, Platform, Version of Browser.
  3. Mostly DesiredCapabilities class used when do we used Selenium Grid.
  4. We have to execute mutiple TestCases on multiple Systems with different browser with Different version and Different Operating System.

Example:

WebDriver driver;
String baseUrl , nodeUrl;
baseUrl = "https://www.facebook.com";
nodeUrl = "http://192.168.10.21:5568/wd/hub";

DesiredCapabilities capability = DesiredCapabilities.firefox();
capability.setBrowserName("firefox");
capability.setPlatform(Platform.WIN8_1);

driver = new RemoteWebDriver(new URL(nodeUrl),capability);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);

Can I embed a custom font in an iPhone application?

I would recommend following one of my favorite short tutorials here: http://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/ from which this information comes.

Step 1 - Drag your .ttf or .otf from Finder into your Project

NOTE - Make sure to click the box to 'Add to targets' on your main application target

Drag font files into your project and click to add them to your target

If you forgot to click to add it to your target then click on the font file in your project hierarchy and on the right side panel click the main app target in the Target Membership section

how to add fonts to app target if you forgot

To make sure your fonts are part of your app target make sure they show up in your Copy Bundle Resources in Build Phases

how to check resources to see if fonts are part of app target

Step 2 - Add the font file names to your Plist

Go to the Custom iOS Target Properties in your Info Section and add a key to the items in that section called Fonts provided by application (you should see it come up as an option as you type it and it will set itself up as an array. Click the little arrow to open up the array items and type in the names of the .ttf or .otf files that you added to let your app know that these are the font files you want available

NOTE - If your app crashes right after this step then check your spelling on the items you add here

example plist with custom fonts added

Step 3 - Find out the names of your fonts so you can call them

Quite often the font name seen by your application is different from what you think it is based on the filename for that font, put this in your code and look over the log your application makes to see what font name to call in your code

Swift

for family: String in UIFont.familyNames(){
  print("\(family)")
  for names: String in UIFont.fontNamesForFamilyName(family){
      print("== \(names)")
  }
}

Objective C

for (NSString* family in [UIFont familyNames]){
    NSLog(@"%@", family);
    for (NSString* name in [UIFont fontNamesForFamilyName: family]){
        NSLog(@"  %@", name);
    }
}

Your log should look something like this:

Example of searching log to find font names

Step 4 - Use your new custom font using the name from Step 3

Swift

 label.font = UIFont(name: "SourceSansPro-Regular", size: 18)

Objective C

 label.font = [UIFont fontWithName:@"SourceSansPro-Regular" size:18];

Embed YouTube Video with No Ads

For whom can help, nowadays in 2018, youtube have options for this:

(Example in Catalan, sorry :)

enter image description here

Translation of the 3 arrows : "Share" - "Embed" - "Show suggested videos when the video is finished"

Compare one String with multiple values in one expression

In Java 8+, you might use a Stream<T> and anyMatch(Predicate<? super T>) with something like

if (Stream.of("val1", "val2", "val3").anyMatch(str::equalsIgnoreCase)) {
    // ...
}

How to convert a Title to a URL slug in jQuery?

Combining a variety of elements from the answers here with normalize provides good coverage. Keep the order of operations to incrementally clean the url.

function clean_url(s) {
    return s.toString().normalize('NFD').replace(/[\u0300-\u036f]/g, "") //remove diacritics
            .toLowerCase()
            .replace(/\s+/g, '-') //spaces to dashes
            .replace(/&/g, '-and-') //ampersand to and
            .replace(/[^\w\-]+/g, '') //remove non-words
            .replace(/\-\-+/g, '-') //collapse multiple dashes
            .replace(/^-+/, '') //trim starting dash
            .replace(/-+$/, ''); //trim ending dash
}

normlize('NFD') breaks accented characters into their components, which are basic letters plus diacritics (the accent part). replace(/[\u0300-\u036f]/g, "") purges all the diacritics, leaving the basic letters by themselves. The rest is explained with inline comments.

How can I initialize C++ object member variables in the constructor?

You're trying to create a ThingOne by using operator= which isn't going to work (incorrect syntax). Also, you're using a class name as a variable name, that is, ThingOne* ThingOne. Firstly, let's fix the variable names:

private:
    ThingOne* t1;
    ThingTwo* t2;

Since these are pointers, they must point to something. If the object hasn't been constructed yet, you'll need to do so explicitly with new in your BigMommaClass constructor:

BigMommaClass::BigMommaClass(int n1, int n2)
{
    t1 = new ThingOne(100);
    t2 = new ThingTwo(n1, n2);
}

Generally initializer lists are preferred for construction however, so it will look like:

BigMommaClass::BigMommaClass(int n1, int n2)
    : t1(new ThingOne(100)), t2(new ThingTwo(n1, n2))
{ }

SSIS Excel Connection Manager failed to Connect to the Source

The recommendations from this article Extracting Data From Excel with SSIS resolved the issue for me.

I downloaded MS Access Database Engine 2010 32 bit driver from the link in that article.

Also set Project Configuration Properties for Debugging Run64BitRuntime = False

In SQL Server 2014 SSMS (Integration Service Catalog -> SSISDB -> Environments -> Projects for all Packages in Validate checked box 32 bit Runtime.

My SSIS packages are working now in both VS 2013 and SQL Server 2014 environments.

How to add fixed button to the bottom right of page

You are specifying .fixedbutton in your CSS (a class) and specifying the id on the element itself.

Change your CSS to the following, which will select the id fixedbutton

#fixedbutton {
    position: fixed;
    bottom: 0px;
    right: 0px; 
}

Here's a jsFiddle courtesy of JoshC.

How do I print bytes as hexadecimal?

I don't know of a better way than:

unsigned char byData[xxx]; 

int nLength = sizeof(byData) * 2;
char *pBuffer = new char[nLength + 1];
pBuffer[nLength] = 0;
for (int i = 0; i < sizeof(byData); i++)
{
    sprintf(pBuffer[2 * i], "%02X", byData[i]);
}

You can speed it up by using a Nibble to Hex method

unsigned char byData[xxx];

const char szNibbleToHex = { "0123456789ABCDEF" };

int nLength = sizeof(byData) * 2;
char *pBuffer = new char[nLength + 1];
pBuffer[nLength] = 0;
for (int i = 0; i < sizeof(byData); i++)
{
    // divide by 16
    int nNibble = byData[i] >> 4;
    pBuffer[2 * i]  = pszNibbleToHex[nNibble];

    nNibble = byData[i] & 0x0F;
    pBuffer[2 * i + 1]  = pszNibbleToHex[nNibble];

}

A method to count occurrences in a list

var wordCount =
    from word in words
    group word by word into g
    select new { g.Key, Count = g.Count() };    

This is taken from one of the examples in the linqpad

How do I get a file's directory using the File object?

In either case, I'd expect file.getParent() (or file.getParentFile()) to give you what you want.

Additionally, if you want to find out whether the original File does exist and is a directory, then exists() and isDirectory() are what you're after.

How can I submit a form using JavaScript?

You can use the below code to submit the form using JavaScript:

document.getElementById('FormID').submit();

How to run a hello.js file in Node.js on windows?

Step For Windows

  1. press the ctrl + r.then type cmd and hit enter.
  2. now command prompt will be open.

  3. after the type cd filepath of file. ex(cd C:\Users\user\Desktop\ ) then hit the enter.

  4. please check if npm installed or not using this command node -v. then if you installed will get node version.
  5. type the command on command prompt like this node filename.js . example(node app.js)

C:\Users\user\Desktop>node app.js

Remove a specific string from an array of string

import java.util.*;

class Array {
    public static void main(String args[]) {
        ArrayList al = new ArrayList();
        al.add("google");
        al.add("microsoft");
        al.add("apple");
        System.out.println(al);
        //i only remove the apple//
        al.remove(2);
        System.out.println(al);
    }
}

Is it possible to import a whole directory in sass using @import?

It might be an old question, but still relevant in 2020, so I might post some update. Since Octobers'19 update we generally should use @use instead of @import, but that's only a remark. Solution to this question is use index files to simplify including whole folders. Example below.

// foundation/_code.scss
code {
  padding: .25em;
  line-height: 0;
}

// foundation/_lists.scss
ul, ol {
  text-align: left;

  & & {
    padding: {
      bottom: 0;
      left: 0;
    }
  }
}

// foundation/_index.scss
@use 'code';
@use 'lists';

// style.scss
@use 'foundation';

https://sass-lang.com/documentation/at-rules/use#index-files

How to delete from select in MySQL?

If you want to delete all duplicates, but one out of each set of duplicates, this is one solution:

DELETE posts
FROM posts
LEFT JOIN (
    SELECT id
    FROM posts
    GROUP BY id
    HAVING COUNT(id) = 1

    UNION

    SELECT id
    FROM posts
    GROUP BY id
    HAVING COUNT(id) != 1
) AS duplicate USING (id)
WHERE duplicate.id IS NULL;

Is there any boolean type in Oracle databases?

Not at the SQL level and that's a pity There is one in PLSQL though

Remove first Item of the array (like popping from stack)

Plunker

$scope.remove = function(item) { 
    $scope.cards.splice(0, 1);     
  }

Made changes to .. now it will remove from the top

What is the dual table in Oracle?

DUAL we mainly used for getting the next number from the sequences.

Syntax : SELECT 'sequence_name'.NEXTVAL FROM DUAL

This will return the one row one column value(NEXTVAL column name).

Is it possible to select the last n items with nth-child?

Because of the definition of the semantics of nth-child, I don't see how this is possible without including the length of the list of elements involved. The point of the semantics is to allow segregation of a bunch of child elements into repeating groups (edit - thanks BoltClock) or into a first part of some fixed length, followed by "the rest". You sort-of want the opposite of that, which is what nth-last-child gives you.

Python readlines() usage and efficient practice for reading

The short version is: The efficient way to use readlines() is to not use it. Ever.


I read some doc notes on readlines(), where people has claimed that this readlines() reads whole file content into memory and hence generally consumes more memory compared to readline() or read().

The documentation for readlines() explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list full of strings out of those lines.

But the documentation for read() likewise guarantees that it reads the whole file into memory, and builds a string, so that doesn't help.


On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.


You can work around this in three ways:

  1. Write a loop around readlines(sizehint), read(size), or readline().
  2. Just use the file as a lazy iterator without calling any of these.
  3. mmap the file, which allows you to treat it as a giant string without first reading it in.

For example, this has to read all of foo at once:

with open('foo') as f:
    lines = f.readlines()
    for line in lines:
        pass

But this only reads about 8K at a time:

with open('foo') as f:
    while True:
        lines = f.readlines(8192)
        if not lines:
            break
        for line in lines:
            pass

And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.

with open('foo') as f:
    while True:
        line = f.readline()
        if not line:
            break
        pass

And this will do the exact same thing as the previous:

with open('foo') as f:
    for line in f:
        pass

Meanwhile:

but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?

Python doesn't make any such guarantees about garbage collection.

The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.

However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.

On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.

Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of mallocs to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).


Putting it all together, here's how I'd write your program:

for filename in os.listdir(input_dir):
    with open(filename, 'rb') as f:
        if filename.endswith(".gz"):
            f = gzip.open(fileobj=f)
        words = (line.split(delimiter) for line in f)
        ... my logic ...  

Or, maybe:

for filename in os.listdir(input_dir):
    if filename.endswith(".gz"):
        f = gzip.open(filename, 'rb')
    else:
        f = open(filename, 'rb')
    with contextlib.closing(f):
        words = (line.split(delimiter) for line in f)
        ... my logic ...

Java time-based map/cache with expiring keys

Typically, a cache should keep objects around some time and shall expose of them some time later. What is a good time to hold an object depends on the use case. I wanted this thing to be simple, no threads or schedulers. This approach works for me. Unlike SoftReferences, objects are guaranteed to be available some minimum amount of time. However, the do not stay around in memory until the sun turns into a red giant.

As useage example think of a slowly responding system that shall be able to check if a request has been done quite recently, and in that case not to perform the requested action twice, even if a hectic user hits the button several times. But, if the same action is requested some time later, it shall be performed again.

class Cache<T> {
    long avg, count, created, max, min;
    Map<T, Long> map = new HashMap<T, Long>();

    /**
     * @param min   minimal time [ns] to hold an object
     * @param max   maximal time [ns] to hold an object
     */
    Cache(long min, long max) {
        created = System.nanoTime();
        this.min = min;
        this.max = max;
        avg = (min + max) / 2;
    }

    boolean add(T e) {
        boolean result = map.put(e, Long.valueOf(System.nanoTime())) != null;
        onAccess();
        return result;
    }

    boolean contains(Object o) {
        boolean result = map.containsKey(o);
        onAccess();
        return result;
    }

    private void onAccess() {
        count++;
        long now = System.nanoTime();
        for (Iterator<Entry<T, Long>> it = map.entrySet().iterator(); it.hasNext();) {
            long t = it.next().getValue();
            if (now > t + min && (now > t + max || now + (now - created) / count > t + avg)) {
                it.remove();
            }
        }
    }
}

Installation error: INSTALL_FAILED_OLDER_SDK

I am on Android Studio. I got this error when min/targetSDKVersion were set to 17. While looking thro this thread, I tried to change the minSDKVersion, voila..problem fixed. Go figure.. :(

    android:minSdkVersion="17"
    android:targetSdkVersion="17" />

Hexadecimal To Decimal in Shell Script

One more way to do it using the shell (bash or ksh, doesn't work with dash):

echo $((16#FF))
255

Use Font Awesome icon as CSS content

Another solution without you having to manually mess around with the Unicode characters can be found in Making Font Awesome awesome - Using icons without i-tags (disclaimer: I wrote this article).

In a nutshell, you can create a new class like this:

.icon::before {
    display: inline-block;
    margin-right: .5em;
    font: normal normal normal 14px/1 FontAwesome;
    font-size: inherit;
    text-rendering: auto;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    transform: translate(0, 0);
}

And then use it with any icon, for example:

<a class="icon fa-car" href="#">This is a link</a>

mysqli_real_connect(): (HY000/2002): No such file or directory

If above solutions doesn't work, try to change the default por from 3306, to another one (i.e. 3307)

How to dismiss keyboard for UITextView with return key?

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if([text isEqualToString:@"\n"])
        [textView resignFirstResponder];
    return YES;
}

yourtextView.delegate=self;

Also add UITextViewDelegate

Don't forget to confirm protocol

IF you didn't add if([text isEqualToString:@"\n"]) you can't edit

Declaring variables inside loops, good practice or bad practice?

Generally, it's a very good practice to keep it very close.

In some cases, there will be a consideration such as performance which justifies pulling the variable out of the loop.

In your example, the program creates and destroys the string each time. Some libraries use a small string optimization (SSO), so the dynamic allocation could be avoided in some cases.

Suppose you wanted to avoid those redundant creations/allocations, you would write it as:

for (int counter = 0; counter <= 10; counter++) {
   // compiler can pull this out
   const char testing[] = "testing";
   cout << testing;
}

or you can pull the constant out:

const std::string testing = "testing";
for (int counter = 0; counter <= 10; counter++) {
   cout << testing;
}

Do most compilers realize that the variable has already been declared and just skip that portion, or does it actually create a spot for it in memory each time?

It can reuse the space the variable consumes, and it can pull invariants out of your loop. In the case of the const char array (above) - that array could be pulled out. However, the constructor and destructor must be executed at each iteration in the case of an object (such as std::string). In the case of the std::string, that 'space' includes a pointer which contains the dynamic allocation representing the characters. So this:

for (int counter = 0; counter <= 10; counter++) {
   string testing = "testing";
   cout << testing;
}

would require redundant copying in each case, and dynamic allocation and free if the variable sits above the threshold for SSO character count (and SSO is implemented by your std library).

Doing this:

string testing;
for (int counter = 0; counter <= 10; counter++) {
   testing = "testing";
   cout << testing;
}

would still require a physical copy of the characters at each iteration, but the form could result in one dynamic allocation because you assign the string and the implementation should see there is no need to resize the string's backing allocation. Of course, you wouldn't do that in this example (because multiple superior alternatives have already been demonstrated), but you might consider it when the string or vector's content varies.

So what do you do with all those options (and more)? Keep it very close as a default -- until you understand the costs well and know when you should deviate.

operator << must take exactly one argument

A friend function is not a member function, so the problem is that you declare operator<< as a friend of A:

 friend ostream& operator<<(ostream&, A&);

then try to define it as a member function of the class logic

 ostream& logic::operator<<(ostream& os, A& a)
          ^^^^^^^

Are you confused about whether logic is a class or a namespace?

The error is because you've tried to define a member operator<< taking two arguments, which means it takes three arguments including the implicit this parameter. The operator can only take two arguments, so that when you write a << b the two arguments are a and b.

You want to define ostream& operator<<(ostream&, const A&) as a non-member function, definitely not as a member of logic since it has nothing to do with that class!

std::ostream& operator<<(std::ostream& os, const A& a)
{
  return os << a.number;
}

XML Document to String

First you need to get rid of all newline characters in all your text nodes. Then you can use an identity transform to output your DOM tree. Look at the javadoc for TransformerFactory#newTransformer().

Relative instead of Absolute paths in Excel VBA

I think the problem is that opening the file without a path will only work if your "current directory" is set correctly.

Try typing "Debug.Print CurDir" in the Immediate Window - that should show the location for your default files as set in Tools...Options.

I'm not sure I'm completely happy with it, perhaps because it's somewhat of a legacy VB command, but you could do this:

ChDir ThisWorkbook.Path

I think I'd prefer to use ThisWorkbook.Path to construct a path to the HTML file. I'm a big fan of the FileSystemObject in the Scripting Runtime (which always seems to be installed), so I'd be happier to do something like this (after setting a reference to Microsoft Scripting Runtime):

Const HTML_FILE_NAME As String = "my_input.html"

With New FileSystemObject
    With .OpenTextFile(.BuildPath(ThisWorkbook.Path, HTML_FILE_NAME), ForReading)
        ' Now we have a TextStream object that we can use to read the file
    End With
End With

Using psql how do I list extensions installed in a database?

This SQL query gives output similar to \dx:

SELECT e.extname AS "Name", e.extversion AS "Version", n.nspname AS "Schema", c.description AS "Description" 
FROM pg_catalog.pg_extension e 
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace 
LEFT JOIN pg_catalog.pg_description c ON c.objoid = e.oid AND c.classoid = 'pg_catalog.pg_extension'::pg_catalog.regclass 
ORDER BY 1;

Thanks to https://blog.dbi-services.com/listing-the-extensions-available-in-postgresql/

How to open a different activity on recyclerView item onclick

The problem occurs in declaring context, while using Glide for ImageView or While using intent in recyclerview for item onClick. I Found this working for me which helps me to Declare context to use in Glide or Intent or Toast.

public class NoteAdapter extends FirestoreRecyclerAdapter<Note,NoteAdapter.NoteHolder> {

Context context;

public NoteAdapter(@NonNull FirestoreRecyclerOptions<Note> options) {
    super(options);
}

@Override
protected void onBindViewHolder(@NonNull NoteHolder holder, int position, @NonNull Note model) {
    holder.r_tv.setText(model.getTitle());
    Glide.with(CategoryActivity.context).load(model.getImage()).into(holder.r_iv);

    context = holder.itemView.getContext();

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(context, SuggestActivity.class);
            context.startActivity(i);
        }
    });

}

@NonNull
@Override
public NoteHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_category,parent,false);

    return new NoteHolder(v);
}

public static class NoteHolder extends RecyclerView.ViewHolder
{
    TextView r_tv;
    ImageView r_iv;

    public NoteHolder(@NonNull View itemView) {
        super(itemView);

        r_tv = itemView.findViewById(R.id.r_tv);
        r_iv = itemView.findViewById(R.id.r_iv);


    }
}
}

What is best way to start and stop hadoop ecosystem, with command line?

From Hadoop page,

start-all.sh 

This will startup a Namenode, Datanode, Jobtracker and a Tasktracker on your machine.

start-dfs.sh

This will bring up HDFS with the Namenode running on the machine you ran the command on. On such a machine you would need start-mapred.sh to separately start the job tracker

start-all.sh/stop-all.sh has to be run on the master node

You would use start-all.sh on a single node cluster (i.e. where you would have all the services on the same node.The namenode is also the datanode and is the master node).

In multi-node setup,

You will use start-all.sh on the master node and would start what is necessary on the slaves as well.

Alternatively,

Use start-dfs.sh on the node you want the Namenode to run on. This will bring up HDFS with the Namenode running on the machine you ran the command on and Datanodes on the machines listed in the slaves file.

Use start-mapred.sh on the machine you plan to run the Jobtracker on. This will bring up the Map/Reduce cluster with Jobtracker running on the machine you ran the command on and Tasktrackers running on machines listed in the slaves file.

hadoop-daemon.sh as stated by Tariq is used on each individual node. The master node will not start the services on the slaves.In a single node setup this will act same as start-all.sh.In a multi-node setup you will have to access each node (master as well as slaves) and execute on each of them.

Have a look at this start-all.sh it call config followed by dfs and mapred

How to post JSON to PHP with curl

Jordans analysis of why the $_POST-array isn't populated is correct. However, you can use

$data = file_get_contents("php://input");

to just retrieve the http body and handle it yourself. See PHP input/output streams.

From a protocol perspective this is actually more correct, since you're not really processing http multipart form data anyway. Also, use application/json as content-type when posting your request.

What is The difference between ListBox and ListView

A ListView is basically like a ListBox (and inherits from it), but it also has a View property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView, but you can easily create your own.

Another difference is the default selection mode: it's Single for a ListBox, but Extended for a ListView

Verify host key with pysftp

One option is to disable the host key requirement:

import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None   
with pysftp.Connection(host, username, password, cnopts=cnopts) as sftp:
    sftp.put(local_path, remote_path)

You can find more info about that here: https://stackoverflow.com/a/38355117/1060738

Important note:

By setting cnopts.hostkeys=None you'll lose the protection against Man-in-the-middle attacks by doing so. Use @martin-prikryl answer to avoid that.

How to send 100,000 emails weekly?

Short answer: While it's technically possible to send 100k e-mails each week yourself, the simplest, easiest and cheapest solution is to outsource this to one of the companies that specialize in it (I did say "cheapest": there's no limit to the amount of development time (and therefore money) that you can sink into this when trying to DIY).

Long answer: If you decide that you absolutely want to do this yourself, prepare for a world of hurt (after all, this is e-mail/e-fail we're talking about). You'll need:

  • e-mail content that is not spam (otherwise you'll run into additional major roadblocks on every step, even legal repercussions)
  • in addition, your content should be easy to distinguish from spam - that may be a bit hard to do in some cases (I heard that a certain pharmaceutical company had to all but abandon e-mail, as their brand names are quite common in spams)
  • a configurable SMTP server of your own, one which won't buckle when you dump 100k e-mails onto it (your ISP's upstream server won't be sufficient here and you'll make the ISP violently unhappy; we used two dedicated boxes)
  • some mail wrapper (e.g. PhpMailer if PHP's your poison of choice; using PHP's mail() is horrible enough by itself)
  • your own sender function to run in a loop, create the mails and pass them to the wrapper (note that you may run into PHP's memory limits if your app has a memory leak; you may need to recycle the sending process periodically, or even better, decouple the "creating e-mails" and "sending e-mails" altogether)

Surprisingly, that was the easy part. The hard part is actually sending it:

  • some servers will ban you when you send too many mails close together, so you need to shuffle and watch your queue (e.g. send one mail to [email protected], then three to other domains, only then another to [email protected])
  • you need to have correct PTR, SPF, DKIM records
  • handling remote server timeouts, misconfigured DNS records and other network pleasantries
  • handling invalid e-mails (and no, regex is the wrong tool for that)
  • handling unsubscriptions (many legitimate newsletters have been reclassified as spam due to many frustrated users who couldn't unsubscribe in one step and instead chose to "mark as spam" - the spam filters do learn, esp. with large e-mail providers)
  • handling bounces and rejects ("no such mailbox [email protected]","mailbox [email protected] full")
  • handling blacklisting and removal from blacklists (Sure, you're not sending spam. Some recipients won't be so sure - with such large list, it will happen sometimes, no matter what precautions you take. Some people (e.g. your not-so-scrupulous competitors) might even go as far to falsely report your mailings as spam - it does happen. On average, it takes weeks to get yourself removed from a blacklist.)

And to top it off, you'll have to manage the legal part of it (various federal, state, and local laws; and even different tangles of laws once you send outside the U.S. (note: you have no way of finding if [email protected] lives in Southwest Elbonia, the country with world's most draconian antispam laws)).

I'm pretty sure I missed a few heads of this hydra - are you still sure you want to do this yourself? If so, there'll be another wave, this time merely the annoying problems inherent in sending an e-mail. (You see, SMTP is a store-and-forward protocol, which means that your e-mail will be shuffled across many SMTP servers around the Internet, in the hope that the next one is a bit closer to the final recipient. Basically, the e-mail is sent to an SMTP server, which puts it into its forward queue; when time comes, it will forward it further to a different SMTP server, until it reaches the SMTP server for the given domain. This forward could happen immediately, or in a few minutes, or hours, or days, or never.) Thus, you'll see the following issues - most of which could happen en route as well as at the destination:

  • the remote SMTP servers don't want to talk to your SMTP server
  • your mails are getting marked as spam (<blink> is not your friend here, nor is <font color=...>)
  • your mails are delivered days, even weeks late (contrary to popular opinion, SMTP is designed to make a best effort to deliver the message sometime in the future - not to deliver it now)
  • your mails are not delivered at all (already sent from e-mail server on hop #4, not sent yet from server on hop #5, the server that currently holds the message crashes, data is lost)
  • your mails are mangled by some braindead server en route (this one is somewhat solvable with base64 encoding, but then the size goes up and the e-mail looks more suspicious)
  • your mails are delivered and the recipients seem not to want them ("I'm sure I didn't sign up for this, I remember exactly what I did a year ago" (of course you do, sir))
  • users with various versions of Microsoft Outlook and its special handling of Internet mail
  • wizard's apprentice mode (a self-reinforcing positive feedback loop - in other words, automated e-mails as replies to automated e-mails as replies to...; you really don't want to be the one to set this off, as you'd anger half the internet at yourself)

and it'll be your job to troubleshoot and solve this (hint: you can't, mostly). The people who run a legit mass-mailing businesses know that in the end you can't solve it, and that they can't solve it either - and they have the reasons well researched, documented and outlined (maybe even as a Powerpoint presentation - complete with sounds and cool transitions - that your bosses can understand), as they've had to explain this a million times before. Plus, for the problems that are actually solvable, they know very well how to solve them.

If, after all this, you are not discouraged and still want to do this, go right ahead: it's even possible that you'll find a better way to do this. Just know that the road ahead won't be easy - sending e-mail is trivial, getting it delivered is hard.

How do you concatenate Lists in C#?

Concat returns a new sequence without modifying the original list. Try myList1.AddRange(myList2).

Store multiple values in single key in json

Use arrays:

{
    "number": ["1", "2", "3"],
    "alphabet": ["a", "b", "c"]
}

You can the access the different values from their position in the array. Counting starts at left of array at 0. myJsonObject["number"][0] == 1 or myJsonObject["alphabet"][2] == 'c'

How to keep :active css style after clicking an element

The :target-pseudo selector is made for these type of situations: http://reference.sitepoint.com/css/pseudoclass-target

It is supported by all modern browsers. To get some IE versions to understand it you can use something like Selectivizr

Here is a tab example with :target-pseudo selector.

What is the difference between Serializable and Externalizable in Java?

Key differences between Serializable and Externalizable

  1. Marker interface: Serializable is marker interface without any methods. Externalizable interface contains two methods: writeExternal() and readExternal().
  2. Serialization process: Default Serialization process will be kicked-in for classes implementing Serializable interface. Programmer defined Serialization process will be kicked-in for classes implementing Externalizable interface.
  3. Maintenance: Incompatible changes may break serialisation.
  4. Backward Compatibility and Control: If you have to support multiple versions, you can have full control with Externalizable interface. You can support different versions of your object. If you implement Externalizable, it's your responsibility to serialize super class
  5. public No-arg constructor: Serializable uses reflection to construct object and does not require no arg constructor. But Externalizable demands public no-arg constructor.

Refer to blog by Hitesh Garg for more details.

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

How do I break out of a loop in Perl?

Simply last would work here:

for my $entry (@array){
    if ($string eq "text"){
         last;
    }
}

If you have nested loops, then last will exit from the innermost loop. Use labels in this case:

LBL_SCORE: {
    for my $entry1 (@array1) {
        for my $entry2 (@array2) {
            if ($entry1 eq $entry2) { # Or any condition
                last LBL_SCORE;
            }
        }
    }
 }

Given a last statement will make the compiler to come out from both the loops. The same can be done in any number of loops, and labels can be fixed anywhere.

Changing background color of text box input not working when empty

Don't add styles to value of input so use like

function checkFilled() {
    var inputElem = document.getElementById("subEmail");
    if (inputElem.value == "") {
        inputElem.style.backgroundColor = "yellow";
                }
        }

Assigning multiple styles on an HTML element

In HTML the style tag has the following syntax:

style="property1:value1;property2:value2"

so in your case:

<h2 style="text-align:center;font-family:tahoma">TITLE</h2>

Hope this helps.

How to extract text from an existing docx file using python-docx

you can try this

import docx

def getText(filename):
    doc = docx.Document(filename)
    fullText = []
    for para in doc.paragraphs:
        fullText.append(para.text)
    return '\n'.join(fullText)

how to call javascript function in html.actionlink in asp.net mvc?

For calling javascript in your action link you simply need to write actionlink like this:

@Html.ActionLink("Delete", "Your-Action", new { id = item.id },
                 new { onclick="return confirm('Are you sure?');"})

Don't get confused between route values and the html attributes.

POST data with request module on Node.JS

EDIT: You should check out Needle. It does this for you and supports multipart data, and a lot more.

I figured out I was missing a header

var request = require('request');
request.post({
  headers: {'content-type' : 'application/x-www-form-urlencoded'},
  url:     'http://localhost/test2.php',
  body:    "mes=heydude"
}, function(error, response, body){
  console.log(body);
});