Programs & Examples On #Adt

Android Development Tools (ADT) is a plugin for the Eclipse IDE that is designed to give you a powerful, integrated environment in which to build Android applications.

How can I update my ADT in Eclipse?

In my case opening 'Help' >> "Install New Software" had no entries for any URLs (previous url's were not there) - so I Manually added 'em. And updated ... and Voilaaaa !! Above posts have been very helpful in resolving this issue for me.

The connection to adb is down, and a severe error has occurred

I restarted eclipse and did the Project -> Clean -> select your project One of them fixed my problem with adb

[2011-12-31 10:50:45 - HelloAndroid] Android Launch!                      good

[2011-12-31 10:50:45 - HelloAndroid] adb is running normally.             good

[2011-12-31 10:50:45 - HelloAndroid] Could not find HelloAndroid.apk!     bad

Thanks for the help. On to the next problem (sigh)

No generated R.java file in my project

I colleague of mine has this problem - a restart of eclipse fixed it.

Which Eclipse version should I use for an Android app?

I literally did this 1 hour ago.

  1. SDK R7
  2. Get Java - if you don't have (its the first image link JDK)
  3. Get Eclipse - it's the first on the list with the most downloads
  4. Android Plugin

Download the appropriate files for your OS. The Android SDK needs java in order to install. Once you get the Android SDK installed go get eclipse and install that. Basically download the file and unzip then in a directory. The android install is the same but it will install a lot more files. (5) Finally open eclipse and go to help > install new software >> and add the url to the plugin - I used this one https://dl-ssl.google.com/android/eclipse/

"SDK Platform Tools component is missing!"

I have been faced with a similar problem with SDK 24.0.2, and ADT 23.0, on windows 7 and Eclipse Luna (4.4.0). The android SDK Manager comes with default Proxy IP of 127.0.0.1 (localhost) and port 8081. So as you try to run the SDK Managers as advised by earlier solutions, it will try to connect through the default proxy settings, which keep on failing(...at least on my system). Therefore, if you do not need proxy settings, simply clear default proxy settings (i.e. remove proxy server IP and Port, leaving the fields empty). Otherwise set them as necessary. To access these settings in eclipse, go Window-> Android SDK Manager->Tools->Options.

Hope this helps someone.

Update Eclipse with Android development tools v. 23

I found these instructions in a comment.

Download the newest version of ADT and use your existing workspace. This is actually the least pain-full upgrade you'll ever do. It didn't mess with the .android folder so I still had my original debug key. Only things missing were a couple of add ons I hardly ever use and they are easily installed into the new version.

Note don't install into your existing adt folder create a new folder so you can still fall back if the new install doesn't work.

How to debug on a real device (using Eclipse/ADT)

Sometimes you need to reset ADB. To do that, in Eclipse, go:

Window>> Show View >> Android (Might be found in the "Other" option)>>Devices

in the device Tab, click the down arrow, and choose reset adb.

What is "android:allowBackup"?

For this lint warning, as for all other lint warnings, note that you can get a fuller explanation than just what is in the one line error message; you don't have to search the web for more info.

If you are using lint via Eclipse, either open the lint warnings view, where you can select the lint error and see a longer explanation, or invoke the quick fix (Ctrl-1) on the error line, and one of the suggestions is "Explain this issue", which will also pop up a fuller explanation. If you are not using Eclipse, you can generate an HTML report from lint (lint --html <filename>) which includes full explanations next to the warnings, or you can ask lint to explain a particular issue. For example, the issue related to allowBackup has the id AllowBackup (shown at the end of the error message), so the fuller explanation is:

$ ./lint --show AllowBackup
AllowBackup
-----------
Summary: Ensure that allowBackup is explicitly set in the application's
manifest

Priority: 3 / 10
Severity: Warning
Category: Security

The allowBackup attribute determines if an application's data can be backed up and restored, as documented here.

By default, this flag is set to true. When this flag is set to true, application data can be backed up and restored by the user using adb backup and adb restore.

This may have security consequences for an application. adb backup allows users who have enabled USB debugging to copy application data off of the device. Once backed up, all application data can be read by the user. adb restore allows creation of application data from a source specified by the user. Following a restore, applications should not assume that the data, file permissions, and directory permissions were created by the application itself.

Setting allowBackup="false" opts an application out of both backup and restore.

To fix this warning, decide whether your application should support backup and explicitly set android:allowBackup=(true|false)

Click here for More information

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

I'm late to this party, but adding my own experience so I can find it again later :)

I ran into this problem after upgrading the android sdk and eclipse ad-ins. No upgrade goes unpunished!

The problem for me was related to library projects, my app references both standard java projects and android library projects. I noticed the Java Build Path settings were including the android library projects src and res folders in the Source list (upvotes to everyone that mention bin in source being issue, src and res was also an issue.)

So the solution was:

  1. Remove all referenced Android libraries source and project references from the Java Build Path section of the settings in both Source list and Project list
  2. Make sure pure java dependencies are listed in Project list, and Checked in the Order and Export tab so the classes are included in the apk
  3. Make sure all Android library dependencies are listed on the Android section of project properties, in the library section below the checked SDK versions.

It was along way to piece all that together from the other solutions! Phew!

How do I set ANDROID_SDK_HOME environment variable?

from command prompt:

set ANDROID_SDK_HOME=C:\[wherever your sdk folder is]

should do the trick.

Uninstalling Android ADT

The only way to remove the ADT plugin from Eclipse is to go to Help > About Eclipse/About ADT > Installation Details.

Select a plug-in you want to uninstall, then click Uninstall... button at the bottom.

enter image description here

If you cannot remove ADT from this location, then your best option is probably to start fresh with a clean Eclipse install.

Eclipse Indigo - Cannot install Android ADT Plugin

Head over to Help -> Install New Software. Click on Available software sites. Delete the Android repo. Uncheck Indigo & Eclipse updates & recheck them. Now head back to Help -> Check for updates. Once done, add the Android repo again. Accept the license & you should be good to go.

(Had to do the same yesterday after getting Indigo)

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).

Solution is: First Update ADT to 22.0.4(Latest version) and then Update SDK Tool to 22.0.4(Latest Version)

The above link says,

ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so

What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).

How to Update your ADT to Latest Version

  1. In Eclipse go to Help
  2. Install New Software ---> Add
  3. inside Add Repository write the Name: ADT (or whatever you want)
  4. and Location: https://dl-ssl.google.com/android/eclipse/
  5. after loading you should get Developer Tools and NDK Plugins
  6. check both if you want to use the Native Developer Kit (NDK) in the future or check Developer Tool only
  7. click Next
  8. Finish

Setting background colour of Android layout element

Kotlin

linearLayout.setBackgroundColor(Color.rgb(0xf4,0x43,0x36))

or

<color name="newColor">#f44336</color>

-

linearLayout.setBackgroundColor(ContextCompat.getColor(vista.context, R.color.newColor))

Setting default permissions for newly created files and sub-directories under a directory in Linux?

To get the right ownership, you can set the group setuid bit on the directory with

chmod g+rwxs dirname

This will ensure that files created in the directory are owned by the group. You should then make sure everyone runs with umask 002 or 007 or something of that nature---this is why Debian and many other linux systems are configured with per-user groups by default.

I don't know of a way to force the permissions you want if the user's umask is too strong.

Image library for Python 3

As of March 30, 2012, I have tried and failed to get the sloonz fork on GitHub to open images. I got it to compile ok, but it didn't actually work. I also tried building gohlke's library, and it compiled also but failed to open any images. Someone mentioned PythonMagick above, but it only compiles on Windows. See PythonMagick on the wxPython wiki.

PIL was last updated in 2009, and while it's website says they are working on a Python 3 port, it's been 3 years, and the mailing list has gone cold.

To solve my Python 3 image manipulation problem, I am using subprocess.call() to execute ImageMagick shell commands. This method works.

See the subprocess module documentation.

Save internal file in my own internal folder in Android

The answer of Mintir4 is fine, I would also do the following to load the file.

FileInputStream fis = myContext.openFileInput(fn);
BufferedReader r = new BufferedReader(new InputStreamReader(fis));
String s = "";

while ((s = r.readLine()) != null) {
    txt += s;
}

r.close();

socket.error:[errno 99] cannot assign requested address and namespace in python

when you bind localhost or 127.0.0.1, it means you can only connect to your service from local.

you cannot bind 10.0.0.1 because it not belong to you, you can only bind ip owned by your computer

you can bind 0.0.0.0 because it means all ip on your computer, so any ip can connect to your service if they can connect to any of your ip

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

Make sure that you are building your web app as "Any CPU". Right click your web project --> Properties --> Build --> and look for the "Platform Target". Choose "Any CPU" or play around with it.

Hope this helps!

mysql error 1364 Field doesn't have a default values

In Windows Server edit my.ini (for example program files\mysql\mysql server n.n\my.ini)

I would not simply set the sql-mode="", rather I suggest one removes STRICT_TRANS_TABLES from the line, leave everything as-was, and then restart MySQL from the services utility. Add a comment for future programmers who you are and what you did.

must appear in the GROUP BY clause or be used in an aggregate function

The problem with specifying non-grouped and non-aggregate fields in group by selects is that engine has no way of knowing which record's field it should return in this case. Is it first? Is it last? There is usually no record that naturally corresponds to aggregated result (min and max are exceptions).

However, there is a workaround: make the required field aggregated as well. In posgres, this should work:

SELECT cname, (array_agg(wmname ORDER BY avg DESC))[1], MAX(avg)
FROM makerar GROUP BY cname;

Note that this creates an array of all wnames, ordered by avg, and returns the first element (arrays in postgres are 1-based).

SQLAlchemy ORDER BY DESCENDING?

from sqlalchemy import desc
someselect.order_by(desc(table1.mycol))

Usage from @jpmc26

Get encoding of a file in Windows

Looking for a Node.js/npm solution? Try encoding-checker:

npm install -g encoding-checker

Usage

Usage: encoding-checker [-p pattern] [-i encoding] [-v]
 
Options:
  --help                 Show help                                     [boolean]
  --version              Show version number                           [boolean]
  --pattern, -p, -d                                               [default: "*"]
  --ignore-encoding, -i                                            [default: ""]
  --verbose, -v                                                 [default: false]

Examples

Get encoding of all files in current directory:

encoding-checker

Return encoding of all md files in current directory:

encoding-checker -p "*.md"

Get encoding of all files in current directory and its subfolders (will take quite some time for huge folders; seemingly unresponsive):

encoding-checker -p "**"

For more examples refer to the npm docu or the official repository.

How to connect HTML Divs with Lines?

You can use SVGs to connect two divs using only HTML and CSS:

<div id="div1" style="width: 100px; height: 100px; top:0; left:0; background:#777; position:absolute;"></div>
<div id="div2" style="width: 100px; height: 100px; top:300px; left:300px; background:#333; position:absolute;"></div>

(please use seperate css file for styling)

Create a svg line and use this line to connect above divs

<svg width="500" height="500"><line x1="50" y1="50" x2="350" y2="350" stroke="black"/></svg>

where,

x1,y1 indicates center of first div and
x2,y2 indicates center of second div

You can check how it looks in the snippet below

_x000D_
_x000D_
<div id="div1" style="width: 100px; height: 100px; top:0; left:0; background:#777; position:absolute;"></div>_x000D_
<div id="div2" style="width: 100px; height: 100px; top:300px; left:300px; background:#333; position:absolute;"></div>_x000D_
_x000D_
<svg width="500" height="500"><line x1="50" y1="50" x2="350" y2="350" stroke="black"/></svg>
_x000D_
_x000D_
_x000D_

Java: Finding the highest value in an array

If you don't want to use any java predefined libraries then below is the

simplest way

   public class Test {

    public static void main(String[] args) {
        double[] decMax = {-2.8, -8.8, 2.3, 7.9, 4.1, -1.4, 11.3, 10.4,
            8.9, 8.1, 5.8, 5.9, 7.8, 4.9, 5.7, -0.9, -0.4, 7.3, 8.3, 6.5, 9.2,
            3.5, 3, 1.1, 6.5, 5.1, -1.2, -5.1, 2, 5.2, 2.1};

        double maxx = decMax[0];

        for (int i = 0; i < decMax.length; i++) {
            if (maxx < decMax[i]) {
                maxx = decMax[i];
            }
        }
        System.out.println(maxx);

    }
}

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Pattern! The group names a (sub)pattern for later use in the regex. See the documentation here for details about how such groups are used.

Convert java.util.Date to java.time.LocalDate

Better way is:

Date date = ...;
Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate()

Advantages of this version:

  • works regardless the input is an instance of java.util.Date or it's a subclass of java.sql.Date (unlike @JodaStephen's way). This is common with JDBC-originated data. java.sql.Date.toInstant() always throws an exception.

  • it's the same for JDK8 and JDK7 with JSR-310 backport

I personally use an utility class (but it is not backport-compatible):

/**
 * Utilities for conversion between the old and new JDK date types 
 * (between {@code java.util.Date} and {@code java.time.*}).
 * 
 * <p>
 * All methods are null-safe.
 */
public class DateConvertUtils {

    /**
     * Calls {@link #asLocalDate(Date, ZoneId)} with the system default time zone.
     */
    public static LocalDate asLocalDate(java.util.Date date) {
        return asLocalDate(date, ZoneId.systemDefault());
    }

    /**
     * Creates {@link LocalDate} from {@code java.util.Date} or it's subclasses. Null-safe.
     */
    public static LocalDate asLocalDate(java.util.Date date, ZoneId zone) {
        if (date == null)
            return null;

        if (date instanceof java.sql.Date)
            return ((java.sql.Date) date).toLocalDate();
        else
            return Instant.ofEpochMilli(date.getTime()).atZone(zone).toLocalDate();
    }

    /**
     * Calls {@link #asLocalDateTime(Date, ZoneId)} with the system default time zone.
     */
    public static LocalDateTime asLocalDateTime(java.util.Date date) {
        return asLocalDateTime(date, ZoneId.systemDefault());
    }

    /**
     * Creates {@link LocalDateTime} from {@code java.util.Date} or it's subclasses. Null-safe.
     */
    public static LocalDateTime asLocalDateTime(java.util.Date date, ZoneId zone) {
        if (date == null)
            return null;

        if (date instanceof java.sql.Timestamp)
            return ((java.sql.Timestamp) date).toLocalDateTime();
        else
            return Instant.ofEpochMilli(date.getTime()).atZone(zone).toLocalDateTime();
    }

    /**
     * Calls {@link #asUtilDate(Object, ZoneId)} with the system default time zone.
     */
    public static java.util.Date asUtilDate(Object date) {
        return asUtilDate(date, ZoneId.systemDefault());
    }

    /**
     * Creates a {@link java.util.Date} from various date objects. Is null-safe. Currently supports:<ul>
     * <li>{@link java.util.Date}
     * <li>{@link java.sql.Date}
     * <li>{@link java.sql.Timestamp}
     * <li>{@link java.time.LocalDate}
     * <li>{@link java.time.LocalDateTime}
     * <li>{@link java.time.ZonedDateTime}
     * <li>{@link java.time.Instant}
     * </ul>
     * 
     * @param zone Time zone, used only if the input object is LocalDate or LocalDateTime.
     * 
     * @return {@link java.util.Date} (exactly this class, not a subclass, such as java.sql.Date)
     */
    public static java.util.Date asUtilDate(Object date, ZoneId zone) {
        if (date == null)
            return null;

        if (date instanceof java.sql.Date || date instanceof java.sql.Timestamp)
            return new java.util.Date(((java.util.Date) date).getTime());
        if (date instanceof java.util.Date)
            return (java.util.Date) date;
        if (date instanceof LocalDate)
            return java.util.Date.from(((LocalDate) date).atStartOfDay(zone).toInstant());
        if (date instanceof LocalDateTime)
            return java.util.Date.from(((LocalDateTime) date).atZone(zone).toInstant());
        if (date instanceof ZonedDateTime)
            return java.util.Date.from(((ZonedDateTime) date).toInstant());
        if (date instanceof Instant)
            return java.util.Date.from((Instant) date);

        throw new UnsupportedOperationException("Don't know hot to convert " + date.getClass().getName() + " to java.util.Date");
    }

    /**
     * Creates an {@link Instant} from {@code java.util.Date} or it's subclasses. Null-safe.
     */
    public static Instant asInstant(Date date) {
        if (date == null)
            return null;
        else
            return Instant.ofEpochMilli(date.getTime());
    }

    /**
     * Calls {@link #asZonedDateTime(Date, ZoneId)} with the system default time zone.
     */
    public static ZonedDateTime asZonedDateTime(Date date) {
        return asZonedDateTime(date, ZoneId.systemDefault());
    }

    /**
     * Creates {@link ZonedDateTime} from {@code java.util.Date} or it's subclasses. Null-safe.
     */
    public static ZonedDateTime asZonedDateTime(Date date, ZoneId zone) {
        if (date == null)
            return null;
        else
            return asInstant(date).atZone(zone);
    }

}

The asLocalDate() method here is null-safe, uses toLocalDate(), if input is java.sql.Date (it may be overriden by the JDBC driver to avoid timezone problems or unnecessary calculations), otherwise uses the abovementioned method.

Permission denied error while writing to a file in Python

I've had the same issue using the cmd (windows command line) like this

C:\Windows\System32> "G:\my folder\myProgram.py"

Where inside the python file something like this

myfile = open('myOutput.txt', 'w')

The error was that when you don't use a full path, python would use your current directory, and because the default directory on cmd is

C:\Windows\System32 

that won't work, as it seems to be write-protected and needs permission & confirmation form an administrator

Instead, you should use full paths, for example:

myfile = open('G:\my folder\myOutput.txt', 'w')

Using python PIL to turn a RGB image into a pure black and white image

from PIL import Image 
image_file = Image.open("convert_image.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('result.png')

yields

enter image description here

Does SVG support embedding of bitmap images?

You can use a data: URL to embed a Base64 encoded version of an image. But it's not very efficient and wouldn't recommend embedding large images. Any reason linking to another file is not feasible?

When is null or undefined used in JavaScript?

You get undefined for the various scenarios:

You declare a variable with var but never set it.

var foo; 
alert(foo); //undefined.

You attempt to access a property on an object you've never set.

var foo = {};
alert(foo.bar); //undefined

You attempt to access an argument that was never provided.

function myFunction (foo) {
  alert(foo); //undefined.
}

As cwolves pointed out in a comment on another answer, functions that don't return a value.

function myFunction () {
}
alert(myFunction());//undefined

A null usually has to be intentionally set on a variable or property (see comments for a case in which it can appear without having been set). In addition a null is of type object and undefined is of type undefined.

I should also note that null is valid in JSON but undefined is not:

JSON.parse(undefined); //syntax error
JSON.parse(null); //null

GROUP BY without aggregate function

Let me give some examples.

Consider this data.

CREATE TABLE DATASET ( VAL1 CHAR ( 1 CHAR ),
                   VAL2 VARCHAR2 ( 10 CHAR ),
                   VAL3 NUMBER );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'b', 'b-details', 2 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'a', 'a-details', 1 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'c', 'c-details', 3 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'a', 'dup', 4 );

INSERT INTO
      DATASET ( VAL1, VAL2, VAL3 )
VALUES
      ( 'c', 'c-details', 5 );

COMMIT;

Whats there in table now

SELECT * FROM DATASET;

VAL1 VAL2             VAL3
---- ---------- ----------
b    b-details           2
a    a-details           1
c    c-details           3
a    dup                 4
c    c-details           5

5 rows selected.

--aggregate with group by

SELECT
      VAL1,
      COUNT ( * )
FROM
      DATASET A
GROUP BY
      VAL1;

VAL1   COUNT(*)
---- ----------
b             1
a             2
c             2

3 rows selected.

--aggregate with group by multiple columns but select partial column

SELECT
      VAL1,
      COUNT ( * )
FROM
      DATASET A
GROUP BY
      VAL1,
      VAL2;

VAL1  
---- 
b             
c             
a             
a             

4 rows selected.

--No aggregate with group by multiple columns

SELECT
      VAL1,
      VAL2
FROM
      DATASET A
GROUP BY
      VAL1,
      VAL2;

    VAL1  
    ---- 
    b    b-details
    c    c-details
    a    dup
    a    a-details

    4 rows selected.

--No aggregate with group by multiple columns

SELECT
      VAL1
FROM
      DATASET A
GROUP BY
      VAL1,
      VAL2;

    VAL1  
    ---- 
    b
    c
    a
    a

    4 rows selected.

You have N columns in select (excluding aggregations), then you should have N or N+x columns

Get data from JSON file with PHP

Try:
$data = file_get_contents ("file.json");
        $json = json_decode($data, true);
        foreach ($json as $key => $value) {
            if (!is_array($value)) {
                echo $key . '=>' . $value . '<br/>';
            } else {
                foreach ($value as $key => $val) {
                    echo $key . '=>' . $val . '<br/>';
                }
            }
        }

How to Resize a Bitmap in Android?

Change:

profileImage.setImageBitmap(
    BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)

To:

Bitmap b = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
profileImage.setImageBitmap(Bitmap.createScaledBitmap(b, 120, 120, false));

How can I clear an HTML file input with JavaScript?

document.getElementById('your_input_id').value=''

Edit:
This one doesn't work in IE and opera, but seems to work for firefox, safari and chrome.

Run bash script from Windows PowerShell

You should put the script as argument for a *NIX shell you run, equivalent to the *NIXish

sh myscriptfile

How to run a .jar in mac?

Make Executable your jar and after that double click on it on Mac OS then it works successfully.

sudo chmod +x filename.jar

Try this, I hope this works.

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

I would do something like this:

;WITH x 
 AS (SELECT *, 
            Row_number() 
              OVER( 
                partition BY employeeid 
                ORDER BY datestart) rn 
     FROM   employeehistory) 
SELECT * 
FROM   x x1 
   LEFT OUTER JOIN x x2 
                ON x1.rn = x2.rn + 1 

Or maybe it would be x2.rn - 1. You'll have to see. In any case, you get the idea. Once you have the table joined on itself, you can filter, group, sort, etc. to get what you need.

Error:attempt to apply non-function

I got the error because of a clumsy typo:

This errors:

knitr::opts_chunk$seet(echo = FALSE)

Error: attempt to apply non-function

After correcting the typo, it works:

knitr::opts_chunk$set(echo = FALSE)

How to query all the GraphQL type fields without writing a long query?

Package graphql-type-json supports custom-scalars type JSON. Use it can show all the field of your json objects. Here is the link of the example in ApolloGraphql Server. https://www.apollographql.com/docs/apollo-server/schema/scalars-enums/#custom-scalars

Difference between JPanel, JFrame, JComponent, and JApplet

Those classes are common extension points for Java UI designs. First off, realize that they don't necessarily have much to do with each other directly, so trying to find a relationship between them might be counterproductive.

JApplet - A base class that let's you write code that will run within the context of a browser, like for an interactive web page. This is cool and all but it brings limitations which is the price for it playing nice in the real world. Normally JApplet is used when you want to have your own UI in a web page. I've always wondered why people don't take advantage of applets to store state for a session so no database or cookies are needed.

JComponent - A base class for objects which intend to interact with Swing.

JFrame - Used to represent the stuff a window should have. This includes borders (resizeable y/n?), titlebar (App name or other message), controls (minimize/maximize allowed?), and event handlers for various system events like 'window close' (permit app to exit yet?).

JPanel - Generic class used to gather other elements together. This is more important with working with the visual layout or one of the provided layout managers e.g. gridbaglayout, etc. For example, you have a textbox that is bigger then the area you have reserved. Put the textbox in a scrolling pane and put that pane into a JPanel. Then when you place the JPanel, it will be more manageable in terms of layout.

Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified

As originally suggested in a comment by GeoMac and documented on NuGet's docs the following worked for me when none of the other answers worked:

Tools / NuGet Package Manager / Package Manager Console

Update-Package -ProjectName MyProjectName -reinstall

What are some examples of commonly used practices for naming git branches?

My personal preference is to delete the branch name after I’m done with a topic branch.

Instead of trying to use the branch name to explain the meaning of the branch, I start the subject line of the commit message in the first commit on that branch with “Branch:” and include further explanations in the body of the message if the subject does not give me enough space.

The branch name in my use is purely a handle for referring to a topic branch while working on it. Once work on the topic branch has concluded, I get rid of the branch name, sometimes tagging the commit for later reference.

That makes the output of git branch more useful as well: it only lists long-lived branches and active topic branches, not all branches ever.

How to compile or convert sass / scss to css with node-sass (no Ruby)?

The installation of these tools may vary on different OS.

Under Windows, node-sass currently supports VS2015 by default, if you only have VS2013 in your box and meet any error while running the command, you can define the version of VS by adding: --msvs_version=2013. This is noted on the node-sass npm page.

So, the safe command line that works on Windows with VS2013 is: npm install --msvs_version=2013 gulp node-sass gulp-sass

How can I convert uppercase letters to lowercase in Notepad++

In my notepad++ I press

Ctrl+A = To select all words

Ctrl+U = To convert lowercase

Ctrl+Shift+U = To convert uppercase

Hope to help you!

React Native fetch() Network Request Failed

The solution is simple update nodejs version 14 or higher

PHP Undefined Index

I don't see php file, but that could be that -
replace in your php file:

$query_age = $_GET['query_age'];

with:

$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);

Most probably, at first time you running your script without ?query_age=[something] and $_GET has no key like query_age.

What is Teredo Tunneling Pseudo-Interface?

Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.

If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)

This IP, site or mobile application is not authorized to use this API key

For iOS or Android apps, the key needs an extra privilege granted.

Go to the Google Console -> APIs and Services -> Library. Tap the Places library for your platform and then tap Enable.

See https://developers.google.com/maps/gmp-get-started#enable-api-sdk

php error: Class 'Imagick' not found

For MAMP running on Mac OSX

Find out the what version of PHP and install the right version via brew

brew install homebrew/php/php56-imagick

Add the extension by modifying the php.ini template in MAMP

enter image description here

Verify the Imagick

enter image description here

How do I loop through children objects in javascript?

The backwards compatible version (IE9+) is

var parent = document.querySelector(selector);
Array.prototype.forEach.call(parent.children, function(child, index){
  // Do stuff
});

The es6 way is

const parent = document.querySelector(selector);
Array.from(parent.children).forEach((child, index) => {
  // Do stuff
});

How to convert a column of DataTable to a List

Is this what you need?

DataTable myDataTable = new DataTable();
List<int> myList = new List<int>();
foreach (DataRow row in myDataTable.Rows)
{
    myList.Add((int)row[0]);
}

How can I make a checkbox readonly? not disabled?

document.getElementById("your checkbox id").disabled=true;

How to add items into a numpy array

If x is just a single scalar value, you could try something like this to ensure the correct shape of the array that is being appended/concatenated to the rightmost column of a:

import numpy as np
a = np.array([[1,3,4],[1,2,3],[1,2,1]])
x = 10
b = np.hstack((a,x*np.ones((a.shape[0],1))))

returns b as:

array([[  1.,   3.,   4.,  10.],
       [  1.,   2.,   3.,  10.],
       [  1.,   2.,   1.,  10.]])

Is there a way to rollback my last push to Git?

Since you are the only user:

git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}

( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )

Without doing any changes to your local repo, you can also do something like:

git push -f origin <sha_of_previous_commit>:master

Generally, in published repos, it is safer to do git revert and then git push

Add params to given URL in Python

python3, self explanatory I guess

from urllib.parse import urlparse, urlencode, parse_qsl

url = 'https://www.linkedin.com/jobs/search?keywords=engineer'

parsed = urlparse(url)
current_params = dict(parse_qsl(parsed.query))
new_params = {'location': 'United States'}
merged_params = urlencode({**current_params, **new_params})
parsed = parsed._replace(query=merged_params)

print(parsed.geturl())
# https://www.linkedin.com/jobs/search?keywords=engineer&location=United+States

How to wrap text in LaTeX tables?

Another option is to insert a minipage in each cell where text wrapping is desired, e.g.:

\begin{table}[H]
\begin{tabular}{l}
\begin{minipage}[t]{0.8\columnwidth}%
a very long line a very long line a very long line a very long line
a very long line a very long line a very long line a very long line
a very long line a very long line a very long line %
\end{minipage}\tabularnewline
\end{tabular}
\end{table}

Replace None with NaN in pandas dataframe

The following line replaces None with NaN:

df['column'].replace('None', np.nan, inplace=True)

Atom menu is missing. How do I re-enable

Open atom editor and then press Alt and menu bar will appear. Now click on View tab and then click on Toggle Menu Bar as seen on this screenshot.

Execute a shell script in current shell with sudo permission

Even the first answer is absolutely brilliant, you probably want to only run script under sudo.

You have to specify the absolute path like:

sudo /home/user/example.sh
sudo ~/example.sh

(both are working)

THIS WONT WORK!

sudo /bin/sh example.sh
sudo example.sh

It will always return

sudo: bin/sh: command not found
sudo: example.sh: command not found

Compiling problems: cannot find crt1.o

This worked for me with Ubuntu 16.04

$ LIBRARY_PATH=/usr/lib/x86_64-linux-gnu
$ export LIBRARY_PATH

How do I expire a PHP session after 30 minutes?

Just Store the current time and If it exceeds 30 minutes by comparing then destroy the current session.

Hibernate: get entity by id

Using EntityManager em;

public User getUserById(Long id) {
     return em.getReference(User.class, id);
}

AngularJS For Loop with Numbers & Ranges

This is jzm's improved answer (i cannot comment else i would comment her/his answer because s/he included errors). The function has a start/end range value, so it's more flexible, and... it works. This particular case is for day of month:

$scope.rangeCreator = function (minVal, maxVal) {
    var arr = [];
   for (var i = minVal; i <= maxVal; i++) {
      arr.push(i);
   }
   return arr;
};


<div class="col-sm-1">
    <select ng-model="monthDays">
        <option ng-repeat="day in rangeCreator(1,31)">{{day}}</option>
    </select>
</div>

How to get an IFrame to be responsive in iOS Safari?

This issue is also present on iOS Chrome.

I glanced through all the solutions above, most are very hacky.

If you don't need support for older browsers, just set the iframe width to 100vw;

iframe {
  max-width: 100%; /* Limits width to 100% of container */
  width: 100vw; /* Sets width to 100% of the viewport width while respecting the max-width above */
}

Note : Check support for viewport units https://caniuse.com/#feat=viewport-units

How do I use Safe Area Layout programmatically?

SafeAreaLayoutGuide is UIView property,

The top of the safeAreaLayoutGuide indicates the unobscured top edge of the view (e.g, not behind the status bar or navigation bar, if present). Similarly for the other edges.

Use safeAreaLayoutGuide for avoid our objects clipping/overlapping from rounded corners, navigation bars, tab bars, toolbars, and other ancestor views.

We can create safeAreaLayoutGuide object & set object constraints respectively.

Constraints for Portrait + Landscape is -

Portrait image

Landscape image

        self.edgesForExtendedLayout = []//Optional our as per your view ladder

        let newView = UIView()
        newView.backgroundColor = .red
        self.view.addSubview(newView)
        newView.translatesAutoresizingMaskIntoConstraints = false
        if #available(iOS 11.0, *) {
            let guide = self.view.safeAreaLayoutGuide
            newView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
            newView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
            newView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
            newView.heightAnchor.constraint(equalToConstant: 100).isActive = true

        }
        else {
            NSLayoutConstraint(item: newView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
            NSLayoutConstraint(item: newView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
            NSLayoutConstraint(item: newView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true

            newView.heightAnchor.constraint(equalToConstant: 100).isActive = true
        }

UILayoutGuide

safeAreaLayoutGuide

How to set corner radius of imageView?

There is one tiny difference in Swift 3.0 and Xcode8

Whenever you want to apply corner radius to UIView, make sure you call yourUIView.layoutIfNeeded() before calling cornerRadius.

Otherwise, it will return the default value for UIView's height and width (1000.0) which will probably make your View disappear.

Always make sure that all effects that changes the size of UIView (Interface builder constraints etc) are applied before setting any layer properties.

Example of UIView class implementation

class BadgeView: UIView {

  override func awakeFromNib() {

    self.layoutIfNeeded()
    layer.cornerRadius = self.frame.height / 2.0
    layer.masksToBounds = true

   }
 }

How to open a workbook specifying its path

Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")

Or, in a more structured way...

Sub openwb()
    Dim sPath As String, sFile As String
    Dim wb As Workbook

    sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
    sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"

    Set wb = Workbooks.Open(sFile)
End Sub

upstream sent too big header while reading response header from upstream

Add the following to your conf file

fastcgi_buffers 16 16k; 
fastcgi_buffer_size 32k;

increase font size of hyperlink text html

You can do like this:

a {font-size: 100px}

Try avoid using font tag because it's deprecated. Use CSS like above instead. You can give your anchors specific class and apply any style for them.

Error handling with PHPMailer

In PHPMailer.php, there are lines as below:

echo $e->getMessage()

Just comment these lines and you will be good to go.

Having services in React application

or you can inject the class inheritance "http" into React Component

via props object.

  1. update :

    ReactDOM.render(<ReactApp data={app} />, document.getElementById('root'));
    
  2. Simply edit React Component ReactApp like this:

    class ReactApp extends React.Component {
    
    state = {
    
        data: ''
    
    }
    
        render(){
    
        return (
            <div>
            {this.props.data.getData()}      
            </div>
    
        )
        }
    }
    

Close/kill the session when the browser or tab is closed

As said, the browser doesn't let the server know when it closes.

Still, there are some ways to achieve close to this behavior. You can put a small AJAX script in place that updates the server regularly that the browser is open. You should pair this with something that fires on actions made by the user, so you can time out an idle session as well as one that has closed out.

What is the convention in JSON for empty vs. null?

There is the question whether we want to differentiate between cases:

  1. "phone" : "" = the value is empty

  2. "phone" : null = the value for "phone" was not set yet

If we want differentiate I would use null for this. Otherwise we would need to add a new field like "isAssigned" or so. This is an old Database issue.

How do I get the parent directory in Python?

os.path.abspath(os.path.join(somepath, '..'))

Observe:

import posixpath
import ntpath

print ntpath.abspath(ntpath.join('C:\\', '..'))
print ntpath.abspath(ntpath.join('C:\\foo', '..'))
print posixpath.abspath(posixpath.join('/', '..'))
print posixpath.abspath(posixpath.join('/home', '..'))

Fixing a systemd service 203/EXEC failure (no such file or directory)

I actually used the answer from How do I run a node.js app as a background service? combined with what dwrz said above. In my case, I was creating a Discord bot that needed to be able to run when I was not around.

With this service in place, I initially got the same error that the initial poster did, which brought me here. I was missing the #!/usr/bin/env node at the top of my executed node.js script.

Since then, no problems, although I intend to see what else can be extended to the service itself.

How to calculate the SVG Path for an arc (of a circle)

This is an old question, but I found the code useful and saved me three minutes of thinking :) So I am adding a small expansion to @opsb's answer.

If you wanted to convert this arc into a slice (to allow for fill) we can modify the code slightly:

_x000D_
_x000D_
function describeArc(x, y, radius, spread, startAngle, endAngle){_x000D_
    var innerStart = polarToCartesian(x, y, radius, endAngle);_x000D_
   var innerEnd = polarToCartesian(x, y, radius, startAngle);_x000D_
    var outerStart = polarToCartesian(x, y, radius + spread, endAngle);_x000D_
    var outerEnd = polarToCartesian(x, y, radius + spread, startAngle);_x000D_
_x000D_
    var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";_x000D_
_x000D_
    var d = [_x000D_
        "M", outerStart.x, outerStart.y,_x000D_
        "A", radius + spread, radius + spread, 0, largeArcFlag, 0, outerEnd.x, outerEnd.y,_x000D_
        "L", innerEnd.x, innerEnd.y, _x000D_
        "A", radius, radius, 0, largeArcFlag, 1, innerStart.x, innerStart.y, _x000D_
        "L", outerStart.x, outerStart.y, "Z"_x000D_
    ].join(" ");_x000D_
_x000D_
    return d;_x000D_
}_x000D_
_x000D_
function polarToCartesian(centerX, centerY, radius, angleInDegrees) {_x000D_
  var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;_x000D_
_x000D_
  return {_x000D_
    x: centerX + (radius * Math.cos(angleInRadians)),_x000D_
    y: centerY + (radius * Math.sin(angleInRadians))_x000D_
  };_x000D_
}_x000D_
_x000D_
var path = describeArc(150, 150, 50, 30, 0, 50)_x000D_
document.getElementById("p").innerHTML = path_x000D_
document.getElementById("path").setAttribute('d',path)
_x000D_
<p id="p">_x000D_
</p>_x000D_
<svg width="300" height="300" style="border:1px gray solid">_x000D_
  <path id="path" fill="blue" stroke="cyan"></path>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

and there you go!

How to get english language word database?

There's no such thing as a "complete" list. Different people have different ways of measuring -- for example, they might include slang, neologisms, multi-word phrases, offensive terms, foreign words, verb conjugations, and so on. Some people have even counted a million words! So you'll have to decide what you want in a word list.

Is it better to use "is" or "==" for number comparison in Python?

Use ==.

Sometimes, on some python implementations, by coincidence, integers from -5 to 256 will work with is (in CPython implementations for instance). But don't rely on this or use it in real programs.

Set min-width in HTML table's <td>

min-width and max-width properties do not work the way you expect for table cells. From spec:

In CSS 2.1, the effect of 'min-width' and 'max-width' on tables, inline tables, table cells, table columns, and column groups is undefined.

This hasn't changed in CSS3.

android: how to change layout on button click?

The logcat shows the error, you should call super.onCreate(savedInstanceState) :

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    //... your code
}

Loop in Jade (currently known as "Pug") template engine

for example:

- for (var i = 0; i < 10; ++i) {
  li= array[i]
- }

you may see https://github.com/visionmedia/jade for detailed document.

Better way to convert an int to a boolean

int i = 0;
bool b = Convert.ToBoolean(i);

Check if element exists in jQuery

your elemId as its name suggests, is an Id attribute, these are all you can do to check if it exists:

Vanilla JavaScript: in case you have more advanced selectors:

//you can use it for more advanced selectors
if(document.querySelectorAll("#elemId").length){}

if(document.querySelector("#elemId")){}

//you can use it if your selector has only an Id attribute
if(document.getElementById("elemId")){}

jQuery:

if(jQuery("#elemId").length){}

Getting DOM elements by classname

If you wish to get the innerhtml of the class without the zend you could use this:

$dom = new DomDocument();
$dom->load($filePath);
$classname = 'main-article';
$finder = new DomXPath($dom);
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
$tmp_dom = new DOMDocument(); 
foreach ($nodes as $node) 
    {
    $tmp_dom->appendChild($tmp_dom->importNode($node,true));
    }
$innerHTML.=trim($tmp_dom->saveHTML()); 
echo $innerHTML;

How to index into a dictionary?

You can't, since dict is unordered. you can use .popitem() to get an arbitrary item, but that will remove it from the dict.

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

Years later, but for what it's worth - This is simple to do.

  • Just RENAME the C:\xampp directory

  • Install the desired new version of XAMPP

  • Simply run the control panel script "xampp-control.exe" directly from within the xampp folder. (Ignore warnings about "must run from C:\xampp - those have nothing to do with multiple installations.)

To switch between these versions of XAMPP, just rename the xampp directories as necessary, and re-run.

How to have multiple CSS transitions on an element?

EDIT: I'm torn on whether to delete this post. As a matter of understanding the CSS syntax, it's good that people know all exists, and it may at times be preferable to a million individual declarations, depending on the structure of your CSS. On the other hand, it may have a performance penalty, although I've yet to see any data supporting that hypothesis. For now, I'll leave it, but I want people to be aware it's a mixed bag.

Original post:

You can also simply significantly with:

.nav a {
    transition: all .2s;
}

FWIW: all is implied if not specified, so transition: .2s; will get you to the same place.

ValueError: Wrong number of items passed - Meaning and suggestions?

for i in range(100):
try:
  #Your code here
  break
except:
  continue

This one worked for me.

Is it possible to style html5 audio tag?

Yes: you can hide the built-in browser UI (by removing the controls attribute from audio) and instead build your own interface and control the playback using Javascript (source):

<audio id="player" src="vincent.mp3"></audio>
<div> 
  <button onclick="document.getElementById('player').play()">Play</button> 
  <button onclick="document.getElementById('player').pause()">Pause</button> 
  <button onclick="document.getElementById('player').volume += 0.1">Vol +</button> 
  <button onclick="document.getElementById('player').volume -= 0.1">Vol -</button> 
</div>

You can then style the elements however you wish using CSS.

MDN HTMLAudioElement API reference

Pass multiple parameters in Html.BeginForm MVC

There are two options here.

  1. a hidden field within the form, or
  2. Add it to the route values parameter in the begin form method.

Edit

@Html.Hidden("clubid", ViewBag.Club.id)

or

 @using(Html.BeginForm("action", "controller",
                       new { clubid = @Viewbag.Club.id }, FormMethod.Post, null)

How do I detect if I am in release or debug mode?

Yes, you will have no problems using:

if (BuildConfig.DEBUG) {
   //It's not a release version.
}

Unless you are importing the wrong BuildConfig class. Make sure you are referencing your project's BuildConfig class, not from any of your dependency libraries.

enter image description here

Creating java date object from year,month,day

java.time

Using java.time framework built into Java 8

int year = 2015;
int month = 12;
int day = 22;
LocalDate.of(year, month, day); //2015-12-22
LocalDate.parse("2015-12-22"); //2015-12-22
//with custom formatter 
DateTimeFormatter.ofPattern formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate.parse("22-12-2015", formatter); //2015-12-22

If you need also information about time(hour,minute,second) use some conversion from LocalDate to LocalDateTime

LocalDate.parse("2015-12-22").atStartOfDay() //2015-12-22T00:00

How do I install package.json dependencies in the current directory using npm

Running:

npm install

from inside your app directory (i.e. where package.json is located) will install the dependencies for your app, rather than install it as a module, as described here. These will be placed in ./node_modules relative to your package.json file (it's actually slightly more complex than this, so check the npm docs here).

You are free to move the node_modules dir to the parent dir of your app if you want, because node's 'require' mechanism understands this. However, if you want to update your app's dependencies with install/update, npm will not see the relocated 'node_modules' and will instead create a new dir, again relative to package.json.

To prevent this, just create a symlink to the relocated node_modules from your app dir:

ln -s ../node_modules node_modules

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

$scope.trustAsHtml=function(scope)
{
    return $sce.trustAsHtml(scope);
}
<p class="card-text w-100" ng-bind-html="trustAsHtml(note.redoq_csd_product_lead_note)"></p>

URL encode sees “&” (ampersand) as “&amp;” HTML entity

Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:

var str, 
    el = document.getElementById("myUrl");

if ("textContent" in el)
    str = encodeURIComponent(el.textContent);
else
    str = encodeURIComponent(el.innerText);

If that isn't the case, you can use the replace() method to replace the HTML entity:

encodeURIComponent(str.replace(/&amp;/g, "&"));

a = open("file", "r"); a.readline() output without \n

That would be:

b.rstrip('\n')

If you want to strip space from each and every line, you might consider instead:

a.read().splitlines()

This will give you a list of lines, without the line end characters.

Image height and width not working?

You must write

<img src="theSource" style="width:30px;height:30px;" />

Inline styling will always take precedence over CSS styling. The width and height attributes are being overridden by your stylesheet, so you need to switch to this format.

What is the official "preferred" way to install pip and virtualenv systemwide?

On Debian the best way to do it would be

sudo apt-get install python-pip

inline if statement java, why is not working

Syntax is Shown below:

"your condition"? "step if true":"step if condition fails"

How can I disable the UITableView selection?

All you have to do is set the selection style on the UITableViewCell instance using either:

Objective-C:

cell.selectionStyle = UITableViewCellSelectionStyleNone;

or

[cell setSelectionStyle:UITableViewCellSelectionStyleNone];

Swift 2:

cell.selectionStyle = UITableViewCellSelectionStyle.None

Swift 3 and 4.x:

cell.selectionStyle = .none

Further, make sure you either don't implement -tableView:didSelectRowAtIndexPath: in your table view delegate or explicitly exclude the cells you want to have no action if you do implement it.

More info here and here

How to make a background 20% transparent on Android

Make the color have 80% in the alpha channel. For example, for red use #CCFF0000:

<TextView
   ...
   android:background="#CCFF0000" />

In the example, CC is the hexadecimal number for 255 * 0.8 = 204. Note that the first two hexadecimal digits are for the alpha channel. The format is #AARRGGBB, where AA is the alpha channel, RR is the red channel, GG is the green channel and BB is the blue channel.

I'm assuming that 20% transparent means 80% opaque. If you meant the other way, instead of CC use 33 which is the hexadecimal for 255 * 0.2 = 51.

In order to calculate the proper value for an alpha transparency value you can follow this procedure:

  1. Given a transparency percentage, for example 20%, you know the opaque percentage value is 80% (this is 100-20=80)
  2. The range for the alpha channel is 8 bits (2^8=256), meaning the range goes from 0 to 255.
  3. Project the opaque percentage into the alpha range, that is, multiply the range (255) by the percentage. In this example 255 * 0.8 = 204. Round to the nearest integer if needed.
  4. Convert the value obtained in 3., which is in base 10, to hexadecimal (base 16). You can use Google for this or any calculator. Using Google, type "204 to hexa" and it will give you the hexadecimal value. In this case it is 0xCC.
  5. Prepend the value obtained in 4. to the desired color. For example, for red, which is FF0000, you will have CCFF0000.

You can take a look at the Android documentation for colors.

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

WebSockets is definitely the future.

Long polling is a dirty workaround to prevent creating connections for each request like AJAX does -- but long polling was created when WebSockets didn't exist. Now due to WebSockets, long polling is going away.

WebRTC allows for peer-to-peer communication.

I recommend learning WebSockets.

Comparison:

of different communication techniques on the web

  • AJAX - requestresponse. Creates a connection to the server, sends request headers with optional data, gets a response from the server, and closes the connection. Supported in all major browsers.

  • Long poll - requestwaitresponse. Creates a connection to the server like AJAX does, but maintains a keep-alive connection open for some time (not long though). During connection, the open client can receive data from the server. The client has to reconnect periodically after the connection is closed, due to timeouts or data eof. On server side it is still treated like an HTTP request, same as AJAX, except the answer on request will happen now or some time in the future, defined by the application logic. support chart (full) | wikipedia

  • WebSockets - clientserver. Create a TCP connection to the server, and keep it open as long as needed. The server or client can easily close the connection. The client goes through an HTTP compatible handshake process. If it succeeds, then the server and client can exchange data in both directions at any time. It is efficient if the application requires frequent data exchange in both ways. WebSockets do have data framing that includes masking for each message sent from client to server, so data is simply encrypted. support chart (very good) | wikipedia

  • WebRTC - peerpeer. Transport to establish communication between clients and is transport-agnostic, so it can use UDP, TCP or even more abstract layers. This is generally used for high volume data transfer, such as video/audio streaming, where reliability is secondary and a few frames or reduction in quality progression can be sacrificed in favour of response time and, at least, some data transfer. Both sides (peers) can push data to each other independently. While it can be used totally independent from any centralised servers, it still requires some way of exchanging endPoints data, where in most cases developers still use centralised servers to "link" peers. This is required only to exchange essential data for establishing a connection, after which a centralised server is not required. support chart (medium) | wikipedia

  • Server-Sent Events - clientserver. Client establishes persistent and long-term connection to server. Only the server can send data to a client. If the client wants to send data to the server, it would require the use of another technology/protocol to do so. This protocol is HTTP compatible and simple to implement in most server-side platforms. This is a preferable protocol to be used instead of Long Polling. support chart (good, except IE) | wikipedia

Advantages:

The main advantage of WebSockets server-side, is that it is not an HTTP request (after handshake), but a proper message based communication protocol. This enables you to achieve huge performance and architecture advantages. For example, in node.js, you can share the same memory for different socket connections, so they can each access shared variables. Therefore, you don't need to use a database as an exchange point in the middle (like with AJAX or Long Polling with a language like PHP). You can store data in RAM, or even republish between sockets straight away.

Security considerations

People are often concerned about the security of WebSockets. The reality is that it makes little difference or even puts WebSockets as better option. First of all, with AJAX, there is a higher chance of MITM, as each request is a new TCP connection that is traversing through internet infrastructure. With WebSockets, once it's connected it is far more challenging to intercept in between, with additionally enforced frame masking when data is streamed from client to server as well as additional compression, which requires more effort to probe data. All modern protocols support both: HTTP and HTTPS (encrypted).

P.S.

Remember that WebSockets generally have a very different approach of logic for networking, more like real-time games had all this time, and not like http.

How do you make websites with Java?

I'll jump in with the notorious "Do you really want to do that" answer.

It seems like your focus is on playing with Java and seeing what it can do. However, if you want to actually develop a web app, you should be aware that, although Java is used in web applications (and in serious ones), there are other technology options which might be more adequate.

Personally, I like (and use) Java for powerful, portable backend services on a server. I've never tried building websites with it, because it never seemed the most obvious ting to do. After growing tired of PHP (which I have been using for years), I lately fell in love with Django, a Python-based web framework.

The Ruby on Rails people have a number of very funny videos on youtube comparing different web technologies to RoR. Of course, these are obviously exaggerated and maybe slightly biased, but I'd say there's more than one grain of truth in each of them. The one about Java is here. ;-)

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

If you are using Android Studio 3.0 or above make sure your project build.gradle should have content similar to-

buildscript {                 
    repositories {
        google()  // add google() before jcenter()
        jcenter()
    }
    dependencies {            
        classpath 'com.android.tools.build:gradle:3.0.1'

    }
}

allprojects {
    repositories {
        google()  // add google() before jcenter()
        jcenter()
    }
}

And for below Android Studio 3.0 and starting from support libraries 26.+ your project build.gradle must look like this-

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

Note- position really matters add google() before jcenter()

check these links below for more details-

1- Building Android Apps

2- Add Build Dependencies

3- Configure Your Build

Rails: select unique values from a column

Model.select(:rating).distinct

Output Django queryset as JSON

Try this:

class JSONListView(ListView):
    queryset = Users.objects.all()


    def get(self, request, *args, **kwargs):
        data = {}
        data["users"] = get_json_list(queryset)
        return JSONResponse(data)


def get_json_list(query_set):
    list_objects = []
    for obj in query_set:
        dict_obj = {}
        for field in obj._meta.get_fields():
            try:
                if field.many_to_many:
                    dict_obj[field.name] = get_json_list(getattr(obj, field.name).all())
                    continue
                dict_obj[field.name] = getattr(obj, field.name)
            except AttributeError:
                continue
        list_objects.append(dict_obj)
    return list_objects

Call function with setInterval in jQuery?

To write the best code, you "should" use the latter approach, with a function reference:

var refreshId = setInterval(function() {}, 5000);

or

function test() {}
var refreshId = setInterval(test, 5000);

but your approach of

function test() {}
var refreshId = setInterval("test()", 5000);

is basically valid, too (as long as test() is global).

Note that there is no such thing really as "in jQuery". You're still writing the Javascript language; you're just using some pre-made functions that are the jQuery library.

Execute function after Ajax call is complete

Add .done() to your function

var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
 $.ajax({                                            
         url: 'api.php',                        
         data: 'id1='+q+'',                                                         
         dataType: 'json',
         async:false,                    
         success: function(data)          
         {   
            id = data[0];              
            vname = data[1];
         }
      }).done(function(){
           printWithAjax(); 
      });



 }//end of the for statement
}//end of ajax call function

VB.NET - How to move to next item a For Each Loop?

I want to be clear that the following code is not good practice. You can use GOTO Label:

For Each I As Item In Items

    If I = x Then
       'Move to next item
        GOTO Label1
    End If

    ' Do something
    Label1:
Next

How to convert list of numpy arrays into single numpy array?

In general you can concatenate a whole sequence of arrays along any axis:

numpy.concatenate( LIST, axis=0 )

but you do have to worry about the shape and dimensionality of each array in the list (for a 2-dimensional 3x5 output, you need to ensure that they are all 2-dimensional n-by-5 arrays already). If you want to concatenate 1-dimensional arrays as the rows of a 2-dimensional output, you need to expand their dimensionality.

As Jorge's answer points out, there is also the function stack, introduced in numpy 1.10:

numpy.stack( LIST, axis=0 )

This takes the complementary approach: it creates a new view of each input array and adds an extra dimension (in this case, on the left, so each n-element 1D array becomes a 1-by-n 2D array) before concatenating. It will only work if all the input arrays have the same shape—even along the axis of concatenation.

vstack (or equivalently row_stack) is often an easier-to-use solution because it will take a sequence of 1- and/or 2-dimensional arrays and expand the dimensionality automatically where necessary and only where necessary, before concatenating the whole list together. Where a new dimension is required, it is added on the left. Again, you can concatenate a whole list at once without needing to iterate:

numpy.vstack( LIST )

This flexible behavior is also exhibited by the syntactic shortcut numpy.r_[ array1, ...., arrayN ] (note the square brackets). This is good for concatenating a few explicitly-named arrays but is no good for your situation because this syntax will not accept a sequence of arrays, like your LIST.

There is also an analogous function column_stack and shortcut c_[...], for horizontal (column-wise) stacking, as well as an almost-analogous function hstack—although for some reason the latter is less flexible (it is stricter about input arrays' dimensionality, and tries to concatenate 1-D arrays end-to-end instead of treating them as columns).

Finally, in the specific case of vertical stacking of 1-D arrays, the following also works:

numpy.array( LIST )

...because arrays can be constructed out of a sequence of other arrays, adding a new dimension to the beginning.

Catch multiple exceptions at once?

This is a classic problem every C# developer faces eventually.

Let me break your question into 2 questions. The first,

Can I catch multiple exceptions at once?

In short, no.

Which leads to the next question,

How do I avoid writing duplicate code given that I can't catch multiple exception types in the same catch() block?

Given your specific sample, where the fall-back value is cheap to construct, I like to follow these steps:

  1. Initialize WebId to the fall-back value.
  2. Construct a new Guid in a temporary variable.
  3. Set WebId to the fully constructed temporary variable. Make this the final statement of the try{} block.

So the code looks like:

try
{
    WebId = Guid.Empty;
    Guid newGuid = new Guid(queryString["web"]);
    // More initialization code goes here like 
    // newGuid.x = y;
    WebId = newGuid;
}
catch (FormatException) {}
catch (OverflowException) {}

If any exception is thrown, then WebId is never set to the half-constructed value, and remains Guid.Empty.

If constructing the fall-back value is expensive, and resetting a value is much cheaper, then I would move the reset code into its own function:

try
{
    WebId = new Guid(queryString["web"]);
    // More initialization code goes here.
}
catch (FormatException) {
    Reset(WebId);
}
catch (OverflowException) {
    Reset(WebId);
}

Python display text with font & color?

Yes. It is possible to draw text in pygame:

# initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' error
myfont = pygame.font.SysFont("monospace", 15)

# render text
label = myfont.render("Some text!", 1, (255,255,0))
screen.blit(label, (100, 100))

Using a bitmask in C#

if ( ( param & karen ) == karen )
{
  // Do stuff
}

The bitwise 'and' will mask out everything except the bit that "represents" Karen. As long as each person is represented by a single bit position, you could check multiple people with a simple:

if ( ( param & karen ) == karen )
{
  // Do Karen's stuff
}
if ( ( param & bob ) == bob )
  // Do Bob's stuff
}

How to change current Theme at runtime in Android

I had a similar problem and I solved in this way..

@Override
public void onCreate(Bundle savedInstanceState) {

    if (getIntent().hasExtra("bundle") && savedInstanceState==null){
        savedInstanceState = getIntent().getExtras().getBundle("bundle");
    }

    //add code for theme

    switch(theme)
    {
    case LIGHT:
        setTheme(R.style.LightTheme);
        break;
    case BLACK:
        setTheme(R.style.BlackTheme);
        break;

    default:
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //code

}

this code is for recreate the Activity saving Bundle and changing the theme. You have to write your own onSaveInstanceState(Bundle outState); From API-11 you can use the method recreate() instead

Bundle temp_bundle = new Bundle();
onSaveInstanceState(temp_bundle);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("bundle", temp_bundle);
startActivity(intent);
finish();

SSL error : routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Normally updating certifi and/or the certifi cacert.pem file would work. I also had to update my version of python. Vs. 2.7.5 wasn't working because of how it handles SNI requests.

Once you have an up to date pem file you can make your http request using:

requests.get(url, verify='/path/to/cacert.pem')

Custom Drawable for ProgressBar/ProgressDialog

Custom progress with scale!

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_no_smile_eyes_off"
            android:scaleGravity="center" />
    </item>
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_no_smile_eyes_on"
            android:scaleGravity="center" />
    </item>
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_smile_eyes_off"
            android:scaleGravity="center" />
    </item>
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_smile_eyes_on"
            android:scaleGravity="center" />
    </item>

</animation-list>

How to do a redirect to another route with react-router?

The simplest solution is:

import { Redirect } from 'react-router';

<Redirect to='/componentURL' />

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

Try conda install graphviz. I had the same problem, I resolved it by mentioned command in MacOS.

How to set the focus for a particular field in a Bootstrap modal, once it appears

I had the same problem with bootstrap 3, focus when i click the link, but not when trigger the event with javascript. The solution:

$('#myModal').on('shown.bs.modal', function () {
    setTimeout(function(){
        $('#inputId').focus();
    }, 100);
});

Probably it´s something about the animation!

How to get JSON from webpage into Python script

This gets a dictionary in JSON format from a webpage with Python 2.X and Python 3.X:

#!/usr/bin/env python

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

import json


def get_jsonparsed_data(url):
    """
    Receive the content of ``url``, parse it as JSON and return the object.

    Parameters
    ----------
    url : str

    Returns
    -------
    dict
    """
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return json.loads(data)


url = ("http://maps.googleapis.com/maps/api/geocode/json?"
       "address=googleplex&sensor=false")
print(get_jsonparsed_data(url))

See also: Read and write example for JSON

Add a CSS class to <%= f.submit %>

As Srdjan Pejic says, you can use

<%= f.submit 'name', :class => 'button' %>

or the new syntax which would be:

<%= f.submit 'name', class: 'button' %>

npm ERR! Error: EPERM: operation not permitted, rename

This might be due to your Antivirus software. If you can not disable AV then you can try modifying your NPM global install location as node installs into APPDATA directory which is actively monitored by AV Engines. Try running following commands-

npm config set prefix "YOUR CUSTOM LOCATION" npm config set cache "YOUR CUSTOM LOCATION"

Delete node_modules directory and install your package again.

What port number does SOAP use?

SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.

One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.

so exclusively open SOAP Port in Firewalls

how to re-format datetime string in php?

You could do it like this:

<?php
$datetime = "20130409163705"; 
$format = "YmdHis";

$date = date_parse_from_format ($format, $datetime);
print_r ($date);
?>

You can look at date_parse_from_format() and the accepted format values.

IIS error, Unable to start debugging on the webserver

If you are using active directory login u need to check password and username.

store return json value in input hidden field

just set the hidden field with javascript :

document.getElementById('elementId').value = 'whatever';

or do I miss something?

Android Intent Cannot resolve constructor

You may use this:

Intent intent = new Intent(getApplicationContext(), ClassName.class);

How to handle change text of span

Found the solution here

Lets say you have span1 as <span id='span1'>my text</span>
text change events can be captured with:

$(document).ready(function(){
    $("#span1").on('DOMSubtreeModified',function(){
         // text change handler
     });

 });
 

Calculate summary statistics of columns in dataframe

To clarify one point in @EdChum's answer, per the documentation, you can include the object columns by using df.describe(include='all'). It won't provide many statistics, but will provide a few pieces of info, including count, number of unique values, top value. This may be a new feature, I don't know as I am a relatively new user.

Date to milliseconds and back to date in Swift

@Travis solution is right, but it loses milliseconds when a Date is generated. I have added a line to include the milliseconds into the date:

If you don't need this precision, use the Travis solution because it will be faster.

extension Date {

    func toMillis() -> Int64! {
        return Int64(self.timeIntervalSince1970 * 1000)
    }

    init(millis: Int64) {
        self = Date(timeIntervalSince1970: TimeInterval(millis / 1000))
        self.addTimeInterval(TimeInterval(Double(millis % 1000) / 1000 ))
    }

}

Git add all files modified, deleted, and untracked?

git add --all or git add -A or git add -A . Stages All

git add . Stages New & Modified But Without Deleted

git add -u Stages Modified & Deleted But Without New

git commit -a Means git add -u And git commit -m "message"

After writing this command follow these steps:-

  1. press i
  2. write your message
  3. press esc
  4. press :wq
  5. press enter

git add <list of files> add specific file

git add *.txt add all the txt files in current directory

git add docs/*/txt add all txt files in docs directory

git add docs/ add all files in docs directory

git add "*.txt" or git add '*.txt' add all the files in the whole project

How to download a file from a URL in C#?

Also you can use DownloadFileAsync method in WebClient class. It downloads to a local file the resource with the specified URI. Also this method does not block the calling thread.

Sample:

    webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");

For more information:

http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/

Formatting a float to 2 decimal places

As already mentioned, you will need to use a formatted result; which is all done through the Write(), WriteLine(), Format(), and ToString() methods.

What has not been mentioned is the Fixed-point Format which allows for a specified number of decimal places. It uses an 'F' and the number following the 'F' is the number of decimal places outputted, as shown in the examples.

Console.WriteLine("{0:F2}", 12);    // 12.00 - two decimal places
Console.WriteLine("{0:F0}", 12.3);  // 12 - ommiting fractions

How to add a new line in textarea element?

You might want to use \n instead of /n.

Android: Clear the back stack

You can use this example to call your Activity A from Activity C

Intent loout = new Intent(context, LoginActivity.class); loout.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); context.startActivity(loout);

Algorithm for solving Sudoku

Not gonna write full code, but I did a sudoku solver a long time ago. I found that it didn't always solve it (the thing people do when they have a newspaper is incomplete!), but now think I know how to do it.

  • Setup: for each square, have a set of flags for each number showing the allowed numbers.
  • Crossing out: just like when people on the train are solving it on paper, you can iteratively cross out known numbers. Any square left with just one number will trigger another crossing out. This will either result in solving the whole puzzle, or it will run out of triggers. This is where I stalled last time.
  • Permutations: there's only 9! = 362880 ways to arrange 9 numbers, easily precomputed on a modern system. All of the rows, columns, and 3x3 squares must be one of these permutations. Once you have a bunch of numbers in there, you can do what you did with the crossing out. For each row/column/3x3, you can cross out 1/9 of the 9! permutations if you have one number, 1/(8*9) if you have 2, and so forth.
  • Cross permutations: Now you have a bunch of rows and columns with sets of potential permutations. But there's another constraint: once you set a row, the columns and 3x3s are vastly reduced in what they might be. You can do a tree search from here to find a solution.

Leave only two decimal places after the dot

// just two decimal places
String.Format("{0:0.00}", 123.4567);      // "123.46"
String.Format("{0:0.00}", 123.4);         // "123.40"
String.Format("{0:0.00}", 123.0);         // "123.00"

http://www.csharp-examples.net/string-format-double/

edit

No idea why they used "String" instead of "string", but the rest is correct.

Get length of array?

Length of an array:

UBound(columns)-LBound(columns)+1

UBound alone is not the best method for getting the length of every array as arrays in VBA can start at different indexes, e.g Dim arr(2 to 10)

UBound will return correct results only if the array is 1-based (starts indexing at 1 e.g. Dim arr(1 to 10). It will return wrong results in any other circumstance e.g. Dim arr(10)

More on the VBA Array in this VBA Array tutorial.

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

Use of main thread to present and dismiss view controller worked for me.

DispatchQueue.main.async { self.present(viewController, animated: true, completion: nil) }

How to get response using cURL in PHP

The crux of the solution is setting

CURLOPT_RETURNTRANSFER => true

then

$response = curl_exec($ch);

CURLOPT_RETURNTRANSFER tells PHP to store the response in a variable instead of printing it to the page, so $response will contain your response. Here's your most basic working code (I think, didn't test it):

// init curl object        
$ch = curl_init();

// define options
$optArray = array(
    CURLOPT_URL => 'http://www.google.com',
    CURLOPT_RETURNTRANSFER => true
);

// apply those options
curl_setopt_array($ch, $optArray);

// execute request and get response
$result = curl_exec($ch);

php static function

In the first class, sayHi() is actually an instance method which you are calling as a static method and you get away with it because sayHi() never refers to $this.

Static functions are associated with the class, not an instance of the class. As such, $this is not available from a static context ($this isn't pointing to any object).

How do I get first element rather than using [0] in jQuery?

You can use the first method:

$('li').first()

http://api.jquery.com/first/

btw I agree with Nick Craver -- use document.getElementById()...

How to Create simple drag and Drop in angularjs

Using HTML 5 Drag and Drop
You can easily archive this using HTML 5 drag and drop feature along with angular directives.

  1. Enable drag by setting draggable = true.
  2. Add directives for parent container and child items.
  3. Override drag and drop functions - 'ondragstart' for parent and 'ondrop' for child.

Find the example below in which list is array of items.
HTML code:

    <div class="item_content" ng-repeat="item in list" draggrble-container>
        <div class="item" draggable-item draggable="true">{{item}}</div>
    </div>

Javascript:

    module.directive("draggableItem",function(){
     return {
      link:function(scope,elem,attr){
        elem[0].ondragstart = function(event){
            scope.$parent.selectedItem = scope.item;
        };
      }
     };
    });


    module.directive("draggrbleContainer",function(){
     return {
        link:function(scope,elem,attr){
            elem[0].ondrop = function(event){
                event.preventDefault();
                let selectedIndex = scope.list.indexOf(scope.$parent.selectedItem);
                let newPosition = scope.list.indexOf(scope.item);
                scope.$parent.list.splice(selectedIndex,1);
                scope.$parent.list.splice(newPosition,0,scope.$parent.selectedItem);
                scope.$apply();
            };
            elem[0].ondragover = function(event){
                event.preventDefault();

            };
        }
     };
    });

Find the complete code here https://github.com/raghavendrarai/SimpleDragAndDrop

Why does my favicon not show up?

Try adding the profile attribute to your head tag and use "image/x-icon" for the type attribute:

<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="img/favicon.ico">

If the above code doesn't work, try using the full icon path for the href attribute:

<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon" type="image/x-icon" href="http://example.com/img/favicon.ico">

numbers not allowed (0-9) - Regex Expression in javascript

Simply:

/^([^0-9]*)$/

That pattern matches any number of characters that is not 0 through 9.

I recommend checking out http://regexpal.com/. It will let you easily test out a regex.

Formatting Decimal places in R

Something like that :

options(digits=2)

Definition of digits option :

digits: controls the number of digits to print when printing numeric values.

Pretty-Printing JSON with PHP

best way to format JSON data is like this!

header('Content-type: application/json; charset=UTF-8');
echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

Replace $response with your Data which is required to be converted to JSON

How to validate array in Laravel?

The below code working for me on array coming from ajax call .

  $form = $request->input('form');
  $rules = array(
            'facebook_account' => 'url',
            'youtube_account' => 'url',
            'twitter_account' => 'url',
            'instagram_account' => 'url',
            'snapchat_account' => 'url',
            'website' => 'url',
        );
        $validation = Validator::make($form, $rules);

        if ($validation->fails()) {
            return Response::make(['error' => $validation->errors()], 400);
        }

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

I'd like to give my give my practice.

Use your preferred IDE, take eclipse for for example here:

  1. Find an appropriate location within the exception stack
  2. Set conditional breakpoint
  3. Debug it
  4. It will print the corrupted jar before exception

enter image description here

Oracle SQL convert date format from DD-Mon-YY to YYYYMM

Am I missing something? You can just convert offer_date in the comparison:

SELECT *
FROM offers
WHERE to_char(offer_date, 'YYYYMM') = (SELECT to_date(create_date, 'YYYYMM') FROM customers where id = '12345678') AND
      offer_rate > 0 

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

You need a development provisioning profile on your build machine. Apps can run on the simulator without a profile, but they are required to run on an actual device.

If you open the project in Xcode, it may automatically set up provisioning for you. Otherwise you will have to create go to the iOS Dev Center and create a profile.

How to write html code inside <?php ?>, I want write html code within the PHP script so that it can be echoed from Backend

Try it like,

<?php 
    $name='your name';
    echo '<table>
       <tr><th>Name</th></tr>
       <tr><td>'.$name.'</td></tr>
    </table>';
?>

Updated

<?php 
    echo '<table>
       <tr><th>Rst</th><th>Marks</th></tr>
       <tr><td>'.$rst4.'</td><td>'.$marks4.'</td></tr>
    </table>';
?>

How to set default value for form field in Symfony2?

You can set a default value, e.g. for the form message, like this:

$defaultData = array('message' => 'Type your message here');
$form = $this->createFormBuilder($defaultData)
    ->add('name', 'text')
    ->add('email', 'email')
    ->add('message', 'textarea')
    ->add('send', 'submit')
    ->getForm();

In case your form is mapped to an Entity, you can go like this (e.g. default username):

$user = new User();
$user->setUsername('John Doe');

$form = $this->createFormBuilder($user)
    ->add('username')
    ->getForm();

Good way of getting the user's location in Android

Recently refactored to obtain the location of the code, learn some good ideas, and finally achieved a relatively perfect library and Demo.

@Gryphius's answer is good

    //request all valid provider(network/gps)
private boolean requestAllProviderUpdates() {
    checkRuntimeEnvironment();
    checkPermission();

    if (isRequesting) {
        EasyLog.d("Request location update is busy");
        return false;
    }


    long minTime = getCheckTimeInterval();
    float minDistance = getCheckMinDistance();

    if (mMapLocationListeners == null) {
        mMapLocationListeners = new HashMap<>();
    }

    mValidProviders = getValidProviders();
    if (mValidProviders == null || mValidProviders.isEmpty()) {
        throw new IllegalArgumentException("Not available provider.");
    }

    for (String provider : mValidProviders) {
        LocationListener locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                if (location == null) {
                    EasyLog.e("LocationListener callback location is null.");
                    return;
                }
                printf(location);
                mLastProviderTimestamp = location.getTime();

                if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
                    finishResult(location);
                } else {
                    doLocationResult(location);
                }

                removeProvider(location.getProvider());
                if (isEmptyValidProviders()) {
                    requestTimeoutMsgInit();
                    removeUpdates();
                }
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }
        };
        getLocationManager().requestLocationUpdates(provider, minTime, minDistance, locationListener);
        mMapLocationListeners.put(provider, locationListener);
        EasyLog.d("Location request %s provider update.", provider);
    }
    isRequesting = true;
    return true;
}

//remove request update
public void removeUpdates() {
    checkRuntimeEnvironment();

    LocationManager locationManager = getLocationManager();
    if (mMapLocationListeners != null) {
        Set<String> keys = mMapLocationListeners.keySet();
        for (String key : keys) {
            LocationListener locationListener = mMapLocationListeners.get(key);
            if (locationListener != null) {
                locationManager.removeUpdates(locationListener);
                EasyLog.d("Remove location update, provider is " + key);
            }
        }
        mMapLocationListeners.clear();
        isRequesting = false;
    }
}

//Compared with the last successful position, to determine whether you need to filter
private boolean isNeedFilter(Location location) {
    checkLocation(location);

    if (mLastLocation != null) {
        float distance = location.distanceTo(mLastLocation);
        if (distance < getCheckMinDistance()) {
            return true;
        }
        if (location.getAccuracy() >= mLastLocation.getAccuracy()
                && distance < location.getAccuracy()) {
            return true;
        }
        if (location.getTime() <= mLastProviderTimestamp) {
            return true;
        }
    }
    return false;
}

private void doLocationResult(Location location) {
    checkLocation(location);

    if (isNeedFilter(location)) {
        EasyLog.d("location need to filtered out, timestamp is " + location.getTime());
        finishResult(mLastLocation);
    } else {
        finishResult(location);
    }
}

//Return to the finished position
private void finishResult(Location location) {
    checkLocation(location);

    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    float accuracy = location.getAccuracy();
    long time = location.getTime();
    String provider = location.getProvider();

    if (mLocationResultListeners != null && !mLocationResultListeners.isEmpty()) {
        String format = "Location result:<%f, %f> Accuracy:%f Time:%d Provider:%s";
        EasyLog.i(String.format(format, latitude, longitude, accuracy, time, provider));

        mLastLocation = location;
        synchronized (this) {
            Iterator<LocationResultListener> iterator =  mLocationResultListeners.iterator();
            while (iterator.hasNext()) {
                LocationResultListener listener = iterator.next();
                if (listener != null) {
                    listener.onResult(location);
                }
                iterator.remove();
            }
        }
    }
}

Complete implementation: https://github.com/bingerz/FastLocation/blob/master/fastlocationlib/src/main/java/cn/bingerz/fastlocation/FastLocation.java

1.Thanks @Gryphius solution ideas, I also share the complete code.

2.Each request to complete the location, it is best to removeUpdates, otherwise the phone status bar will always display the positioning icon

UnicodeEncodeError: 'ascii' codec can't encode character at special name

Try setting the system default encoding as utf-8 at the start of the script, so that all strings are encoded using that.

Example -

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

The above should set the default encoding as utf-8 .

How to get current foreground activity context in android?

I did the Following in Kotlin

  1. Create Application Class
  2. Edit the Application Class as Follows

    class FTApplication: MultiDexApplication() {
    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }
    
    init {
        instance = this
    }
    
    val mFTActivityLifecycleCallbacks = FTActivityLifecycleCallbacks()
    
    override fun onCreate() {
        super.onCreate()
    
        registerActivityLifecycleCallbacks(mFTActivityLifecycleCallbacks)
    }
    
    companion object {
        private var instance: FTApplication? = null
    
        fun currentActivity(): Activity? {
    
            return instance!!.mFTActivityLifecycleCallbacks.currentActivity
        }
    }
    
     }
    
  3. Create the ActivityLifecycleCallbacks class

    class FTActivityLifecycleCallbacks: Application.ActivityLifecycleCallbacks {
    
    var currentActivity: Activity? = null
    
    override fun onActivityPaused(activity: Activity?) {
        currentActivity = activity
    }
    
    override fun onActivityResumed(activity: Activity?) {
        currentActivity = activity
    }
    
    override fun onActivityStarted(activity: Activity?) {
        currentActivity = activity
    }
    
    override fun onActivityDestroyed(activity: Activity?) {
    }
    
    override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {
    }
    
    override fun onActivityStopped(activity: Activity?) {
    }
    
    override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
        currentActivity = activity
    }
    
    }
    
  4. you can now use it in any class by calling the following: FTApplication.currentActivity()

System.IO.IOException: file used by another process

It worked for me.

Here is my test code. Test run follows:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            FileInfo f = new FileInfo(args[0]);
            bool result = modifyFile(f, args[1],args[2]);
        }
        private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod) 
        { 
            Boolean result = false; 
            FileStream fs = new FileStream(file.FullName + ".tmp", FileMode.Create, FileAccess.Write); 
            StreamWriter sw = new StreamWriter(fs); 
            StreamReader streamreader = file.OpenText(); 
            String originalPath = file.FullName; 
            string input = streamreader.ReadToEnd(); 
            Console.WriteLine("input : {0}", input); 
            String tempString = input.Replace(extractedMethod, modifiedMethod); 
            Console.WriteLine("replaced String {0}", tempString); 
            try 
            { 
                sw.Write(tempString); 
                sw.Flush(); 
                sw.Close(); 
                sw.Dispose(); 
                fs.Close(); 
                fs.Dispose(); 
                streamreader.Close(); 
                streamreader.Dispose(); 
                File.Copy(originalPath, originalPath + ".old", true); 
                FileInfo newFile = new FileInfo(originalPath + ".tmp"); 
                File.Delete(originalPath); 
                File.Copy(originalPath + ".tmp", originalPath, true); 
                result = true; 
            } 
            catch (Exception ex) 
            { 
                Console.WriteLine(ex); 
            } 
            return result; 
        }
    }
}


C:\testarea>ConsoleApplication1.exe file.txt padding testing
input :         <style type="text/css">
        <!--
         #mytable {
          border-collapse: collapse;
          width: 300px;
         }
         #mytable th,
         #mytable td
         {
          border: 1px solid #000;
          padding: 3px;
         }
         #mytable tr.highlight {
          background-color: #eee;
         }
        //-->
        </style>
replaced String         <style type="text/css">
        <!--
         #mytable {
          border-collapse: collapse;
          width: 300px;
         }
         #mytable th,
         #mytable td
         {
          border: 1px solid #000;
          testing: 3px;
         }
         #mytable tr.highlight {
          background-color: #eee;
         }
        //-->
        </style>

How can I position my jQuery dialog to center?

Are you running into this in IE only? If so, try adding this to the FIRST line of your page's HEAD tag:

<meta http-equiv="X-UA-Compatible" content="IE=7" />

I had though that all compatibility issues were fixed in later jQueries, but I ran into this one today.

How do I check if the mouse is over an element in jQuery?

Just a note about the popular and helpful Arthur Goldsmith answer above: If you're moving your mouse from one element to another in IE (at least until IE 9) you may have some trouble getting this to work correctly if the new element has a transparent background (which it would by default). My workaround was the give the new element a transparent background image.

How to close jQuery Dialog within the dialog?

$(this).parents(".ui-dialog-content").dialog('close')

Simple, I like to make sure I don't:

  1. hardcode dialog #id values.
  2. Close all dialogs.

Disable scrolling in webview?

If you subclass Webview, you can simply override onTouchEvent to filter out the move-events that trigger scrolling.

public class SubWebView extends WebView {

    @Override
    public boolean onTouchEvent (MotionEvent ev)    {
        if(ev.getAction() == MotionEvent.ACTION_MOVE) {
            postInvalidate();
            return true;
        }
        return super.onTouchEvent(ev);
    }
    ...

How to check for null in Twig?

     //test if varibale exist
     {% if var is defined %}
         //todo
     {% endif %}

     //test if variable is not null
     {% if var is not null %}
         //todo
     {% endif %}

Maximum size of a varchar(max) variable

As far as I can tell there is no upper limit in 2008.

In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg variable with

Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.

the code below fails with

REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.

However it appears these limitations have quietly been lifted. On 2008

DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681); 

SET @y = REPLICATE(@y,92681);

SELECT LEN(@y) 

Returns

8589767761

I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory

Running

select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid

Returned

internal_objects_alloc_page_co 
------------------------------ 
2144456    

so I presume this all just gets stored in LOB pages in tempdb with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681); statement. The initial variable assignment to @y and the LEN calculation did not increase this.

The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE method isn't supported for varchar(max) variables.

Addition

I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max) and nvarchar(max) + varchar(max). Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes. again. The script for that is below (may take a long time to run).

DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647); 
SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1)  /*4294967294, 4294967292*/


DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823); 
SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2)  /*2147483646, 4294967292*/


DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3)   /*6442450940, 12884901880*/

/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3
INTO Test

SQL Server - Adding a string to a text column (concat equivalent)

like said before best would be to set datatype of the column to nvarchar(max), but if that's not possible you can do the following using cast or convert:

-- create a test table 
create table test (
    a text
) 
-- insert test value
insert into test (a) values ('this is a text')
-- the following does not work !!!
update test set a = a + ' and a new text added'
-- but this way it works: 
update test set a = cast ( a as nvarchar(max))  + cast (' and a new text added' as nvarchar(max) )
-- test result
select * from test
-- column a contains:
this is a text and a new text added

hope that helps

Debugging "Element is not clickable at point" error

This might help someone who is using WebdriverIO:

function(){
    var runInBrowser = function(argument) { 
        argument.click();
    };
    var elementToClickOn = browser.$('element');
    browser.execute(runInBrowser, elementToClickOn);
}

Source : https://www.intricatecloud.io/2018/11/webdriverio-tips-element-wrapped-in-div-is-not-clickable/

Code not running in IE 11, works fine in Chrome

Replace the startsWith function with:

yourString.indexOf(searchString, position) // where position can be set to 0

This will support all browsers including IE

Position can be set to 0 for string matching from the start meaning 0th position.

How can you flush a write using a file descriptor?

Have you tried disabling buffering?

setvbuf(fd, NULL, _IONBF, 0);

Can the Unix list command 'ls' output numerical chmod permissions?

it almost can ..

 ls -l | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/) \
             *2^(8-i));if(k)printf("%0o ",k);print}'

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

Try executing this SQL command:

> grant all privileges 
  on YOUR_DATABASE.* 
  to 'asdfsdf'@'localhost' 
  identified by 'your_password';
> flush privileges; 

It seems that you are having issues with connecting to the database and not writing to the folder you’re mentioning.

Also, make sure you have granted FILE to user 'asdfsdf'@'localhost'.

> GRANT FILE ON *.* TO 'asdfsdf'@'localhost';

First Or Create

Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate now has second parameter values, which is being used for new record, but not for search

$user = User::firstOrCreate([
    'email' => '[email protected]'
], [
    'firstName' => 'Taylor',
    'lastName' => 'Otwell'
]);

Java generics: multiple generic parameters?

You can follow one of the below approaches:

1) Basic, single type :

//One type
public static <T> void fill(List <T> list, T val) {

    for(int i=0; i<list.size(); i++){
        list.set(i, val);
    }

}

2) Multiple Types :

// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {

    return val1+" "+val2;

}

3) Below will raise compiler error as 'T3 is not in the listing of generic types that are used in function declaration part.

//Raised compilation error
public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {
    return 0;
}

Correct : Compiles fine

public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {
    return 0;
}

Sample Class Code :

package generics.basics;

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

public class GenericMethods {

/*
 Declare the generic type parameter T in this method. 

 After the qualifiers public and static, you put <T> and 
 then followed it by return type, method name, and its parameters.

 Observe : type of val is 'T' and not '<T>'

 * */
//One type
public static <T> void fill(List <T> list, T val) {

    for(int i=0; i<list.size(); i++){
        list.set(i, val);
    }

}

// multiple types as parameters
public static <T1, T2> String multipleTypeArgument(T1 val1, T2 val2) {

    return val1+" "+val2;

}

/*// Q: To audience -> will this compile ? 
 * 
 * public static <T1, T2> T3 returnTypeGeneric(T1 val1, T2 val2) {

    return 0;

}*/

 public static <T1, T2, T3> T3 returnTypeGeneric(T1 val1, T2 val2) {

    return null;

}

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.add(10);
    list.add(20);
    System.out.println(list.toString());
    fill(list, 100);
    System.out.println(list.toString());

    List<String> Strlist = new ArrayList<>();
    Strlist.add("Chirag");
    Strlist.add("Nayak");
    System.out.println(Strlist.toString());
    fill(Strlist, "GOOD BOY");
    System.out.println(Strlist.toString());


    System.out.println(multipleTypeArgument("Chirag", 100));
    System.out.println(multipleTypeArgument(100,"Nayak"));

}

}

// class definition ends

Sample Output:

[10, 20]
[100, 100]
[Chirag, Nayak]
[GOOD BOY, GOOD BOY]
Chirag 100
100 Nayak

print memory address of Python variable

According to the manual, in CPython id() is the actual memory address of the variable. If you want it in hex format, call hex() on it.

x = 5
print hex(id(x))

this will print the memory address of x.

How to compile and run C files from within Notepad++ using NppExec plugin?

In windows if you are using a portable version of MinGW you must set path variable or you have error libintl-8.dll not found. My path is C:\Program Files (x86)\CodeBlocks\MinGW\bin

How to remove old Docker containers

You can remove only stopped containers. Stop all of them in the beginning

docker stop $(docker ps -a -q)

Then you can remove

docker rm $(docker ps -a -q)

Implementing INotifyPropertyChanged - does a better way exist?

Another Idea...

 public class ViewModelBase : INotifyPropertyChanged
{
    private Dictionary<string, object> _propertyStore = new Dictionary<string, object>();
    protected virtual void SetValue<T>(T value, [CallerMemberName] string propertyName="") {
        _propertyStore[propertyName] = value;
        OnPropertyChanged(propertyName);
    }
    protected virtual T GetValue<T>([CallerMemberName] string propertyName = "")
    {
        object ret;
        if (_propertyStore.TryGetValue(propertyName, out ret))
        {
            return (T)ret;
        }
        else
        {
            return default(T);
        }
    }

    //Usage
    //public string SomeProperty {
    //    get { return GetValue<string>();  }
    //    set { SetValue(value); }
    //}

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        var temp = PropertyChanged;
        if (temp != null)
            temp.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Conditional logic in AngularJS template

Angular 1.1.5 introduced the ng-if directive. That's the best solution for this particular problem. If you are using an older version of Angular, consider using angular-ui's ui-if directive.

If you arrived here looking for answers to the general question of "conditional logic in templates" also consider:


Original answer:

Here is a not-so-great "ng-if" directive:

myApp.directive('ngIf', function() {
    return {
        link: function(scope, element, attrs) {
            if(scope.$eval(attrs.ngIf)) {
                // remove '<div ng-if...></div>'
                element.replaceWith(element.children())
            } else {
                element.replaceWith(' ')
            }
        }
    }
});

that allows for this HTML syntax:

<div ng-repeat="message in data.messages" ng-class="message.type">
   <hr>
   <div ng-if="showFrom(message)">
       <div>From: {{message.from.name}}</div>
   </div>    
   <div ng-if="showCreatedBy(message)">
      <div>Created by: {{message.createdBy.name}}</div>
   </div>    
   <div ng-if="showTo(message)">
      <div>To: {{message.to.name}}</div>
   </div>    
</div>

Fiddle.

replaceWith() is used to remove unneeded content from the DOM.

Also, as I mentioned on Google+, ng-style can probably be used to conditionally load background images, should you want to use ng-show instead of a custom directive. (For the benefit of other readers, Jon stated on Google+: "both methods use ng-show which I'm trying to avoid because it uses display:none and leaves extra markup in the DOM. This is a particular problem in this scenario because the hidden element will have a background image which will still be loaded in most browsers.").
See also How do I conditionally apply CSS styles in AngularJS?

The angular-ui ui-if directive watches for changes to the if condition/expression. Mine doesn't. So, while my simple implementation will update the view correctly if the model changes such that it only affects the template output, it won't update the view correctly if the condition/expression answer changes.

E.g., if the value of a from.name changes in the model, the view will update. But if you delete $scope.data.messages[0].from, the from name will be removed from the view, but the template will not be removed from the view because the if-condition/expression is not being watched.

How to run crontab job every week on Sunday

10 * * * Sun

Position 1 for minutes, allowed values are 1-60
position 2 for hours, allowed values are 1-24
position 3 for day of month ,allowed values are 1-31
position 4 for month ,allowed values are 1-12 
position 5 for day of week ,allowed values are 1-7 or and the day starts at Monday. 

Finding height in Binary Search Tree

Here is a solution in Java a bit lengthy but works..

public static int getHeight (Node root){
    int lheight = 0, rheight = 0;
    if(root==null) {
        return 0;
    }
    else {
        if(root.left != null) {
            lheight = 1 + getHeight(root.left);
            System.out.println("lheight" + " " + lheight);
        }
        if (root.right != null) {
            rheight = 1+ getHeight(root.right);
            System.out.println("rheight" + " " + rheight);
        }
        if(root != null && root.left == null && root.right == null) {
            lheight += 1; 
            rheight += 1;
        }

    }
    return Math.max(lheight, rheight);
    }

Omitting all xsi and xsd namespaces when serializing an object in .NET?

This is the 2nd of two answers.

If you want to just strip all namespaces arbitrarily from a document during serialization, you can do this by implementing your own XmlWriter.

The easiest way is to derive from XmlTextWriter and override the StartElement method that emits namespaces. The StartElement method is invoked by the XmlSerializer when emitting any elements, including the root. By overriding the namespace for each element, and replacing it with the empty string, you've stripped the namespaces from the output.

public class NoNamespaceXmlWriter : XmlTextWriter
{
    //Provide as many contructors as you need
    public NoNamespaceXmlWriter(System.IO.TextWriter output)
        : base(output) { Formatting= System.Xml.Formatting.Indented;}

    public override void WriteStartDocument () { }

    public override void WriteStartElement(string prefix, string localName, string ns)
    {
        base.WriteStartElement("", localName, "");
    }
}

Suppose this is the type:

// explicitly specify a namespace for this type,
// to be used during XML serialization.
[XmlRoot(Namespace="urn:Abracadabra")]
public class MyTypeWithNamespaces
{
    // private fields backing the properties
    private int _Epoch;
    private string _Label;

    // explicitly define a distinct namespace for this element
    [XmlElement(Namespace="urn:Whoohoo")]
    public string Label
    {
        set {  _Label= value; } 
        get { return _Label; } 
    }

    // this property will be implicitly serialized to XML using the
    // member name for the element name, and inheriting the namespace from
    // the type.
    public int Epoch
    {
        set {  _Epoch= value; } 
        get { return _Epoch; } 
    }
}

Here's how you would use such a thing during serialization:

        var o2= new MyTypeWithNamespaces { ..intializers.. };
        var builder = new System.Text.StringBuilder();
        using ( XmlWriter writer = new NoNamespaceXmlWriter(new System.IO.StringWriter(builder)))
        {
            s2.Serialize(writer, o2, ns2);
        }            
        Console.WriteLine("{0}",builder.ToString());

The XmlTextWriter is sort of broken, though. According to the reference doc, when it writes it does not check for the following:

  • Invalid characters in attribute and element names.

  • Unicode characters that do not fit the specified encoding. If the Unicode characters do not fit the specified encoding, the XmlTextWriter does not escape the Unicode characters into character entities.

  • Duplicate attributes.

  • Characters in the DOCTYPE public identifier or system identifier.

These problems with XmlTextWriter have been around since v1.1 of the .NET Framework, and they will remain, for backward compatibility. If you have no concerns about those problems, then by all means use the XmlTextWriter. But most people would like a bit more reliability.

To get that, while still suppressing namespaces during serialization, instead of deriving from XmlTextWriter, define a concrete implementation of the abstract XmlWriter and its 24 methods.

An example is here:

public class XmlWriterWrapper : XmlWriter
{
    protected XmlWriter writer;

    public XmlWriterWrapper(XmlWriter baseWriter)
    {
        this.Writer = baseWriter;
    }

    public override void Close()
    {
        this.writer.Close();
    }

    protected override void Dispose(bool disposing)
    {
        ((IDisposable) this.writer).Dispose();
    }

    public override void Flush()
    {
        this.writer.Flush();
    }

    public override string LookupPrefix(string ns)
    {
        return this.writer.LookupPrefix(ns);
    }

    public override void WriteBase64(byte[] buffer, int index, int count)
    {
        this.writer.WriteBase64(buffer, index, count);
    }

    public override void WriteCData(string text)
    {
        this.writer.WriteCData(text);
    }

    public override void WriteCharEntity(char ch)
    {
        this.writer.WriteCharEntity(ch);
    }

    public override void WriteChars(char[] buffer, int index, int count)
    {
        this.writer.WriteChars(buffer, index, count);
    }

    public override void WriteComment(string text)
    {
        this.writer.WriteComment(text);
    }

    public override void WriteDocType(string name, string pubid, string sysid, string subset)
    {
        this.writer.WriteDocType(name, pubid, sysid, subset);
    }

    public override void WriteEndAttribute()
    {
        this.writer.WriteEndAttribute();
    }

    public override void WriteEndDocument()
    {
        this.writer.WriteEndDocument();
    }

    public override void WriteEndElement()
    {
        this.writer.WriteEndElement();
    }

    public override void WriteEntityRef(string name)
    {
        this.writer.WriteEntityRef(name);
    }

    public override void WriteFullEndElement()
    {
        this.writer.WriteFullEndElement();
    }

    public override void WriteProcessingInstruction(string name, string text)
    {
        this.writer.WriteProcessingInstruction(name, text);
    }

    public override void WriteRaw(string data)
    {
        this.writer.WriteRaw(data);
    }

    public override void WriteRaw(char[] buffer, int index, int count)
    {
        this.writer.WriteRaw(buffer, index, count);
    }

    public override void WriteStartAttribute(string prefix, string localName, string ns)
    {
        this.writer.WriteStartAttribute(prefix, localName, ns);
    }

    public override void WriteStartDocument()
    {
        this.writer.WriteStartDocument();
    }

    public override void WriteStartDocument(bool standalone)
    {
        this.writer.WriteStartDocument(standalone);
    }

    public override void WriteStartElement(string prefix, string localName, string ns)
    {
        this.writer.WriteStartElement(prefix, localName, ns);
    }

    public override void WriteString(string text)
    {
        this.writer.WriteString(text);
    }

    public override void WriteSurrogateCharEntity(char lowChar, char highChar)
    {
        this.writer.WriteSurrogateCharEntity(lowChar, highChar);
    }

    public override void WriteValue(bool value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteValue(DateTime value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteValue(decimal value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteValue(double value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteValue(int value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteValue(long value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteValue(object value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteValue(float value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteValue(string value)
    {
        this.writer.WriteValue(value);
    }

    public override void WriteWhitespace(string ws)
    {
        this.writer.WriteWhitespace(ws);
    }


    public override XmlWriterSettings Settings
    {
        get
        {
            return this.writer.Settings;
        }
    }

    protected XmlWriter Writer
    {
        get
        {
            return this.writer;
        }
        set
        {
            this.writer = value;
        }
    }

    public override System.Xml.WriteState WriteState
    {
        get
        {
            return this.writer.WriteState;
        }
    }

    public override string XmlLang
    {
        get
        {
            return this.writer.XmlLang;
        }
    }

    public override System.Xml.XmlSpace XmlSpace
    {
        get
        {
            return this.writer.XmlSpace;
        }
    }        
}

Then, provide a derived class that overrides the StartElement method, as before:

public class NamespaceSupressingXmlWriter : XmlWriterWrapper
{
    //Provide as many contructors as you need
    public NamespaceSupressingXmlWriter(System.IO.TextWriter output)
        : base(XmlWriter.Create(output)) { }

    public NamespaceSupressingXmlWriter(XmlWriter output)
        : base(XmlWriter.Create(output)) { }

    public override void WriteStartElement(string prefix, string localName, string ns)
    {
        base.WriteStartElement("", localName, "");
    }
}

And then use this writer like so:

        var o2= new MyTypeWithNamespaces { ..intializers.. };
        var builder = new System.Text.StringBuilder();
        var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent= true };
        using ( XmlWriter innerWriter = XmlWriter.Create(builder, settings))
            using ( XmlWriter writer = new NamespaceSupressingXmlWriter(innerWriter))
            {
                s2.Serialize(writer, o2, ns2);
            }            
        Console.WriteLine("{0}",builder.ToString());

Credit for this to Oleg Tkachenko.

How do I resize an image using PIL and maintain its aspect ratio?

My ugly example.

Function get file like: "pic[0-9a-z].[extension]", resize them to 120x120, moves section to center and save to "ico[0-9a-z].[extension]", works with portrait and landscape:

def imageResize(filepath):
    from PIL import Image
    file_dir=os.path.split(filepath)
    img = Image.open(filepath)

    if img.size[0] > img.size[1]:
        aspect = img.size[1]/120
        new_size = (img.size[0]/aspect, 120)
    else:
        aspect = img.size[0]/120
        new_size = (120, img.size[1]/aspect)
    img.resize(new_size).save(file_dir[0]+'/ico'+file_dir[1][3:])
    img = Image.open(file_dir[0]+'/ico'+file_dir[1][3:])

    if img.size[0] > img.size[1]:
        new_img = img.crop( (
            (((img.size[0])-120)/2),
            0,
            120+(((img.size[0])-120)/2),
            120
        ) )
    else:
        new_img = img.crop( (
            0,
            (((img.size[1])-120)/2),
            120,
            120+(((img.size[1])-120)/2)
        ) )

    new_img.save(file_dir[0]+'/ico'+file_dir[1][3:])

CodeIgniter removing index.php from url

Besides these answers, one can just, add index.php or edit it (if it is already there) - for security you want to disable index.php anyway, from listing the files in your website directory - then change the content into

<?php
   header('location:your_required_starting.php'); 
?>

What are the most common font-sizes for H1-H6 tags

It would depend on the browser's default stylesheet. You can view an (unofficial) table of CSS2.1 User Agent stylesheet defaults here.

Based on the page listed above, the default sizes look something like this:

    IE7     IE8     FF2         FF3         Opera   Safari 3.1
H1  24pt    2em     32px        32px        32px    32px       
H2  18pt    1.5em   24px        24px        24px    24px
H3  13.55pt 1.17em  18.7333px   18.7167px   18px    19px
H4  n/a     n/a     n/a         n/a         n/a     n/a
H5  10pt    0.83em  13.2667px   13.2833px   13px    13px
H6  7.55pt  0.67em  10.7333px   10.7167px   10px    11px

Also worth taking a look at is the default stylesheet for HTML 4. The W3C recommends using these styles as the default. An abridged excerpt:

h1 { font-size: 2em; }
h2 { font-size: 1.5em; }
h3 { font-size: 1.17em; }
h4 { font-size: 1.12em; }
h5 { font-size: .83em; }
h6 { font-size: .75em; }

Hope this information is helpful.

How do I convert an array object to a string in PowerShell?

$a = "This", "Is", "a", "cat"

foreach ( $word in $a ) { $sent = "$sent $word" }
$sent = $sent.Substring(1)

Write-Host $sent

How do you disable viewport zooming on Mobile Safari?

Using the CSS touch-action property is the most elegant solution. Tested on iOS 13.5 and iOS 14.

To disable pinch zoom gestures and and double-tap to zoom:

body {
  touch-action: pan-x pan-y;
}

If your app also has no need for panning, i.e. scrolling, use this:

body {
  touch-action: none;
}

Unique on a dataframe with only selected columns

Minor update in @Joran's code.
Using the code below, you can avoid the ambiguity and only get the unique of two columns:

dat <- data.frame(id=c(1,1,3), id2=c(1,1,4) ,somevalue=c("x","y","z"))    
dat[row.names(unique(dat[,c("id", "id2")])), c("id", "id2")]

How to define dimens.xml for every different screen size in android?

Use Scalable DP

Although making a different layout for different screen sizes is theoretically a good idea, it can get very difficult to accommodate for all screen dimensions, and pixel densities. Having over 20+ different dimens.xml files as suggested in the above answers, is not easy to manage at all.

How To Use:

To use sdp:

  1. Include implementation 'com.intuit.sdp:sdp-android:1.0.5' in your build.gradle,
  2. Replace any dp value such as 50dp with a @dimen/50_sdp like so:

    <TextView
     android:layout_width="@dimen/_50sdp"
     android:layout_height="@dimen/_50sdp"
     android:text="Hello World!" />
    

How It Works:

sdp scales with the screen size because it is essentially a huge list of different dimens.xml for every possible dp value.

enter image description here

See It In Action:

Here it is on three devices with widely differing screen dimensions, and densities:

enter image description here

Note that the sdp size unit calculation includes some approximation due to some performance and usability constraints.

How to add a column in TSQL after a specific column?

/* Script to change the column order of a table
Note this will create a new table to replace the original table
HOWEVER it doesn't copy the triggers or other table properties - just the data
*/

Generate a new table with the columns in the order that you require

Select Column2, Column1, Column3 Into NewTable from OldTable

Delete the original table

Drop Table OldTable;

Rename the new table

EXEC sp_rename 'NewTable', 'OldTable';

Chrome Extension: Make it run every page load

If it needs to run on the onload event of the page, meaning that the document and all its assets have loaded, this needs to be in a content script embedded in each page for which you wish to track onload.

How to see query history in SQL Server Management Studio

You can Monitor SQL queries by SQL Profiler if you need it

S3 Static Website Hosting Route All Paths to Index.html

I see 4 solutions to this problem. The first 3 were already covered in answers and the last one is my contribution.

  1. Set the error document to index.html.
    Problem: the response body will be correct, but the status code will be 404, which hurts SEO.

  2. Set the redirection rules.
    Problem: URL polluted with #! and page flashes when loaded.

  3. Configure CloudFront.
    Problem: all pages will return 404 from origin, so you need to chose if you won't cache anything (TTL 0 as suggested) or if you will cache and have issues when updating the site.

  4. Prerender all pages.
    Problem: additional work to prerender pages, specially when the pages changes frequently. For example, a news website.

My suggestion is to use option 4. If you prerender all pages, there will be no 404 errors for expected pages. The page will load fine and the framework will take control and act normally as a SPA. You can also set the error document to display a generic error.html page and a redirection rule to redirect 404 errors to a 404.html page (without the hashbang).

Regarding 403 Forbidden errors, I don't let them happen at all. In my application, I consider that all files within the host bucket are public and I set this with the everyone option with the read permission. If your site have pages that are private, letting the user to see the HTML layout should not be an issue. What you need to protect is the data and this is done in the backend.

Also, if you have private assets, like user photos, you can save them in another bucket. Because private assets need the same care as data and can't be compared to the asset files that are used to host the app.

Insertion Sort vs. Selection Sort

Insertion sort do not swap things. Even though it make use of a temp variable, The point of making use of temp var is when we found a value at an index to be less compared to the value to its previous index, we shift the greater value to the place of lesser value's index which would over write things. Then we use the temp var to be substituted at the previous index. Example: 10, 20, 30, 50, 40. iteration 1: 10, 20, 30, 50, 50. [temp = 40] iteration 2: 10,20, 30, 40(temp's value), 50. So, we just insert a value at the desired position from some variable.

But When we consider selection sort, We first find the index having lower value and swap that value with the value from first index and keep on repeatedly swapping till all the indices get sorted. This is exactly same as traditional swapping of two numbers. Example: 30, 20 ,10, 40, 50. Iteration 1: 10, 20, 30, 40, 50. Here temp var is used exclusively for swapping.

Is there a replacement for unistd.h for Windows (Visual C)?

Create your own unistd.h header and include the needed headers for function prototypes.

Math functions in AngularJS bindings

Why not wrap the whole math obj in a filter?

var app = angular.module('fMathFilters',[]);


function math() {
    return function(input,arg) {
        if(input) {
            return Math[arg](input);
        }

        return 0;
    }
}

return app.filter('math',[math]);

and to use:

{{ number_var | math:'ceil'}}

Return char[]/string from a function

char* charP = createStr();

Would be correct if your function was correct. Unfortunately you are returning a pointer to a local variable in the function which means that it is a pointer to undefined data as soon as the function returns. You need to use heap allocation like malloc for the string in your function in order for the pointer you return to have any meaning. Then you need to remember to free it later.

Using @property versus getters and setters

Prefer properties. It's what they're there for.

The reason is that all attributes are public in Python. Starting names with an underscore or two is just a warning that the given attribute is an implementation detail that may not stay the same in future versions of the code. It doesn't prevent you from actually getting or setting that attribute. Therefore, standard attribute access is the normal, Pythonic way of, well, accessing attributes.

The advantage of properties is that they are syntactically identical to attribute access, so you can change from one to another without any changes to client code. You could even have one version of a class that uses properties (say, for code-by-contract or debugging) and one that doesn't for production, without changing the code that uses it. At the same time, you don't have to write getters and setters for everything just in case you might need to better control access later.

How to redraw DataTable with new data

I was having same issue, and the solution was working but with some alerts and warnings so here is full solution, the key was to check for existing DataTable object or not, if yes just clear the table and add jsonData, if not just create new.

            var table;
            if ($.fn.dataTable.isDataTable('#example')) {
                table = $('#example').DataTable();
                table.clear();
                table.rows.add(jsonData).draw();
            }
            else {
                table = $('#example').DataTable({
                    "data": jsonData,
                    "deferRender": true,
                    "pageLength": 25,
                    "retrieve": true,

Versions

  • JQuery: 3.3.1
  • DataTable: 1.10.20

Find Oracle JDBC driver in Maven repository

For whatever reason, I could not get any of the above solutions to work. (Still can't.)

What I did instead was to include the jar in my project (blech) and then create a "system" dependency for it that indicates the path to the jar. It's probably not the RIGHT way to do it, but it does work. And it eliminates the need for the other developers on the team (or the guy setting up the build server) to put the jar in their local repositories.

UPDATE: This solution works for me when I run Hibernate Tools. It does NOT appear to work for building the WAR file, however. It doesn't include the ojdbc6.jar file in the target WAR file.

1) Create a directory called "lib" in the root of your project.

2) Copy the ojdbc6.jar file there (whatever the jar is called.)

3) Create a dependency that looks something like this:

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc</artifactId>
    <version>14</version>
    <scope>system</scope>
    <systemPath>${basedir}/lib/ojdbc6.jar</systemPath> <!-- must match file name -->
</dependency>

Ugly, but works for me.

To include the files in the war file add the following to your pom

<build>
    <finalName>MyAppName</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <webResources>
                    <resource>
                        <directory>${basedir}/src/main/java</directory>
                        <targetPath>WEB-INF/classes</targetPath>
                        <includes>
                            <include>**/*.properties</include>
                            <include>**/*.xml</include>
                            <include>**/*.css</include>
                            <include>**/*.html</include>
                        </includes>
                    </resource>
                    <resource>
                        <directory>${basedir}/lib</directory>
                        <targetPath>WEB-INF/lib</targetPath>
                        <includes>
                            <include>**/*.jar</include>
                        </includes>
                    </resource>
                </webResources>
            </configuration>
        </plugin>

        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

Me did not nothing, just copied development Bin folder DLLs to online deployed Bin folder and it worked fine for me.

preferredStatusBarStyle isn't called

The NavigationController or TabBarController are the ones that need to provide the style. Here is how I solved: https://stackoverflow.com/a/39072526/242769

Removing Duplicate Values from ArrayList

List<String> list = new ArrayList<String>();
        list.add("Krishna");
        list.add("Krishna");
        list.add("Kishan");
        list.add("Krishn");
        list.add("Aryan");
        list.add("Harm");

HashSet<String> hs=new HashSet<>(list);

System.out.println("=========With Duplicate Element========");
System.out.println(list);
System.out.println("=========Removed Duplicate Element========");
System.out.println(hs);

How do I get today's date in C# in mm/dd/yyyy format?

If you want it without the year:

DateTime.Now.ToString("MM/DD");

DateTime.ToString() has a lot of cool format strings:

http://msdn.microsoft.com/en-us/library/aa326721.aspx

How can I clear the NuGet package cache using the command line?

If you need to clear the NuGet cache for your build server/agent you can find the cache for NuGet packages here:

%windir%/ServiceProfiles/[account under build service runs]\AppData\Local\NuGet\Cache

Example:

C:\Windows\ServiceProfiles\NetworkService\AppData\Local\NuGet\Cache

How can I see normal print output created during pytest run?

In an upvoted comment to the accepted answer, Joe asks:

Is there any way to print to the console AND capture the output so that it shows in the junit report?

In UNIX, this is commonly referred to as teeing. Ideally, teeing rather than capturing would be the py.test default. Non-ideally, neither py.test nor any existing third-party py.test plugin (...that I know of, anyway) supports teeing – despite Python trivially supporting teeing out-of-the-box.

Monkey-patching py.test to do anything unsupported is non-trivial. Why? Because:

  • Most py.test functionality is locked behind a private _pytest package not intended to be externally imported. Attempting to do so without knowing what you're doing typically results in the public pytest package raising obscure exceptions at runtime. Thanks alot, py.test. Really robust architecture you got there.
  • Even when you do figure out how to monkey-patch the private _pytest API in a safe manner, you have to do so before running the public pytest package run by the external py.test command. You cannot do this in a plugin (e.g., a top-level conftest module in your test suite). By the time py.test lazily gets around to dynamically importing your plugin, any py.test class you wanted to monkey-patch has long since been instantiated – and you do not have access to that instance. This implies that, if you want your monkey-patch to be meaningfully applied, you can no longer safely run the external py.test command. Instead, you have to wrap the running of that command with a custom setuptools test command that (in order):
    1. Monkey-patches the private _pytest API.
    2. Calls the public pytest.main() function to run the py.test command.

This answer monkey-patches py.test's -s and --capture=no options to capture stderr but not stdout. By default, these options capture neither stderr nor stdout. This isn't quite teeing, of course. But every great journey begins with a tedious prequel everyone forgets in five years.

Why do this? I shall now tell you. My py.test-driven test suite contains slow functional tests. Displaying the stdout of these tests is helpful and reassuring, preventing leycec from reaching for killall -9 py.test when yet another long-running functional test fails to do anything for weeks on end. Displaying the stderr of these tests, however, prevents py.test from reporting exception tracebacks on test failures. Which is completely unhelpful. Hence, we coerce py.test to capture stderr but not stdout.

Before we get to it, this answer assumes you already have a custom setuptools test command invoking py.test. If you don't, see the Manual Integration subsection of py.test's well-written Good Practices page.

Do not install pytest-runner, a third-party setuptools plugin providing a custom setuptools test command also invoking py.test. If pytest-runner is already installed, you'll probably need to uninstall that pip3 package and then adopt the manual approach linked to above.

Assuming you followed the instructions in Manual Integration highlighted above, your codebase should now contain a PyTest.run_tests() method. Modify this method to resemble:

class PyTest(TestCommand):
             .
             .
             .
    def run_tests(self):
        # Import the public "pytest" package *BEFORE* the private "_pytest"
        # package. While importation order is typically ignorable, imports can
        # technically have side effects. Tragicomically, that is the case here.
        # Importing the public "pytest" package establishes runtime
        # configuration required by submodules of the private "_pytest" package.
        # The former *MUST* always be imported before the latter. Failing to do
        # so raises obtuse exceptions at runtime... which is bad.
        import pytest
        from _pytest.capture import CaptureManager, FDCapture, MultiCapture

        # If the private method to be monkey-patched no longer exists, py.test
        # is either broken or unsupported. In either case, raise an exception.
        if not hasattr(CaptureManager, '_getcapture'):
            from distutils.errors import DistutilsClassError
            raise DistutilsClassError(
                'Class "pytest.capture.CaptureManager" method _getcapture() '
                'not found. The current version of py.test is either '
                'broken (unlikely) or unsupported (likely).'
            )

        # Old method to be monkey-patched.
        _getcapture_old = CaptureManager._getcapture

        # New method applying this monkey-patch. Note the use of:
        #
        # * "out=False", *NOT* capturing stdout.
        # * "err=True", capturing stderr.
        def _getcapture_new(self, method):
            if method == "no":
                return MultiCapture(
                    out=False, err=True, in_=False, Capture=FDCapture)
            else:
                return _getcapture_old(self, method)

        # Replace the old with the new method.
        CaptureManager._getcapture = _getcapture_new

        # Run py.test with all passed arguments.
        errno = pytest.main(self.pytest_args)
        sys.exit(errno)

To enable this monkey-patch, run py.test as follows:

python setup.py test -a "-s"

Stderr but not stdout will now be captured. Nifty!

Extending the above monkey-patch to tee stdout and stderr is left as an exercise to the reader with a barrel-full of free time.

How to add a new row to datagridview programmatically

This is how I add a row if the dgrview is empty: (myDataGridView has two columns in my example)

DataGridViewRow row = new DataGridViewRow();
row.CreateCells(myDataGridView);

row.Cells[0].Value = "some value";
row.Cells[1].Value = "next columns value";

myDataGridView.Rows.Add(row);

According to docs: "CreateCells() clears the existing cells and sets their template according to the supplied DataGridView template".

How do I speed up the gwt compiler?

The GWT compiler is doing a lot of code analysis so it is going to be difficult to speed it up. This session from Google IO 2008 will give you a good idea of what GWT is doing and why it does take so long.

My recommendation is for development use Hosted Mode as much as possible and then only compile when you want to do your testing. This does sound like the solution you've come to already, but basically that's why Hosted Mode is there (well, that and debugging).

You can speed up the GWT compile but only compiling for some browsers, rather than 5 kinds which GWT does by default. If you want to use Hosted Mode make sure you compile for at least two browsers; if you compile for a single browser then the browser detection code is optimised away and then Hosted Mode doesn't work any more.

An easy way to configure compiling for fewer browsers is to create a second module which inherits from your main module:

<module rename-to="myproject">
  <inherits name="com.mycompany.MyProject"/>
  <!-- Compile for IE and Chrome -->
  <!-- If you compile for only one browser, the browser detection javascript
       is optimised away and then Hosted Mode doesn't work -->
  <set-property name="user.agent" value="ie6,safari"/>
</module>

If the rename-to attribute is set the same then the output files will be same as if you did a full compile

iconv - Detected an illegal character in input string

this bellow solution worked for me

$result_encr="##Sƒ";

iconv("cp1252", "utf-8//IGNORE", $result_encr);

What is inf and nan?

I use inf/-inf as initial values to find minimum/maximum value of a measurement. Lets say that you measure temperature with a sensor and you want to keep track of minimum/maximum temperature. The sensor might provide a valid temperature or might be broken. Pseudocode:

# initial value of the temperature
t = float('nan')          
# initial value of minimum temperature, so any measured temp. will be smaller
t_min = float('inf')      
# initial value of maximum temperature, so any measured temp. will be bigger
t_max = float('-inf')     
while True:
    # measure temperature, if sensor is broken t is not changed
    t = measure()     
    # find new minimum temperature
    t_min = min(t_min, t) 
    # find new maximum temperature
    t_max = max(t_max, t) 

The above code works because inf/-inf/nan are valid for min/max operation, so there is no need to deal with exceptions.

Java 8 Lambda filter by Lists

Something like:

clients.stream.filter(c->{
   users.stream.filter(u->u.getName().equals(c.getName()).count()>0
}).collect(Collectors.toList());

This is however not an awfully efficient way to do it. Unless the collections are very small, you will be better of building a set of user names and using that in the condition.

"if not exist" command in batch file

if not exist "%USERPROFILE%\.qgis-custom\" (
    mkdir "%USERPROFILE%\.qgis-custom" 2>nul
    if not errorlevel 1 (
        xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
    )
)

You have it almost done. The logic is correct, just some little changes.

This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).

If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.

If everyting is ok, files are copied.

All paths are quoted to avoid problems with spaces.

It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files

mkdir "%USERPROFILE%\.qgis-custom" 2>nul 
if not errorlevel 1 (
    xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)

In both code samples, files are not copied if the folder is not being created during the script execution.

EDITED - As dbenham comments, the same code can be written as a single line

md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e

The code after the && will only be executed if the previous command does not set errorlevel. If mkdir fails, xcopy is not executed.