Programs & Examples On #Writeablebitmapex

The WriteableBitmapEx library is a collection of extension methods for the WriteableBitmap. The WriteableBitmap class is available for Windows Phone, WPF, WinRT Metro Style XAML and Silverlight and allows the direct manipulation of a bitmap and could be used to generate fast procedural images by drawing directly to a bitmap.

Most efficient way to check if a file is empty in Java on Windows

This is an improvement of Saik0's answer based on Anwar Shaikh's comment that too big files (above available memory) will throw an exception:

Using Apache Commons FileUtils

private void printEmptyFileName(final File file) throws IOException {
    /*Arbitrary big-ish number that definitely is not an empty file*/
    int limit = 4096;
    if(file.length < limit && FileUtils.readFileToString(file).trim().isEmpty()) {
        System.out.println("File is empty: " + file.getName());
    }        
}

How to get a user's client IP address in ASP.NET?

use this

Dns.GetHostEntry(Dns.GetHostName())

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

If someone is using the new DataTables (which is awesome btw) and want to use array of objects then you can do so easily with the columns option. Refer to the following link for an excellent example on this.

DataTables with Array of Objects

I was struggling with this for the past 2 days and this solved it. I didn't wanted to switch to multi-dimensional arrays for other code reasons so was looking for a solution like this.

How to get base url with jquery or javascript?

var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];

How to parse a string in JavaScript?

as amber and sinan have noted above, the javascritp '.split' method will work just fine. Just pass it the string separator(-) and the string that you intend to split('123-abc-itchy-knee') and it will do the rest.

    var coolVar = '123-abc-itchy-knee';
    var coolVarParts = coolVar.split('-'); // this is an array containing the items

    var1=coolVarParts[0]; //this will retrieve 123

To access each item from the array just use the respective index(indices start at zero).

Most efficient way to append arrays in C#?

using this we can add two array with out any loop.

I believe if you have 2 arrays of the same type that you want to combine into one of array, there's a very simple way to do that.

Here's the code:

String[] TextFils = Directory.GetFiles(basePath, "*.txt");
String[] ExcelFils = Directory.GetFiles(basePath, "*.xls");
String[] finalArray = TextFils.Concat(ExcelFils).ToArray();

or

String[] Fils = Directory.GetFiles(basePath, "*.txt");
String[] ExcelFils = Directory.GetFiles(basePath, "*.xls");
Fils = Fils.Concat(ExcelFils).ToArray();

H2 in-memory database. Table not found

DB_CLOSE_DELAY=-1

hbm2ddl closes the connection after creating the table, so h2 discards it.

If you have your connection-url configured like this

jdbc:h2:mem:test

the content of the database is lost at the moment the last connection is closed.

If you want to keep your content you have to configure the url like this

jdbc:h2:mem:test;DB_CLOSE_DELAY=-1

If doing so, h2 will keep its content as long as the vm lives.

Notice the semicolon (;) rather than colon (:).

See the In-Memory Databases section of the Features page. To quote:

By default, closing the last connection to a database closes the database. For an in-memory database, this means the content is lost. To keep the database open, add ;DB_CLOSE_DELAY=-1 to the database URL. To keep the content of an in-memory database as long as the virtual machine is alive, use jdbc:h2:mem:test;DB_CLOSE_DELAY=-1.

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

Let's break down the full URL that a client would type into their address bar to reach your servlet:

http://www.example.com:80/awesome-application/path/to/servlet/path/info?a=1&b=2#boo

The parts are:

  1. scheme: http
  2. hostname: www.example.com
  3. port: 80
  4. context path: awesome-application
  5. servlet path: path/to/servlet
  6. path info: path/info
  7. query: a=1&b=2
  8. fragment: boo

The request URI (returned by getRequestURI) corresponds to parts 4, 5 and 6.

(incidentally, even though you're not asking for this, the method getRequestURL would give you parts 1, 2, 3, 4, 5 and 6).

Now:

  • part 4 (the context path) is used to select your particular application out of many other applications that may be running in the server
  • part 5 (the servlet path) is used to select a particular servlet out of many other servlets that may be bundled in your application's WAR
  • part 6 (the path info) is interpreted by your servlet's logic (e.g. it may point to some resource controlled by your servlet).
  • part 7 (the query) is also made available to your servlet using getQueryString
  • part 8 (the fragment) is not even sent to the server and is relevant and known only to the client

The following always holds (except for URL encoding differences):

requestURI = contextPath + servletPath + pathInfo

The following example from the Servlet 3.0 specification is very helpful:


Note: image follows, I don't have the time to recreate in HTML:

enter image description here

Oracle "Partition By" Keyword

EMPNO     DEPTNO DEPT_COUNT

 7839         10          4
 5555         10          4
 7934         10          4
 7782         10          4 --- 4 records in table for dept 10
 7902         20          4
 7566         20          4
 7876         20          4
 7369         20          4 --- 4 records in table for dept 20
 7900         30          6
 7844         30          6
 7654         30          6
 7521         30          6
 7499         30          6
 7698         30          6 --- 6 records in table for dept 30

Here we are getting count for respective deptno. As for deptno 10 we have 4 records in table emp similar results for deptno 20 and 30 also.

How to read a CSV file from a URL with Python?

This question is tagged python-2.x so it didn't seem right to tamper with the original question, or the accepted answer. However, Python 2 is now unsupported, and this question still has good google juice for "python csv urllib", so here's an updated Python 3 solution.

It's now necessary to decode urlopen's response (in bytes) into a valid local encoding, so the accepted answer has to be modified slightly:

import csv, urllib.request

url = 'http://winterolympicsmedals.com/medals.csv'
response = urllib.request.urlopen(url)
lines = [l.decode('utf-8') for l in response.readlines()]
cr = csv.reader(lines)

for row in cr:
    print(row)

Note the extra line beginning with lines =, the fact that urlopen is now in the urllib.request module, and print of course requires parentheses.

It's hardly advertised, but yes, csv.reader can read from a list of strings.

And since someone else mentioned pandas, here's a one-liner to display the CSV in a console-friendly output:

python3 -c 'import pandas
df = pandas.read_csv("http://winterolympicsmedals.com/medals.csv")
print(df.to_string())'

(Yes, it's three lines, but you can copy-paste it as one command. ;)

How to find the php.ini file used by the command line?

You can get a full phpinfo() using :

php -i 

And, in there, there is the php.ini file used :

$ php -i | grep 'Configuration File'
Configuration File (php.ini) Path => /etc
Loaded Configuration File => /etc/php.ini

On Windows use find instead:

php -i|find/i"configuration file"

Include headers when using SELECT INTO OUTFILE?

This will alow you to have ordered columns and/or a limit

SELECT 'ColName1', 'ColName2', 'ColName3'
UNION ALL
SELECT * from (SELECT ColName1, ColName2, ColName3
    FROM YourTable order by ColName1 limit 3) a
    INTO OUTFILE '/path/outfile';

Coarse-grained vs fine-grained

In term of dataset like a text file ,Coarse-grained meaning we can transform the whole dataset but not an individual element on the dataset While fine-grained means we can transform individual element on the dataset.

How to download/checkout a project from Google Code in Windows?

If you don't want to install TortoiseSVN, you can simply install 'Subversion for Windows' from here:

http://sourceforge.net/projects/win32svn/

After installing, just open up a command prompt, go the folder you want to download into, then past in the checkout command as indicated on the project's 'source' page. E.g.

svn checkout http://projectname.googlecode.com/svn/trunk/ projectname-read-only

Note the space between the URL and the last string is intentional, the last string is the folder name into which the source will be downloaded.

What is null in Java?

There are two major categories of types in Java: primitive and reference. Variables declared of a primitive type store values; variables declared of a reference type store references.

String x = null;

In this case, the initialization statement declares a variables “x”. “x” stores String reference. It is null here. First of all, null is not a valid object instance, so there is no memory allocated for it. It is simply a value that indicates that the object reference is not currently referring to an object.

Java Wait for thread to finish

I imagine that you're calling your download in a background thread such as provided by a SwingWorker. If so, then simply call your next code sequentially in the same SwingWorker's doInBackground method.

How to detect when a UIScrollView has finished scrolling

If you're into Rx, you can extend UIScrollView like this:

import RxSwift
import RxCocoa

extension Reactive where Base: UIScrollView {
    public var didEndScrolling: ControlEvent<Void> {
        let source = Observable
            .merge([base.rx.didEndDragging.map { !$0 },
                    base.rx.didEndDecelerating.mapTo(true)])
            .filter { $0 }
            .mapTo(())
        return ControlEvent(events: source)
    }
}

which will allow you to just do like this:

scrollView.rx.didEndScrolling.subscribe(onNext: {
    // Do what needs to be done here
})

This will take into account both dragging and deceleration.

Precision String Format Specifier In Swift

You can still use NSLog in Swift as in Objective-C just without the @ sign.

NSLog("%.02f %.02f %.02f", r, g, b)

Edit: After working with Swift since a while I would like to add also this variation

    var r=1.2
    var g=1.3
    var b=1.4
    NSLog("\(r) \(g) \(b)")

Output:

2014-12-07 21:00:42.128 MyApp[1626:60b] 1.2 1.3 1.4

Run a .bat file using python code

import subprocess

filepath="D:/path/to/batch/myBatch.bat"
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)

stdout, stderr = p.communicate()
print p.returncode # is 0 if success

How do I add a new class to an element dynamically?

Since everyone has given you jQuery/JS answers to this, I will provide an additional solution. The answer to your question is still no, but using LESS (a CSS Pre-processor) you can do this easily.

.first-class {
  background-color: yellow;
}
.second-class:hover {
  .first-class;
}

Quite simply, any time you hover over .second-class it will give it all the properties of .first-class. Note that it won't add the class permanently, just on hover. You can learn more about LESS here: Getting Started with LESS

Here is a SASS way to do it as well:

.first-class {
  background-color: yellow;
}
.second-class {
  &:hover {
    @extend .first-class;
  }
}

Didn't Java once have a Pair class?

Map.Entry

Java 1.6 and upper have two implementation of Map.Entry interface pairing a key with a value:

UML diagram of SimpleEntry & SimpleImmutableEntry classes inheriting from Map.Entry interface

For example

Map.Entry < Month, Boolean > pair = 
    new AbstractMap.SimpleImmutableEntry <>( 
        Month.AUGUST , 
        Boolean.TRUE 
    )
;

pair.toString(): AUGUST=true

I use it when need to store pairs (like size and object collection).

This piece from my production code:

public Map<L1Risk, Map.Entry<int[], Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>>>>
        getEventTable(RiskClassifier classifier) {
    Map<L1Risk, Map.Entry<int[], Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>>>> l1s = new HashMap<>();
    Map<L2Risk, Map.Entry<int[], Map<L3Risk, List<Event>>>> l2s = new HashMap<>();
    Map<L3Risk, List<Event>> l3s = new HashMap<>();
    List<Event> events = new ArrayList<>();
    ...
    map.put(l3s, events);
    map.put(l2s, new AbstractMap.SimpleImmutableEntry<>(l3Size, l3s));
    map.put(l1s, new AbstractMap.SimpleImmutableEntry<>(l2Size, l2s));
}

Code looks complicated but instead of Map.Entry you limited to array of object (with size 2) and lose type checks...

Why am I getting "undefined reference to sqrt" error even though I include math.h header?

You need to link the with the -lm linker option

You need to compile as

gcc test.c  -o test -lm

gcc (Not g++) historically would not by default include the mathematical functions while linking. It has also been separated from libc onto a separate library libm. To link with these functions you have to advise the linker to include the library -l linker option followed by the library name m thus -lm.

Laravel view not found exception

If your path to view is true first try to config:cache and route:cache if nothing changed check your resource path permission are true.

example: your can do it in ubuntu with :

sudo chgrp -R www-data resources/views
sudo usermod -a -G www-data $USER

Get my phone number in android

private String getMyPhoneNumber(){
    TelephonyManager mTelephonyMgr;
    mTelephonyMgr = (TelephonyManager)
        getSystemService(Context.TELEPHONY_SERVICE); 
    return mTelephonyMgr.getLine1Number();
}

private String getMy10DigitPhoneNumber(){
    String s = getMyPhoneNumber();
    return s.substring(2);
}

Convert a timedelta to days, hours and minutes

timedeltas have a days and seconds attribute .. you can convert them yourself with ease.

Change color of bootstrap navbar on hover link?

.nav > li > a:focus, 
.nav > li > a:hover 
{
    text-decoration: underline;
    background-color: pink;
}

pandas unique values multiple columns

pd.unique returns the unique values from an input array, or DataFrame column or index.

The input to this function needs to be one-dimensional, so multiple columns will need to be combined. The simplest way is to select the columns you want and then view the values in a flattened NumPy array. The whole operation looks like this:

>>> pd.unique(df[['Col1', 'Col2']].values.ravel('K'))
array(['Bob', 'Joe', 'Bill', 'Mary', 'Steve'], dtype=object)

Note that ravel() is an array method that returns a view (if possible) of a multidimensional array. The argument 'K' tells the method to flatten the array in the order the elements are stored in the memory (pandas typically stores underlying arrays in Fortran-contiguous order; columns before rows). This can be significantly faster than using the method's default 'C' order.


An alternative way is to select the columns and pass them to np.unique:

>>> np.unique(df[['Col1', 'Col2']].values)
array(['Bill', 'Bob', 'Joe', 'Mary', 'Steve'], dtype=object)

There is no need to use ravel() here as the method handles multidimensional arrays. Even so, this is likely to be slower than pd.unique as it uses a sort-based algorithm rather than a hashtable to identify unique values.

The difference in speed is significant for larger DataFrames (especially if there are only a handful of unique values):

>>> df1 = pd.concat([df]*100000, ignore_index=True) # DataFrame with 500000 rows
>>> %timeit np.unique(df1[['Col1', 'Col2']].values)
1 loop, best of 3: 1.12 s per loop

>>> %timeit pd.unique(df1[['Col1', 'Col2']].values.ravel('K'))
10 loops, best of 3: 38.9 ms per loop

>>> %timeit pd.unique(df1[['Col1', 'Col2']].values.ravel()) # ravel using C order
10 loops, best of 3: 49.9 ms per loop

How do you programmatically update query params in react-router?

Example using react-router v4, redux-thunk and react-router-redux(5.0.0-alpha.6) package.

When user uses search feature, I want him to be able to send url link for same query to a colleague.

import { push } from 'react-router-redux';
import qs from 'query-string';

export const search = () => (dispatch) => {
    const query = { firstName: 'John', lastName: 'Doe' };

    //API call to retrieve records
    //...

    const searchString = qs.stringify(query);

    dispatch(push({
        search: searchString
    }))
}

SQL: capitalize first letter only

Please check the query without using a function:

declare @T table(Insurance varchar(max))

insert into @T values ('wezembeek-oppem')
insert into @T values ('roeselare')
insert into @T values ('BRUGGE')
insert into @T values ('louvain-la-neuve')

select (
       select upper(T.N.value('.', 'char(1)'))+
                lower(stuff(T.N.value('.', 'varchar(max)'), 1, 1, ''))+(CASE WHEN RIGHT(T.N.value('.', 'varchar(max)'), 1)='-' THEN '' ELSE ' ' END)
       from X.InsXML.nodes('/N') as T(N)
       for xml path(''), type
       ).value('.', 'varchar(max)') as Insurance
from 
  (
  select cast('<N>'+replace(
            replace(
                Insurance, 
                ' ', '</N><N>'),
            '-', '-</N><N>')+'</N>' as xml) as InsXML
  from @T
  ) as X

How to remove duplicate values from a multi-dimensional array in PHP

Simple solution:

array_unique($array, SORT_REGULAR)

EnterKey to press button in VBA Userform

Use the TextBox's Exit event handler:

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Logincode_Click  
End Sub

Get the IP Address of local computer

from torial: If you use winsock, here's a way: http://tangentsoft.net/wskfaq/examples/ipaddr.html

As for the subnet portion of the question; there is not platform agnostic way to retrieve the subnet mask as the POSIX socket API (which all modern operating systems implement) does not specify this. So you will have to use whatever method is available on the platform you are using.

$(document).click() not working correctly on iPhone. jquery

try this, applies only to iPhone and iPod so you're not making everything turn blue on chrome or firefox mobile;

/iP/i.test(navigator.userAgent) && $('*').css('cursor', 'pointer');

basically, on iOS, things aren't "clickable" by default -- they're "touchable" (pfffff) so you make them "clickable" by giving them a pointer cursor. makes total sense, right??

import sun.misc.BASE64Encoder results in error compiled in Eclipse

Java 6 ships the javax.xml.bind.DatatypeConverter. This class provides two static methods that support the same decoding & encoding:

parseBase64Binary() / printBase64Binary()

Update: Since Java 8 we now have a much better Base64 Support.

Use this and you will not need an extra library, like Apache Commons Codec.

How to merge rows in a column into one cell in excel?

Inside CONCATENATE you can use TRANSPOSE if you expand it (F9) then remove the surrounding {}brackets like this recommends

=CONCATENATE(TRANSPOSE(B2:B19))

Becomes

=CONCATENATE("Oh ","combining ", "a " ...)

CONCATENATE(TRANSPOSE(B2:B19))

You may need to add your own separator on the end, say create a column C and transpose that column.

=B1&" "
=B2&" "
=B3&" "

Replacing characters in Ant property

Just an FYI for answer Replacing characters in Ant property - if you are trying to use this inside of a maven execution, you can't reference maven variables directly. You will need something like this:

...
<target>
<property name="propATemp" value="${propA}"/>
    <loadresource property="propB">
    <propertyresource name="propATemp" />
...

Http Basic Authentication in Java using HttpClient?

This is the code from the accepted answer above, with some changes made regarding the Base64 encoding. The code below compiles.

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.codec.binary.Base64;


public class HttpBasicAuth {

    public static void main(String[] args) {

        try {
            URL url = new URL ("http://ip:port/login");

            Base64 b = new Base64();
            String encoding = b.encodeAsString(new String("test1:test1").getBytes());

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty  ("Authorization", "Basic " + encoding);
            InputStream content = (InputStream)connection.getInputStream();
            BufferedReader in   = 
                new BufferedReader (new InputStreamReader (content));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        } 
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Array.size() vs Array.length

array.length isn't necessarily the number of items in the array:

var a = ['car1', 'car2', 'car3'];
a[100] = 'car100';
a.length; // 101

The length of the array is one more than the highest index.

As stated before Array.size() is not a valid method.

More information

C# Validating input for textbox on winforms

With WinForms you can use the ErrorProvider in conjunction with the Validating event to handle the validation of user input. The Validating event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.

http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx

Why am I getting this error Premature end of file?

For those who reached this post for Answer:

This happens mainly because the InputStream the DOM parser is consuming is empty

So in what I ran across, there might be two situations:

  1. The InputStream you passed into the parser has been used and thus emptied.
  2. The File or whatever you created the InputStream from may be an empty file or string or whatever. The emptiness might be the reason caused the problem. So you need to check your source of the InputStream.

Enable remote connections for SQL Server Express 2012

All you need to do is open the relevant port on the server's firewall.

Easy way to test a URL for 404 in PHP?

If you are looking for an easiest solution and the one you can try in one go on php5 do

file_get_contents('www.yoursite.com');
//and check by echoing
echo $http_response_header[0];

MySQLi count(*) always returns 1

$result->num_rows; only returns the number of row(s) affected by a query. When you are performing a count(*) on a table it only returns one row so you can not have an other result than 1.

Maven error: Not authorized, ReasonPhrase:Unauthorized

The issue may happen while fetching dependencies from a remote repository. In my case, the repository did not need any authentication and it has been resolved by removing the servers section in the settings.xml file:

<servers>
    <server>
      <id>SomeRepo</id>
      <username>SomeUN</username>
      <password>SomePW</password>
    </server>
</servers>

ps: I guess your target is mvn clean install instead of maven install clean

Check free disk space for current partition in bash

  1. df command : Report file system disk space usage
  2. du command : Estimate file space usage

Type df -h or df -k to list free disk space:

 $ df -h

OR

 $ df -k

du shows how much space one or more files or directories is using:

 $ du -sh

The -s option summarizes the space a directory is using and -h option provides Human-readable output.

How can I get table names from an MS Access Database?

To build on Ilya's answer try the following query:

SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~") 
        AND ((Left([Name],4))<>"MSys") 
        AND ((MSysObjects.Type) In (1,4,6)))
order by MSysObjects.Name 

(this one works without modification with an MDB)

ACCDB users may need to do something like this

SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~") 
        AND ((Left([Name],4))<>"MSys") 
        AND ((MSysObjects.Type) In (1,4,6))
        AND ((MSysObjects.Flags)=0))
order by MSysObjects.Name 

As there is an extra table is included that appears to be a system table of some sort.

Reversing a string in C

easy and simple code xD

void strrev (char s[]) {

int i;
int dim = strlen (s);
char l;

for (i = 0; i < dim / 2; i++) {
    l = s[i];
    s[i] = s[dim-i-1];
    s[dim-i-1] = l;
    }

}

What's the difference between console.dir and console.log?

Well, the Console Standard (as of commit ef88ec7a39fdfe79481d7d8f2159e4a323e89648) currently calls for console.dir to apply generic JavaScript object formatting before passing it to Printer (a spec-level operation), but for a single-argument console.log call, the spec ends up passing the JavaScript object directly to Printer.

Since the spec actually leaves almost everything about the Printer operation to the implementation, it's left to their discretion what type of formatting to use for console.log().

How to print VARCHAR(MAX) using Print Statement?

This should work properly this is just an improvement of previous answers.

DECLARE @Counter INT
DECLARE @Counter1 INT
SET @Counter = 0
SET @Counter1 = 0
DECLARE @TotalPrints INT
SET @TotalPrints = (LEN(@QUERY) / 4000) + 1
print @TotalPrints 
WHILE @Counter < @TotalPrints 
BEGIN
-- Do your printing...
print(substring(@query,@COUNTER1,@COUNTER1+4000))

set @COUNTER1 = @Counter1+4000
SET @Counter = @Counter + 1
END

How might I schedule a C# Windows Service to perform a task daily?

Try this:

public partial class Service : ServiceBase
{
    private Timer timer;
    public Service()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        SetTimer();
    }

    private void SetTimer()
    {
        if (timer == null)
        {
            timer = new Timer();
            timer.AutoReset = true;
            timer.Interval = 60000 * Convert.ToDouble(ConfigurationManager.AppSettings["IntervalMinutes"]);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Start();
        }
    }

    private void timer_Elapsed(object source, System.Timers.ElapsedEventArgs e)
    {
        //Do some thing logic here
    }

    protected override void OnStop()
    {
        // disposed all service objects
    }
}

How to remove pip package after deleting it manually

packages installed using pip can be uninstalled completely using

pip uninstall <package>

refrence link

pip uninstall is likely to fail if the package is installed using python setup.py install as they do not leave behind metadata to determine what files were installed.

packages still show up in pip list if their paths(.pth file) still exist in your site-packages or dist-packages folder. You'll need to remove them as well in case you're removing using rm -rf

How to delete a record in Django models?

There are a couple of ways:

To delete it directly:

SomeModel.objects.filter(id=id).delete()

To delete it from an instance:

instance = SomeModel.objects.get(id=id)
instance.delete()

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

UTF-8: General? Bin? Unicode?

Really, I tested saving values like 'é' and 'e' in column with unique index and they cause duplicate error on both 'utf8_unicode_ci' and 'utf8_general_ci'. You can save them only in 'utf8_bin' collated column.

And mysql docs (in http://dev.mysql.com/doc/refman/5.7/en/charset-applications.html) suggest into its examples set 'utf8_general_ci' collation.

[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci

How to convert FileInputStream to InputStream?

You would typically first read from the input stream and then close it. You can wrap the FileInputStream in another InputStream (or Reader). It will be automatically closed when you close the wrapping stream/reader.

If this is a method returning an InputStream to the caller, then it is the caller's responsibility to close the stream when finished with it. If you close it in your method, the caller will not be able to use it.

To answer some of your comments...

To send the contents InputStream to a remote consumer, you would write the content of the InputStream to an OutputStream, and then close both streams.

The remote consumer does not know anything about the stream objects you have created. He just receives the content, in an InputStream which he will create, read from and close.

Can I use GDB to debug a running process?

Yes. Use the attach command. Check out this link for more information. Typing help attach at a GDB console gives the following:

(gdb) help attach

Attach to a process or file outside of GDB. This command attaches to another target, of the same type as your last "target" command ("info files" will show your target stack). The command may take as argument a process id, a process name (with an optional process-id as a suffix), or a device file. For a process id, you must have permission to send the process a signal, and it must have the same effective uid as the debugger. When using "attach" to an existing process, the debugger finds the program running in the process, looking first in the current working directory, or (if not found there) using the source file search path (see the "directory" command). You can also use the "file" command to specify the program, and to load its symbol table.


NOTE: You may have difficulty attaching to a process due to improved security in the Linux kernel - for example attaching to the child of one shell from another.

You'll likely need to set /proc/sys/kernel/yama/ptrace_scope depending on your requirements. Many systems now default to 1 or higher.

The sysctl settings (writable only with CAP_SYS_PTRACE) are:

0 - classic ptrace permissions: a process can PTRACE_ATTACH to any other
    process running under the same uid, as long as it is dumpable (i.e.
    did not transition uids, start privileged, or have called
    prctl(PR_SET_DUMPABLE...) already). Similarly, PTRACE_TRACEME is
    unchanged.

1 - restricted ptrace: a process must have a predefined relationship
    with the inferior it wants to call PTRACE_ATTACH on. By default,
    this relationship is that of only its descendants when the above
    classic criteria is also met. To change the relationship, an
    inferior can call prctl(PR_SET_PTRACER, debugger, ...) to declare
    an allowed debugger PID to call PTRACE_ATTACH on the inferior.
    Using PTRACE_TRACEME is unchanged.

2 - admin-only attach: only processes with CAP_SYS_PTRACE may use ptrace
    with PTRACE_ATTACH, or through children calling PTRACE_TRACEME.

3 - no attach: no processes may use ptrace with PTRACE_ATTACH nor via
    PTRACE_TRACEME. Once set, this sysctl value cannot be changed.

Why am I getting "void value not ignored as it ought to be"?

  int a = srand(time(NULL));

The prototype for srand is void srand(unsigned int) (provided you included <stdlib.h>).
This means it returns nothing ... but you're using the value it returns (???) to assign, by initialization, to a.


Edit: this is what you need to do:

#include <stdlib.h> /* srand(), rand() */
#include <time.h>   /* time() */

#define ARRAY_SIZE 1024

void getdata(int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
        arr[i] = rand();
    }
}

int main(void)
{
    int arr[ARRAY_SIZE];
    srand(time(0));
    getdata(arr, ARRAY_SIZE);
    /* ... */
}

Turning off hibernate logging console output

For those who don't want elegant solutions, just a quick and dirty way to stop those messages, here is a solution that worked for me (I use Hibernate 4.3.6 and Eclipse and no answers provided above (or found on the internet) worked; neither log4j config files nor setting the logging level programatically)

public static void main(String[] args) {
    //magical - do not touch
    @SuppressWarnings("unused")
    org.jboss.logging.Logger logger = org.jboss.logging.Logger.getLogger("org.hibernate");
    java.util.logging.Logger.getLogger("org.hibernate").setLevel(java.util.logging.Level.WARNING); //or whatever level you need

    ...
}

I used it in a tutorial program downloaded from this site

Convert UTC/GMT time to local time

I know this is an older question, but I ran into a similar situation, and I wanted to share what I had found for future searchers, possibly including myself :).

DateTime.Parse() can be tricky -- see here for example.

If the DateTime is coming from a Web service or some other source with a known format, you might want to consider something like

DateTime.ParseExact(dateString, 
                   "MM/dd/yyyy HH:mm:ss", 
                   CultureInfo.InvariantCulture, 
                   DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)

or, even better,

DateTime.TryParseExact(...)

The AssumeUniversal flag tells the parser that the date/time is already UTC; the combination of AssumeUniversal and AdjustToUniversal tells it not to convert the result to "local" time, which it will try to do by default. (I personally try to deal exclusively with UTC in the business / application / service layer(s) anyway. But bypassing the conversion to local time also speeds things up -- by 50% or more in my tests, see below.)

Here's what we were doing before:

DateTime.Parse(dateString, new CultureInfo("en-US"))

We had profiled the app and found that the DateTime.Parse represented a significant percentage of CPU usage. (Incidentally, the CultureInfo constructor was not a significant contributor to CPU usage.)

So I set up a console app to parse a date/time string 10000 times in a variety of ways. Bottom line:
Parse() 10 sec
ParseExact() (converting to local) 20-45 ms
ParseExact() (not converting to local) 10-15 ms
... and yes, the results for Parse() are in seconds, whereas the others are in milliseconds.

SQL Server check case-sensitivity?

SQL server determines case sensitivity by COLLATION.

COLLATION can be set at various levels.

  1. Server-level
  2. Database-level
  3. Column-level
  4. Expression-level

Here is the MSDN reference.

One can check the COLLATION at each level as mentioned in Raj More's answer.

Check Server Collation

SELECT SERVERPROPERTY('COLLATION')

Check Database Collation

SELECT DATABASEPROPERTYEX('AdventureWorks', 'Collation') SQLCollation;

Check Column Collation

select table_name, column_name, collation_name
from INFORMATION_SCHEMA.COLUMNS
where table_name = @table_name

Check Expression Collation

For expression level COLLATION you need to look at the expression. :)

It would be generally at the end of the expression as in below example.

SELECT name FROM customer ORDER BY name COLLATE Latin1_General_CS_AI;

Collation Description

For getting description of each COLLATION value try this.

SELECT * FROM fn_helpcollations()

And you should see something like this.

enter image description here

You can always put a WHERE clause to filter and see description only for your COLLATION.

You can find a list of collations here.

Html- how to disable <a href>?

<script>
    $(document).ready(function(){
        $('#connectBtn').click(function(e){
            e.preventDefault();
        })
    });
</script>

This will prevent the default action.

How can I sanitize user input with PHP?

PHP 5.2 introduced the filter_var function.

It supports a great deal of SANITIZE, VALIDATE filters.

http://php.net/manual/en/function.filter-var.php

Prolog "or" operator, query

you can 'invoke' alternative bindings on Y this way:

...registered(X, Y), (Y=ct101; Y=ct102; Y=ct103).

Note the parenthesis are required to keep the correct execution control flow. The ;/2 it's the general or operator. For your restricted use you could as well choice the more idiomatic

...registered(X, Y), member(Y, [ct101,ct102,ct103]).

that on backtracking binds Y to each member of the list.

edit I understood with a delay your last requirement. If you want that Y match all 3 values the or is inappropriate, use instead

...registered(X, ct101), registered(X, ct102), registered(X, ct103).

or the more compact

...findall(Y, registered(X, Y), L), sort(L, [ct101,ct102,ct103]).

findall/3 build the list in the very same order that registered/2 succeeds. Then I use sort to ensure the matching.

...setof(Y, registered(X, Y), [ct101,ct102,ct103]).

setof/3 also sorts the result list

Error: EACCES: permission denied

I had problem on Linux. I wrote

chown -R myUserName /home/myusername/myfolder

in my project folder.

WARNING: this is NOT the right way to fix it; DO NOT RUN IT, if you aren't sure of what could be the consequences.

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

ICollection<T> is used because the IEnumerable<T> interface provides no way of adding items, removing items, or otherwise modifying the collection.

Full-screen iframe with a height of 100%

You can can call a function which will calculate the iframe's body hieght when the iframe is loaded:

<script type="text/javascript">
    function iframeloaded(){
       var lastHeight = 0, curHeight = 0, $frame = $('iframe:eq(0)');
       curHeight = $frame.contents().find('body').height();
       if ( curHeight != lastHeight ) {
           $frame.css('height', (lastHeight = curHeight) + 'px' );
       }
    }
</script>

<iframe onload="iframeloaded()" src=...>

Python Pandas Counting the Occurrences of a Specific value

Try this:

(df[education]=='9th').sum()

IO Error: The Network Adapter could not establish the connection

To resolve the Network Adapter Error I had to remove the - in the name of the computer name.

Uncaught TypeError: undefined is not a function while using jQuery UI

use jQuery.noConflict()

var j = jQuery.noConflict();
j(document).ready(function(){
    j('#datetimepicker').datepicker();
})

If...Then...Else with multiple statements after Then

This works with multiple statements:

if condition1 Then stmt1:stmt2 Else if condition2 Then stmt3:stmt4 Else stmt5:stmt6

Or you can split it over multiple lines:

if condition1 Then stmt1:stmt2
Else if condition2 Then stmt3:stmt4
Else stmt5:stmt6

Find a private field with Reflection?

One thing that you need to be aware of when reflecting on private members is that if your application is running in medium trust (as, for instance, when you are running on a shared hosting environment), it won't find them -- the BindingFlags.NonPublic option will simply be ignored.

Giving multiple conditions in for loop in Java

A basic for statement includes

  • 0..n initialization statements (ForInit)
  • 0..1 expression statements that evaluate to boolean or Boolean (ForStatement) and
  • 0..n update statements (ForUpdate)

If you need multiple conditions to build your ForStatement, then use the standard logic operators (&&, ||, |, ...) but - I suggest to use a private method if it gets to complicated:

for (int i = 0, j = 0; isMatrixElement(i,j,myArray); i++, j++) { 
   // ...
}

and

private boolean isMatrixElement(i,j,myArray) {
  return (i < myArray.length) && (j < myArray[i].length);  //  stupid dummy code!
}

How can I declare and use Boolean variables in a shell script?

Here is a simple example which works for me:

temp1=true
temp2=false

if [ "$temp1" = true ] || [ "$temp2" = true ]
then
    echo "Do something." 
else
    echo "Do something else."
fi

You don't have write permissions for the /var/lib/gems/2.3.0 directory

If you want to use the distribution Ruby instead of rb-env/rvm, you can set up a GEM_HOME for your current user. Start by creating a directory to store the Ruby gems for your user:

$ mkdir ~/.ruby

Then update your shell to use that directory for GEM_HOME and to update your PATH variable to include the Ruby gem bin directory.

$ echo 'export GEM_HOME=~/.ruby/' >> ~/.bashrc
$ echo 'export PATH="$PATH:~/.ruby/bin"' >> ~/.bashrc
$ source ~/.bashrc

(That last line will reload the environment variables in your current shell.)

Now you should be able to install Ruby gems under your user using the gem command. I was able to get this working with Ruby 2.5.1 under Ubuntu 18.04. If you are using a shell that is not Bash, then you will need to edit the startup script for that shell instead of bashrc.

How do I access the HTTP request header fields via JavaScript?

Almost by definition, the client-side JavaScript is not at the receiving end of a http request, so it has no headers to read. Most commonly, your JavaScript is the result of an http response. If you are trying to get the values of the http request that generated your response, you'll have to write server side code to embed those values in the JavaScript you produce.

It gets a little tricky to have server-side code generate client side code, so be sure that is what you need. For instance, if you want the User-agent information, you might find it sufficient to get the various values that JavaScript provides for browser detection. Start with navigator.appName and navigator.appVersion.

How do I find the duplicates in a list and create another list with them?

>>> l = [1,2,3,4,4,5,5,6,1]
>>> set([x for x in l if l.count(x) > 1])
set([1, 4, 5])

Git on Mac OS X v10.7 (Lion)

It's part of Xcode. You'll need to reinstall the developer tools.

how can I Update top 100 records in sql server

this piece of code can do its job

UPDATE TOP (100) table_name set column_name = value;

If you want to show the last 100 records, you can use this if you need.

With OrnekWith
as
(
Select Top(100) * from table_name Order By ID desc
)
Update table_name Set column_name = value;

How to join three table by laravel eloquent model

With Eloquent its very easy to retrieve relational data. Checkout the following example with your scenario in Laravel 5.

We have three models:

1) Article (belongs to user and category)

2) Category (has many articles)

3) User (has many articles)


1) Article.php

<?php

namespace App\Models;
 use Eloquent;

class Article extends Eloquent{

    protected $table = 'articles';

    public function user()
    {
        return $this->belongsTo('App\Models\User');
    }

    public function category()
    {
        return $this->belongsTo('App\Models\Category');
    }

}

2) Category.php

<?php

namespace App\Models;

use Eloquent;

class Category extends Eloquent
{
    protected $table = "categories";

    public function articles()
    {
        return $this->hasMany('App\Models\Article');
    }

}

3) User.php

<?php

namespace App\Models;
use Eloquent;

class User extends Eloquent
{
    protected $table = 'users';

    public function articles()
    {
        return $this->hasMany('App\Models\Article');
    }

}

You need to understand your database relation and setup in models. User has many articles. Category has many articles. Articles belong to user and category. Once you setup the relationships in Laravel, it becomes easy to retrieve the related information.

For example, if you want to retrieve an article by using the user and category, you would need to write:

$article = \App\Models\Article::with(['user','category'])->first();

and you can use this like so:

//retrieve user name 
$article->user->user_name  

//retrieve category name 
$article->category->category_name

In another case, you might need to retrieve all the articles within a category, or retrieve all of a specific user`s articles. You can write it like this:

$categories = \App\Models\Category::with('articles')->get();

$users = \App\Models\Category::with('users')->get();

You can learn more at http://laravel.com/docs/5.0/eloquent

How to convert an array into an object using stdClass()

To convert array to object using stdClass just add (object) to array u declare.

EX:

echo $array['value'];
echo $object->value;

to convert object to array

$obj = (object)$array;

to convert array to object

$arr = (array)$object

with these methods you can swap between array and object very easily.


Another method is to use json

$object = json_decode(json_encode($array), FALSE);

But this is a much more memory intensive way to do and is not supported by versions of PHP <= 5.1

Best way to compare dates in Android

String date = "03/26/2012 11:00:00";
    String dateafter = "03/26/2012 11:59:00";
    SimpleDateFormat dateFormat = new SimpleDateFormat(
            "MM/dd/yyyy hh:mm:ss");
    Date convertedDate = new Date();
    Date convertedDate2 = new Date();
    try {
        convertedDate = dateFormat.parse(date);
        convertedDate2 = dateFormat.parse(dateafter);
        if (convertedDate2.after(convertedDate)) {
            txtView.setText("true");
        } else {
            txtView.setText("false");
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

it return true.. and you can also check before and equal with help of date.before and date.equal..

How to target only IE (any version) within a stylesheet?

Another working solution for IE specific styling is

<html data-useragent="Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)">

And then your selector

html[data-useragent*='MSIE 10.0'] body .my-class{
        margin-left: -0.4em;
    }

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

For debugging purposes, you could use print(repr(data)).

To display text, always print Unicode. Don't hardcode the character encoding of your environment such as Cp850 inside your script. To decode the HTTP response, see A good way to get the charset/encoding of an HTTP response in Python.

To print Unicode to Windows console, you could use win-unicode-console package.

Stop Visual Studio from launching a new browser window when starting debug?

Joao Costa answer also holds true for .Net core 2 projects.

launchsettings.json --> "launchBrowser": false

"profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": false,
      "environmentVariables": {
        "Hosting:Environment": "Development"
      }
    }
}

How to find length of digits in an integer?

Python 2.* ints take either 4 or 8 bytes (32 or 64 bits), depending on your Python build. sys.maxint (2**31-1 for 32-bit ints, 2**63-1 for 64-bit ints) will tell you which of the two possibilities obtains.

In Python 3, ints (like longs in Python 2) can take arbitrary sizes up to the amount of available memory; sys.getsizeof gives you a good indication for any given value, although it does also count some fixed overhead:

>>> import sys
>>> sys.getsizeof(0)
12
>>> sys.getsizeof(2**99)
28

If, as other answers suggests, you're thinking about some string representation of the integer value, then just take the len of that representation, be it in base 10 or otherwise!

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME

ImportError: No module named sqlalchemy

Install Flask-SQLAlchemy with pip in your virtualenv:

pip install flask_sqlalchemy

Then import flask_sqlalchemy in your code:

from flask_sqlalchemy import SQLAlchemy

library not found for -lPods

Be sure that you open .xcworkspace, not .xcodeproj

Setting focus to iframe contents

i had a similar problem where i was trying to focus on a txt area in an iframe loaded from another page. in most cases it work. There was an issue where it would fire in FF when the iFrame was loaded but before it was visible. so the focus never seemed to be set correctly.

i worked around this with a simular solution to cheeming's answer above

    var iframeID = document.getElementById("modalIFrame"); 
//focus the IFRAME element 
$(iframeID).focus(); 
//use JQuery to find the control in the IFRAME and set focus 
$(iframeID).contents().find("#emailTxt").focus(); 

How to convert PDF files to images

The PDF engine used in Google Chrome, called PDFium, is open source under the "BSD 3-clause" license. I believe this allows redistribution when used in a commercial product.

There is a .NET wrapper for it called PdfiumViewer (NuGet) which works well to the extent I have tried it. It is under the Apache license which also allows redistribution.

(Note that this is NOT the same 'wrapper' as https://pdfium.patagames.com/ which requires a commercial license*)

(There is one other PDFium .NET wrapper, PDFiumSharp, but I have not evaluated it.)

In my opinion, so far, this may be the best choice of open-source (free as in beer) PDF libraries to do the job which do not put restrictions on the closed-source / commercial nature of the software utilizing them. I don't think anything else in the answers here satisfy that criteria, to the best of my knowledge.

How to get exception message in Python properly

I too had the same problem. Digging into this I found that the Exception class has an args attribute, which captures the arguments that were used to create the exception. If you narrow the exceptions that except will catch to a subset, you should be able to determine how they were constructed, and thus which argument contains the message.

try:
   # do something that may raise an AuthException
except AuthException as ex:
   if ex.args[0] == "Authentication Timeout.":
      # handle timeout
   else:
      # generic handling

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

I had the same issue. Jenkins's build was falling because of this error..after long hours troubleshooting.

Link to download ojdbc as per your requirement - https://www.oracle.com/database/technologies/maven-central-guide.html

I have downloaded in my maven/bin location and executed the below command.

mvn install:install-file -Dfile=ojdbc8-12.2.0.1.jar -DgroupId=com.oracle -DartifactId=ojdbc8 -Dversion=12.2.0.1 -Dpackaging=jar

POM.xml

<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>12.2.0.1</version>
</dependency>

How can I use jQuery to move a div across the screen

Use jQuery

html

<div id="b">&nbsp;</div>

css

div#b {
    position: fixed;
    top:40px;
    left:0;
    width: 40px;
    height: 40px;
    background: url(http://www.wiredforwords.com/IMAGES/FlyingBee.gif) 0 0 no-repeat;
}

script

var b = function($b,speed){


    $b.animate({
        "left": "50%"
    }, speed);
};

$(function(){
    b($("#b"), 5000);
});

see jsfiddle http://jsfiddle.net/vishnurajv/Q4Jsh/

Bootstrap 3 Horizontal Divider (not in a dropdown)

As I found the default Bootstrap <hr/> size unsightly, here's some simple HTML and CSS to balance out the element visually:

HTML:

<hr class="half-rule"/>

CSS:

.half-rule { 
    margin-left: 0;
    text-align: left;
    width: 50%;
 }

String date to xmlgregoriancalendar conversion

Found the solution as below.... posting it as it could help somebody else too :)

DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = format.parse("2014-04-24 11:15:00");

GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);

XMLGregorianCalendar xmlGregCal =  DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);

System.out.println(xmlGregCal);

Output:

2014-04-24T11:15:00.000+02:00

Is it possible to open developer tools console in Chrome on Android phone?

Please do yourself a favor and just hit the easy button:

download Web Inspector (Open Source) from the Play store.

A CAVEAT: ATTOW, console output does not accept rest params! I.e. if you have something like this:

console.log('one', 'two', 'three');

you will only see

one

logged to the console. You'll need to manually wrap the params in an Array and join, like so:

console.log([ 'one', 'two', 'three' ].join(' '));

to see the expected output.

But the app is open source! A patch may be imminent! The patcher could even be you!

Visual Studio Code open tab in new window

If you are using the excellent

VSCode for Mac, 2020

simply tap Apple-Shift-N (as in "new window")

Drag whatever you want there.

C# Change A Button's Background Color

WinForm:

private void button1_Click(object sender, EventArgs e)
{
   button2.BackColor = Color.Red;
}

WPF:

private void button1_Click(object sender, RoutedEventArgs e)
{
   button2.Background = Brushes.Blue;
}

SQL Server 2012 can't start because of a login failure

The answer to this may be identical to the problem with full blown SQL Server (NTService\MSSQLSERVER) and this is to reset the password. The ironic thing is, there is no password.

Steps are:

  • Right click on the Service in the Services mmc
  • Click Properties
  • Click on the Log On tab
  • The password fields will appear to have entries in them...
  • Blank out both Password fields
  • Click "OK"

This should re-grant access to the service and it should start up again. Weird?

NOTE: if the problem comes back after a few hours or days, then you probably have a group policy which is overriding your settings and it's coming and taking the right away again.

How to get the category title in a post in Wordpress?

You can use

<?php the_category(', '); ?>

which would output them in a comma separated list.

You can also do the same for tags as well:

<?php the_tags('<em>:</em>', ', ', ''); ?>

Detect if HTML5 Video element is playing

I just added that to the media object manually

let media = document.querySelector('.my-video');
media.isplaying = false;

...

if(media.isplaying) //do something

Then just toggle it when i hit play or pause.

Error: Main method not found in class Calculate, please define the main method as: public static void main(String[] args)

Where you have written the code

public class Main {
    public static void main(String args[])
    {
        Calculate obj = new Calculate(1,2,'+');
        obj.getAnswer();
    }
}

Here you have to run the class "Main" instead of the class you created at the start of the program. To do so pls go to Run Configuration and search for this class name"Main" which is having the main method inside this(public static void main(String args[])). And you will get your output.

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

This is what I ended up doing. Hopefully someone might find it useful.

@Transactional
public void deleteGroup(Long groupId) {
    Group group = groupRepository.findById(groupId).orElseThrow();
    group.getUsers().forEach(u -> u.getGroups().remove(group));
    userRepository.saveAll(group.getUsers());
    groupRepository.delete(group);
}

Working with UTF-8 encoding in Python source

In the source header you can declare:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
....

It is described in the PEP 0263:

Then you can use UTF-8 in strings:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

u = 'idzie waz waska drózka'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)

This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).

In addition, it may be worth verifying that your text editor properly encodes your code in UTF-8. Otherwise, you may have invisible characters that are not interpreted as UTF-8.

Haskell: Converting Int to String

The opposite of read is show.

Prelude> show 3
"3"

Prelude> read $ show 3 :: Int
3

c# write text on bitmap

var bmp = new Bitmap(@"path\picture.bmp");
using( Graphics g = Graphics.FromImage( bmp ) )
{
    g.DrawString( ... );
}

picturebox1.Image = bmp;

Remove a fixed prefix/suffix from a string in Bash

Using the =~ operator:

$ string="hello-world"
$ prefix="hell"
$ suffix="ld"
$ [[ "$string" =~ ^$prefix(.*)$suffix$ ]] && echo "${BASH_REMATCH[1]}"
o-wor

jQuery.active function

This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache (where all of jQuery.data() goes).

I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart() and $.ajaxStop() (which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.


When jQuery starts an AJAX request, this happens:

if ( s.global && ! jQuery.active++ ) {
  jQuery.event.trigger( "ajaxStart" );
}

This is what causes the $.ajaxStart() event to fire, the number of connections just went from 0 to 1 (jQuery.active++ isn't 0 after this one, and !0 == true), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend abort via return false or an ajax call complete function runs):

if ( s.global && ! --jQuery.active ) {
  jQuery.event.trigger( "ajaxStop" );
}

This is what causes the $.ajaxStop() event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.

Syntax error near unexpected token 'fi'

The first problem with your script is that you have to put a space after the [.
Type type [ to see what is really happening. It should tell you that [ is an alias to test command, so [ ] in bash is not some special syntax for conditionals, it is just a command on its own. What you should prefer in bash is [[ ]]. This common pitfall is greatly explained here and here.

Another problem is that you didn't quote "$f" which might become a problem later. This is explained here

You can use arithmetic expressions in if, so you don't have to use [ ] or [[ ]] at all in some cases. More info here

Also there's no need to use \n in every echo, because echo places newlines by default. If you want TWO newlines to appear, then use echo -e 'start\n' or echo $'start\n' . This $'' syntax is explained here

To make it completely perfect you should place -- before arbitrary filenames, otherwise rm might treat it as a parameter if the file name starts with dashes. This is explained here.

So here's your script:

#!/bin/bash
echo "start"
for f in *.jpg
do
    fname="${f##*/}"
    echo "fname is $fname"
    if (( fname % 2 == 1 )); then
        echo "removing $fname"
        rm -- "$f"
    fi
done

Is there a way to define a min and max value for EditText in Android?

//still has some problem but Here you can use min, max at any range (positive or negative)

// in filter calss
 @Override
 public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        try {
            // Remove the string out of destination that is to be replaced
            int input;
            String newVal = dest.toString() + source.toString();
            if (newVal.length() == 1 && newVal.charAt(0) == '-') {
                input = min; //allow
            }
            else {
                newVal = dest.toString().substring(0, dstart) + dest.toString().substring(dend, dest.toString().length());
                // Add the new string in
                newVal = newVal.substring(0, dstart) + source.toString() + newVal.substring(dstart, newVal.length());
                input = Integer.parseInt(newVal);
            }

            //int input = Integer.parseInt(dest.toString() + source.toString());

            if (isInRange(min, max, input))
                return null;
        } catch (NumberFormatException nfe) {
        }
        return "";
    }

//also the filler must set as below: in the edit createview
// to allow enter number and backspace.
et.setFilters(new InputFilter[]{new InputFilterMinMax(min >= 10 ?  "0" : String.valueOf(min), max >-10 ? String.valueOf(max) :"0" )});



//and at same time must check range in the TextWatcher()
et.addTextChangedListener(new
 TextWatcher() {

      @Override
      public void afterTextChanged (Editable editable)
      {
         String tmpstr = et.getText().toString();
         if (!tmpstr.isEmpty() && !tmpstr.equals("-") ) {
             int datavalue = Integer.parseInt(tmpstr);
             if ( datavalue >= min || datavalue <= max) {
               // accept data ...     
             }
         }
      }
 });

Collections sort(List<T>,Comparator<? super T>) method example

You probably want something like this:

Collections.sort(students, new Comparator<Student>() {
                     public int compare(Student s1, Student s2) {
                           if(s1.getName() != null && s2.getName() != null && s1.getName().comareTo(s1.getName()) != 0) {
                               return s1.getName().compareTo(s2.getName());
                           } else {
                             return s1.getAge().compareTo(s2.getAge());
                          }
                      }
);

This sorts the students first by name. If a name is missing, or two students have the same name, they are sorted by their age.

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

This ORA error is occurred because of violation of unique constraint.

ORA-00001: unique constraint (constraint_name) violated

This is caused because of trying to execute an INSERT or UPDATE statement that has created a duplicate value in a field restricted by a unique index.

You can resolve this either by

  • changing the constraint to allow duplicates, or
  • drop the unique constraint or you can change your SQL to avoid duplicate inserts

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

Webkit based browsers (like Google Chrome or Safari) has built-in developer tools. In Chrome you can open it Menu->Tools->Developer Tools. The Network tab allows you to see all information about every request and response:

enter image description here

In the bottom of the picture you can see that I've filtered request down to XHR - these are requests made by javascript code.

Tip: log is cleared every time you load a page, at the bottom of the picture, the black dot button will preserve log.

After analyzing requests and responses you can simulate these requests from your web-crawler and extract valuable data. In many cases it will be easier to get your data than parsing HTML, because that data does not contain presentation logic and is formatted to be accessed by javascript code.

Firefox has similar extension, it is called firebug. Some will argue that firebug is even more powerful but I like the simplicity of webkit.

How to format a JavaScript date

Two pure JS one-liners

In this answer I develop JD Smith idea. I was able to shorten the JD Smith regexp

_x000D_
_x000D_
let format= d=> d.toString().replace(/\w+ (\w+) (\d+) (\d+).*/,'$2-$1-$3');_x000D_
_x000D_
console.log( format(Date()) );
_x000D_
_x000D_
_x000D_

Dave also base on JD Smith idea but he avoid regexp and give very nice solution - I short a little his solution (by change split param) and opaque it in wrapper

_x000D_
_x000D_
let format= (d,a=d.toString().split` `)=> a[2]+"-"+a[1]+"-"+a[3];_x000D_
_x000D_
console.log( format(Date()) );
_x000D_
_x000D_
_x000D_

docker mounting volumes on host

This is from the Docker documentation itself, might be of help, simple and plain:

"The host directory is, by its nature, host-dependent. For this reason, you can’t mount a host directory from Dockerfile, the VOLUME instruction does not support passing a host-dir, because built images should be portable. A host directory wouldn’t be available on all potential hosts.".

How can I print literal curly-brace characters in a string and also use .format on it?

The OP wrote this comment:

I was trying to format a small JSON for some purposes, like this: '{"all": false, "selected": "{}"}'.format(data) to get something like {"all": false, "selected": "1,2"}

It's pretty common that the "escaping braces" issue comes up when dealing with JSON.

I suggest doing this:

import json
data = "1,2"
mydict = {"all": "false", "selected": data}
json.dumps(mydict)

It's cleaner than the alternative, which is:

'{{"all": false, "selected": "{}"}}'.format(data)

Using the json library is definitely preferable when the JSON string gets more complicated than the example.

Git asks for username every time I push

The easiest way I found was with this command:

git config --global credential.https://github.com.username <your_username>

This works on a site by site basis and modifies your global git config.

To see the changes, use:

git config --global --edit

In Python, how do I index a list with another list?

A functional approach:

a = [1,"A", 34, -123, "Hello", 12]
b = [0, 2, 5]

from operator import itemgetter

print(list(itemgetter(*b)(a)))
[1, 34, 12]

How can I convert a hex string to a byte array?

Here's a nice fun LINQ example.

public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                     .ToArray();
}

How do I find a default constraint using INFORMATION_SCHEMA?

There seems to be no Default Constraint names in the Information_Schema views.

use SELECT * FROM sysobjects WHERE xtype = 'D' AND name = @name to find a default constraint by name

Copy a git repo without history

Deleting the .git folder is probably the easiest path since you don't want/need the history (as Stephan said).

So you can create a new repo from your latest commit: (How to clone seed/kick-start project without the whole history?)

git clone <git_url>

then delete .git, and afterwards run

git init

Or if you want to reuse your current repo: Make the current commit the only (initial) commit in a Git repository?

Follow the above steps then:

git add .
git commit -m "Initial commit"

Push to your repo.

git remote add origin <github-uri>
git push -u --force origin master

Can't choose class as main class in IntelliJ

Select the folder containing the package tree of these classes, right-click and choose "Mark Directory as -> Source Root"

How do I use setsockopt(SO_REUSEADDR)?

I think you should use SO_LINGER options (with timeout 0). In this case, you connection will close immediately after closing your program; and next restart will be able to bind again.

example:

linger lin;
lin.l_onoff = 0;
lin.l_linger = 0;
setsockopt(fd, SOL_SOCKET, SO_LINGER, (const char *)&lin, sizeof(int));

see definition: http://man7.org/linux/man-pages/man7/socket.7.html

SO_LINGER
          Sets or gets the SO_LINGER option.  The argument is a linger
          structure.

              struct linger {
                  int l_onoff;    /* linger active */
                  int l_linger;   /* how many seconds to linger for */
              };

          When enabled, a close(2) or shutdown(2) will not return until
          all queued messages for the socket have been successfully sent
          or the linger timeout has been reached.  Otherwise, the call
          returns immediately and the closing is done in the background.
          When the socket is closed as part of exit(2), it always
          lingers in the background.

More about SO_LINGER: TCP option SO_LINGER (zero) - when it's required

Calculate AUC in R?

I found some of the solutions here to be slow and/or confusing (and some of them don't handle ties correctly) so I wrote my own data.table based function auc_roc() in my R package mltools.

library(data.table)
library(mltools)

preds <- c(.1, .3, .3, .9)
actuals <- c(0, 0, 1, 1)

auc_roc(preds, actuals)  # 0.875

auc_roc(preds, actuals, returnDT=TRUE)
   Pred CountFalse CountTrue CumulativeFPR CumulativeTPR AdditionalArea CumulativeArea
1:  0.9          0         1           0.0           0.5          0.000          0.000
2:  0.3          1         1           0.5           1.0          0.375          0.375
3:  0.1          1         0           1.0           1.0          0.500          0.875

Set value of hidden input with jquery

Suppose you have a hidden input, named XXX, if you want to assign a value to the following

<script type="text/javascript">

    $(document).ready(function(){
    $('#XXX').val('any value');
    })
</script>

Can you use CSS to mirror/flip text?

direction: rtl; is probably what you are looking for.

How do you remove a specific revision in the git history?

Answers of rado and kareem do nothing for me (only message "Current branch is up to date." appears). Possibly this happens because '^' symbol doesn't work in Windows console. However, according to this comment, replacing '^' by '~1' solves the problem.

git rebase --onto <commit-id>^ <commit-id>

Sending private messages to user

In order for a bot to send a message, you need <client>.send() , the client is where the bot will send a message to(A channel, everywhere in the server, or a PM). Since you want the bot to PM a certain user, you can use message.author as your client. (you can replace author as mentioned user in a message or something, etc)

Hence, the answer is: message.author.send("Your message here.")

I recommend looking up the Discord.js documentation about a certain object's properties whenever you get stuck, you might find a particular function that may serve as your solution.

How to take screenshot of a div with JavaScript?

As far as I know its not possible with javascript.

What you can do for every result create a screenshot, save it somewhere and point the user when clicked on save result. (I guess no of result is only 10 so not a big deal to create 10 jpeg image of results)

remove / reset inherited css from an element

From what I understand you want to use a div that inherits from no class but yours. As mentioned in the previous reply you cannot completely reset a div inheritance. However, what worked for me with that issue was to use another element - one that is not frequent and certainly not used in the current html page. A good example, is to use instead of then customize it to look just like your ideal would.

area { background-color : red; }

java.net.URL read stream to byte[]

The content length is just a HTTP header. You cannot trust it. Just read everything you can from the stream.

Available is definitely wrong. It's just the number of bytes that can be read without blocking.

Another issue is your resource handling. Closing the stream has to happen in any case. try/catch/finally will do that.

Can't compile C program on a Mac after upgrade to Mojave

apue.h dependency was still missing in my /usr/local/include after I managed to fix this problem on Mac OS Catalina following the instructions of this answer

I downloaded the dependency manually from git and placed it in /usr/local/include

How to write DataFrame to postgres table?

Pandas 0.24.0+ solution

In Pandas 0.24.0 a new feature was introduced specifically designed for fast writes to Postgres. You can learn more about it here: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method

import csv
from io import StringIO

from sqlalchemy import create_engine

def psql_insert_copy(table, conn, keys, data_iter):
    # gets a DBAPI connection that can provide a cursor
    dbapi_conn = conn.connection
    with dbapi_conn.cursor() as cur:
        s_buf = StringIO()
        writer = csv.writer(s_buf)
        writer.writerows(data_iter)
        s_buf.seek(0)

        columns = ', '.join('"{}"'.format(k) for k in keys)
        if table.schema:
            table_name = '{}.{}'.format(table.schema, table.name)
        else:
            table_name = table.name

        sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(
            table_name, columns)
        cur.copy_expert(sql=sql, file=s_buf)

engine = create_engine('postgresql://myusername:mypassword@myhost:5432/mydatabase')
df.to_sql('table_name', engine, method=psql_insert_copy)

Python convert decimal to hex

hex_map = {0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:'A', 11:'B', 12:'C', 13:'D', 14:'E', 15:'F'}

def to_hex(n):
    result = ""
    if n == 0:
        return '0'
    while n != 0:
        result += str(hex_map[(n % 16)])
        n = n // 16
    return '0x'+result[::-1]

How to make a JSON call to a url?

You make a bog standard HTTP GET Request. You get a bog standard HTTP Response with an application/json content type and a JSON document as the body. You then parse this.

Since you have tagged this 'JavaScript' (I assume you mean "from a web page in a browser"), and I assume this is a third party service, you're stuck. You can't fetch data from remote URI in JavaScript unless explicit workarounds (such as JSONP) are put in place.

Oh wait, reading the documentation you linked to - JSONP is available, but you must say 'js' not 'json' and specify a callback: format=js&callback=foo

Then you can just define the callback function:

function foo(myData) { 
    // do stuff with myData
}

And then load the data:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = theUrlForTheApi;
document.body.appendChild(script);

Angular is automatically adding 'ng-invalid' class on 'required' fields

Try to add the class for validation dynamically, when the form has been submitted or the field is invalid. Use the form name and add the 'name' attribute to the input. Example with Bootstrap:

<div class="form-group" ng-class="{'has-error': myForm.$submitted && (myForm.username.$invalid && !myForm.username.$pristine)}">
    <label class="col-sm-2 control-label" for="username">Username*</label>
    <div class="col-sm-10 col-md-9">
        <input ng-model="data.username" id="username" name="username" type="text" class="form-control input-md" required>
    </div>
</div>

It is also important, that your form has the ng-submit="" attribute:

<form name="myForm" ng-submit="checkSubmit()" novalidate>
 <!-- input fields here -->
 ....

  <button type="submit">Submit</button>
</form>

You can also add an optional function for validation to the form:

//within your controller (some extras...)

$scope.checkSubmit = function () {

   if ($scope.myForm.$valid) {
        alert('All good...'); //next step!

   }
   else {
        alert('Not all fields valid! Do something...');
    }

 }

Now, when you load your app the class 'has-error' will only be added when the form is submitted or the field has been touched. Instead of:
!myForm.username.$pristine

You could also use:
myForm.username.$dirty

Javascript date regex DD/MM/YYYY

If you are in Javascript already, couldn't you just use Date.Parse() to validate a date instead of using regEx.

RegEx for date is actually unwieldy and hard to get right especially with leap years and all.

Should a function have only one return statement?

I would say it would be incredibly unwise to decide arbitrarily against multiple exit points as I have found the technique to be useful in practice over and over again, in fact I have often refactored existing code to multiple exit points for clarity. We can compare the two approaches thus:-

string fooBar(string s, int? i) {
  string ret = "";
  if(!string.IsNullOrEmpty(s) && i != null) {
    var res = someFunction(s, i);

    bool passed = true;
    foreach(var r in res) {
      if(!r.Passed) {
        passed = false;
        break;
      }
    }

    if(passed) {
      // Rest of code...
    }
  }

  return ret;
}

Compare this to the code where multiple exit points are permitted:-

string fooBar(string s, int? i) {
  var ret = "";
  if(string.IsNullOrEmpty(s) || i == null) return null;

  var res = someFunction(s, i);

  foreach(var r in res) {
      if(!r.Passed) return null;
  }

  // Rest of code...

  return ret;
}

I think the latter is considerably clearer. As far as I can tell the criticism of multiple exit points is a rather archaic point of view these days.

Getting RSA private key from PEM BASE64 Encoded private key file

This is PKCS#1 format of a private key. Try this code. It doesn't use Bouncy Castle or other third-party crypto providers. Just java.security and sun.security for DER sequece parsing. Also it supports parsing of a private key in PKCS#8 format (PEM file that has a header "-----BEGIN PRIVATE KEY-----").

import sun.security.util.DerInputStream;
import sun.security.util.DerValue;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Base64;

public static PrivateKey pemFileLoadPrivateKeyPkcs1OrPkcs8Encoded(File pemFileName) throws GeneralSecurityException, IOException {
        // PKCS#8 format
        final String PEM_PRIVATE_START = "-----BEGIN PRIVATE KEY-----";
        final String PEM_PRIVATE_END = "-----END PRIVATE KEY-----";

        // PKCS#1 format
        final String PEM_RSA_PRIVATE_START = "-----BEGIN RSA PRIVATE KEY-----";
        final String PEM_RSA_PRIVATE_END = "-----END RSA PRIVATE KEY-----";

        Path path = Paths.get(pemFileName.getAbsolutePath());

        String privateKeyPem = new String(Files.readAllBytes(path));

        if (privateKeyPem.indexOf(PEM_PRIVATE_START) != -1) { // PKCS#8 format
            privateKeyPem = privateKeyPem.replace(PEM_PRIVATE_START, "").replace(PEM_PRIVATE_END, "");
            privateKeyPem = privateKeyPem.replaceAll("\\s", "");

            byte[] pkcs8EncodedKey = Base64.getDecoder().decode(privateKeyPem);

            KeyFactory factory = KeyFactory.getInstance("RSA");
            return factory.generatePrivate(new PKCS8EncodedKeySpec(pkcs8EncodedKey));

        } else if (privateKeyPem.indexOf(PEM_RSA_PRIVATE_START) != -1) {  // PKCS#1 format

            privateKeyPem = privateKeyPem.replace(PEM_RSA_PRIVATE_START, "").replace(PEM_RSA_PRIVATE_END, "");
            privateKeyPem = privateKeyPem.replaceAll("\\s", "");

            DerInputStream derReader = new DerInputStream(Base64.getDecoder().decode(privateKeyPem));

            DerValue[] seq = derReader.getSequence(0);

            if (seq.length < 9) {
                throw new GeneralSecurityException("Could not parse a PKCS1 private key.");
            }

            // skip version seq[0];
            BigInteger modulus = seq[1].getBigInteger();
            BigInteger publicExp = seq[2].getBigInteger();
            BigInteger privateExp = seq[3].getBigInteger();
            BigInteger prime1 = seq[4].getBigInteger();
            BigInteger prime2 = seq[5].getBigInteger();
            BigInteger exp1 = seq[6].getBigInteger();
            BigInteger exp2 = seq[7].getBigInteger();
            BigInteger crtCoef = seq[8].getBigInteger();

            RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);

            KeyFactory factory = KeyFactory.getInstance("RSA");

            return factory.generatePrivate(keySpec);
        }

        throw new GeneralSecurityException("Not supported format of a private key");
    }

ERROR in Cannot find module 'node-sass'

Run:

npm rebuild node-sass --force              

and it'll work fine.

Keep CMD open after BAT file executes

Depending on how you are running the command, you can put /k after cmd to keep the window open.

cmd /k my_script.bat

Simply adding cmd /k to the end of your batch file will work too. Credit to Luigi D'Amico who posted about this in the comments below.

Trying to detect browser close event

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<script type="text/javascript" language="javascript">

var validNavigation = false;

function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}

function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
  if (!validNavigation) {

            var ref="load";
      $.ajax({
            type: 'get',
            async: false,
            url: 'logout.php',
 data:
            {
                ref:ref               
            },
             success:function(data)
            {
                console.log(data);
            }
            });
     endSession();
  }
 }

// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
  validNavigation = true;
}
});

// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});

 // Attach the event submit for all forms in the page
 $("form").bind("submit", function() {
 validNavigation = true;
 });

 // Attach the event click for all inputs in the page
 $("input[type=submit]").bind("click", function() {
 validNavigation = true;
 });

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();  
}); 
</script> 

This is used for when logged in user close the browser or browser tab it will automatically logout the user account...

How to draw a rounded Rectangle on HTML Canvas?

I started with @jhoff's solution, but rewrote it to use width/height parameters, and using arcTo makes it quite a bit more terse:

CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) {
  if (w < 2 * r) r = w / 2;
  if (h < 2 * r) r = h / 2;
  this.beginPath();
  this.moveTo(x+r, y);
  this.arcTo(x+w, y,   x+w, y+h, r);
  this.arcTo(x+w, y+h, x,   y+h, r);
  this.arcTo(x,   y+h, x,   y,   r);
  this.arcTo(x,   y,   x+w, y,   r);
  this.closePath();
  return this;
}

Also returning the context so you can chain a little. E.g.:

ctx.roundRect(35, 10, 225, 110, 20).stroke(); //or .fill() for a filled rect

How do you round UP a number in Python?

>>> def roundup(number):
...     return round(number+.5)
>>> roundup(2.3)
3
>>> roundup(19.00000000001)
20

This function requires no modules.

Hadoop "Unable to load native-hadoop library for your platform" warning

This line right here:

export JAVA_LIBRARY_PATH=$HADOOP_HOME/lib/native:$JAVA_LIBRARY_PATH

From KunBetter's answer is where the money is

How can I get a character in a string by index?

Do you mean like this

int index = 2;
string s = "hello";
Console.WriteLine(s[index]);

string also implements IEnumberable<char> so you can also enumerate it like this

foreach (char c in s)
    Console.WriteLine(c);

What's the difference setting Embed Interop Types true and false in Visual Studio?

I noticed that when it's set to false, I'm able to see the value of an item using the debugger. When it was set to true, I was getting an error - item.FullName.GetValue The embedded interop type 'FullName' does not contain a definition for 'QBFC11Lib.IItemInventoryRet' since it was not used in the compiled assembly. Consider casting to object or changing the 'Embed Interop Types' property to true.

Using awk to print all columns from the nth to the last

awk '{out=$2; for(i=3;i<=NF;i++){out=out" "$i}; print out}'

My answer is based on the one of VeeArr, but I noticed it started with a white space before it would print the second column (and the rest). As I only have 1 reputation point, I can't comment on it, so here it goes as a new answer:

start with "out" as the second column and then add all the other columns (if they exist). This goes well as long as there is a second column.

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Just add the following rules to the parent element:

display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */

Here's a sample demo (Resize window to see the image align)

Browser support for Flexbox nowadays is quite good.

For cross-browser compatibility for display: flex and align-items, you can add the older flexbox syntax as well:

display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;

Remove file from SVN repository without deleting local copy

Deleting files and folders

If you want to delete an item from the repository, but keep it locally as an unversioned file/folder, use Extended Context Menu ? Delete (keep local). You have to hold the Shift key while right clicking on the item in the explorer list pane (right pane) in order to see this in the extended context menu.

Delete completely:
right mouse click ? Menu ? Delete

Delete & Keep local:
Shift + right mouse click ? Menu ? Delete

How to remove RVM (Ruby Version Manager) from my system

If the other answers don’t remove RVM throughly enough for you, RVM’s Troubleshooting page contains this section:

How do I completely clean out all traces of RVM from my system, including for system wide installs?

Here is a custom script which we name as cleanout-rvm. While you can definitely use rvm implode as a regular user or rvmsudo rvm implode for a system wide install, this script is useful as it steps completely outside of RVM and cleans out RVM without using RVM itself, leaving no traces.

#!/bin/bash
/usr/bin/sudo rm -rf $HOME/.rvm $HOME/.rvmrc /etc/rvmrc /etc/profile.d/rvm.sh /usr/local/rvm /usr/local/bin/rvm
/usr/bin/sudo /usr/sbin/groupdel rvm
/bin/echo "RVM is removed. Please check all .bashrc|.bash_profile|.profile|.zshrc for RVM source lines and delete
or comment out if this was a Per-User installation."

How do you remove a Cookie in a Java Servlet

In my environment, following code works. Although looks redundant at first glance, cookies[i].setValue(""); and cookies[i].setPath("/"); are necessary to clear the cookie properly.

private void eraseCookie(HttpServletRequest req, HttpServletResponse resp) {
    Cookie[] cookies = req.getCookies();
    if (cookies != null)
        for (Cookie cookie : cookies) {
            cookie.setValue("");
            cookie.setPath("/");
            cookie.setMaxAge(0);
            resp.addCookie(cookie);
        }
}

How to run a PowerShell script from a batch file

If your PowerShell login script is running after 5 minutes (as mine was) on a 2012 server, there is a GPO setting on a server - 'Configure Login script Delay' the default setting 'not configured' this will leave a 5-minute delay before running the login script.

Where to place the 'assets' folder in Android Studio?

follow these steps 

1)file->New->Folder
 there are multiple options like
      aidl folder
      assets folder
      jni folder
2) choose options assets folder
3) then there is option to change path of assets folder if you 
    want to change then check otherwise left that checkbox of cahnge folder location
4) click on finish 

How to generate keyboard events?

Every platform is going to have a different approach to being able to generate keyboard events. This is because they each need to make use of system libraries (and system extensions). For a cross platform solution, you would need to take each of these solutions and wrap then into a platform check to perform the proper approach.

For windows, you might be able to use the pywin32 extension. win32api.keybd_event

win32api.keybd_event

keybd_event(bVk, bScan, dwFlags, dwExtraInfo)

Simulate a keyboard event

Parameters

bVk : BYTE - Virtual-key code
bScan : BYTE - Hardware scan code
dwFlags=0 : DWORD - Flags specifying various function options
dwExtraInfo=0 : DWORD - Additional data associated with keystroke

You will need to investigate pywin32 for how to properly use it, as I have never used it.

Custom Adapter for List View

A more compact example of a custom adapter (using list array as my data):

class MyAdapter extends ArrayAdapter<Object> {
    public ArrayAdapter(Context context, List<MyObject> objectList) {
        super(context, R.layout.my_list_item, R.id.textViewTitle, objectList.toArray());
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = super.getView(position, convertView, parent);
        TextView title = (TextView) row.findViewById(R.id.textViewTitle);
        ImageView icon = (ImageView) row.findViewById(R.id.imageViewAccessory);
        MyObject obj = (MyObject) getItem(position);
        icon.setImageBitmap( ... );
        title.setText(obj.name);
        return row;
    }
}

And this is how to use it:

List<MyObject> objectList = ...
MyAdapter adapter = new MyAdapter(this.getActivity(), objectList);
listView.setAdapter(adapter);

Is there a way to suppress JSHint warning for one given line?

As you can see in the documentation of JSHint you can change options per function or per file. In your case just place a comment in your file or even more local just in the function that uses eval:

/*jshint evil:true */

function helloEval(str) {
    /*jshint evil:true */
    eval(str);
}

Test if object implements interface

I had a situation where I was passing a variable to a method and wasn't sure if it was going to be an interface or an object.

The goals were:

  1. If item is an interface, instantiate an object based on that interface with the interface being a parameter in the constructor call.
  2. If the item is an object, return a null since the constuctor for my calls are expecting an interface and I didn't want the code to tank.

I achieved this with the following:

    if(!typeof(T).IsClass)
    {
       // If your constructor needs arguments...
       object[] args = new object[] { my_constructor_param };
       return (T)Activator.CreateInstance(typeof(T), args, null);
    }
    else
       return default(T);

When do you use Java's @Override annotation and why?

There are many good answers here, so let me offer another way to look at it...

There is no overkill when you are coding. It doesn't cost you anything to type @override, but the savings can be immense if you misspelled a method name or got the signature slightly wrong.

Think about it this way: In the time you navigated here and typed this post, you pretty much used more time than you will spend typing @override for the rest of your life; but one error it prevents can save you hours.

Java does all it can to make sure you didn't make any mistakes at edit/compile time, this is a virtually free way to solve an entire class of mistakes that aren't preventable in any other way outside of comprehensive testing.

Could you come up with a better mechanism in Java to ensure that when the user intended to override a method, he actually did?

Another neat effect is that if you don't provide the annotation it will warn you at compile time that you accidentally overrode a parent method--something that could be significant if you didn't intend to do it.

Run Bash Command from PHP

Your shell_exec is executed by www-data user, from its directory. You can try

putenv("PATH=/home/user/bin/:" .$_ENV["PATH"]."");

Where your script is located in /home/user/bin Later on you can

$output = "<pre>".shell_exec("scriptname v1 v2")."</pre>";
echo $output;

To display the output of command. (Alternatively, without exporting path, try giving entire path of your script instead of just ./script.sh

Difference between e.target and e.currentTarget

make an example:

var body = document.body,
    btn = document.getElementById( 'id' );
body.addEventListener( 'click', function( event ) {
    console.log( event.currentTarget === body );
    console.log( event.target === btn );
}, false );

when you click 'btn', and 'true' and 'true' will be appeared!

Find the most frequent number in a NumPy array

Starting in Python 3.4, the standard library includes the statistics.mode function to return the single most common data point.

from statistics import mode

mode([1, 2, 3, 1, 2, 1, 1, 1, 3, 2, 2, 1])
# 1

If there are multiple modes with the same frequency, statistics.mode returns the first one encountered.


Starting in Python 3.8, the statistics.multimode function returns a list of the most frequently occurring values in the order they were first encountered:

from statistics import multimode

multimode([1, 2, 3, 1, 2])
# [1, 2]

Matrix Multiplication in pure Python?

The fault occurs here:

C[i][j]+=A[i][k]*B[k][j]

It crashes when k=2. This is because the tuple A[i] has only 2 values, and therefore you can only call it up to A[i][1] before it errors.

EDIT: Listen to Gerard's answer too, your C is wrong. It should be C=[[0 for row in range(len(A))] for col in range(len(A[0]))].

Just a tip: you could replace the first loop with a multiplication, so it would be C=[[0]*len(A) for col in range(len(A[0]))]

How to comment lines in rails html.erb files?

Note that if you want to comment out a single line of printing erb you should do like this

<%#= ["Buck", "Papandreou"].join(" you ") %>

How to elegantly check if a number is within a range?

How about something like this?

if (theNumber.isBetween(low, high, IntEx.Bounds.INCLUSIVE_INCLUSIVE))
{
}

with the extension method as follows (tested):

public static class IntEx
{
    public enum Bounds 
    {
        INCLUSIVE_INCLUSIVE, 
        INCLUSIVE_EXCLUSIVE, 
        EXCLUSIVE_INCLUSIVE, 
        EXCLUSIVE_EXCLUSIVE
    }

    public static bool isBetween(this int theNumber, int low, int high, Bounds boundDef)
    {
        bool result;
        switch (boundDef)
        {
            case Bounds.INCLUSIVE_INCLUSIVE:
                result = ((low <= theNumber) && (theNumber <= high));
                break;
            case Bounds.INCLUSIVE_EXCLUSIVE:
                result = ((low <= theNumber) && (theNumber < high));
                break;
            case Bounds.EXCLUSIVE_INCLUSIVE:
                result = ((low < theNumber) && (theNumber <= high));
                break;
            case Bounds.EXCLUSIVE_EXCLUSIVE:
                result = ((low < theNumber) && (theNumber < high));
                break;
            default:
                throw new System.ArgumentException("Invalid boundary definition argument");
        }
        return result;
    }
}

How to get an isoformat datetime string including the default timezone?

Something like the following example. Note I'm in Eastern Australia (UTC + 10 hours at the moment).

>>> import datetime
>>> dtnow = datetime.datetime.now();dtutcnow = datetime.datetime.utcnow()
>>> dtnow
datetime.datetime(2010, 8, 4, 9, 33, 9, 890000)
>>> dtutcnow
datetime.datetime(2010, 8, 3, 23, 33, 9, 890000)
>>> delta = dtnow - dtutcnow
>>> delta
datetime.timedelta(0, 36000)
>>> hh,mm = divmod((delta.days * 24*60*60 + delta.seconds + 30) // 60, 60)
>>> hh,mm
(10, 0)
>>> "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm)
'2010-08-04T09:33:09.890000+10:00'
>>>

How do I create a readable diff of two spreadsheets using git diff?

I found an openoffice macro here that will invoke openoffice's compare documents function on two files. Unfortunately, openoffice's spreadsheet compare seems a little flaky; I just had the 'Reject All' button insert a superfluous column in my document.

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

Doing

SET FOREIGN_KEY_CHECKS=0;

before the Operation can also do the trick.

How to create a self-signed certificate for a domain name for development?

Another option is to create a self-signed certificate that allows you to specify the domain name per website. This means you can use it across many domain names.

In IIS Manager

  1. Click machine name node
  2. Open Server Certificates
  3. In Actions panel, choose 'Create Self-Signed Certificate'
  4. In 'Specify a friendly name...' name it *Dev (select 'Personal' from type list)
  5. Save

Now, on your website in IIS...

  1. Manage the bindings
  2. Create a new binding for Https
  3. Choose your self-signed certificate from the list
  4. Once selected, the domain name box will become enabled and you'll be able to input your domain name.

enter image description here

Inline instantiation of a constant List

You are looking for a simple code, like this:

    List<string> tagList = new List<string>(new[]
    {
         "A"
        ,"B"
        ,"C"
        ,"D"
        ,"E"
    });

Setting timezone in Python

Be aware that running

import os
os.system("tzutil /s \"Central Standard Time\"");

will alter Windows system time, NOT just the local python environment time (so is definitley NOT the same as:

>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()

which will only set in the current environment time (in Unix only)

OpenCV - Apply mask to a color image

Well, here is a solution if you want the background to be other than a solid black color. We only need to invert the mask and apply it in a background image of the same size and then combine both background and foreground. A pro of this solution is that the background could be anything (even other image).

This example is modified from Hough Circle Transform. First image is the OpenCV logo, second the original mask, third the background + foreground combined.

apply mask and get a customized background

# http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html
import cv2
import numpy as np

# load the image
img = cv2.imread('E:\\FOTOS\\opencv\\opencv_logo.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# detect circles
gray = cv2.medianBlur(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 5)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=50, minRadius=0, maxRadius=0)
circles = np.uint16(np.around(circles))

# draw mask
mask = np.full((img.shape[0], img.shape[1]), 0, dtype=np.uint8)  # mask is only 
for i in circles[0, :]:
    cv2.circle(mask, (i[0], i[1]), i[2], (255, 255, 255), -1)

# get first masked value (foreground)
fg = cv2.bitwise_or(img, img, mask=mask)

# get second masked value (background) mask must be inverted
mask = cv2.bitwise_not(mask)
background = np.full(img.shape, 255, dtype=np.uint8)
bk = cv2.bitwise_or(background, background, mask=mask)

# combine foreground+background
final = cv2.bitwise_or(fg, bk)

Note: It is better to use the opencv methods because they are optimized.

Java 8 stream reverse order

Here's the solution I've come up with:

private static final Comparator<Integer> BY_ASCENDING_ORDER = Integer::compare;
private static final Comparator<Integer> BY_DESCENDING_ORDER = BY_ASCENDING_ORDER.reversed();

then using those comparators:

IntStream.range(-range, 0).boxed().sorted(BY_DESCENDING_ORDER).forEach(// etc...

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

Webpack and Browserify

Webpack and Browserify do pretty much the same job, which is processing your code to be used in a target environment (mainly browser, though you can target other environments like Node). Result of such processing is one or more bundles - assembled scripts suitable for targeted environment.

For example, let's say you wrote ES6 code divided into modules and want to be able to run it in a browser. If those modules are Node modules, the browser won't understand them since they exist only in the Node environment. ES6 modules also won't work in older browsers like IE11. Moreover, you might have used experimental language features (ES next proposals) that browsers don't implement yet so running such script would just throw errors. Tools like Webpack and Browserify solve these problems by translating such code to a form a browser is able to execute. On top of that, they make it possible to apply a huge variety of optimisations on those bundles.

However, Webpack and Browserify differ in many ways, Webpack offers many tools by default (e.g. code splitting), while Browserify can do this only after downloading plugins but using both leads to very similar results. It comes down to personal preference (Webpack is trendier). Btw, Webpack is not a task runner, it is just processor of your files (it processes them by so called loaders and plugins) and it can be run (among other ways) by a task runner.


Webpack Dev Server

Webpack Dev Server provides a similar solution to Browsersync - a development server where you can deploy your app rapidly as you are working on it, and verify your development progress immediately, with the dev server automatically refreshing the browser on code changes or even propagating changed code to browser without reloading with so called hot module replacement.


Task runners vs NPM scripts

I've been using Gulp for its conciseness and easy task writing, but have later found out I need neither Gulp nor Grunt at all. Everything I have ever needed could have been done using NPM scripts to run 3rd-party tools through their API. Choosing between Gulp, Grunt or NPM scripts depends on taste and experience of your team.

While tasks in Gulp or Grunt are easy to read even for people not so familiar with JS, it is yet another tool to require and learn and I personally prefer to narrow my dependencies and make things simple. On the other hand, replacing these tasks with the combination of NPM scripts and (propably JS) scripts which run those 3rd party tools (eg. Node script configuring and running rimraf for cleaning purposes) might be more challenging. But in the majority of cases, those three are equal in terms of their results.


Examples

As for the examples, I suggest you have a look at this React starter project, which shows you a nice combination of NPM and JS scripts covering the whole build and deploy process. You can find those NPM scripts in package.json in the root folder, in a property named scripts. There you will mostly encounter commands like babel-node tools/run start. Babel-node is a CLI tool (not meant for production use), which at first compiles ES6 file tools/run (run.js file located in tools) - basically a runner utility. This runner takes a function as an argument and executes it, which in this case is start - another utility (start.js) responsible for bundling source files (both client and server) and starting the application and development server (the dev server will be probably either Webpack Dev Server or Browsersync).

Speaking more precisely, start.js creates both client and server side bundles, starts an express server and after a successful launch initializes Browser-sync, which at the time of writing looked like this (please refer to react starter project for the newest code).

const bs = Browsersync.create();  
bs.init({
      ...(DEBUG ? {} : { notify: false, ui: false }),

      proxy: {
        target: host,
        middleware: [wpMiddleware, ...hotMiddlewares],
      },

      // no need to watch '*.js' here, webpack will take care of it for us,
      // including full page reloads if HMR won't work
      files: ['build/content/**/*.*'],
}, resolve)

The important part is proxy.target, where they set server address they want to proxy, which could be http://localhost:3000, and Browsersync starts a server listening on http://localhost:3001, where the generated assets are served with automatic change detection and hot module replacement. As you can see, there is another configuration property files with individual files or patterns Browser-sync watches for changes and reloads the browser if some occur, but as the comment says, Webpack takes care of watching js sources by itself with HMR, so they cooperate there.

Now I don't have any equivalent example of such Grunt or Gulp configuration, but with Gulp (and somewhat similarly with Grunt) you would write individual tasks in gulpfile.js like

gulp.task('bundle', function() {
  // bundling source files with some gulp plugins like gulp-webpack maybe
});

gulp.task('start', function() {
  // starting server and stuff
});

where you would be doing essentially pretty much the same things as in the starter-kit, this time with task runner, which solves some problems for you, but presents its own issues and some difficulties during learning the usage, and as I say, the more dependencies you have, the more can go wrong. And that is the reason I like to get rid of such tools.

Upload file to SFTP using PowerShell

Using PuTTY's pscp.exe (which I have in an $env:path directory):

pscp -sftp -pw passwd c:\filedump\* user@host:/Outbox/
mv c:\filedump\* c:\backup\*

How to style components using makeStyles and still have lifecycle methods in Material UI?

What we ended up doing is stopped using the class components and created Functional Components, using useEffect() from the Hooks API for lifecycle methods. This allows you to still use makeStyles() with Lifecycle Methods without adding the complication of making Higher-Order Components. Which is much simpler.

Example:

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Redirect } from 'react-router-dom';

import { Container, makeStyles } from '@material-ui/core';

import LogoButtonCard from '../molecules/Cards/LogoButtonCard';

const useStyles = makeStyles(theme => ({
  root: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    margin: theme.spacing(1)
  },
  highlight: {
    backgroundColor: 'red',
  }
}));

// Highlight is a bool
const Welcome = ({highlight}) => { 
  const [userName, setUserName] = useState('');
  const [isAuthenticated, setIsAuthenticated] = useState(true);
  const classes = useStyles();

  useEffect(() => {
    axios.get('example.com/api/username/12')
         .then(res => setUserName(res.userName));
  }, []);

  if (!isAuthenticated()) {
    return <Redirect to="/" />;
  }
  return (
    <Container maxWidth={false} className={highlight ? classes.highlight : classes.root}>
      <LogoButtonCard
        buttonText="Enter"
        headerText={isAuthenticated && `Welcome, ${userName}`}
        buttonAction={login}
      />
   </Container>
   );
  }
}

export default Welcome;

Get Selected value from dropdown using JavaScript

Maybe it's the comma in your if condition.

function answers() {
var answer=document.getElementById("mySelect");
 if(answer[answer.selectedIndex].value == "To measure time.") {
  alert("That's correct!"); 
 }
}

You can also write it like this.

function answers(){
 document.getElementById("mySelect").value!="To measure time."||(alert('That's correct!'))
}

Loop through a comma-separated shell variable

#/bin/bash   
TESTSTR="abc,def,ghij"

for i in $(echo $TESTSTR | tr ',' '\n')
do
echo $i
done

I prefer to use tr instead of sed, becouse sed have problems with special chars like \r \n in some cases.

other solution is to set IFS to certain separator

How to open a WPF Popup when another control is clicked, using XAML markup only?

another way to do it:

<Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
                    <StackPanel>
                        <Image Source="{Binding ProductImage,RelativeSource={RelativeSource TemplatedParent}}" Stretch="Fill" Width="65" Height="85"/>
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        <Button x:Name="myButton" Width="40" Height="10">
                            <Popup Width="100" Height="70" IsOpen="{Binding ElementName=myButton,Path=IsMouseOver, Mode=OneWay}">
                                <StackPanel Background="Yellow">
                                    <ItemsControl ItemsSource="{Binding Produkt.SubProducts}"/>
                                </StackPanel>
                            </Popup>
                        </Button>
                    </StackPanel>
                </Border>

Swift presentViewController

Try this:

let vc = ViewController() //change this to your class name
self.presentViewController(vc, animated: true, completion: nil)

With Swift3:

self.present(vc, animated: true, completion: nil)

Error: Configuration with name 'default' not found in Android Studio

I also facing this issue but i follow the following steps:-- 1) I add module(Library) to a particular folder name ThirdPartyLib

To resolve this issue i go settings.gradle than just add follwing:-

project(':').projectDir = new File('ThirdPartyLib/')

:- is module name...

Finishing current activity from a fragment

This does not need assertion, Latest update in fragment in android JetPack

requireActivity().finish();

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

You could use feature detection to see if browser is IE10 or greater like so:

var isIE = false;
if (window.navigator.msPointerEnabled) {
    isIE = true;
}

Only true if > IE9

How to restart kubernetes nodes?

Get nodes

kubectl get nodes

Result:

NAME            STATUS     AGE
192.168.1.157   NotReady   42d
192.168.1.158   Ready      42d
192.168.1.159   Ready      42d

Describe node

Here is a NotReady on the node of 192.168.1.157. Then debugging this notready node, and you can read offical documents - Application Introspection and Debugging.

kubectl describe node 192.168.1.157

Partial Result:

Conditions:
Type          Status          LastHeartbeatTime                       LastTransitionTime                      Reason                  Message
----          ------          -----------------                       ------------------                      ------                  -------
OutOfDisk     Unknown         Sat, 28 Dec 2016 12:56:01 +0000         Sat, 28 Dec 2016 12:56:41 +0000         NodeStatusUnknown       Kubelet stopped posting node status.
Ready         Unknown         Sat, 28 Dec 2016 12:56:01 +0000         Sat, 28 Dec 2016 12:56:41 +0000         NodeStatusUnknown       Kubelet stopped posting node status.

There is a OutOfDisk on my node, then Kubelet stopped posting node status. So, I must free some disk space, using the command of df on my Ubuntu14.04 I can check the details of memory, and using the command of docker rmi image_id/image_name under the role of su I can remove the useless images.

Login in node

Login in 192.168.1.157 by using ssh, like ssh [email protected], and switch to the 'su' by sudo su;

Restart kubelet

/etc/init.d/kubelet restart

Result:

stop: Unknown instance: 
kubelet start/running, process 59261

Get nodes again

On the master:

kubectl get nodes

Result:

NAME            STATUS    AGE
192.168.1.157   Ready     42d
192.168.1.158   Ready     42d
192.168.1.159   Ready     42d

Ok, that node works fine.

Here is a reference: Kubernetes

Python Create unix timestamp five minutes in the future

def expiration_time():
    import datetime,calendar
    timestamp = calendar.timegm(datetime.datetime.now().timetuple())
    returnValue = datetime.timedelta(minutes=5).total_seconds() + timestamp
    return returnValue

How to change Named Range Scope

I added some additional lines of code to JS20'07'11's previous Makro to make sure that the name of the sheet's Named Ranges isn't already a name of the workbook's Named Ranges. Without these lines the already definied workbook scooped Named range is deleted and replaced.

Public Sub RescopeNamedRangesToWorkbookV2()
Dim wb As Workbook
Dim ws As Worksheet
Dim objNameWs As Name
Dim objNameWb As Name
Dim sWsName As String
Dim sWbName As String
Dim sRefersTo As String
Dim sObjName As String
Set wb = ActiveWorkbook
Set ws = ActiveSheet
sWsName = ws.Name
sWbName = wb.Name

'Loop through names in worksheet.
For Each objNameWs In ws.Names


'Check name is visble.
    If objNameWs.Visible = True Then
'Check name refers to a range on the active sheet.
        If InStr(1, objNameWs.RefersTo, sWsName, vbTextCompare) Then
            sRefersTo = objNameWs.RefersTo
            sObjName = objNameWs.Name
'Check name is scoped to the worksheet.
            If objNameWs.Parent.Name <> sWbName Then
'Delete the current name scoped to worksheet replacing with workbook scoped name.
                sObjName = Mid(sObjName, InStr(1, sObjName, "!") + 1, Len(sObjName))
'Check to see if there already is a Named Range with the same Name with the full workbook scope.
                For Each objNameWb In wb.Names
                    If sObjName = objNameWb.Name Then
                    MsgBox "There is already a Named range with ""Workbook scope"" named """ + sObjName + """. Change either Named Range names or delete one before running this Macro."
                    Exit Sub
                    End If
                Next objNameWb
                objNameWs.Delete
                wb.Names.Add Name:=sObjName, RefersTo:=sRefersTo
            End If
        End If
    End If
Next objNameWs
End Sub

How to prevent rm from reporting that a file was not found?

I had same issue for cshell. The only solution I had was to create a dummy file that matched pattern before "rm" in my script.

Best way to combine two or more byte arrays in C#

For primitive types (including bytes), use System.Buffer.BlockCopy instead of System.Array.Copy. It's faster.

I timed each of the suggested methods in a loop executed 1 million times using 3 arrays of 10 bytes each. Here are the results:

  1. New Byte Array using System.Array.Copy - 0.2187556 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 0.1406286 seconds
  3. IEnumerable<byte> using C# yield operator - 0.0781270 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 0.0781270 seconds

I increased the size of each array to 100 elements and re-ran the test:

  1. New Byte Array using System.Array.Copy - 0.2812554 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 0.2500048 seconds
  3. IEnumerable<byte> using C# yield operator - 0.0625012 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 0.0781265 seconds

I increased the size of each array to 1000 elements and re-ran the test:

  1. New Byte Array using System.Array.Copy - 1.0781457 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 1.0156445 seconds
  3. IEnumerable<byte> using C# yield operator - 0.0625012 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 0.0781265 seconds

Finally, I increased the size of each array to 1 million elements and re-ran the test, executing each loop only 4000 times:

  1. New Byte Array using System.Array.Copy - 13.4533833 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 13.1096267 seconds
  3. IEnumerable<byte> using C# yield operator - 0 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 0 seconds

So, if you need a new byte array, use

byte[] rv = new byte[a1.Length + a2.Length + a3.Length];
System.Buffer.BlockCopy(a1, 0, rv, 0, a1.Length);
System.Buffer.BlockCopy(a2, 0, rv, a1.Length, a2.Length);
System.Buffer.BlockCopy(a3, 0, rv, a1.Length + a2.Length, a3.Length);

But, if you can use an IEnumerable<byte>, DEFINITELY prefer LINQ's Concat<> method. It's only slightly slower than the C# yield operator, but is more concise and more elegant.

IEnumerable<byte> rv = a1.Concat(a2).Concat(a3);

If you have an arbitrary number of arrays and are using .NET 3.5, you can make the System.Buffer.BlockCopy solution more generic like this:

private byte[] Combine(params byte[][] arrays)
{
    byte[] rv = new byte[arrays.Sum(a => a.Length)];
    int offset = 0;
    foreach (byte[] array in arrays) {
        System.Buffer.BlockCopy(array, 0, rv, offset, array.Length);
        offset += array.Length;
    }
    return rv;
}

*Note: The above block requires you adding the following namespace at the the top for it to work.

using System.Linq;

To Jon Skeet's point regarding iteration of the subsequent data structures (byte array vs. IEnumerable<byte>), I re-ran the last timing test (1 million elements, 4000 iterations), adding a loop that iterates over the full array with each pass:

  1. New Byte Array using System.Array.Copy - 78.20550510 seconds
  2. New Byte Array using System.Buffer.BlockCopy - 77.89261900 seconds
  3. IEnumerable<byte> using C# yield operator - 551.7150161 seconds
  4. IEnumerable<byte> using LINQ's Concat<> - 448.1804799 seconds

The point is, it is VERY important to understand the efficiency of both the creation and the usage of the resulting data structure. Simply focusing on the efficiency of the creation may overlook the inefficiency associated with the usage. Kudos, Jon.

How do I tell if a regular file does not exist in Bash?

The test command ([ here) has a "not" logical operator which is the exclamation point (similar to many other languages). Try this:

if [ ! -f /tmp/foo.txt ]; then
    echo "File not found!"
fi

Is it possible to write to the console in colour in .NET?

Yes, it is possible as follows. These colours can be used in a console application to view some errors in red, etc.

Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;//after this line every text will be white on blue background
Console.WriteLine("White on blue.");
Console.WriteLine("Another line.");
Console.ResetColor();//reset to the defoult colour

Applying an ellipsis to multiline text

I have just been playing around a little bit with this concept. Basically, if you are ok with potentially having a pixel or so cut off from your last character, here is a pure css and html solution:

The way this works is by absolutely positioning a div below the viewable region of a viewport. We want the div to offset up into the visible region as our content grows. If the content grows too much, our div will offset too high, so upper bound the height our content can grow.

HTML:

<div class="text-container">
  <span class="text-content">
    PUT YOUR TEXT HERE
    <div class="ellipsis">...</div> // You could even make this a pseudo-element
  </span>
</div>

CSS:

.text-container {
    position: relative;
    display: block;
    color: #838485;
    width: 24em;
    height: calc(2em + 5px); // This is the max height you want to show of the text. A little extra space is for characters that extend below the line like 'j'
    overflow: hidden;
    white-space: normal;
}

.text-content {
  word-break: break-all;
  position: relative;
  display: block;
  max-height: 3em;       // This prevents the ellipsis element from being offset too much. It should be 1 line height greater than the viewport 
}

.ellipsis {
  position: absolute;
  right: 0;
  top: calc(4em + 2px - 100%); // Offset grows inversely with content height. Initially extends below the viewport, as content grows it offsets up, and reaches a maximum due to max-height of the content
  text-align: left;
  background: white;
}

I have tested this in Chrome, FF, Safari, and IE 11.

You can check it out here: http://codepen.io/puopg/pen/vKWJwK

You might even be able to alleviate the abrupt cut off of the character with some CSS magic.

EDIT: I guess one thing that this imposes is word-break: break-all since otherwise the content would not extend to the very end of the viewport. :(

What is the difference between supervised learning and unsupervised learning?

Supervised learning: say a kid goes to kinder-garden. here teacher shows him 3 toys-house,ball and car. now teacher gives him 10 toys. he will classify them in 3 box of house,ball and car based on his previous experience. so kid was first supervised by teachers for getting right answers for few sets. then he was tested on unknown toys. aa

Unsupervised learning: again kindergarten example.A child is given 10 toys. he is told to segment similar ones. so based on features like shape,size,color,function etc he will try to make 3 groups say A,B,C and group them. bb

The word Supervise means you are giving supervision/instruction to machine to help it find answers. Once it learns instructions, it can easily predict for new case.

Unsupervised means there is no supervision or instruction how to find answers/labels and machine will use its intelligence to find some pattern in our data. Here it will not make prediction, it will just try to find clusters which has similar data.

Set default time in bootstrap-datetimepicker

Set a default input value as per this GitHub issue.

HTML

<input type="text" id="datetimepicker-input"></input>

jQuery

var d = new Date();

var month = d.getMonth()+1;
var day = d.getDate();

var output = d.getFullYear() + '/' +
(month<10 ? '0' : '') + month + '/' +
(day<10 ? '0' : '') + day;

$("#datetimepicker-input").val(output + " 00:01:00");

jsFiddle
JavaScript date source

EDIT - setLocalDate/setDate

var d = new Date();
var month = d.getMonth();
var day = d.getDate();
var year = d.getFullYear();

$('#startdatetime-from').datetimepicker({
    language: 'en',
    format: 'yyyy-MM-dd hh:mm'
});
$("#startdatetime-from").data('DateTimePicker').setLocalDate(new Date(year, month, day, 00, 01));

jsFiddle

Await operator can only be used within an Async method

You can only use await in an async method, and Main cannot be async.

You'll have to use your own async-compatible context, call Wait on the returned Task in the Main method, or just ignore the returned Task and just block on the call to Read. Note that Wait will wrap any exceptions in an AggregateException.

If you want a good intro, see my async/await intro post.

How to switch back to 'master' with git?

According to the Git Cheatsheet you have to create the branch first

git branch [branchName]

and then

git checkout [branchName]

UIView background color in Swift

The response by @Miknash and @wolfgang gutierrez barrera was helpful to me. Only difference was I had to add rgbValue: to the function call.

UIColorFromHex(rgbValue: 0xA6D632,alpha: 1 ) like so

T-SQL: Looping through an array of known values

Make a connection to your DB using a procedural programming language (here Python), and do the loop there. This way you can do complicated loops as well.

# make a connection to your db
import pyodbc
conn = pyodbc.connect('''
                        Driver={ODBC Driver 13 for SQL Server};
                        Server=serverName;
                        Database=DBname;
                        UID=userName;
                        PWD=password;
                      ''')
cursor = conn.cursor()

# run sql code
for id in [4, 7, 12, 22, 19]:
  cursor.execute('''
    exec p_MyInnerProcedure {}
  '''.format(id))