Programs & Examples On #Here api

This is the tag for information about the HERE platform APIs, which allow you to embed HERE Maps into your own web apps, and retrieve map information such as addresses and coordinates. Official documentation: https://developer.here.com/

How to overplot a line on a scatter plot in python?

I'm partial to scikits.statsmodels. Here an example:

import statsmodels.api as sm
import numpy as np
import matplotlib.pyplot as plt

X = np.random.rand(100)
Y = X + np.random.rand(100)*0.1

results = sm.OLS(Y,sm.add_constant(X)).fit()

print results.summary()

plt.scatter(X,Y)

X_plot = np.linspace(0,1,100)
plt.plot(X_plot, X_plot*results.params[0] + results.params[1])

plt.show()

The only tricky part is sm.add_constant(X) which adds a columns of ones to X in order to get an intercept term.

     Summary of Regression Results
=======================================
| Dependent Variable:            ['y']|
| Model:                           OLS|
| Method:                Least Squares|
| Date:               Sat, 28 Sep 2013|
| Time:                       09:22:59|
| # obs:                         100.0|
| Df residuals:                   98.0|
| Df model:                        1.0|
==============================================================================
|                   coefficient     std. error    t-statistic          prob. |
------------------------------------------------------------------------------
| x1                      1.007       0.008466       118.9032         0.0000 |
| const                 0.05165       0.005138        10.0515         0.0000 |
==============================================================================
|                          Models stats                      Residual stats  |
------------------------------------------------------------------------------
| R-squared:                     0.9931   Durbin-Watson:              1.484  |
| Adjusted R-squared:            0.9930   Omnibus:                    12.16  |
| F-statistic:                1.414e+04   Prob(Omnibus):           0.002294  |
| Prob (F-statistic):        9.137e-108   JB:                        0.6818  |
| Log likelihood:                 223.8   Prob(JB):                  0.7111  |
| AIC criterion:                 -443.7   Skew:                     -0.2064  |
| BIC criterion:                 -438.5   Kurtosis:                   2.048  |
------------------------------------------------------------------------------

example plot

How do I create batch file to rename large number of files in a folder?

@ECHO off & SETLOCAL EnableDelayedExpansion

SET "_dir=" REM Must finish with '\'
SET "_ext=jpg"
SET "_toEdit=Vacation2010"
SET "_with=December"
FOR %%f IN ("%_dir%*.%_ext%") DO (
    CALL :modifyString "%_toEdit%" "%_with%" "%%~Nf" fileName 
    RENAME "%%f" "!fileName!%%~Xf"
)
GOTO end

:modifyString what with in toReturn
    SET "__in=%~3"
    SET "__in=!__in:%~1=%~2!"
    IF NOT "%~4" == "" (
        SET %~4=%__in%
    ) ELSE (
        ECHO %__in%
    )
    EXIT /B

:end

This script allows you to change the name of all the files that contain Vacation2010 with the same name, but with December instead of Vacation2010.

If you copy and paste the code, you have to save the .bat in the same folder of the photos. If you want to save the script in another directory [E.G. you have a favorite folder for the utilities] you have to change the value of _dir with the path of the photos.

If you have to do the same work for other photos [or others files changig _ext] you have to change the value of _toEdit with the string you want to change [or erase] and the value of _with with the string you want to put instead of _toEdit [SET "_with=" if you simply want to erase the string specified in _toEdit].

URL rewriting with PHP

this is an .htaccess file that forward almost all to index.php

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} !-l
RewriteCond %{REQUEST_FILENAME} !\.(ico|css|png|jpg|gif|js)$ [NC]
# otherwise forward it to index.php
RewriteRule . index.php

then is up to you parse $_SERVER["REQUEST_URI"] and route to picture.php or whatever

Change action bar color in android

Maybe this can help you also. It's from the website:

http://nathanael.hevenet.com/android-dev-changing-the-title-bar-background/

First things first you need to have a custom theme declared for your application (or activity, depending on your needs). Something like…

<!-- Somewhere in AndroidManifest.xml -->
<application ... android:theme="@style/ThemeSelector">

Then, declare your custom theme for two cases, API versions with and without the Holo Themes. For the old themes we’ll customize the windowTitleBackgroundStyle attribute, and for the newer ones the ActionBarStyle.

<!-- res/values/styles.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="ThemeSelector" parent="android:Theme.Light">
        <item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item>
    </style>

    <style name="WindowTitleBackground">     
        <item name="android:background">@color/title_background</item>
    </style>

</resources>

<!-- res/values-v11/styles.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="ThemeSelector" parent="android:Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/ActionBar</item>
    </style>

    <style name="ActionBar" parent="android:style/Widget.Holo.ActionBar">     
        <item name="android:background">@color/title_background</item>
    </style>

</resources>

That’s it!

Converting a double to an int in C#

Because Convert.ToInt32 rounds:

Return Value: rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

...while the cast truncates:

When you convert from a double or float value to an integral type, the value is truncated.

Update: See Jeppe Stig Nielsen's comment below for additional differences (which however do not come into play if score is a real number as is the case here).

How do I use select with date condition?

Another feature is between:

Select * from table where date between '2009/01/30' and '2009/03/30'

Convert PDF to clean SVG?

I found that xfig did an excellent job:

pstoedit -f fig foo.pdf foo.fig
xfig foo.fig

export to svg

It did much better job than inkscape. Actually it was probably pdtoedit that did it.

Render Partial View Using jQuery in ASP.NET MVC

You'll need to create an Action on your Controller that returns the rendered result of the "UserDetails" partial view or control. Then just use an Http Get or Post from jQuery to call the Action to get the rendered html to be displayed.

Send file using POST from a Python script

Looks like python requests does not handle extremely large multi-part files.

The documentation recommends you look into requests-toolbelt.

Here's the pertinent page from their documentation.

What is the correct way to create a single-instance WPF application?

I can't find a short solution here so I hope someone will like this:

UPDATED 2018-09-20

Put this code in your Program.cs:

using System.Diagnostics;

static void Main()
{
    Process thisProcess = Process.GetCurrentProcess();
    Process[] allProcesses = Process.GetProcessesByName(thisProcess.ProcessName);
    if (allProcesses.Length > 1)
    {
        // Don't put a MessageBox in here because the user could spam this MessageBox.
        return;
    }

    // Optional code. If you don't want that someone runs your ".exe" with a different name:

    string exeName = AppDomain.CurrentDomain.FriendlyName;
    // in debug mode, don't forget that you don't use your normal .exe name.
    // Debug uses the .vshost.exe.
    if (exeName != "the name of your executable.exe") 
    {
        // You can add a MessageBox here if you want.
        // To point out to users that the name got changed and maybe what the name should be or something like that^^ 
        MessageBox.Show("The executable name should be \"the name of your executable.exe\"", 
            "Wrong executable name", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }

    // Following code is default code:
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new MainForm());
}

Convert List<T> to ObservableCollection<T> in WP7

Apparently, your project is targeting Windows Phone 7.0. Unfortunately the constructors that accept IEnumerable<T> or List<T> are not available in WP 7.0, only the parameterless constructor. The other constructors are available in Silverlight 4 and above and WP 7.1 and above, just not in WP 7.0.

I guess your only option is to take your list and add the items into a new instance of an ObservableCollection individually as there are no readily available methods to add them in bulk. Though that's not to stop you from putting this into an extension or static method yourself.

var list = new List<SomeType> { /* ... */ };
var oc = new ObservableCollection<SomeType>();
foreach (var item in list)
    oc.Add(item);

But don't do this if you don't have to, if you're targeting framework that provides the overloads, then use them.

Are "while(true)" loops so bad?

It's bad in the sense that structured programming constructs are preferred to (the somewhat unstructured) break and continue statements. They are, by comparison, preferred to "goto" according to this principle.

I'd always recommend making your code as structured as possible... although, as Jon Skeet points out, don't make it more structured than that!

How to check if X server is running?

The bash script solution:

if ! xset q &>/dev/null; then
    echo "No X server at \$DISPLAY [$DISPLAY]" >&2
    exit 1
fi

Doesn't work if you login from another console (Ctrl+Alt+F?) or ssh. For me this solution works in my Archlinux:

#!/bin/sh
ps aux|grep -v grep|grep "/usr/lib/Xorg"
EXITSTATUS=$?
if [ $EXITSTATUS -eq 0 ]; then
  echo "X server running"
  exit 1
fi

You can change /usr/lib/Xorg for only Xorg or the proper command on your system.

How do I translate an ISO 8601 datetime string into a Python datetime object?

Since Python 3.7 and no external libraries, you can use the strptime function from the datetime module:

datetime.datetime.strptime('2019-01-04T16:41:24+0200', "%Y-%m-%dT%H:%M:%S%z")

For more formatting options, see here.

Python 2 doesn't support the %z format specifier, so it's best to explicitly use Zulu time everywhere if possible:

datetime.datetime.strptime("2007-03-04T21:08:12Z", "%Y-%m-%dT%H:%M:%SZ")

Android Endless List

May be a little late but the following solution happened very useful in my case. In a way all you need to do is add to your ListView a Footer and create for it addOnLayoutChangeListener.

http://developer.android.com/reference/android/widget/ListView.html#addFooterView(android.view.View)

For example:

ListView listView1 = (ListView) v.findViewById(R.id.dialogsList); // Your listView
View loadMoreView = getActivity().getLayoutInflater().inflate(R.layout.list_load_more, null); // Getting your layout of FooterView, which will always be at the bottom of your listview. E.g. you may place on it the ProgressBar or leave it empty-layout.
listView1.addFooterView(loadMoreView); // Adding your View to your listview 

...

loadMoreView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
         Log.d("Hey!", "Your list has reached bottom");
    }
});

This event fires once when a footer becomes visible and works like a charm.

Curl : connection refused

Try curl -v http://localhost:8080/ instead of 127.0.0.1

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

You have to change from wb to w:

def __init__(self):
    self.myCsv = csv.writer(open('Item.csv', 'wb')) 
    self.myCsv.writerow(['title', 'link'])

to

def __init__(self):
    self.myCsv = csv.writer(open('Item.csv', 'w'))
    self.myCsv.writerow(['title', 'link'])

After changing this, the error disappears, but you can't write to the file (in my case). So after all, I don't have an answer?

Source: How to remove ^M

Changing to 'rb' brings me the other error: io.UnsupportedOperation: write

How to implement an STL-style iterator and avoid common pitfalls?

I was/am in the same boat as you for different reasons (partly educational, partly constraints). I had to re-write all the containers of the standard library and the containers had to conform to the standard. That means, if I swap out my container with the stl version, the code would work the same. Which also meant that I had to re-write the iterators.

Anyway, I looked at EASTL. Apart from learning a ton about containers that I never learned all this time using the stl containers or through my undergraduate courses. The main reason is that EASTL is more readable than the stl counterpart (I found this is simply because of the lack of all the macros and straight forward coding style). There are some icky things in there (like #ifdefs for exceptions) but nothing to overwhelm you.

As others mentioned, look at cplusplus.com's reference on iterators and containers.

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

how to use "AND", "OR" for RewriteCond on Apache?

Having trouble wrapping my head around this.

Have a rewrite rule with four conditions.
The first three conditions A, B, C are to be AND which is then OR with D

RewriteCond A       true
RewriteCond B       false
RewriteCond C [OR]  true
RewriteCond D       true
RewriteRule ...

But that seems to be an expression of A and B and (C or D) = false (don't rewrite)

How can I get to the desired expression? (A and B and C) or D = true (rewrite)

Preferably without using the additional steps of setting environment variables.

HELP!!!

How to retrieve Key Alias and Key Password for signed APK in android studio(migrated from Eclipse)

You might like to try this password breaker.

http://maxcamillo.github.io/android-keystore-password-recover/index.html

I was using the Dictionary Attack method. It worked for me because there were only a few combinations to my password that I could think of.

Linux - Install redis-cli only

To install 3.0 which is the latest stable version:

$ git clone http://github.com/antirez/redis.git 
$ cd redis && git checkout 3.0 
$ make redis-cli 

Optionally, you can put the compiled executable in your load path for convenience:

$ ln -s src/redis-cli /usr/local/bin/redis-cli

Duplicating a MySQL table, indices, and data

Expanding on this answer one could use a stored procedure:

CALL duplicate_table('tableName');

Which will result in a duplicate table called tableName_20181022235959 If called when

SELECT NOW();

results:

2018-10-22 23:59:59

Implementation

DELIMITER $$
CREATE PROCEDURE duplicate_table(IN tableName VARCHAR(255))
  BEGIN
    DECLARE schemaName VARCHAR(255) DEFAULT SCHEMA();
    DECLARE today VARCHAR(14) DEFAULT REPLACE(REPLACE(REPLACE(NOW(), '-', ''), ' ', ''), ':', ''); -- update @ year 10000
    DECLARE backupTableName VARCHAR(255) DEFAULT CONCAT(tableName, '_', today);

    IF fn_table_exists(schemaName, tableName)
      THEN
        CALL statement(CONCAT('CREATE TABLE IF NOT EXISTS ', backupTableName,' LIKE ', tableName));
        CALL statement(CONCAT('INSERT INTO ', backupTableName,' SELECT * FROM ', tableName));
        CALL statement(CONCAT('CHECKSUM TABLE ', backupTableName,', ', tableName));
      ELSE
        SELECT CONCAT('ERROR: Table "', tableName, '" does not exist in the schema "', schemaName, '".') AS ErrorMessage;
      END IF;
  END $$
DELIMITER ;

DELIMITER $$
CREATE FUNCTION fn_table_exists(schemaName VARCHAR(255), tableName VARCHAR(255))
  RETURNS TINYINT(1)
  BEGIN
    DECLARE totalTablesCount INT DEFAULT (
      SELECT COUNT(*)
      FROM information_schema.TABLES
      WHERE (TABLE_SCHEMA COLLATE utf8_general_ci = schemaName COLLATE utf8_general_ci)
        AND (TABLE_NAME COLLATE utf8_general_ci = tableName COLLATE utf8_general_ci)
    );
    RETURN IF(
      totalTablesCount > 0,
      TRUE,
      FALSE
    );
  END $$
DELIMITER ;

DELIMITER $$
CREATE PROCEDURE statement(IN dynamic_statement TEXT)
  BEGIN
      SET @dynamic_statement := dynamic_statement;
      PREPARE prepared_statement FROM @dynamic_statement;
      EXECUTE prepared_statement;
      DEALLOCATE PREPARE prepared_statement;
  END $$
DELIMITER ;

Remove category & tag base from WordPress url - without a plugin

The non-category plugin did not work for me.

For Multisite WordPress the following works:

  1. Go to network admin sites;
  2. Open site under \;
  3. Go to settings;
  4. Under permalinks structure type /%category%/%postname%/. This will display your url as www.domainname.com/categoryname/postname;
  5. Now go to your site dashboard (not network dashboard);
  6. Open settings;
  7. Open permalink. Do not save (the permalink will show uneditable field as yourdoamainname/blog/. Ignore it. If you save now the work you did in step 4 will be overwritten. This step of opening permalink page but not saving in needed to update the database.

How to configure Chrome's Java plugin so it uses an existing JDK in the machine

I came across a similar issue but instead of changing the regedit I decided to change the Chrome settings

Try the following steps

  1. In the chrome browser type: chrome://plugins/
  2. Click on + Details (top right corner) to expand all the plugin details.
  3. Find Java and click on Disable for the path(s) that you don't want to be used.

You might have to restart the browser to see the changes. This also assumes that the Java that you have enabled is the latest Java.

Hope this helps

Explaining Python's '__enter__' and '__exit__'

Python calls __enter__ when execution enters the context of the with statement and it’s time to acquire the resource. When execution leaves the context again, Python calls __exit__ to free up the resource

Let's consider Context Managers and the “with” Statement in Python. Context Manager is a simple “protocol” (or interface) that your object needs to follow so it can be used with the with statement. Basically all you need to do is add enter and exit methods to an object if you want it to function as a context manager. Python will call these two methods at the appropriate times in the resource management cycle.

Let’s take a look at what this would look like in practical terms. Here’s how a simple implementation of the open() context manager might look like:

class ManagedFile:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        self.file = open(self.name, 'w')
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()

Our ManagedFile class follows the context manager protocol and now supports the with statement.

>>> with ManagedFile('hello.txt') as f:
...    f.write('hello, world!')
...    f.write('bye now')`enter code here`

Python calls enter when execution enters the context of the with statement and it’s time to acquire the resource. When execution leaves the context again, Python calls exit to free up the resource.

Writing a class-based context manager isn’t the only way to support the with statement in Python. The contextlib utility module in the standard library provides a few more abstractions built on top of the basic context manager protocol. This can make your life a little easier if your use cases matches what’s offered by contextlib.

Rails where condition using NOT NIL

It's not a bug in ARel, it's a bug in your logic.

What you want here is:

Foo.includes(:bar).where(Bar.arel_table[:id].not_eq(nil))

MySQL Daemon Failed to Start - centos 6

Yet another tip that worked for me. Run the command:

$ mysql_install_db

What is the best way to prevent session hijacking?

The SSL only helps with sniffing attacks. If an attacker has access to your machine I will assume they can copy your secure cookie too.

At the very least, make sure old cookies lose their value after a while. Even a successful hijaking attack will be thwarted when the cookie stops working. If the user has a cookie from a session that logged in more than a month ago, make them reenter their password. Make sure that whenever a user clicks on your site's "log out" link, that the old session UUID can never be used again.

I'm not sure if this idea will work but here goes: Add a serial number into your session cookie, maybe a string like this:

SessionUUID, Serial Num, Current Date/Time

Encrypt this string and use it as your session cookie. Regularly change the serial num - maybe when the cookie is 5 minutes old and then reissue the cookie. You could even reissue it on every page view if you wanted to. On the server side, keep a record of the last serial num you've issued for that session. If someone ever sends a cookie with the wrong serial number it means that an attacker may be using a cookie they intercepted earlier so invalidate the session UUID and ask the user to reenter their password and then reissue a new cookie.

Remember that your user may have more than one computer so they may have more than one active session. Don't do something that forces them to log in again every time they switch between computers.

How to check if user input is not an int value

Simply throw Exception if input is invalid

Scanner sc=new Scanner(System.in);
try
{
  System.out.println("Please input an integer");
  //nextInt will throw InputMismatchException
  //if the next token does not match the Integer
  //regular expression, or is out of range
  int usrInput=sc.nextInt();
}
catch(InputMismatchException exception)
{
  //Print "This is not an integer"
  //when user put other than integer
  System.out.println("This is not an integer");
}

How to execute powershell commands from a batch file?

Looking for the possibility to put a powershell script into a batch file, I found this thread. The idea of walid2mi did not worked 100% for my script. But via a temporary file, containing the script it worked out. Here is the skeleton of the batch file:

;@echo off
;setlocal ENABLEEXTENSIONS
;rem make from X.bat a X.ps1 by removing all lines starting with ';' 
;Findstr -rbv "^[;]" %0 > %~dpn0.ps1 
;powershell -ExecutionPolicy Unrestricted -File %~dpn0.ps1 %*
;del %~dpn0.ps1
;endlocal
;goto :EOF
;rem Here start your power shell script.
param(
    ,[switch]$help
)

What is a vertical tab?

similar to R0byn's experience, i was experimenting with a Powerpoint slide presentation and dumped out the main body of text on the slide, finding that all the places where one would typically find carriage return (ASCII 13/0x0d/^M) or line feed/new line (ASCII 10/0x0a/^J) characters, it uses vertical tab (ASCII 11/0x0b/^K) instead, presumably for the exact reason that dan04 described above for Word: to serve as a "newline" while staying within the same paragraph. good question though as i totally thought this character would be as useless as a teletype terminal today.

How do I find the index of a character in a string in Ruby?

You can use this

"abcdefg".index('c')   #=> 2

ORA-01861: literal does not match format string

If you are using JPA to hibernate make sure the Entity has the correct data type for a field defined against a date column like use java.util.Date instead of String.

How to find my Subversion server version number?

Try this:

ssh your_user@your_server svnserve --version

svnserve, version 1.3.1 (r19032)
   compiled May  8 2006, 07:38:44

I hope it helps.

How do I use a custom deleter with a std::unique_ptr member?

Assuming that create and destroy are free functions (which seems to be the case from the OP's code snippet) with the following signatures:

Bar* create();
void destroy(Bar*);

You can write your class Foo like this

class Foo {

    std::unique_ptr<Bar, void(*)(Bar*)> ptr_;

    // ...

public:

    Foo() : ptr_(create(), destroy) { /* ... */ }

    // ...
};

Notice that you don't need to write any lambda or custom deleter here because destroy is already a deleter.

Open File in Another Directory (Python)

import os
import os.path
import shutil

You find your current directory:

d = os.getcwd() #Gets the current working directory

Then you change one directory up:

os.chdir("..") #Go up one directory from working directory

Then you can get a tupple/list of all the directories, for one directory up:

o = [os.path.join(d,o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))] # Gets all directories in the folder as a tuple

Then you can search the tuple for the directory you want and open the file in that directory:

for item in o:
    if os.path.exists(item + '\\testfile.txt'):
    file = item + '\\testfile.txt'

Then you can do stuf with the full file path 'file'

Spring MVC UTF-8 Encoding

In addition to Benjamin's answer (which I've only skimmed), you need to make sure that your files are actually stored using the proper encoding (that would be UTF-8 for source code, JSPs etc., but note that Java Properties files must be encoded as ISO 8859-1 by definition).

The problem with this is that it's not possible to tell what encoding has been used to store a file. Your only option is to open the file using a specific encoding, and checking whether or not the content makes sense. You can also try to convert the file from the assumed encoding to the desired encoding using iconv - if that produces an error, your assumption was incorrect. So if you assume that hello.jsp is encoded as UTF-8, run "iconv -f UTF-16 -t UTF-8 hello.jsp" and check for errors.

If you should find out that your files are not properly encoded, you need to find out why. It's probably the editor or IDE you used to create the file. In case of Eclipse (and STS), make sure the Text File Encoding (Preferences / General / Workspace) is set to UTF-8 (it unfortunately defaults to your system's platform encoding).

What makes encoding problems so difficult to debug is that there's so many components involved (text editor, borwser, plus each and every software component in between, in some cases including a database), and each of them has the potential to introduce an error.

How do I make an html link look like a button?

This is what I used. Link button is

<div class="link-button"><a href="/">Example</a></div>

CSS

/* body is sans-serif */ 

.link-button {
    margin-top:15px;
    max-width:90px;
    background-color:#eee;
    border-color:#888888;
    color:#333;
    display:inline-block;
    vertical-align:middle;
    text-align:center;
    text-decoration:none;
    align-items:flex-start;
    cursor:default;
    -webkit-appearence: push-button;
    border-style: solid;
    border-width: 1px;
    border-radius: 5px;
    font-size: 1em;
    font-family: inherit;
    border-color: #000;
    padding-left: 5px;
    padding-right: 5px;
    width: 100%;
    min-height: 30px;
}

.link-button a {
    margin-top:4px;
    display:inline-block;
    text-decoration:none;
    color:#333;
}

.link-button:hover {
    background-color:#888;
}

.link-button:active {
    background-color:#333;
}

.link-button:hover a, .link-button:active a {
    color:#fff;
}

How to check if a file exists in the Documents directory in Swift?

Swift 4.x version

    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url = NSURL(fileURLWithPath: path)
    if let pathComponent = url.appendingPathComponent("nameOfFileHere") {
        let filePath = pathComponent.path
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: filePath) {
            print("FILE AVAILABLE")
        } else {
            print("FILE NOT AVAILABLE")
        }
    } else {
        print("FILE PATH NOT AVAILABLE")
    }

Swift 3.x version

    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let url = URL(fileURLWithPath: path)

    let filePath = url.appendingPathComponent("nameOfFileHere").path
    let fileManager = FileManager.default
    if fileManager.fileExists(atPath: filePath) {
        print("FILE AVAILABLE")
    } else {
        print("FILE NOT AVAILABLE")
    }

Swift 2.x version, need to use URLByAppendingPathComponent

    let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let url = NSURL(fileURLWithPath: path)
    let filePath = url.URLByAppendingPathComponent("nameOfFileHere").path!
    let fileManager = NSFileManager.defaultManager()
    if fileManager.fileExistsAtPath(filePath) {
        print("FILE AVAILABLE")
    } else {
        print("FILE NOT AVAILABLE")
    }

How to format a number as percentage in R?

You can use the scales package just for this operation (without loading it with require or library)

scales::percent(m)

Finding the direction of scrolling in a UIScrollView?

Alternatively, it is possible to observe key path "contentOffset". This is useful when it's not possible for you to set/change the delegate of the scroll view.

[yourScrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];

After adding the observer, you could now:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    CGFloat newOffset = [[change objectForKey:@"new"] CGPointValue].y;
    CGFloat oldOffset = [[change objectForKey:@"old"] CGPointValue].y;
    CGFloat diff = newOffset - oldOffset;
    if (diff < 0 ) { //scrolling down
        // do something
    }
}

Do remember to remove the observer when needed. e.g. you could add the observer in viewWillAppear and remove it in viewWillDisappear

Angular Material: mat-select not selecting default

A very simple way to achieve this is using a formControl with a default value, inside a FormGroup (optional) for example. This is an example using an unit selector to an area input:

ts

H_AREA_UNIT = 1;
M_AREA_UNIT = 2;

exampleForm: FormGroup;

this.exampleForm = this.formBuilder.group({
  areaUnit: [this.H_AREA_UNIT],
});

html

<form [formGroup]="exampleForm">
 <mat-form-field>
   <mat-label>Unit</mat-label>
   <mat-select formControlName="areaUnit">
     <mat-option [value]="H_AREA_UNIT">h</mat-option>
     <mat-option [value]="M_AREA_UNIT">m</mat-option>
   </mat-select>
 </mat-form-field>
</form>

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

Insert data using Entity Framework model

It should be:

context.TableName.AddObject(TableEntityInstance);

Where:

  1. TableName: the name of the table in the database.
  2. TableEntityInstance: an instance of the table entity class.

If your table is Orders, then:

Order order = new Order();
context.Orders.AddObject(order);

For example:

 var id = Guid.NewGuid();

 // insert
 using (var db = new EfContext("name=EfSample"))
 {
    var customers = db.Set<Customer>();
    customers.Add( new Customer { CustomerId = id, Name = "John Doe" } );

    db.SaveChanges();
 }

Here is a live example:

public void UpdatePlayerScreen(byte[] imageBytes, string installationKey)
{
  var player = (from p in this.ObjectContext.Players where p.InstallationKey == installationKey select p).FirstOrDefault();

  var current = (from d in this.ObjectContext.Screenshots where d.PlayerID == player.ID select d).FirstOrDefault();

  if (current != null)
  {
    current.Screen = imageBytes;
    current.Refreshed = DateTime.Now;

    this.ObjectContext.SaveChanges();
  }
  else
  {
    Screenshot screenshot = new Screenshot();

    screenshot.ID = Guid.NewGuid();
    screenshot.Interval = 1000;
    screenshot.IsTurnedOn = true;
    screenshot.PlayerID = player.ID;
    screenshot.Refreshed = DateTime.Now;
    screenshot.Screen = imageBytes;

    this.ObjectContext.Screenshots.AddObject(screenshot);
    this.ObjectContext.SaveChanges();
  }
}

How to get HttpContext.Current in ASP.NET Core?

Necromancing.
YES YOU CAN, and this is how.
A secret tip for those migrating large junks chunks of code:
The following method is an evil carbuncle of a hack which is actively engaged in carrying out the express work of satan (in the eyes of .NET Core framework developers), but it works:

In public class Startup

add a property

public IConfigurationRoot Configuration { get; }

And then add a singleton IHttpContextAccessor to DI in ConfigureServices.

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

Then in Configure

    public void Configure(
              IApplicationBuilder app
             ,IHostingEnvironment env
             ,ILoggerFactory loggerFactory
    )
    {

add the DI Parameter IServiceProvider svp, so the method looks like:

    public void Configure(
           IApplicationBuilder app
          ,IHostingEnvironment env
          ,ILoggerFactory loggerFactory
          ,IServiceProvider svp)
    {

Next, create a replacement class for System.Web:

namespace System.Web
{

    namespace Hosting
    {
        public static class HostingEnvironment 
        {
            public static bool m_IsHosted;

            static HostingEnvironment()
            {
                m_IsHosted = false;
            }

            public static bool IsHosted
            {
                get
                {
                    return m_IsHosted;
                }
            }
        }
    }


    public static class HttpContext
    {
        public static IServiceProvider ServiceProvider;

        static HttpContext()
        { }


        public static Microsoft.AspNetCore.Http.HttpContext Current
        {
            get
            {
                // var factory2 = ServiceProvider.GetService<Microsoft.AspNetCore.Http.IHttpContextAccessor>();
                object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));

                // Microsoft.AspNetCore.Http.HttpContextAccessor fac =(Microsoft.AspNetCore.Http.HttpContextAccessor)factory;
                Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
                // context.Response.WriteAsync("Test");

                return context;
            }
        }


    } // End Class HttpContext 


}

Now in Configure, where you added the IServiceProvider svp, save this service provider into the static variable "ServiceProvider" in the just created dummy class System.Web.HttpContext (System.Web.HttpContext.ServiceProvider)

and set HostingEnvironment.IsHosted to true

System.Web.Hosting.HostingEnvironment.m_IsHosted = true;

this is essentially what System.Web did, just that you never saw it (I guess the variable was declared as internal instead of public).

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    ServiceProvider = svp;
    System.Web.HttpContext.ServiceProvider = svp;
    System.Web.Hosting.HostingEnvironment.m_IsHosted = true;


    app.UseCookieAuthentication(new CookieAuthenticationOptions()
    {
        AuthenticationScheme = "MyCookieMiddlewareInstance",
        LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Unauthorized/"),
        AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Account/Forbidden/"),
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest

       , CookieHttpOnly=false

    });

Like in ASP.NET Web-Forms, you'll get a NullReference when you're trying to access a HttpContext when there is none, such as it used to be in Application_Start in global.asax.

I stress again, this only works if you actually added

services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

like I wrote you should.
Welcome to the ServiceLocator pattern within the DI pattern ;)
For risks and side effects, ask your resident doctor or pharmacist - or study the sources of .NET Core at github.com/aspnet, and do some testing.


Perhaps a more maintainable method would be adding this helper class

namespace System.Web
{

    public static class HttpContext
    {
        private static Microsoft.AspNetCore.Http.IHttpContextAccessor m_httpContextAccessor;


        public static void Configure(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
        {
            m_httpContextAccessor = httpContextAccessor;
        }


        public static Microsoft.AspNetCore.Http.HttpContext Current
        {
            get
            {
                return m_httpContextAccessor.HttpContext;
            }
        }


    }


}

And then calling HttpContext.Configure in Startup->Configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();


    System.Web.HttpContext.Configure(app.ApplicationServices.
        GetRequiredService<Microsoft.AspNetCore.Http.IHttpContextAccessor>()
    );

Content Security Policy "data" not working for base64 Images in Chrome 28

Try this

data to load:

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='#343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>

get a utf8 to base64 convertor and convert the "svg" string to:

PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

and the CSP is

img-src data: image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

Conda environments not showing up in Jupyter Notebook

While @coolscitist's answer worked for me, there is also a way that does not clutter your kernel environment with the complete jupyter package+deps. It is described in the ipython docs and is (I suspect) only necessary if you run the notebook server in a non-base environment.

conda activate name_of_your_kernel_env
conda install ipykernel
python -m ipykernel install --prefix=/home/your_username/.conda/envs/name_of_your_jupyter_server_env --name 'name_of_your_kernel_env'

You can check if it works using

conda activate name_of_your_jupyter_server_env 
jupyter kernelspec list

How to create an array from a CSV file using PHP and the fgetcsv function

Old question, but still relevant for PHP 5.2 users. str_getcsv is available from PHP 5.3. I've written a small function that works with fgetcsv itself.

Below is my function from https://gist.github.com/4152628:

function parse_csv_file($csvfile) {
    $csv = Array();
    $rowcount = 0;
    if (($handle = fopen($csvfile, "r")) !== FALSE) {
        $max_line_length = defined('MAX_LINE_LENGTH') ? MAX_LINE_LENGTH : 10000;
        $header = fgetcsv($handle, $max_line_length);
        $header_colcount = count($header);
        while (($row = fgetcsv($handle, $max_line_length)) !== FALSE) {
            $row_colcount = count($row);
            if ($row_colcount == $header_colcount) {
                $entry = array_combine($header, $row);
                $csv[] = $entry;
            }
            else {
                error_log("csvreader: Invalid number of columns at line " . ($rowcount + 2) . " (row " . ($rowcount + 1) . "). Expected=$header_colcount Got=$row_colcount");
                return null;
            }
            $rowcount++;
        }
        //echo "Totally $rowcount rows found\n";
        fclose($handle);
    }
    else {
        error_log("csvreader: Could not read CSV \"$csvfile\"");
        return null;
    }
    return $csv;
}

Returns

Begin Reading CSV

Array
(
    [0] => Array
        (
            [vid] => 
            [agency] => 
            [division] => Division
            [country] => 
            [station] => Duty Station
            [unit] => Unit / Department
            [grade] => 
            [funding] => Fund Code
            [number] => Country Office Position Number
            [wnumber] => Wings Position Number
            [title] => Position Title
            [tor] => Tor Text
            [tor_file] => 
            [status] => 
            [datetime] => Entry on Wings
            [laction] => 
            [supervisor] => Supervisor Index Number
            [asupervisor] => Alternative Supervisor Index
            [author] => 
            [category] => 
            [parent] => Reporting to Which Position Number
            [vacant] => Status (Vacant / Filled)
            [index] => Index Number
        )

    [1] => Array
        (
            [vid] => 
            [agency] => WFP
            [division] => KEN Kenya, The Republic Of
            [country] => 
            [station] => Nairobi
            [unit] => Human Resources Officer P4
            [grade] => P-4
            [funding] => 5000001
            [number] => 22018154
            [wnumber] => 
            [title] => Human Resources Officer P4
            [tor] => 
            [tor_file] => 
            [status] => 
            [datetime] => 
            [laction] => 
            [supervisor] => 
            [asupervisor] => 
            [author] => 
            [category] => Professional
            [parent] => 
            [vacant] => 
            [index] => xxxxx
        )
) 

Update multiple values in a single statement

Try this:

update MasterTbl M,
       (select sum(X) as sX,
               sum(Y) as sY,
               sum(Z) as sZ,
               MasterID
        from   DetailTbl
        group by MasterID) A
set
  M.TotalX=A.sX,
  M.TotalY=A.sY,
  M.TotalZ=A.sZ
where
  M.ID=A.MasterID

change type of input field with jQuery

I haven't tested in IE (since I needed this for an iPad site) - a form I couldn't change the HTML but I could add JS:

document.getElementById('phonenumber').type = 'tel';

(Old school JS is ugly next to all the jQuery!)

But, http://bugs.jquery.com/ticket/1957 links to MSDN: "As of Microsoft Internet Explorer 5, the type property is read/write-once, but only when an input element is created with the createElement method and before it is added to the document." so maybe you could duplicate the element, change the type, add to DOM and remove the old one?

How to reload or re-render the entire page using AngularJS

If you want to refresh the controller while refreshing any services you are using, you can use this solution:

  • Inject $state

i.e.

app.controller('myCtrl',['$scope','MyService','$state', function($scope,MyService,$state) {

    //At the point where you want to refresh the controller including MyServices

    $state.reload();

    //OR:

    $state.go($state.current, {}, {reload: true});
}

This will refresh the controller and the HTML as well you can call it Refresh or Re-Render.

How to set the env variable for PHP?

For windows: Go to your "system properties" please.then follow as bellow.

Advanced system settings(from left sidebar)->Environment variables(very last option)->path(from lower box/system variables called as I know)->edit

then concatenate the "php" location you have in your pc (usually it is where your xampp is installed say c:/xampp/php)

N.B : Please never forget to set semicolon (;) between your recent concatenated path and the existed path in your "Path"

Something like C:\Program Files\Git\usr\bin;C:\xampp\php

Hope this will help.Happy coding. :) :)

Add data dynamically to an Array

$array[] = 'Hi';

pushes on top of the array.

$array['Hi'] = 'FooBar';

sets a specific index.

Psql list all tables

A one-line example is

\dt schemaname.* 

in your senario

\dt public.*

Count lines in large files

I have a 645GB text file, and none of the earlier exact solutions (e.g. wc -l) returned an answer within 5 minutes.

Instead, here is Python script that computes the approximate number of lines in a huge file. (My text file apparently has about 5.5 billion lines.) The Python script does the following:

A. Counts the number of bytes in the file.

B. Reads the first N lines in the file (as a sample) and computes the average line length.

C. Computes A/B as the approximate number of lines.

It follows along the line of Nico's answer, but instead of taking the length of one line, it computes the average length of the first N lines.

Note: I'm assuming an ASCII text file, so I expect the Python len() function to return the number of chars as the number of bytes.

Put this code into a file line_length.py:

#!/usr/bin/env python

# Usage:
# python line_length.py <filename> <N> 

import os
import sys
import numpy as np

if __name__ == '__main__':

    file_name = sys.argv[1]
    N = int(sys.argv[2]) # Number of first lines to use as sample.
    file_length_in_bytes = os.path.getsize(file_name)
    lengths = [] # Accumulate line lengths.
    num_lines = 0

    with open(file_name) as f:
        for line in f:
            num_lines += 1
            if num_lines > N:
                break
            lengths.append(len(line))

    arr = np.array(lengths)
    lines_count = len(arr)
    line_length_mean = np.mean(arr)
    line_length_std = np.std(arr)

    line_count_mean = file_length_in_bytes / line_length_mean

    print('File has %d bytes.' % (file_length_in_bytes))
    print('%.2f mean bytes per line (%.2f std)' % (line_length_mean, line_length_std))
    print('Approximately %d lines' % (line_count_mean))

Invoke it like this with N=5000.

% python line_length.py big_file.txt 5000

File has 645620992933 bytes.
116.34 mean bytes per line (42.11 std)
Approximately 5549547119 lines

So there are about 5.5 billion lines in the file.

What's the difference between Cache-Control: max-age=0 and no-cache?

Old question now, but if anyone else comes across this through a search as I did, it appears that IE9 will be making use of this to configure the behaviour of resources when using the back and forward buttons. When max-age=0 is used, the browser will use the last version when viewing a resource on a back/forward press. If no-cache is used, the resource will be refetched.

Further details about IE9 caching can be seen on this msdn caching blog post.

php.ini: which one?

Generally speaking, the cli/php.ini file is used when the PHP binary is called from the command-line.
You can check that running php --ini from the command-line.

fpm/php.ini will be used when PHP is run as FPM -- which is the case with an nginx installation.
And you can check that calling phpinfo() from a php page served by your webserver.

cgi/php.ini, in your situation, will most likely not be used.


Using two distinct php.ini files (one for CLI, and the other one to serve pages from your webserver) is done quite often, and has one main advantages : it allows you to have different configuration values in each case.

Typically, in the php.ini file that's used by the web-server, you'll specify a rather short max_execution_time : web pages should be served fast, and if a page needs more than a few dozen seconds (30 seconds, by default), it's probably because of a bug -- and the page's generation should be stopped.
On the other hand, you can have pretty long scripts launched from your crontab (or by hand), which means the php.ini file that will be used is the one in cli/. For those scripts, you'll specify a much longer max_execution_time in cli/php.ini than you did in fpm/php.ini.

max_execution_time is a common example ; you could do the same with several other configuration directives, of course.

How to resize images proportionally / keeping the aspect ratio?

2 Steps:

Step 1) calculate the ratio of the original width / original height of Image.

Step 2) multiply the original_width/original_height ratio by the new desired height to get the new width corresponding to the new height.

Git for beginners: The definitive practical guide

How do you branch?

The default branch in a git repository is called master.

To create a new branch use

git branch <branch-name>

To see a list of all branches in the current repository type

git branch

If you want to switch to another branch you can use

git checkout <branch-name>

To create a new branch and switch to it in one step

git checkout -b <branch-name>

To delete a branch, use

git branch -d <branch-name>

To create a branch with the changes from the current branch, do

git stash
git stash branch <branch-name>

Django ChoiceField

Better Way to Provide Choice inside a django Model :

from django.db import models

class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    GRADUATE = 'GR'
    YEAR_IN_SCHOOL_CHOICES = [
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
        (GRADUATE, 'Graduate'),
    ]
    year_in_school = models.CharField(
        max_length=2,
        choices=YEAR_IN_SCHOOL_CHOICES,
        default=FRESHMAN,
    )

Turn off axes in subplots

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2)


To turn off axes for all subplots, do either:

[axi.set_axis_off() for axi in ax.ravel()]

or

map(lambda axi: axi.set_axis_off(), ax.ravel())

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

How to create dynamic href in react render function?

You can use ES6 backtick syntax too

<a href={`/customer/${item._id}`} >{item.get('firstName')} {item.get('lastName')}</a>

More info on es6 template literals

In Angular, I need to search objects in an array

Saw this thread but I wanted to search for IDs that did not match my search. Code to do that:

found = $filter('filter')($scope.fish, {id: '!fish_id'}, false);

'setInterval' vs 'setTimeout'

setInterval repeats the call, setTimeout only runs it once.

How to reverse an animation on mouse out after hover

Have tried several solutions here, nothing worked flawlessly; then Searched the web a bit more, to find GSAP at https://greensock.com/ (subject to license, but it's pretty permissive); once you reference the lib ...

 <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.2.4/gsap.min.js"></script>

... you can go:

  var el = document.getElementById('divID');    

  // create a timeline for this element in paused state
  var tl = new TimelineMax({paused: true});

  // create your tween of the timeline in a variable
  tl
  .set(el,{willChange:"transform"})
  .to(el, 1, {transform:"rotate(60deg)", ease:Power1.easeInOut});

  // store the tween timeline in the javascript DOM node
  el.animation = tl;

  //create the event handler
  $(el).on("mouseenter",function(){
    //this.style.willChange = 'transform';
    this.animation.play();
  }).on("mouseleave",function(){
     //this.style.willChange = 'auto';
    this.animation.reverse();
  });

And it will work flawlessly.

Reading multiple Scanner inputs

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

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

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

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

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

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

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

Remove composer

Additional information about removing/uninstalling composer

Answers above did not help me, but what did help me is removing:

  1. ~/.cache/composer
  2. ~/.local/share/composer
  3. ~/.config/composer

Hope this helps.

In c# is there a method to find the max of 3 numbers?

Well, you can just call it twice:

int max3 = Math.Max(x, Math.Max(y, z));

If you find yourself doing this a lot, you could always write your own helper method... I would be happy enough seeing this in my code base once, but not regularly.

(Note that this is likely to be more efficient than Andrew's LINQ-based answer - but obviously the more elements you have the more appealing the LINQ approach is.)

EDIT: A "best of both worlds" approach might be to have a custom set of methods either way:

public static class MoreMath
{
    // This method only exists for consistency, so you can *always* call
    // MoreMath.Max instead of alternating between MoreMath.Max and Math.Max
    // depending on your argument count.
    public static int Max(int x, int y)
    {
        return Math.Max(x, y);
    }

    public static int Max(int x, int y, int z)
    {
        // Or inline it as x < y ? (y < z ? z : y) : (x < z ? z : x);
        // Time it before micro-optimizing though!
        return Math.Max(x, Math.Max(y, z));
    }

    public static int Max(int w, int x, int y, int z)
    {
        return Math.Max(w, Math.Max(x, Math.Max(y, z)));
    }

    public static int Max(params int[] values)
    {
        return Enumerable.Max(values);
    }
}

That way you can write MoreMath.Max(1, 2, 3) or MoreMath.Max(1, 2, 3, 4) without the overhead of array creation, but still write MoreMath.Max(1, 2, 3, 4, 5, 6) for nice readable and consistent code when you don't mind the overhead.

I personally find that more readable than the explicit array creation of the LINQ approach.

CREATE DATABASE permission denied in database 'master' (EF code-first)

I had the same problem. This what worked for me:

  1. Go to SQL Server Management Studio and run it as Administrator.
  2. Choose Security -> Then Logins
  3. Choose the usernames or whatever users that will access your database under the Logins and Double Click it.
  4. Give them a Server Roles that will give them credentials to create database. On my case, public was already checked so I checked dbcreator and sysadmin.
  5. Run update-database again on Package Manager Console. Database should now successfully created.

Here is an image so that you can get the bigger picture, I blurred my credentials of course:enter image description here

Multiple commands on a single line in a Windows batch file

Use:

echo %time% & dir & echo %time%

This is, from memory, equivalent to the semi-colon separator in bash and other UNIXy shells.

There's also && (or ||) which only executes the second command if the first succeeded (or failed), but the single ampersand & is what you're looking for here.


That's likely to give you the same time however since environment variables tend to be evaluated on read rather than execute.

You can get round this by turning on delayed expansion:

pax> cmd /v:on /c "echo !time! & ping 127.0.0.1 >nul: & echo !time!"
15:23:36.77
15:23:39.85

That's needed from the command line. If you're doing this inside a script, you can just use setlocal:

@setlocal enableextensions enabledelayedexpansion
@echo off
echo !time! & ping 127.0.0.1 >nul: & echo !time!
endlocal

How does @synchronized lock/unlock in Objective-C?

Actually

{
  @synchronized(self) {
    return [[myString retain] autorelease];
  }
}

transforms directly into:

// needs #import <objc/objc-sync.h>
{
  objc_sync_enter(self)
    id retVal = [[myString retain] autorelease];
  objc_sync_exit(self);
  return retVal;
}

This API available since iOS 2.0 and imported using...

#import <objc/objc-sync.h>

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

I don't really see a way to do this as-is. I think you might need to remove the overflow:hidden from div#1 and add another div within div#1 (ie as a sibling to div#2) to hold your unspecified 'content' and add the overflow:hidden to that instead. I don't think that overflow can be (or should be able to be) over-ridden.

C++ convert from 1 char to string?

I honestly thought that the casting method would work fine. Since it doesn't you can try stringstream. An example is below:

#include <sstream>
#include <string>
std::stringstream ss;
std::string target;
char mychar = 'a';
ss << mychar;
ss >> target;

How to remove the Flutter debug banner?

If you are using IntelliJ IDEA, there is an option in the flutter inspector to disable it.

run the project

open the flutter inspector

hide slow banner

When you are in the Flutter Inspector, click or choose "More Actions."

Picture of the Flutter Inspector

When the menu appears, choose "Hide Debug Mode Banner"

Picture of Hide Debug Mode Banner

Get selected value in dropdown list using JavaScript

Make a drop-down menu with several options (As many as you want!)

<select>
  <option value="giveItAName">Give it a name
  <option value="bananaShark">Ridiculous animal
  <ooption value="Unknown">Give more options!
</select>

I made a bit hilarious. Here's the code snippet:

_x000D_
_x000D_
<select>_x000D_
  <option value="RidiculousObject">Banana Shark_x000D_
  <option value="SuperDuperCoding">select tag and option tag!_x000D_
  <option value="Unknown">Add more tags to add more options!_x000D_
</select>_x000D_
<h1>Only 1 option (Useless)</h1>_x000D_
<select>_x000D_
  <option value="Single">Single Option_x000D_
</select>  
_x000D_
_x000D_
_x000D_

yay the snippet worked

Best XML Parser for PHP

the crxml parser is a real easy to parser.

This class has got a search function, which takes a node name with any namespace as an argument. It searches the xml for the node and prints out the access statement to access that node using this class. This class also makes xml generation very easy.

you can download this class at

http://freshmeat.net/projects/crxml

or from phpclasses.org

http://www.phpclasses.org/package/6769-PHP-Manipulate-XML-documents-as-array.html

Resource leak: 'in' is never closed

If you are using JDK7 or 8, you can use try-catch with resources.This will automatically close the scanner.

try ( Scanner scanner = new Scanner(System.in); )
  {
    System.out.println("Enter the width of the Rectangle: ");
    width = scanner.nextDouble();
    System.out.println("Enter the height of the Rectangle: ");
    height = scanner.nextDouble();
  }
catch(Exception ex)
{
    //exception handling...do something (e.g., print the error message)
    ex.printStackTrace();
}

Differentiate between function overloading and function overriding

Overloading means having methods with same name but different signature Overriding means rewriting the virtual method of the base class.............

How do I include a newline character in a string in Delphi?

I dont have a copy of Delphi to hand, but I'm fairly certain if you set the wordwrap property to true and the autosize property to false it should wrap any text you put it at the size you make the label. If you want to line break in a certain place then it might work if you set the above settings and paste from a text editor.

Hope this helps.

How do you run `apt-get` in a dockerfile behind a proxy?

If you have the proxies set up correctly, and still cannot reach the internet, it could be the DNS resolution. Check /etc/resolve.conf on the host Ubuntu VM. If it contains nameserver 127.0.1.1, that is wrong.

Run these commands on the host Ubuntu VM to fix it:

sudo vi /etc/NetworkManager/NetworkManager.conf
# Comment out the line `dns=dnsmasq` with a `#`

# restart the network manager service
sudo systemctl restart network-manager

cat /etc/resolv.conf

Now /etc/resolv.conf should have a valid value for nameserver, which will be copied by the docker containers.

AngularJS: How to make angular load script inside ng-include?

I used this method to load a script file dynamically (inside a controller).

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://maps.googleapis.com/maps/api/js";
document.body.appendChild(script);

Add Class to Object on Page Load

I would recommend using jQuery with this function:

$(document).ready(function(){
 $('#about').addClass('expand');
});

This will add the expand class to an element with id of about when the dom is ready on page load.

Find CRLF in Notepad++

If you need to do a complex regexp replacement including \r\n, you can workaround the limitation by a three-step approach:

  1. Replace all \r\n by a tag, let's say #GO# ? Check 'Extended', replace \r\n by #GO#
  2. Perform your regexp, example removing multiline ICON="*" from an html bookmarks ? Check regexp, replace ICON=.[^"]+.> by >
  3. Put back \r\n ? Check 'Extended', replace #GO# by \r\n

Adding values to a C# array

You have to allocate the array first:

int [] terms = new int[400]; // allocate an array of 400 ints
for(int runs = 0; runs < terms.Length; runs++) // Use Length property rather than the 400 magic number again
{
    terms[runs] = value;
}

Adding gif image in an ImageView in android

This is what worked for me:

In your build.gradle (project) write mavenCentral() in the buildscript{} and allprojects {}. It should look like this:

buildscript {
    repositories {
        jcenter()
        **mavenCentral()**
    }
//more code ...
}
allprojects {
    repositories {
        jcenter()
        **mavenCentral()**
    }
}

Then, in build.gradle(module) add in dependencies{} this snippet:

compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.4'

it should look like this:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'
    testCompile 'junit:junit:4.12'
    **compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.4'**
}

Put your .gif image in your drawable folder. Now go to app > res > layout > activity_main.xml and add this snipped for your .gif:

<pl.droidsonroids.gif.GifImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/YOUR_GIF_IMAGE"
    android:background="#000000" //for black background
    />

And you're done :)

Helpful links: https://github.com/koral--/android-gif-drawable

https://www.youtube.com/watch?v=EOFY0cwNjuk

Hope this helps.

Gradients on UIView and UILabels On iPhone

Mirko Froehlich's answer worked for me, except when i wanted to use custom colors. The trick is to specify UI color with Hue, saturation and brightness instead of RGB.

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = myView.bounds;
UIColor *startColour = [UIColor colorWithHue:.580555 saturation:0.31 brightness:0.90 alpha:1.0];
UIColor *endColour = [UIColor colorWithHue:.58333 saturation:0.50 brightness:0.62 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)[startColour CGColor], (id)[endColour CGColor], nil];
[myView.layer insertSublayer:gradient atIndex:0];

To get the Hue, Saturation and Brightness of a color, use the in built xcode color picker and go to the HSB tab. Hue is measured in degrees in this view, so divide the value by 360 to get the value you will want to enter in code.

Write to CSV file and export it?

A comment about Will's answer, you might want to replace HttpContext.Current.Response.End(); with HttpContext.Current.ApplicationInstance.CompleteRequest(); The reason is that Response.End() throws a System.Threading.ThreadAbortException. It aborts a thread. If you have an exception logger, it will be littered with ThreadAbortExceptions, which in this case is expected behavior.

Intuitively, sending a CSV file to the browser should not raise an exception.

See here for more Is Response.End() considered harmful?

How do I change the background color of a plot made with ggplot2

Here's a custom theme to make the ggplot2 background white and a bunch of other changes that's good for publications and posters. Just tack on +mytheme. If you want to add or change options by +theme after +mytheme, it will just replace those options from +mytheme.

library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())

mytheme = list(
    theme_classic()+
        theme(panel.background = element_blank(),strip.background = element_rect(colour=NA, fill=NA),panel.border = element_rect(fill = NA, color = "black"),
              legend.title = element_blank(),legend.position="bottom", strip.text = element_text(face="bold", size=9),
              axis.text=element_text(face="bold"),axis.title = element_text(face="bold"),plot.title = element_text(face = "bold", hjust = 0.5,size=13))
)

ggplot(data=data.frame(a=c(1,2,3), b=c(2,3,4)), aes(x=a, y=b)) + mytheme + geom_line()

custom ggplot theme

Viewing localhost website from mobile device

Use Conveyor by Keyoti (extensión de Visual Studio). Extension visual studio

Printf width specifier to maintain precision of floating-point value

I recommend @Jens Gustedt hexadecimal solution: use %a.

OP wants “print with maximum precision (or at least to the most significant decimal)”.

A simple example would be to print one seventh as in:

#include <float.h>
int Digs = DECIMAL_DIG;
double OneSeventh = 1.0/7.0;
printf("%.*e\n", Digs, OneSeventh);
// 1.428571428571428492127e-01

But let's dig deeper ...

Mathematically, the answer is "0.142857 142857 142857 ...", but we are using finite precision floating point numbers. Let's assume IEEE 754 double-precision binary. So the OneSeventh = 1.0/7.0 results in the value below. Also shown are the preceding and following representable double floating point numbers.

OneSeventh before = 0.1428571428571428 214571170656199683435261249542236328125
OneSeventh        = 0.1428571428571428 49212692681248881854116916656494140625
OneSeventh after  = 0.1428571428571428 769682682968777953647077083587646484375

Printing the exact decimal representation of a double has limited uses.

C has 2 families of macros in <float.h> to help us.
The first set is the number of significant digits to print in a string in decimal so when scanning the string back, we get the original floating point. There are shown with the C spec's minimum value and a sample C11 compiler.

FLT_DECIMAL_DIG   6,  9 (float)                           (C11)
DBL_DECIMAL_DIG  10, 17 (double)                          (C11)
LDBL_DECIMAL_DIG 10, 21 (long double)                     (C11)
DECIMAL_DIG      10, 21 (widest supported floating type)  (C99)

The second set is the number of significant digits a string may be scanned into a floating point and then the FP printed, still retaining the same string presentation. There are shown with the C spec's minimum value and a sample C11 compiler. I believe available pre-C99.

FLT_DIG   6, 6 (float)
DBL_DIG  10, 15 (double)
LDBL_DIG 10, 18 (long double)

The first set of macros seems to meet OP's goal of significant digits. But that macro is not always available.

#ifdef DBL_DECIMAL_DIG
  #define OP_DBL_Digs (DBL_DECIMAL_DIG)
#else  
  #ifdef DECIMAL_DIG
    #define OP_DBL_Digs (DECIMAL_DIG)
  #else  
    #define OP_DBL_Digs (DBL_DIG + 3)
  #endif
#endif

The "+ 3" was the crux of my previous answer. Its centered on if knowing the round-trip conversion string-FP-string (set #2 macros available C89), how would one determine the digits for FP-string-FP (set #1 macros available post C89)? In general, add 3 was the result.

Now how many significant digits to print is known and driven via <float.h>.

To print N significant decimal digits one may use various formats.

With "%e", the precision field is the number of digits after the lead digit and decimal point. So - 1 is in order. Note: This -1 is not in the initial int Digs = DECIMAL_DIG;

printf("%.*e\n", OP_DBL_Digs - 1, OneSeventh);
// 1.4285714285714285e-01

With "%f", the precision field is the number of digits after the decimal point. For a number like OneSeventh/1000000.0, one would need OP_DBL_Digs + 6 to see all the significant digits.

printf("%.*f\n", OP_DBL_Digs    , OneSeventh);
// 0.14285714285714285
printf("%.*f\n", OP_DBL_Digs + 6, OneSeventh/1000000.0);
// 0.00000014285714285714285

Note: Many are use to "%f". That displays 6 digits after the decimal point; 6 is the display default, not the precision of the number.

How to make div's percentage width relative to parent div and not viewport

Specifying a non-static position, e.g., position: absolute/relative on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

_x000D_
_x000D_
#outer {_x000D_
  min-width: 2000px; _x000D_
  min-height: 1000px; _x000D_
  background: #3e3e3e; _x000D_
  position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
  left: 1%; _x000D_
  top: 45px; _x000D_
  width: 50%; _x000D_
  height: auto; _x000D_
  position: absolute; _x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
  background: #efffef;_x000D_
  position: absolute; _x000D_
  height: 400px; _x000D_
  right: 0px; _x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="inner">_x000D_
    <div id="inner-inner"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Check if string contains \n Java

If the string was constructed in the same program, I would recommend using this:

String newline = System.getProperty("line.separator");
boolean hasNewline = word.contains(newline);

But if you are specced to use \n, this driver illustrates what to do:

class NewLineTest {
    public static void main(String[] args) {
        String hasNewline = "this has a newline\n.";
        String noNewline = "this doesn't";

        System.out.println(hasNewline.contains("\n"));
        System.out.println(hasNewline.contains("\\n"));
        System.out.println(noNewline.contains("\n"));
        System.out.println(noNewline.contains("\\n"));

    }

}

Resulted in

true
false
false
false

In reponse to your comment:

class NewLineTest {
    public static void main(String[] args) {
        String word = "test\n.";
        System.out.println(word.length());
        System.out.println(word);
        word = word.replace("\n","\n ");
        System.out.println(word.length());
        System.out.println(word);

    }

}

Results in

6
test
.
7
test
 .

How do I programmatically force an onchange event on an input?

Using JQuery you can do the following:

// for the element which uses ID
$("#id").trigger("change");

// for the element which uses class name
$(".class_name").trigger("change");

Android Error - Open Failed ENOENT

With sdk, you can't write to the root of internal storage. This cause your error.

Edit :

Based on your code, to use internal storage with sdk:

final File dir = new File(context.getFilesDir() + "/nfs/guille/groce/users/nicholsk/workspace3/SQLTest");
dir.mkdirs(); //create folders where write files
final File file = new File(dir, "BlockForTest.txt");

How to concatenate string and int in C?

Use sprintf (or snprintf if like me you can't count) with format string "pre_%d_suff".

For what it's worth, with itoa/strcat you could do:

char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");

How can I permanently enable line numbers in IntelliJ?

IntelliJ 2019 community edition has line number by default. If you want to show or hide line numbers, go to the following settings to change the appearance.

go to ? File ? Setting ? Editor ? General ? Appearance ? [Check] Show line numbers

show_line_numbers

What does the shrink-to-fit viewport meta attribute do?

As stats on iOS usage, indicating that iOS 9.0-9.2.x usage is currently at 0.17%. If these numbers are truly indicative of global use of these versions, then it’s even more likely to be safe to remove shrink-to-fit from your viewport meta tag.

After 9.2.x. IOS remove this tag check on its' browser.

You can check this page https://www.scottohara.me/blog/2018/12/11/shrink-to-fit.html

NSPhotoLibraryUsageDescription key must be present in Info.plist to use camera roll

For camera access use:

<key>NSCameraUsageDescription</key>
<string>Camera Access Warning</string>

How do I add the contents of an iterable to a set?

You can add elements of a list to a set like this:

>>> foo = set(range(0, 4))
>>> foo
set([0, 1, 2, 3])
>>> foo.update(range(2, 6))
>>> foo
set([0, 1, 2, 3, 4, 5])

How do I detect what .NET Framework versions and service packs are installed?

See How to: Determine Which .NET Framework Versions Are Installed (MSDN).

MSDN proposes one function example that seems to do the job for version 1-4. According to the article, the method output is:

v2.0.50727  2.0.50727.4016  SP2
v3.0  3.0.30729.4037  SP2
v3.5  3.5.30729.01  SP1
v4
  Client  4.0.30319
  Full  4.0.30319

Note that for "versions 4.5 and later" there is another function.

How to include JavaScript file or library in Chrome console?

Do you use some AJAX framework? Using jQuery it would be:

$.getScript('script.js');

If you're not using any framework then see the answer by Harmen.

(Maybe it is not worth to use jQuery just to do this one simple thing (or maybe it is) but if you already have it loaded then you might as well use it. I have seen websites that have jQuery loaded e.g. with Bootstrap but still use the DOM API directly in a way that is not always portable, instead of using the already loaded jQuery for that, and many people are not aware of the fact that even getElementById() doesn't work consistently on all browsers - see this answer for details.)

UPDATE:

It's been years since I wrote this answer and I think it's worth pointing out here that today you can use:

to dynamically load scripts. Those may be relevant to people reading this question.

See also: The Fluent 2014 talk by Guy Bedford: Practical Workflows for ES6 Modules.

jQuery validation plugin: accept only alphabetical characters?

Both Nick and Adam's answers work really well.

I'd like to add a note if you want to allow latin characters like á and ç as I wanted to do:

jQuery.validator.addMethod('lettersonly', function(value, element) {
    return this.optional(element) || /^[a-z áãâäàéêëèíîïìóõôöòúûüùçñ]+$/i.test(value);
}, "Letters and spaces only please");

How can I set the background color of <option> in a <select> element?

I assume you mean the <select> input element?

Support for that is pretty new, but FF 3.6, Chrome and IE 8 render this all right:

_x000D_
_x000D_
<select name="select">
  <option value="1" style="background-color: blue">Test</option>
  <option value="2" style="background-color: green">Test</option>
</select>
_x000D_
_x000D_
_x000D_

Generate random numbers uniformly over an entire range

This is not the code, but this logic may help you.

static double rnd(void)
{
   return (1.0 / (RAND_MAX + 1.0) * ((double)(rand())) );
}

static void InitBetterRnd(unsigned int seed)
{
    register int i;
    srand( seed );
    for( i = 0; i < POOLSIZE; i++){
        pool[i] = rnd();
    }
}

 // This function returns a number between 0 and 1
 static double rnd0_1(void)
 {
    static int i = POOLSIZE-1;
    double r;

    i = (int)(POOLSIZE*pool[i]);
    r = pool[i];
    pool[i] = rnd();
    return (r);
}

Using ng-if as a switch inside ng-repeat?

Try to surround strings (hoot, story, article) with quotes ':

<div ng-repeat = "data in comments">
    <div ng-if="data.type == 'hoot' ">
        //different template with hoot data
    </div>
    <div ng-if="data.type == 'story' ">
        //different template with story data
    </div>
    <div ng-if="data.type == 'article' ">
        //different template with article data
    </div> 
</div>

Removing packages installed with go get

It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src and the package file under $GOPATH/pkg/<architecture>, for example: $GOPATH/pkg/windows_amd64.

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

None of the answers here helped. I needed to have "apply plugin: 'com.google.gms.google-services'" in my gradle. What helped was updating Android Studio to the latest version. I was then able to add the plugin and connect to Firebase Messaging Service.

Clearing an HTML file upload field via JavaScript

Just another one for the pot but you can actually change the type of an input. If you set the type to text, then back to file, it seems to reset the element.

var myFileInput = document.getElementById('myfileinput');
myFileInput.type = "text";
myFileInput.type = "file";

It resets. Tested in Google Chrome, Opera, Edge, IE 11

Import python package from local directory into interpreter

I used pathlib to add my module directory to my system path as I wanted to avoid installing the module as a package and @maninthecomputer response didn't work for me

import sys
from pathlib import Path

cwd = str(Path(__file__).parent)
sys.path.insert(0, cwd)
from my_module import my_function

Count number of rows within each group

If your trying the aggregate solutions above and you get the error:

invalid type (list) for variable

Because you're using date or datetime stamps, try using as.character on the variables:

aggregate(x ~ as.character(Year) + Month, data = df, FUN = length)

On one or both of the variables.

WAMP shows error 'MSVCR100.dll' is missing when install

To solve this issue you have to install all Microsoft redistribution packages 2010,2012(x86 and x64) than uninstall wampserver from control panel and reinstall new copy of wamp server this error will be get fixed

How to add style from code behind?

You can use the CssClass property of the hyperlink:

LiteralControl ltr = new LiteralControl();
        ltr.Text = "<style type=\"text/css\" rel=\"stylesheet\">" +
                    @".d
                    {
                        background-color:Red;
                    }
                    .d:hover
                    {
                        background-color:Yellow;
                    }
                    </style>
                    ";
        this.Page.Header.Controls.Add(ltr);
        this.HyperLink1.CssClass = "d";

How to test if a double is an integer

My simple solution:

private boolean checkIfInt(double value){
 return value - Math.floor(value) == 0;
 }

Animate change of view background color on Android

best way is to use ValueAnimator and ColorUtils.blendARGB

 ValueAnimator valueAnimator = ValueAnimator.ofFloat(0.0f, 1.0f);
 valueAnimator.setDuration(325);
 valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {

              float fractionAnim = (float) valueAnimator.getAnimatedValue();

              view.setBackgroundColor(ColorUtils.blendARGB(Color.parseColor("#FFFFFF")
                                    , Color.parseColor("#000000")
                                    , fractionAnim));
        }
});
valueAnimator.start();

Ripple effect on Android Lollipop CardView

Add these two line code into your xml view to give ripple effect on your cardView.

android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"

CSS - Syntax to select a class within an id

#navigation .navigationLevel2 li
{
    color: #f00;
}

Array.Add vs +=

The most common idiom for creating an array without using the inefficient += is something like this, from the output of a loop:

$array = foreach($i in 1..10) { 
  $i
}
$array

Getting an Embedded YouTube Video to Auto Play and Loop

YouTubes HTML5 embed code:

<iframe width="560" height="315" src="http://www.youtube.com/embed/GRonxog5mbw?autoplay=1&loop=1&playlist=GRonxog5mbw" frameborder="0" allowfullscreen></iframe>?

You can read about it here: ... (EDIT Link died.) ... View original content on Internet Archive project.

http://web.archive.org/web/20121016180134/http://brianwong.com/blog/2012-youtube-embed-code-autoplay-on-and-all-other-parameters/

How do I find Waldo with Mathematica?

I agree with @GregoryKlopper that the right way to solve the general problem of finding Waldo (or any object of interest) in an arbitrary image would be to train a supervised machine learning classifier. Using many positive and negative labeled examples, an algorithm such as Support Vector Machine, Boosted Decision Stump or Boltzmann Machine could likely be trained to achieve high accuracy on this problem. Mathematica even includes these algorithms in its Machine Learning Framework.

The two challenges with training a Waldo classifier would be:

  1. Determining the right image feature transform. This is where @Heike's answer would be useful: a red filter and a stripped pattern detector (e.g., wavelet or DCT decomposition) would be a good way to turn raw pixels into a format that the classification algorithm could learn from. A block-based decomposition that assesses all subsections of the image would also be required ... but this is made easier by the fact that Waldo is a) always roughly the same size and b) always present exactly once in each image.
  2. Obtaining enough training examples. SVMs work best with at least 100 examples of each class. Commercial applications of boosting (e.g., the face-focusing in digital cameras) are trained on millions of positive and negative examples.

A quick Google image search turns up some good data -- I'm going to have a go at collecting some training examples and coding this up right now!

However, even a machine learning approach (or the rule-based approach suggested by @iND) will struggle for an image like the Land of Waldos!

Rails: FATAL - Peer authentication failed for user (PG::Error)

If you get that error message (Peer authentication failed for user (PG::Error)) when running unit tests, make sure the test database exists.

vertical divider between two columns in bootstrap

_x000D_
_x000D_
.row.vertical-divider {_x000D_
  overflow: hidden;_x000D_
}_x000D_
.row.vertical-divider > div[class^="col-"] {_x000D_
  text-align: center;_x000D_
  padding-bottom: 100px;_x000D_
  margin-bottom: -100px;_x000D_
  border-left: 3px solid #F2F7F9;_x000D_
  border-right: 3px solid #F2F7F9;_x000D_
}_x000D_
.row.vertical-divider div[class^="col-"]:first-child {_x000D_
  border-left: none;_x000D_
}_x000D_
.row.vertical-divider div[class^="col-"]:last-child {_x000D_
  border-right: none;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="row vertical-divider" style="margin-top: 30px">_x000D_
  <div class="col-xs-6">Hi there</div>_x000D_
  <div class="col-xs-6">Hi world<br/>hi world</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Loop through files in a folder using VBA?

The Dir function is the way to go, but the problem is that you cannot use the Dir function recursively, as stated here, towards the bottom.

The way that I've handled this is to use the Dir function to get all of the sub-folders for the target folder and load them into an array, then pass the array into a function that recurses.

Here's a class that I wrote that accomplishes this, it includes the ability to search for filters. (You'll have to forgive the Hungarian Notation, this was written when it was all the rage.)

Private m_asFilters() As String
Private m_asFiles As Variant
Private m_lNext As Long
Private m_lMax As Long

Public Function GetFileList(ByVal ParentDir As String, Optional ByVal sSearch As String, Optional ByVal Deep As Boolean = True) As Variant
    m_lNext = 0
    m_lMax = 0

    ReDim m_asFiles(0)
    If Len(sSearch) Then
        m_asFilters() = Split(sSearch, "|")
    Else
        ReDim m_asFilters(0)
    End If

    If Deep Then
        Call RecursiveAddFiles(ParentDir)
    Else
        Call AddFiles(ParentDir)
    End If

    If m_lNext Then
        ReDim Preserve m_asFiles(m_lNext - 1)
        GetFileList = m_asFiles
    End If

End Function

Private Sub RecursiveAddFiles(ByVal ParentDir As String)
    Dim asDirs() As String
    Dim l As Long
    On Error GoTo ErrRecursiveAddFiles
    'Add the files in 'this' directory!


    Call AddFiles(ParentDir)

    ReDim asDirs(-1 To -1)
    asDirs = GetDirList(ParentDir)
    For l = 0 To UBound(asDirs)
        Call RecursiveAddFiles(asDirs(l))
    Next l
    On Error GoTo 0
Exit Sub
ErrRecursiveAddFiles:
End Sub
Private Function GetDirList(ByVal ParentDir As String) As String()
    Dim sDir As String
    Dim asRet() As String
    Dim l As Long
    Dim lMax As Long

    If Right(ParentDir, 1) <> "\" Then
        ParentDir = ParentDir & "\"
    End If
    sDir = Dir(ParentDir, vbDirectory Or vbHidden Or vbSystem)
    Do While Len(sDir)
        If GetAttr(ParentDir & sDir) And vbDirectory Then
            If Not (sDir = "." Or sDir = "..") Then
                If l >= lMax Then
                    lMax = lMax + 10
                    ReDim Preserve asRet(lMax)
                End If
                asRet(l) = ParentDir & sDir
                l = l + 1
            End If
        End If
        sDir = Dir
    Loop
    If l Then
        ReDim Preserve asRet(l - 1)
        GetDirList = asRet()
    End If
End Function
Private Sub AddFiles(ByVal ParentDir As String)
    Dim sFile As String
    Dim l As Long

    If Right(ParentDir, 1) <> "\" Then
        ParentDir = ParentDir & "\"
    End If

    For l = 0 To UBound(m_asFilters)
        sFile = Dir(ParentDir & "\" & m_asFilters(l), vbArchive Or vbHidden Or vbNormal Or vbReadOnly Or vbSystem)
        Do While Len(sFile)
            If Not (sFile = "." Or sFile = "..") Then
                If m_lNext >= m_lMax Then
                    m_lMax = m_lMax + 100
                    ReDim Preserve m_asFiles(m_lMax)
                End If
                m_asFiles(m_lNext) = ParentDir & sFile
                m_lNext = m_lNext + 1
            End If
            sFile = Dir
        Loop
    Next l
End Sub

Representing null in JSON

There is only one way to represent null; that is with null.

console.log(null === null);   // true
console.log(null === true);   // false
console.log(null === false);  // false
console.log(null === 'null'); // false
console.log(null === "null"); // false
console.log(null === "");     // false
console.log(null === []);     // false
console.log(null === 0);      // false

That is to say; if any of the clients that consume your JSON representation use the === operator; it could be a problem for them.

no value

If you want to convey that you have an object whose attribute myCount has no value:

{ "myCount": null }

no attribute / missing attribute

What if you to convey that you have an object with no attributes:

{}

Client code will try to access myCount and get undefined; it's not there.

empty collection

What if you to convey that you have an object with an attribute myCount that is an empty list:

{ "myCount": [] }

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

Try this:

.countTable table tr td:first-child + td

You could also reiterate in order to style the others columns:

.countTable table tr td:first-child + td + td {...} /* third column */
.countTable table tr td:first-child + td + td + td {...} /* fourth column */
.countTable table tr td:first-child + td + td + td +td {...} /* fifth column */

How to initialize a vector of vectors on a struct?

Like this:

#include <vector>

// ...

std::vector<std::vector<int>> A(dimension, std::vector<int>(dimension));

(Pre-C++11 you need to leave whitespace between the angled brackets.)

How to store NULL values in datetime fields in MySQL?

I had this problem on windows.

This is the solution:

To pass '' for NULL you should disable STRICT_MODE (which is enabled by default on Windows installations)

BTW It's funny to pass '' for NULL. I don't know why they let this kind of behavior.

How do you underline a text in Android XML?

I used below method, it worked for me. Below is example for Button but we can use in TextView as well.

Button btnClickMe = (Button) findViewById(R.id.btn_click_me);
btnClickMe.setPaintFlags(btnClickMe.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

Receiving login prompt using integrated windows authentication

Windows authentication in IIS7.0 or IIS7.5 does not work with kerberos (provider=Negotiate) when the application pool identity is ApplicationPoolIdentity One has to use Network Service or another build-in account. Another possibility is to use NTLM to get Windows Authenticatio to work (in Windows Authentication, Providers, put NTLM on top or remove negotiate)

chris van de vijver

Using SQL LOADER in Oracle to import CSV file

LOAD DATA INFILE 'D:\CertificationInputFile.csv' INTO TABLE CERT_EXCLUSION_LIST FIELDS TERMINATED BY "|" OPTIONALLY ENCLOSED BY '"' ( CERTIFICATIONNAME, CERTIFICATIONVERSION )

Delete all rows in an HTML table

Very crude, but this also works:

var Table = document.getElementById("mytable");
Table.innerHTML = "";

What is the convention for word separator in Java package names?

Anyone can use underscore _ (its Okay)

No one should use hypen - (its Bad practice)

No one should use capital letters inside package names (Bad practice)

NOTE: Here "Bad Practice" is meant for technically you are allowed to use that, but conventionally its not in good manners to write.

Source: Naming a Package(docs.oracle)

How to build PDF file from binary string returned from a web-service using javascript

I realize this is a rather old question, but here's the solution I came up with today:

doSomethingToRequestData().then(function(downloadedFile) {
  // create a download anchor tag
  var downloadLink      = document.createElement('a');
  downloadLink.target   = '_blank';
  downloadLink.download = 'name_to_give_saved_file.pdf';

  // convert downloaded data to a Blob
  var blob = new Blob([downloadedFile.data], { type: 'application/pdf' });

  // create an object URL from the Blob
  var URL = window.URL || window.webkitURL;
  var downloadUrl = URL.createObjectURL(blob);

  // set object URL as the anchor's href
  downloadLink.href = downloadUrl;

  // append the anchor to document body
  document.body.append(downloadLink);

  // fire a click event on the anchor
  downloadLink.click();

  // cleanup: remove element and revoke object URL
  document.body.removeChild(downloadLink);
  URL.revokeObjectURL(downloadUrl);
}

Command-line Unix ASCII-based charting / plotting tool

Another simpler/lighter alternative to gnuplot is ervy, a NodeJS based terminal charts tool.

Supported types: scatter (XY points), bar, pie, bullet, donut and gauge.

Usage examples with various options can be found on the projects GitHub repo

enter image description here

enter image description here

Rails 4: before_filter vs. before_action

As we can see in ActionController::Base, before_action is just a new syntax for before_filter.

However all before_filters syntax are deprecated in Rails 5.0 and will be removed in Rails 5.1

Why is lock(this) {...} bad?

It is bad form to use this in lock statements because it is generally out of your control who else might be locking on that object.

In order to properly plan parallel operations, special care should be taken to consider possible deadlock situations, and having an unknown number of lock entry points hinders this. For example, any one with a reference to the object can lock on it without the object designer/creator knowing about it. This increases the complexity of multi-threaded solutions and might affect their correctness.

A private field is usually a better option as the compiler will enforce access restrictions to it, and it will encapsulate the locking mechanism. Using this violates encapsulation by exposing part of your locking implementation to the public. It is also not clear that you will be acquiring a lock on this unless it has been documented. Even then, relying on documentation to prevent a problem is sub-optimal.

Finally, there is the common misconception that lock(this) actually modifies the object passed as a parameter, and in some way makes it read-only or inaccessible. This is false. The object passed as a parameter to lock merely serves as a key. If a lock is already being held on that key, the lock cannot be made; otherwise, the lock is allowed.

This is why it's bad to use strings as the keys in lock statements, since they are immutable and are shared/accessible across parts of the application. You should use a private variable instead, an Object instance will do nicely.

Run the following C# code as an example.

public class Person
{
    public int Age { get; set;  }
    public string Name { get; set; }

    public void LockThis()
    {
        lock (this)
        {
            System.Threading.Thread.Sleep(10000);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        var nancy = new Person {Name = "Nancy Drew", Age = 15};
        var a = new Thread(nancy.LockThis);
        a.Start();
        var b = new Thread(Timewarp);
        b.Start(nancy);
        Thread.Sleep(10);
        var anotherNancy = new Person { Name = "Nancy Drew", Age = 50 };
        var c = new Thread(NameChange);
        c.Start(anotherNancy);
        a.Join();
        Console.ReadLine();
    }

    static void Timewarp(object subject)
    {
        var person = subject as Person;
        if (person == null) throw new ArgumentNullException("subject");
        // A lock does not make the object read-only.
        lock (person.Name)
        {
            while (person.Age <= 23)
            {
                // There will be a lock on 'person' due to the LockThis method running in another thread
                if (Monitor.TryEnter(person, 10) == false)
                {
                    Console.WriteLine("'this' person is locked!");
                }
                else Monitor.Exit(person);
                person.Age++;
                if(person.Age == 18)
                {
                    // Changing the 'person.Name' value doesn't change the lock...
                    person.Name = "Nancy Smith";
                }
                Console.WriteLine("{0} is {1} years old.", person.Name, person.Age);
            }
        }
    }

    static void NameChange(object subject)
    {
        var person = subject as Person;
        if (person == null) throw new ArgumentNullException("subject");
        // You should avoid locking on strings, since they are immutable.
        if (Monitor.TryEnter(person.Name, 30) == false)
        {
            Console.WriteLine("Failed to obtain lock on 50 year old Nancy, because Timewarp(object) locked on string \"Nancy Drew\".");
        }
        else Monitor.Exit(person.Name);

        if (Monitor.TryEnter("Nancy Drew", 30) == false)
        {
            Console.WriteLine("Failed to obtain lock using 'Nancy Drew' literal, locked by 'person.Name' since both are the same object thanks to inlining!");
        }
        else Monitor.Exit("Nancy Drew");
        if (Monitor.TryEnter(person.Name, 10000))
        {
            string oldName = person.Name;
            person.Name = "Nancy Callahan";
            Console.WriteLine("Name changed from '{0}' to '{1}'.", oldName, person.Name);
        }
        else Monitor.Exit(person.Name);
    }
}

Console output

'this' person is locked!
Nancy Drew is 16 years old.
'this' person is locked!
Nancy Drew is 17 years old.
Failed to obtain lock on 50 year old Nancy, because Timewarp(object) locked on string "Nancy Drew".
'this' person is locked!
Nancy Smith is 18 years old.
'this' person is locked!
Nancy Smith is 19 years old.
'this' person is locked!
Nancy Smith is 20 years old.
Failed to obtain lock using 'Nancy Drew' literal, locked by 'person.Name' since both are the same object thanks to inlining!
'this' person is locked!
Nancy Smith is 21 years old.
'this' person is locked!
Nancy Smith is 22 years old.
'this' person is locked!
Nancy Smith is 23 years old.
'this' person is locked!
Nancy Smith is 24 years old.
Name changed from 'Nancy Drew' to 'Nancy Callahan'.

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

Here is a more complete example using a fieldset for accessibility reasons and specifying the first button as the default. Without a fieldset, what the radio buttons are for as a whole can not be programmatically determined.

Model

public class MyModel
{
    public bool IsMarried { get; set; }
}

View

<fieldset>
    <legend>Married</legend>

    @Html.RadioButtonFor(e => e.IsMarried, true, new { id = "married-true" })
    @Html.Label("married-true", "Yes")

    @Html.RadioButtonFor(e => e.IsMarried, false, new { id = "married-false" })
    @Html.Label("married-false", "No")
</fieldset>

You can add a @checked argument to the anonymous object to set the radio button as the default:

new { id = "married-true", @checked = 'checked' }

Note that you can bind to a string by replacing true and false with the string values.

Get the generated SQL statement from a SqlCommand object?

needed to cover non-Stored procedures too so I augmented CommandAsSql library (see comments under @Flapper's answer above) with this logic:

    private static void CommandAsSql_Text(this SqlCommand command, System.Text.StringBuilder sql)
    {
        string query = command.CommandText;

        foreach (SqlParameter p in command.Parameters)
            query = Regex.Replace(query, "\\B" + p.ParameterName + "\\b", p.ParameterValueForSQL()); //the first one is \B, the 2nd one is \b, since ParameterName starts with @ which is a non-word character in RegEx (see https://stackoverflow.com/a/2544661)

        sql.AppendLine(query);
    }

the pull request is at: https://github.com/jphellemons/CommandAsSql/pull/3/commits/527d696dc6055c5bcf858b9700b83dc863f04896

the Regex idea was based on @stambikk's and EvZ's comments above and the "Update:" section of https://stackoverflow.com/a/2544661/903783 that mentions "negative look-behind assertion". The use of \B instead of \b for word boundary detection at the start of the regular expression is because the p.parameterName will always start with a "@" which is not a word character.

note that ParameterValueForSQL() is an extension method defined at the CommandAsSql library to handle issues like single-quoting string parameter values etc.

Is it possible to decompile an Android .apk file?

Decompilation of APK file is possible. But it might be difficult to understand the code if it is obfuscated.

ApkTool to view resources inside APK File

  • Extracts AndroidManifest.xml and everything in res folder(layout xml files, images, htmls used on webview etc..)
  • command : apktool.bat d sampleApp.apk
  • NOTE: You can achieve this by using zip utility like 7-zip. But, It also extracts the .smali file of all .class files.

Using dex2jar

  • Generates .jar file from .apk file, we need JD-GUI to view the source code from this .jar.
  • command : dex2jar sampleApp.apk

Decompiling .jar using JD-GUI

  • decompiles the .class files (obfuscated- in a case of the android app, but a readable original code is obtained in a case of other .jar file). i.e., we get .java back from the application.

Add ripple effect to my button with button background color?

Add the "?attr/selectableItemBackground" to your view's android:foreground attribute if it already has a background along with android:clickable="true".

What is a web service endpoint?

Updated answer, from Peter in comments :

This is de "old terminology", use directally the WSDL2 "endepoint" definition (WSDL2 translated "port" to "endpoint").


Maybe you find an answer in this document : http://www.w3.org/TR/wsdl.html

A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations. The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services:

  • Types– a container for data type definitions using some type system (such as XSD).
  • Message– an abstract, typed definition of the data being communicated.
  • Operation– an abstract description of an action supported by the service.
  • Port Type–an abstract set of operations supported by one or more endpoints.
  • Binding– a concrete protocol and data format specification for a particular port type.
  • Port– a single endpoint defined as a combination of a binding and a network address.
  • Service– a collection of related endpoints.

http://www.ehow.com/info_12212371_definition-service-endpoint.html

The endpoint is a connection point where HTML files or active server pages are exposed. Endpoints provide information needed to address a Web service endpoint. The endpoint provides a reference or specification that is used to define a group or family of message addressing properties and give end-to-end message characteristics, such as references for the source and destination of endpoints, and the identity of messages to allow for uniform addressing of "independent" messages. The endpoint can be a PC, PDA, or point-of-sale terminal.

Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

I had the same problem on Windows.

The source of the problem is simple, it is access permission on folders and files.

In your project folder, you need

  1. After cloning the project, change the properties of the folder and change the permissions of the user (give full access to the current user).
  2. Remove the read-only option from the project folder. (Steps 1 and 2 take a long time because they are replicated to the entire tree below).
  3. Inside the project folder, reinstall the node (npm install reinstall -g)
  4. Disable Antivirus. (optional)
  5. Disable Firewall. (optional)
  6. Restart PC.
  7. Clear the npm cache (npm clear)
  8. Install the dependencies of your project (npm install)

After that, error "Error: EPERM: operation not permitted, unlink" will no longer be displayed.

Remember to reactivate the firewall and antivirus if necessary.

Service has zero application (non-infrastructure) endpoints

I ran Visual Studio in Administrator mode and it worked for me :) Also, ensure that the app.config file which you are using for writing WCF configuration must be in the project where "ServiceHost" class is used, and not in actual WCF service project.

Android ADB stop application command like "force-stop" for non rooted device

If you want to kill the Sticky Service,the following command NOT WORKING:

adb shell am force-stop <PACKAGE>
adb shell kill <PID>

The following command is WORKING:

adb shell pm disable <PACKAGE>

If you want to restart the app,you must run command below first:

adb shell pm enable <PACKAGE>

What's the difference between isset() and array_key_exists()?

Answer to an old question as no answer here seem to address the 'warning' problem (explanation follows)

Basically, in this case of checking if a key exists in an array, isset

  • tells if the expression (array) is defined, and the key is set
  • no warning or error if the var is not defined, not an array ...
  • but returns false if the value for that key is null

and array_key_exists

  • tells if a key exists in an array as the name implies
  • but gives a warning if the array parameter is not an array

So how do we check if a key exists which value may be null in a variable

  • that may or may not be an array
  • (or similarly is a multidimensional array for which the key check happens at dim 2 and dim 1 value may not be an array for the 1st dim (etc...))

without getting a warning, without missing the existing key when its value is null (what were the PHP devs thinking would also be an interesting question, but certainly not relevant on SO). And of course we don't want to use @

isset($var[$key]);            // silent but misses null values
array_key_exists($key, $var); // works but warning if $var not defined/array

It seems is_array should be involved in the equation, but it gives a warning if $var is not defined, so that could be a solution:

if (isset($var[$key]) || 
    isset($var) && is_array($var) && array_key_exists($key, $var)) ...

which is likely to be faster if the tests are mainly on non-null values. Otherwise for an array with mostly null values

if (isset($var) && is_array($var) && array_key_exists($key, $var)) ...

will do the work.

Convert RGBA PNG to RGB with PIL

It's not broken. It's doing exactly what you told it to; those pixels are black with full transparency. You will need to iterate across all pixels and convert ones with full transparency to white.

What is the cleanest way to disable CSS transition effects temporarily?

You can disable animation, transition, trasforms for all of element in page with this css code

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '* {' +
'/*CSS transitions*/' +
' -o-transition-property: none !important;' +
' -moz-transition-property: none !important;' +
' -ms-transition-property: none !important;' +
' -webkit-transition-property: none !important;' +
'  transition-property: none !important;' +
'/*CSS transforms*/' +
'  -o-transform: none !important;' +
' -moz-transform: none !important;' +
'   -ms-transform: none !important;' +
'  -webkit-transform: none !important;' +
'   transform: none !important;' +
'  /*CSS animations*/' +
'   -webkit-animation: none !important;' +
'   -moz-animation: none !important;' +
'   -o-animation: none !important;' +
'   -ms-animation: none !important;' +
'   animation: none !important;}';
   document.getElementsByTagName('head')[0].appendChild(style);

Why am I getting "Thread was being aborted" in ASP.NET?

For a web service hosted in ASP.NET, the configuration property is executionTimeout:

<configuration> <system.web>

<httpRuntime executionTimeout="360" />

</system.web>

</configuration>

Set this and the thread abort exception will go away :)

Excel: Search for a list of strings within a particular string using array formulas?

  1. Arange your word list with delimiter which never occures in the words, f.e. |
  2. swap arguments in find call - we want search if cell value is matching one of the words in pattern string {=FIND("cell I want to search","list of words I want to search for")}
  3. if the patterns are similar, there is a risk of getting more results than wanted, we restrict just correct results via adding &"|" to the cell value tested (works well with array formulas) cell G3 could contain: {=SUM(FIND($A$1:$A$100&"|";A3))} this ensures spreadsheet will compare strings like "cellvlaue|" againts "pattern1|", "pattern2|" etc. which sorts out conflicts like pattern1="newly added", pattern2="added" (sum of all cells matching "added" would be too high, including the target values for cells matching "newly added", which would be a logical error)

Python: create dictionary using dict() with integer keys?

There are also these 'ways':

>>> dict.fromkeys(range(1, 4))
{1: None, 2: None, 3: None}
>>> dict(zip(range(1, 4), range(1, 4)))
{1: 1, 2: 2, 3: 3}

Mythical man month 10 lines per developer day - how close on large projects?

I think project size and the number of developers involved are big factors in this. I'm far above this over my career but I've worked alone all that time so there's no loss to working with other programmers.

Ruby Hash to array of values

hash  = { :a => ["a", "b", "c"], :b => ["b", "c"] }
hash.values #=> [["a","b","c"],["b","c"]]

Bootstrap 3 collapsed menu doesn't close on click

The problem could be you are using out of date versions of bootstrap or jquery, OR you are calling more than one version in your markup.

Just keep the latest versions, you only need the one reference. Solves the problem.

PHP and MySQL Select a Single Value

Try this

$value = mysql_result($result, 0);

Python POST binary data

Basically what you do is correct. Looking at redmine docs you linked to, it seems that suffix after the dot in the url denotes type of posted data (.json for JSON, .xml for XML), which agrees with the response you get - Processing by AttachmentsController#upload as XML. I guess maybe there's a bug in docs and to post binary data you should try using http://redmine/uploads url instead of http://redmine/uploads.xml.

Btw, I highly recommend very good and very popular Requests library for http in Python. It's much better than what's in the standard lib (urllib2). It supports authentication as well but I skipped it for brevity here.

import requests
with open('./x.png', 'rb') as f:
    data = f.read()
res = requests.post(url='http://httpbin.org/post',
                    data=data,
                    headers={'Content-Type': 'application/octet-stream'})

# let's check if what we sent is what we intended to send...
import json
import base64

assert base64.b64decode(res.json()['data'][len('data:application/octet-stream;base64,'):]) == data

UPDATE

To find out why this works with Requests but not with urllib2 we have to examine the difference in what's being sent. To see this I'm sending traffic to http proxy (Fiddler) running on port 8888:

Using Requests

import requests

data = 'test data'
res = requests.post(url='http://localhost:8888',
                    data=data,
                    headers={'Content-Type': 'application/octet-stream'})

we see

POST http://localhost:8888/ HTTP/1.1
Host: localhost:8888
Content-Length: 9
Content-Type: application/octet-stream
Accept-Encoding: gzip, deflate, compress
Accept: */*
User-Agent: python-requests/1.0.4 CPython/2.7.3 Windows/Vista

test data

and using urllib2

import urllib2

data = 'test data'    
req = urllib2.Request('http://localhost:8888', data)
req.add_header('Content-Length', '%d' % len(data))
req.add_header('Content-Type', 'application/octet-stream')
res = urllib2.urlopen(req)

we get

POST http://localhost:8888/ HTTP/1.1
Accept-Encoding: identity
Content-Length: 9
Host: localhost:8888
Content-Type: application/octet-stream
Connection: close
User-Agent: Python-urllib/2.7

test data

I don't see any differences which would warrant different behavior you observe. Having said that it's not uncommon for http servers to inspect User-Agent header and vary behavior based on its value. Try to change headers sent by Requests one by one making them the same as those being sent by urllib2 and see when it stops working.

hidden field in php

Can I use a field of the type ... and retrieve it after the GET / POST method ...

Yes (haven't you tried?)

Are there any other ways of using hidden fields in PHP?

You mean other ways of retrieving the value? No.
Of course you can use hidden fields for what ever you want.


Btw. input fiels have no end tag. So write either just <input ...> or as self-closing tag <input .../>.

Renaming Columns in an SQL SELECT Statement

select column1 as xyz,
      column2 as pqr,
.....

from TableName;

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

As the accepted answer suggests you can add "using" to all views by adding to section of config file.

But for a single view you could just use

@using SomeNamespace.Extensions

How to implement authenticated routes in React Router 4?

You're going to want to use the Redirect component. There's a few different approaches to this problem. Here's one I like, have a PrivateRoute component that takes in an authed prop and then renders based on that props.

function PrivateRoute ({component: Component, authed, ...rest}) {
  return (
    <Route
      {...rest}
      render={(props) => authed === true
        ? <Component {...props} />
        : <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
    />
  )
}

Now your Routes can look something like this

<Route path='/' exact component={Home} />
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<PrivateRoute authed={this.state.authed} path='/dashboard' component={Dashboard} />

If you're still confused, I wrote this post that may help - Protected routes and authentication with React Router v4

How do I convert a String to an int in Java?

I'm have a solution, but I do not know how effective it is. But it works well, and I think you could improve it. On the other hand, I did a couple of tests with JUnit which step correctly. I attached the function and testing:

static public Integer str2Int(String str) {
    Integer result = null;
    if (null == str || 0 == str.length()) {
        return null;
    }
    try {
        result = Integer.parseInt(str);
    } 
    catch (NumberFormatException e) {
        String negativeMode = "";
        if(str.indexOf('-') != -1)
            negativeMode = "-";
        str = str.replaceAll("-", "" );
        if (str.indexOf('.') != -1) {
            str = str.substring(0, str.indexOf('.'));
            if (str.length() == 0) {
                return (Integer)0;
            }
        }
        String strNum = str.replaceAll("[^\\d]", "" );
        if (0 == strNum.length()) {
            return null;
        }
        result = Integer.parseInt(negativeMode + strNum);
    }
    return result;
}

Testing with JUnit:

@Test
public void testStr2Int() {
    assertEquals("is numeric", (Integer)(-5), Helper.str2Int("-5"));
    assertEquals("is numeric", (Integer)50, Helper.str2Int("50.00"));
    assertEquals("is numeric", (Integer)20, Helper.str2Int("$ 20.90"));
    assertEquals("is numeric", (Integer)5, Helper.str2Int(" 5.321"));
    assertEquals("is numeric", (Integer)1000, Helper.str2Int("1,000.50"));
    assertEquals("is numeric", (Integer)0, Helper.str2Int("0.50"));
    assertEquals("is numeric", (Integer)0, Helper.str2Int(".50"));
    assertEquals("is numeric", (Integer)0, Helper.str2Int("-.10"));
    assertEquals("is numeric", (Integer)Integer.MAX_VALUE, Helper.str2Int(""+Integer.MAX_VALUE));
    assertEquals("is numeric", (Integer)Integer.MIN_VALUE, Helper.str2Int(""+Integer.MIN_VALUE));
    assertEquals("Not
     is numeric", null, Helper.str2Int("czv.,xcvsa"));
    /**
     * Dynamic test
     */
    for(Integer num = 0; num < 1000; num++) {
        for(int spaces = 1; spaces < 6; spaces++) {
            String numStr = String.format("%0"+spaces+"d", num);
            Integer numNeg = num * -1;
            assertEquals(numStr + ": is numeric", num, Helper.str2Int(numStr));
            assertEquals(numNeg + ": is numeric", numNeg, Helper.str2Int("- " + numStr));
        }
    }
}

Get current controller in view

Create base class for all controllers and put here name attribute:

public abstract class MyBaseController : Controller
{
    public abstract string Name { get; }
}

In view

@{
    var controller = ViewContext.Controller as MyBaseController;
    if (controller != null)
    {
       @controller.Name
    }
}

Controller example

 public class SampleController: MyBaseController 
    { 
      public override string Name { get { return "Sample"; } 
    }

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

This probably won't be a popular answer, but you almost certainly do not want to do this. If you want a copy that's a merge, then use copy (or deepcopy, depending on what you want) and then update. The two lines of code are much more readable - more Pythonic - than the single line creation with .items() + .items(). Explicit is better than implicit.

In addition, when you use .items() (pre Python 3.0), you're creating a new list that contains the items from the dict. If your dictionaries are large, then that is quite a lot of overhead (two large lists that will be thrown away as soon as the merged dict is created). update() can work more efficiently, because it can run through the second dict item-by-item.

In terms of time:

>>> timeit.Timer("dict(x, **y)", "x = dict(zip(range(1000), range(1000)))\ny=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000)
15.52571702003479
>>> timeit.Timer("temp = x.copy()\ntemp.update(y)", "x = dict(zip(range(1000), range(1000)))\ny=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000)
15.694622993469238
>>> timeit.Timer("dict(x.items() + y.items())", "x = dict(zip(range(1000), range(1000)))\ny=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000)
41.484580039978027

IMO the tiny slowdown between the first two is worth it for the readability. In addition, keyword arguments for dictionary creation was only added in Python 2.3, whereas copy() and update() will work in older versions.

Can I pass column name as input parameter in SQL stored Procedure

You can pass the column name but you cannot use it in a sql statemnt like

Select @Columnname From Table

One could build a dynamic sql string and execute it like EXEC (@SQL)

For more information see this answer on dynamic sql.

Dynamic SQL Pros and Cons

Use curly braces to initialize a Set in Python

Compare also the difference between {} and set() with a single word argument.

>>> a = set('aardvark')
>>> a
{'d', 'v', 'a', 'r', 'k'} 
>>> b = {'aardvark'}
>>> b
{'aardvark'}

but both a and b are sets of course.

laravel 5.4 upload image

You can use it by easy way, through store method in your controller

like the below

First, we must create a form with file input to let us upload our file.

{{Form::open(['route' => 'user.store', 'files' => true])}}

{{Form::label('user_photo', 'User Photo',['class' => 'control-label'])}}
{{Form::file('user_photo')}}
{{Form::submit('Save', ['class' => 'btn btn-success'])}}

{{Form::close()}}

Here is how we can handle file in our controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{

  public function store(Request $request)
  {

  // get current time and append the upload file extension to it,
  // then put that name to $photoName variable.
  $photoName = time().'.'.$request->user_photo->getClientOriginalExtension();

  /*
  talk the select file and move it public directory and make avatars
  folder if doesn't exsit then give it that unique name.
  */
  $request->user_photo->move(public_path('avatars'), $photoName);

  }
}

That’s it. Now you can save the $photoName to the database as a user_photo field value. You can use asset(‘avatars’) function in your view and access the photos.

Redirect form to different URL based on select option element

you can use this simple way

<select onchange="location = this.value;">
                <option value="/finished">Finished</option>
                <option value="/break">Break</option>
                <option value="/issue">Issues</option>
                <option value="/downtime">Downtime</option>
</select>

will redirect to route url you can direct to .html page or direct to some link just change value in option.

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

If you have MFA enabled on GitLab you should go to Repository Settings/Repository ->Deploy Keys and create one, then use it as login while importing repo on GitHub

Taking inputs with BufferedReader in Java

You can't read individual integers in a single line separately using BufferedReader as you do using Scannerclass. Although, you can do something like this in regard to your query :

import java.io.*;
class Test
{
   public static void main(String args[])throws IOException
    {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       int t=Integer.parseInt(br.readLine());
       for(int i=0;i<t;i++)
       {
         String str=br.readLine();
         String num[]=br.readLine().split(" ");
         int num1=Integer.parseInt(num[0]);
         int num2=Integer.parseInt(num[1]);
         //rest of your code
       }
    }
}

I hope this will help you.

How do I get SUM function in MySQL to return '0' if no values are found?

Use IFNULL or COALESCE:

SELECT IFNULL(SUM(Column1), 0) AS total FROM...

SELECT COALESCE(SUM(Column1), 0) AS total FROM...

The difference between them is that IFNULL is a MySQL extension that takes two arguments, and COALESCE is a standard SQL function that can take one or more arguments. When you only have two arguments using IFNULL is slightly faster, though here the difference is insignificant since it is only called once.

Android: alternate layout xml for landscape mode

By default, the layouts in /res/layout are applied to both portrait and landscape.

If you have for example

/res/layout/main.xml

you can add a new folder /res/layout-land, copy main.xml into it and make the needed adjustments.

orientation

See also http://www.androidpeople.com/android-portrait-amp-landscape-differeent-layouts and http://www.devx.com/wireless/Article/40792/1954 for some more options.

Changing Tint / Background color of UITabBar

Swift 3 using appearance from your AppDelegate do the following:

UITabBar.appearance().barTintColor = your_color

how to find host name from IP with out login to the host

You can do a reverse DNS lookup with host, too. Just give it the IP address as an argument:

$ host 192.168.0.10
server10 has address 192.168.0.10

Change values of select box of "show 10 entries" of jquery datatable

$(document).ready(function() {
    $('#example').dataTable( {
    "aLengthMenu": [[25, 50, 75, -1], [25, 50, 75, "All"]],
    "pageLength": 25
    } );
} );

aLengthMenu : This parameter allows you to readily specify the entries in the length drop down menu that DataTables shows when pagination is enabled. It can be either a 1D array of options which will be used for both the displayed option and the value, or a 2D array which will use the array in the first position as the value, and the array in the second position as the displayed options (useful for language strings such as 'All').

Update

Since DataTables v1.10, the options you are looking for are pageLength and lengthMenu

Selenium WebDriver: Wait for complex page with JavaScript to load

Don't know how to do that but in my case, end of page load & rendering match with FAVICON displayed in Firefox tab.

So if we can get the favicon image in the webbrowser, the web page is fully loaded.

But how perform this ....

Reference an Element in a List of Tuples

Here's a quick example:

termList = []
termList.append(('term1', [1,2,3,4]))
termList.append(('term2', [5,6,7,8]))
termList.append(('term3', [9,10,11,12]))

result = [x[1] for x in termList if x[0] == 'term3']

print(result)

Change the Textbox height?

This is what worked nicely for me since all I wanted to do was set the height of the textbox. The property is Read-Only and the property is in the Unit class so you can't just set it. So I just created a new Unit and the constructor lets me set the height, then set the textbox to that unit instead.

Unit height = txtTextBox.Height;
double oldHeight = height.Value;
double newHeight = height.Value + 20; //Added 20 pixels
Unit newHeightUnit = new Unit(newHeight);
txtTextBox.Height = newHeightUnit;

How does it work - requestLocationUpdates() + LocationRequest/Listener

You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:

mLocationClient.requestLocationUpdates(mLocationRequest, this);

Be sure that the LocationListener you're implementing is from the google api, that is import this:

import com.google.android.gms.location.LocationListener;

and not this:

import android.location.LocationListener;

and it should work just fine.

It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html

The mysqli extension is missing. Please check your PHP configuration

Copy libmysql.dll from the PHP installation folder to the windows folder.

Combining two expressions (Expression<Func<T, bool>>)

Well, you can use Expression.AndAlso / OrElse etc to combine logical expressions, but the problem is the parameters; are you working with the same ParameterExpression in expr1 and expr2? If so, it is easier:

var body = Expression.AndAlso(expr1.Body, expr2.Body);
var lambda = Expression.Lambda<Func<T,bool>>(body, expr1.Parameters[0]);

This also works well to negate a single operation:

static Expression<Func<T, bool>> Not<T>(
    this Expression<Func<T, bool>> expr)
{
    return Expression.Lambda<Func<T, bool>>(
        Expression.Not(expr.Body), expr.Parameters[0]);
}

Otherwise, depending on the LINQ provider, you might be able to combine them with Invoke:

// OrElse is very similar...
static Expression<Func<T, bool>> AndAlso<T>(
    this Expression<Func<T, bool>> left,
    Expression<Func<T, bool>> right)
{
    var param = Expression.Parameter(typeof(T), "x");
    var body = Expression.AndAlso(
            Expression.Invoke(left, param),
            Expression.Invoke(right, param)
        );
    var lambda = Expression.Lambda<Func<T, bool>>(body, param);
    return lambda;
}

Somewhere, I have got some code that re-writes an expression-tree replacing nodes to remove the need for Invoke, but it is quite lengthy (and I can't remember where I left it...)


Generalized version that picks the simplest route:

static Expression<Func<T, bool>> AndAlso<T>(
    this Expression<Func<T, bool>> expr1,
    Expression<Func<T, bool>> expr2)
{
    // need to detect whether they use the same
    // parameter instance; if not, they need fixing
    ParameterExpression param = expr1.Parameters[0];
    if (ReferenceEquals(param, expr2.Parameters[0]))
    {
        // simple version
        return Expression.Lambda<Func<T, bool>>(
            Expression.AndAlso(expr1.Body, expr2.Body), param);
    }
    // otherwise, keep expr1 "as is" and invoke expr2
    return Expression.Lambda<Func<T, bool>>(
        Expression.AndAlso(
            expr1.Body,
            Expression.Invoke(expr2, param)), param);
}

Starting from .NET 4.0, there is the ExpressionVisitor class which allows you to build expressions that are EF safe.

    public static Expression<Func<T, bool>> AndAlso<T>(
        this Expression<Func<T, bool>> expr1,
        Expression<Func<T, bool>> expr2)
    {
        var parameter = Expression.Parameter(typeof (T));

        var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter);
        var left = leftVisitor.Visit(expr1.Body);

        var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter);
        var right = rightVisitor.Visit(expr2.Body);

        return Expression.Lambda<Func<T, bool>>(
            Expression.AndAlso(left, right), parameter);
    }



    private class ReplaceExpressionVisitor
        : ExpressionVisitor
    {
        private readonly Expression _oldValue;
        private readonly Expression _newValue;

        public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
        {
            _oldValue = oldValue;
            _newValue = newValue;
        }

        public override Expression Visit(Expression node)
        {
            if (node == _oldValue)
                return _newValue;
            return base.Visit(node);
        }
    }

How do I REALLY reset the Visual Studio window layout?

I tried most of the suggestions, and none of them worked. I didn't get a chance to try /resetuserdata. Finally I reinstalled the plugin and uninstalled it again, and the windows went away.

onclick="location.href='link.html'" does not load page in Safari

Try this:

onclick="javascript:location.href='http://www.uol.com.br/'"

Worked fine for me in Firefox, Chrome and IE (wow!!)

How to initialize var?

Well, I think you can assign it to a new object. Something like:

var v = new object();

How to center a View inside of an Android Layout?

I was able to center a view using

android:layout_centerHorizontal="true" 

and

android:layout_centerVertical="true" 

params.

Multiplying Two Columns in SQL Server

In a query you can just do something like:

SELECT ColumnA * ColumnB FROM table

or

SELECT ColumnA - ColumnB FROM table

You can also create computed columns in your table where you can permanently use your formula.

Apache server keeps crashing, "caught SIGTERM, shutting down"

SIGTERM is used to restart Apache (provided that it's setup in init to auto-restart): http://httpd.apache.org/docs/2.2/stopping.html

The entries you see in the logs are almost certainly there because your provider used SIGTERM for that purpose. If it's truly crashing, not even serving static content, then that sounds like some sort of a thread/connection exhaustion issue. Perhaps a DoS that holds connections open?

Should definitely be something for your provider to investigate.

Eclipse: Frustration with Java 1.7 (unbound library)

Updated eclipse.ini file with key-value property

-Dosgi.requiredJavaVersion=1.5 

to

-Dosgi.requiredJavaVersion=1.8

because, that is my JAVA version.

Also, selected JRE 1.8 as my project library

Cannot find name 'require' after upgrading to Angular4

As for me, using VSCode and Angular 5, only had to add "node" to types in tsconfig.app.json. Save, and restart the server.

_x000D_
_x000D_
{_x000D_
    "compilerOptions": {_x000D_
    .._x000D_
    "types": [_x000D_
      "node"_x000D_
    ]_x000D_
  }_x000D_
  .._x000D_
}
_x000D_
_x000D_
_x000D_

One curious thing, is that this problem "cannot find require (", does not happen when excuting with ts-node

Selecting fields from JSON output

Assuming you are dealing with a JSON-string in the input, you can parse it using the json package, see the documentation.

In the specific example you posted you would need

x = json.loads("""{
 "accountWide": true,
 "criteria": [
     {
         "description": "some description",
         "id": 7553,
         "max": 1,
         "orderIndex": 0
     }
  ]
 }""")
description = x['criteria'][0]['description']
id = x['criteria'][0]['id']
max = x['criteria'][0]['max']

Getting error "No such module" using Xcode, but the framework is there

In my case, the problem was simply that some of the projects that used the framework had a deployment target iOS version previous to the deployment target iOS version of the framework. Once I changed the framework deployment target iOS version, the error went away. enter image description here

Python Socket Multiple Clients

This program will open 26 sockets where you would be able to connect a lot of TCP clients to it.

#!usr/bin/python
from thread import *
import socket
import sys

def clientthread(conn):
    buffer=""
    while True:
        data = conn.recv(8192)
        buffer+=data
        print buffer
    #conn.sendall(reply)
    conn.close()

def main():
    try:
        host = '192.168.1.3'
        port = 6666
        tot_socket = 26
        list_sock = []
        for i in range(tot_socket):
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
            s.bind((host, port+i))
            s.listen(10)
            list_sock.append(s)
            print "[*] Server listening on %s %d" %(host, (port+i))

        while 1:
            for j in range(len(list_sock)):
                conn, addr = list_sock[j].accept()
                print '[*] Connected with ' + addr[0] + ':' + str(addr[1])
                start_new_thread(clientthread ,(conn,))
        s.close()

    except KeyboardInterrupt as msg:
        sys.exit(0)


if __name__ == "__main__":
    main()

Shell script not running, command not found

#! /bin/bash
  ^---

remove the indicated space. The shebang should be

#!/bin/bash

performSelector may cause a leak because its selector is unknown

Strange but true: if acceptable (i.e. result is void and you don't mind letting the runloop cycle once), add a delay, even if this is zero:

[_controller performSelector:NSSelectorFromString(@"someMethod")
    withObject:nil
    afterDelay:0];

This removes the warning, presumably because it reassures the compiler that no object can be returned and somehow mismanaged.

How to remove MySQL root password

I have also been through this problem,

First i tried setting my password of root to blank using command :

SET PASSWORD FOR root@localhost=PASSWORD('');

But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.

SET PASSWORD FOR [email protected]=PASSWORD('');

Just replace localhost with 127.0.0.1 and you are done .