Programs & Examples On #Cornerradius

is for questions dealing with the radius used when drawing rounded corners for a layer's background.

How to set corner radius of imageView?

in swift 3 'CGRectGetWidth' has been replaced by property 'CGRect.width'

    view.layer.cornerRadius = view.frame.width/4.0
    view.clipsToBounds = true

How to set cornerRadius for only top-left and top-right corner of a UIView?

Another version of Stephane's answer.

import UIKit

    class RoundCornerView: UIView {
    var corners : UIRectCorner = [.topLeft,.topRight,.bottomLeft,.bottomRight]
        var roundCornerRadius : CGFloat = 0.0
        override func layoutSubviews() {
            super.layoutSubviews()
            if corners.rawValue > 0 && roundCornerRadius > 0.0 {
                self.roundCorners(corners: corners, radius: roundCornerRadius)
            }
        }
        private func roundCorners(corners: UIRectCorner, radius: CGFloat) {
            let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            layer.mask = mask
        }

    }

How is Docker different from a virtual machine?

With a virtual machine, we have a server, we have a host operating system on that server, and then we have a hypervisor. And then running on top of that hypervisor, we have any number of guest operating systems with an application and its dependent binaries, and libraries on that server. It brings a whole guest operating system with it. It's quite heavyweight. Also there's a limit to how much you can actually put on each physical machine.

Enter image description here

Docker containers on the other hand, are slightly different. We have the server. We have the host operating system. But instead a hypervisor, we have the Docker engine, in this case. In this case, we're not bringing a whole guest operating system with us. We're bringing a very thin layer of the operating system, and the container can talk down into the host OS in order to get to the kernel functionality there. And that allows us to have a very lightweight container.

All it has in there is the application code and any binaries and libraries that it requires. And those binaries and libraries can actually be shared across different containers if you want them to be as well. And what this enables us to do, is a number of things. They have much faster startup time. You can't stand up a single VM in a few seconds like that. And equally, taking them down as quickly.. so we can scale up and down very quickly and we'll look at that later on.

Enter image description here

Every container thinks that it’s running on its own copy of the operating system. It’s got its own file system, own registry, etc. which is a kind of a lie. It’s actually being virtualized.

Get my phone number in android

Robi Code is work for me, just put if !null so that if phone number is null, user can fill the phone number by him/her self.

editTextPhoneNumber = (EditText) findViewById(R.id.editTextPhoneNumber);
TelephonyManager tMgr;
tMgr= (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
if (mPhoneNumber != null){
editTextPhoneNumber.setText(mPhoneNumber);
}

Import-CSV and Foreach

You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):

Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
   Write-Host $_.IP1
   Write-Host $_.IP2
   ...
}

How to convert string date to Timestamp in java?

tl;dr

java.sql.Timestamp                  
.valueOf(                           // Class-method parses SQL-style formatted date-time strings.
    "2007-11-11 12:13:14"
)                                   // Returns a `Timestamp` object.
.toInstant()                        // Converts from terrible legacy classes to modern *java.time* class.

java.sql.Timestamp.valueOf parses SQL format

If you can use the full four digits for the year, your input string of 2007-11-11 12:13:14 would be in standard SQL format assuming this value is meant to be in UTC time zone.

The java.sql.Timestamp class has a valueOf method to directly parse such strings.

String input = "2007-11-11 12:13:14" ;
java.sql.Timestamp ts = java.sql.Timestamp.valueOf( input ) ;

java.time

In Java 8 and later, the java.time framework makes it easier to verify the results. The j.s.Timestamp class has a nasty habit of implicitly applying your JVM’s current default timestamp when generating a string representation via its toString method. In contrast, the java.time classes by default use the standard ISO 8601 formats.

System.out.println( "Output: " + ts.toInstant().toString() );

How to get the path of current worksheet in VBA?

Always nice to have:

Dim myPath As String     
Dim folderPath As String 

folderPath = Application.ActiveWorkbook.Path    
myPath = Application.ActiveWorkbook.FullName

Python: CSV write by column rather than row

wr.writerow(item)  #column by column
wr.writerows(item) #row by row

This is quite simple if your goal is just to write the output column by column.

If your item is a list:

yourList = []

with open('yourNewFileName.csv', 'w', ) as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    for word in yourList:
        wr.writerow([word])

What is the best way to generate a unique and short file name in Java

I use current milliseconds with random numbers

i.e

Random random=new Random();
String ext = ".jpeg";
File dir = new File("/home/pregzt");
String name = String.format("%s%s",System.currentTimeMillis(),random.nextInt(100000)+ext);
File file = new File(dir, name);

macro for Hide rows in excel 2010

Well, you're on the right path, Benno!

There are some tips regarding VBA programming that might help you out.

  1. Use always explicit references to the sheet you want to interact with. Otherwise, Excel may 'assume' your code applies to the active sheet and eventually you'll see it screws your spreadsheet up.

  2. As lionz mentioned, get in touch with the native methods Excel offers. You might use them on most of your tricks.

  3. Explicitly declare your variables... they'll show the list of methods each object offers in VBA. It might save your time digging on the internet.

Now, let's have a draft code...

Remember this code must be within the Excel Sheet object, as explained by lionz. It only applies to Sheet 2, is up to you to adapt it to both Sheet 2 and Sheet 3 in the way you prefer.

Hope it helps!

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim oSheet As Excel.Worksheet

    'We only want to do something if the changed cell is B6, right?
    If Target.Address = "$B$6" Then

        'Checks if it's a number...
        If IsNumeric(Target.Value) Then

            'Let's avoid values out of your bonds, correct?
            If Target.Value > 0 And Target.Value < 51 Then

                'Let's assign the worksheet we'll show / hide rows to one variable and then
                '   use only the reference to the variable itself instead of the sheet name.
                '   It's safer.

                'You can alternatively replace 'sheet 2' by 2 (without quotes) which will represent
                '   the sheet index within the workbook
                Set oSheet = ActiveWorkbook.Sheets("Sheet 2")

                'We'll unhide before hide, to ensure we hide the correct ones
                oSheet.Range("A7:A56").EntireRow.Hidden = False

                oSheet.Range("A" & Target.Value + 7 & ":A56").EntireRow.Hidden = True

            End If

        End If

    End If

End Sub

What is the best way to create and populate a numbers table?

Here is a short and fast in-memory solution that I came up with utilizing the Table Valued Constructors introduced in SQL Server 2008:

It will return 1,000,000 rows, however you can either add/remove CROSS JOINs, or use TOP clause to modify this.

;WITH v AS (SELECT * FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) v(z))

SELECT N FROM (SELECT ROW_NUMBER() OVER (ORDER BY v1.z)-1 N FROM v v1 
    CROSS JOIN v v2 CROSS JOIN v v3 CROSS JOIN v v4 CROSS JOIN v v5 CROSS JOIN v v6) Nums

Note that this could be quickly calculated on the fly, or (even better) stored in a permanent table (just add an INTO clause after the SELECT N segment) with a primary key on the N field for improved efficiency.

Objects inside objects in javascript

var pause_menu = {
    pause_button : { someProperty : "prop1", someOther : "prop2" },
    resume_button : { resumeProp : "prop", resumeProp2 : false },
    quit_button : false
};

then:

pause_menu.pause_button.someProperty //evaluates to "prop1"

etc etc.

Replace last occurrence of a string in a string

For the interested: I've written a function that utilises preg_match so that you're able to replace from right hand side using regex.

function preg_rreplace($search, $replace, $subject) {
    preg_match_all($search, $subject, $matches, PREG_SET_ORDER);
    $lastMatch = end($matches);

    if ($lastMatch && false !== $pos = strrpos($subject, $lastMatchedStr = $lastMatch[0])) {
        $subject = substr_replace($subject, $replace, $pos, strlen($lastMatchedStr));
    }

    return $subject;
}

Or as a shorthand combination/implementation of both options:

function str_rreplace($search, $replace, $subject) {
    return (false !== $pos = strrpos($subject, $search)) ?
        substr_replace($subject, $replace, $pos, strlen($search)) : $subject;
}
function preg_rreplace($search, $replace, $subject) {
    preg_match_all($search, $subject, $matches, PREG_SET_ORDER);
    return ($lastMatch = end($matches)) ? str_rreplace($lastMatch[0], $replace, $subject) : $subject;
}

based on https://stackoverflow.com/a/3835653/3017716 and https://stackoverflow.com/a/23343396/3017716

How to call getClass() from a static method in Java?

I wrestled with this myself. A nice trick is to use use the current thread to get a ClassLoader when in a static context. This will work in a Hadoop MapReduce as well. Other methods work when running locally, but return a null InputStream when used in a MapReduce.

public static InputStream getResource(String resource) throws Exception {
   ClassLoader cl = Thread.currentThread().getContextClassLoader();
   InputStream is = cl.getResourceAsStream(resource);
   return is;
}

Change the Bootstrap Modal effect

I copied model code from w3school bootstrap model and added following css. This code provides beautiful animation. You can try it.

.modal.fade .modal-dialog {
     -webkit-transform: scale(0.1);
     -moz-transform: scale(0.1);
     -ms-transform: scale(0.1);
     transform: scale(0.1);
     top: 300px;
     opacity: 0;
     -webkit-transition: all 0.3s;
     -moz-transition: all 0.3s;
     transition: all 0.3s;
}

.modal.fade.in .modal-dialog {
    -webkit-transform: scale(1);
    -moz-transform: scale(1);
    -ms-transform: scale(1);
    transform: scale(1);
    -webkit-transform: translate3d(0, -300px, 0);
    transform: translate3d(0, -300px, 0);
    opacity: 1;
}

m2e lifecycle-mapping not found

this step works on me : 1. Remove your project on eclipse 2. Re import project 3. Delete target folder on your project 4. mvn or mvnw install

Count the number of times a string appears within a string

Here, I'll over-architect the answer using LINQ. Just shows that there's more than 'n' ways to cook an egg:

public int countTrue(string data)
{
    string[] splitdata = data.Split(',');

    var results = from p in splitdata
            where p.Contains("true")
            select p;

    return results.Count();
}

Why do this() and super() have to be the first statement in a constructor?

Because the JLS says so. Could the JLS be changed in a compatible manner to allow it? Yup.

However, it would complicate the language spec, which is already more than complicated enough. It wouldn't be a highly useful thing to do and there are ways around it (call another constructor with the result of a static method or lambda expression this(fn()) - the method is called before the other constructor, and hence also the super constructor). So the power to weight ratio of doing the change is unfavourable.

Note that this rule alone does not prevent use of fields before the super class has completed construction.

Consider these illegal examples.

super(this.x = 5);

super(this.fn());

super(fn());

super(x);

super(this instanceof SubClass);
// this.getClass() would be /really/ useful sometimes.

This example is legal, but "wrong".

class MyBase {
    MyBase() {
        fn();
    }
    abstract void fn();
}
class MyDerived extends MyBase {
    void fn() {
       // ???
    }
}

In the above example, if MyDerived.fn required arguments from the MyDerived constructor they would need to be sleazed through with a ThreadLocal. ;(

Incidentally, since Java 1.4, the synthetic field that contains the outer this is assigned before inner classes super constructor is called. This caused peculiar NullPointerException events in code compiled to target earlier versions.

Note also, in the presence of unsafe publication, construction can be viewed reordered by other threads, unless precautions are made.

Edit March 2018: In message Records: construction and validation Oracle is suggesting this restriction be removed (but unlike C#, this will be definitely unassigned (DU) before constructor chaining).

Historically, this() or super() must be first in a constructor. This restriction was never popular, and perceived as arbitrary. There were a number of subtle reasons, including the verification of invokespecial, that contributed to this restriction. Over the years, we've addressed these at the VM level, to the point where it becomes practical to consider lifting this restriction, not just for records, but for all constructors.

Android Studio is slow (how to speed up)?

I detected another reason - Thumbs.db, which affected performance badly.

Go to File > Settings > Editor > File Types and in field Ignore files and folders add this: Thumbs.db;

Now, Android Studio runs like a charm.

Disable double-tap "zoom" option in browser on touch devices

<head>
<title>Site</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> 
etc...
</head>

I've used that very recently and it works fine on iPad. Haven't tested on Android or other devices (because the website will be displayed on iPad only).

What is a Windows Handle?

Think of the window in Windows as being a struct that describes it. This struct is an internal part of Windows and you don't need to know the details of it. Instead, Windows provides a typedef for pointer to struct for that struct. That's the "handle" by which you can get hold on the window.,

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

Visual Studio 2010 always thinks project is out of date, but nothing has changed

Visual Studio 2013 -- "Forcing recompile of all source files due to missing PDB". I turned on detailed build output to locate the issue: I enabled "Detailed" build output under "Tools" ? "Projects and Solutions" ? "Build and Run".

I had several projects, all C++, I set the option for under project settings: (C/C++ ? Debug Information Format) to Program Database (/Zi) for the problem project. However, this did not stop the problem for that project. The problem came from one of the other C++ projects in the solution.

I set all C++ projects to "Program Database (/Zi)". This fixed the problem.

Again, the project reporting the problem was not the problem project. Try setting all projects to "Program Database (/Zi)" to fix the problem.

Java Compare Two Lists

EDIT

Here are two versions. One using ArrayList and other using HashSet

Compare them and create your own version from this, until you get what you need.

This should be enough to cover the:

P.S: It is not a school assignment :) So if you just guide me it will be enough

part of your question.

continuing with the original answer:

You may use a java.util.Collection and/or java.util.ArrayList for that.

The retainAll method does the following:

Retains only the elements in this collection that are contained in the specified collection

see this sample:

import java.util.Collection;
import java.util.ArrayList;
import java.util.Arrays;

public class Repeated {
    public static void main( String  [] args ) {
        Collection listOne = new ArrayList(Arrays.asList("milan","dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta"));
        Collection listTwo = new ArrayList(Arrays.asList("hafil", "iga", "binga", "mike", "dingo"));

        listOne.retainAll( listTwo );
        System.out.println( listOne );
    }
}

EDIT

For the second part ( similar values ) you may use the removeAll method:

Removes all of this collection's elements that are also contained in the specified collection.

This second version gives you also the similar values and handles repeated ( by discarding them).

This time the Collection could be a Set instead of a List ( the difference is, the Set doesn't allow repeated values )

import java.util.Collection;
import java.util.HashSet;
import java.util.Arrays;

class Repeated {
      public static void main( String  [] args ) {

          Collection<String> listOne = Arrays.asList("milan","iga",
                                                    "dingo","iga",
                                                    "elpha","iga",
                                                    "hafil","iga",
                                                    "meat","iga", 
                                                    "neeta.peeta","iga");

          Collection<String> listTwo = Arrays.asList("hafil",
                                                     "iga",
                                                     "binga", 
                                                     "mike", 
                                                     "dingo","dingo","dingo");

          Collection<String> similar = new HashSet<String>( listOne );
          Collection<String> different = new HashSet<String>();
          different.addAll( listOne );
          different.addAll( listTwo );

          similar.retainAll( listTwo );
          different.removeAll( similar );

          System.out.printf("One:%s%nTwo:%s%nSimilar:%s%nDifferent:%s%n", listOne, listTwo, similar, different);
      }
}

Output:

$ java Repeated
One:[milan, iga, dingo, iga, elpha, iga, hafil, iga, meat, iga, neeta.peeta, iga]

Two:[hafil, iga, binga, mike, dingo, dingo, dingo]

Similar:[dingo, iga, hafil]

Different:[mike, binga, milan, meat, elpha, neeta.peeta]

If it doesn't do exactly what you need, it gives you a good start so you can handle from here.

Question for the reader: How would you include all the repeated values?

regular expression for DOT

...

[.]{1}

or

[.]{2}

?

How do I get the file name from a String containing the Absolute file path?

You can use FileInfo object to get all information of your file.

    FileInfo f = new FileInfo(@"C:\Hello\AnotherFolder\The File Name.PDF");
    MessageBox.Show(f.Name);
    MessageBox.Show(f.FullName);
    MessageBox.Show(f.Extension );
    MessageBox.Show(f.DirectoryName);

Installing Numpy on 64bit Windows 7 with Python 2.7.3

The (unofficial) binaries (http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy) worked for me.
I've tried Mingw, Cygwin, all failed due to varies reasons. I am on Windows 7 Enterprise, 64bit.

Converting any object to a byte array in java

As i've mentioned in other, similar questions, you may want to consider compressing the data as the default java serialization is a bit verbose. you do this by putting a GZIPInput/OutputStream between the Object streams and the Byte streams.

How to loop through a dataset in powershell?

Here's a practical example (build a dataset from your current location):

$ds = new-object System.Data.DataSet
$ds.Tables.Add("tblTest")
[void]$ds.Tables["tblTest"].Columns.Add("Name",[string])
[void]$ds.Tables["tblTest"].Columns.Add("Path",[string])

dir | foreach {
    $dr = $ds.Tables["tblTest"].NewRow()
    $dr["Name"] = $_.name
    $dr["Path"] = $_.fullname
    $ds.Tables["tblTest"].Rows.Add($dr)
}


$ds.Tables["tblTest"]

$ds.Tables["tblTest"] is an object that you can manipulate just like any other Powershell object:

$ds.Tables["tblTest"] | foreach {
    write-host 'Name value is : $_.name
    write-host 'Path value is : $_.path
}

Keras model.summary() result - Understanding the # of Parameters

The easiest way to calculate number of neurons in one layer is: Param value / (number of units * 4)

  • Number of units is in predictivemodel.add(Dense(514,...)
  • Param value is Param in model.summary() function

For example in Paul Lo's answer , number of neurons in one layer is 264710 / (514 * 4 ) = 130

Check whether a path is valid

private bool IsValidPath(string path)
{
    Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
    if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
    string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
    strTheseAreInvalidFileNameChars += @":/?*" + "\"";
    Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
    if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
        return false;

    DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(path));
    if (!dir.Exists)
        dir.Create();
    return true;
}

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

Just another possibility. I had to restart the sql server service to fix this issue for me.

How to pass a list from Python, by Jinja2 to JavaScript

I had a similar problem using Flask, but I did not have to resort to JSON. I just passed a list letters = ['a','b','c'] with render_template('show_entries.html', letters=letters), and set

var letters = {{ letters|safe }}

in my javascript code. Jinja2 replaced {{ letters }} with ['a','b','c'], which javascript interpreted as an array of strings.

SQL Delete Records within a specific Range

You gave a condition ID (>79 and < 296) then the answer is:

delete from tab
where id > 79 and id < 296

this is the same as:

delete from tab
where id between 80 and 295

if id is an integer.

All answered:

delete from tab
where id between 79 and 296

this is the same as:

delete from tab
where id => 79 and id <= 296

Mind the difference.

Execute specified function every X seconds

You can do this easily by adding a Timer to your form (from the designer) and setting it's Tick-function to run your isonline-function.

How can I convert a series of images to a PDF from the command line on linux?

Use convert from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)

How To Launch Git Bash from DOS Command Line?

You can add git path to environment variables

  • For x86

%SYSTEMDRIVE%\Program Files (x86)\Git\bin\

  • For x64

%PROGRAMFILES%\Git\bin\

Open cmd and write this command to open git bash

sh --login

OR

bash --login

OR

sh

OR

bash

You can see this GIF image for more details:

https://media1.giphy.com/media/WSxbZkPFY490wk3abN/giphy.gif

How do you allow spaces to be entered using scanf?

This example uses an inverted scanset, so scanf keeps taking in values until it encounters a '\n'-- newline, so spaces get saved as well

#include <stdio.h>

int main (int argc, char const *argv[])
{
    char name[20];
    scanf("%[^\n]s",name);
    printf("%s\n", name);
    return 0;
}

Property [title] does not exist on this collection instance

When you're using get() you get a collection. In this case you need to iterate over it to get properties:

@foreach ($collection as $object)
    {{ $object->title }}
@endforeach

Or you could just get one of objects by it's index:

{{ $collection[0]->title }}

Or get first object from collection:

{{ $collection->first() }}

When you're using find() or first() you get an object, so you can get properties with simple:

{{ $object->title }}

Python convert decimal to hex

Apart from using the hex() inbuilt function, this works well:

letters = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F']
decimal_number = int(input("Enter a number to convert to hex: "))
print(str(letters[decimal_number//16])+str(letters[decimal_number%16]))

However this only works for converting decimal numbers up to 255 (to give a two diget hex number).

onclick event pass <li> id or value

I prefer to use the HTML5 data API, check this documentation:

A example

_x000D_
_x000D_
$('#some-list li').click(function() {_x000D_
  var textLoaded = 'Loading element with id='_x000D_
         + $(this).data('id');_x000D_
   $('#loading-content').text(textLoaded);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul id='some-list'>_x000D_
  <li data-id='1'>One </li>_x000D_
  <li data-id='2'>Two </li>_x000D_
  <!-- ... more li -->_x000D_
  <li data-id='n'>Other</li>_x000D_
</ul>_x000D_
_x000D_
<h1 id='loading-content'></h1>
_x000D_
_x000D_
_x000D_

How can I create a table with borders in Android?

A border between cells is doubled in above answers. So, you can try this solution:

<item
    android:left="-1dp"
    android:top="-1dp">

    <shape xmlns:android="http://schemas.android.com/apk/res/android"
           android:shape="rectangle">
        <solid android:color="#fff"/>
        <stroke
            android:width="1dp"
            android:color="#ccc"/>
    </shape>
</item>

React.js: Wrapping one component into another

Try:

var Wrapper = React.createClass({
  render: function() {
    return (
      <div className="wrapper">
        before
          {this.props.children}
        after
      </div>
    );
  }
});

See Multiple Components: Children and Type of the Children props in the docs for more info.

Hibernate: best practice to pull all lazy collections

Not the best solution, but here is what I got:

1) Annotate getter you want to initialize with this annotation:

@Retention(RetentionPolicy.RUNTIME)
public @interface Lazy {

}

2) Use this method (can be put in a generic class, or you can change T with Object class) on a object after you read it from database:

    public <T> void forceLoadLazyCollections(T entity) {

    Session session = getSession().openSession();
    Transaction tx = null;
    try {

        tx = session.beginTransaction();
        session.refresh(entity);
        if (entity == null) {
            throw new RuntimeException("Entity is null!");
        }
        for (Method m : entityClass.getMethods()) {

            Lazy annotation = m.getAnnotation(Lazy.class);
            if (annotation != null) {
                m.setAccessible(true);
                logger.debug(" method.invoke(obj, arg1, arg2,...); {} field", m.getName());
                try {
                    Hibernate.initialize(m.invoke(entity));
                }
                catch (Exception e) {
                    logger.warn("initialization exception", e);
                }
            }
        }

    }
    finally {
        session.close();
    }
}

Cannot connect to repo with TortoiseSVN

I've found that replacing the first part of the URL with IP address numbers instead of words worked for me.

For example use:

http://111.11.11.111/svn/Directory

instead of:

http://www.url.com/svn/Directory

Put request with simple string as request body

Another simple solution is to surround the content variable in your given code with braces like this:

 let content = 'Hello world' 
 axios.put(url, {content}).then(response => {
    resolve(response.data.content)
  }, response => {
    this.handleEditError(response)
  })

Caveat: But this will not send it as string; it will wrap it in a json body that will look like this: {content: "Hello world"}

How to change color in markdown cells ipython/jupyter notebook?

For example, if you want to make the color of "text" green, just type:

<font color='green'>text</font>

Get value (String) of ArrayList<ArrayList<String>>(); in Java

Because the second element is null after you clear the list.

Use:

String s = myList.get(0);

And remember, index 0 is the first element.

Search for string within text column in MySQL

Using like might take longer time so use full_text_search:

SELECT * FROM items WHERE MATCH(items.xml) AGAINST ('your_search_word')

postgresql sequence nextval in schema

SELECT last_value, increment_by from "other_schema".id_seq;

for adding a seq to a column where the schema is not public try this.

nextval('"other_schema".id_seq'::regclass)

Get epoch for a specific date using Javascript

You can create a Date object, and call getTime on it:

new Date(2010, 6, 26).getTime() / 1000

Getting "TypeError: failed to fetch" when the request hasn't actually failed

I have a similar problem and as I'm newbie, here are some facts for somebody to comment:

I'm sending form data to Google sheet this way (scriptURL is https://script.google.com/macros/s/AKfy..., showSuccess() is showing a simple image):

fetch(scriptURL, {method: 'POST', body: new FormData(form)})
.then(response => showSuccess())
.catch(error => alert('Error! ' + error.message))

Executed in Edge my HTML doesn't show error and Network tab reports this 3 requests: Edge execution Executed in Chrome my HTML (index.htm) shows Failed to fetch error and Network tab reports this 2 requests: Chrome execution The value in the second column is blocked:other and there is also an error in Console tab:

GET https://script.googleusercontent.com/macros/echo?user_content_key=D-ABF... net::ERR_BLOCKED_BY_CLIENT

In order to suspend installed Chrome extensions, I executed my code in an Incognito window and there is no error message and Network tab reports this 2 requests: Incognito execution

My guess is that something (extension?) prevents Chrome to read the request's answer (the GET request is blocked).

SELECT * WHERE NOT EXISTS

SELECT * from employees
WHERE NOT EXISTS (SELECT name FROM eotm_dyn)

Never returns any records unless eotm_dyn is empty. You need to some kind of criteria on SELECT name FROM eotm_dyn like

SELECT * from employees
WHERE NOT EXISTS (
    SELECT name FROM eotm_dyn WHERE eotm_dyn.employeeid = employees.employeeid
)

assuming that the two tables are linked by a foreign key relationship. At this point you could use a variety of other options including a LEFT JOIN. The optimizer will typically handle them the same in most cases, however.

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

Have you tried using Unix style slashes (/ instead of \)?

\ is often an escape or command character, and may be the source of confusion. I have never had issues with this, but I also do not have Windows, so I cannot test it.

Additionally, the permissions may be based on the user running psql, or maybe the user executing the postmaster service, check that both have read to that file in that directory.

How can I listen for keypress event on the whole page?

yurzui's answer didn't work for me, it might be a different RC version, or it might be a mistake on my part. Either way, here's how I did it with my component in Angular2 RC4 (which is now quite outdated).

@Component({
    ...
    host: {
        '(document:keydown)': 'handleKeyboardEvents($event)'
    }
})
export class MyComponent {
    ...
    handleKeyboardEvents(event: KeyboardEvent) {
        this.key = event.which || event.keyCode;
    }
}

Is it possible to declare two variables of different types in a for loop?

Not possible, but you can do:

float f;
int i;
for (i = 0,f = 0.0; i < 5; i++)
{
  //...
}

Or, explicitly limit the scope of f and i using additional brackets:

{
    float f; 
    int i;
    for (i = 0,f = 0.0; i < 5; i++)
    {
       //...
    }
}

What does T&& (double ampersand) mean in C++11?

An rvalue reference is a type that behaves much like the ordinary reference X&, with several exceptions. The most important one is that when it comes to function overload resolution, lvalues prefer old-style lvalue references, whereas rvalues prefer the new rvalue references:

void foo(X& x);  // lvalue reference overload
void foo(X&& x); // rvalue reference overload

X x;
X foobar();

foo(x);        // argument is lvalue: calls foo(X&)
foo(foobar()); // argument is rvalue: calls foo(X&&)

So what is an rvalue? Anything that is not an lvalue. An lvalue being an expression that refers to a memory location and allows us to take the address of that memory location via the & operator.

It is almost easier to understand first what rvalues accomplish with an example:

 #include <cstring>
 class Sample {
  int *ptr; // large block of memory
  int size;
 public:
  Sample(int sz=0) : ptr{sz != 0 ? new int[sz] : nullptr}, size{sz} 
  {
     if (ptr != nullptr) memset(ptr, 0, sz);
  }
  // copy constructor that takes lvalue 
  Sample(const Sample& s) : ptr{s.size != 0 ? new int[s.size] :\
      nullptr}, size{s.size}
  {
     if (ptr != nullptr) memcpy(ptr, s.ptr, s.size);
     std::cout << "copy constructor called on lvalue\n";
  }

  // move constructor that take rvalue
  Sample(Sample&& s) 
  {  // steal s's resources
     ptr = s.ptr;
     size = s.size;        
     s.ptr = nullptr; // destructive write
     s.size = 0;
     cout << "Move constructor called on rvalue." << std::endl;
  }    
  // normal copy assignment operator taking lvalue
  Sample& operator=(const Sample& s)
  {
   if(this != &s) {
      delete [] ptr; // free current pointer
      size = s.size;

      if (size != 0) {
        ptr = new int[s.size];
        memcpy(ptr, s.ptr, s.size);
      } else 
         ptr = nullptr;
     }
     cout << "Copy Assignment called on lvalue." << std::endl;
     return *this;
  }    
 // overloaded move assignment operator taking rvalue
 Sample& operator=(Sample&& lhs)
 {
   if(this != &s) {
      delete [] ptr; //don't let ptr be orphaned 
      ptr = lhs.ptr;   //but now "steal" lhs, don't clone it.
      size = lhs.size; 
      lhs.ptr = nullptr; // lhs's new "stolen" state
      lhs.size = 0;
   }
   cout << "Move Assignment called on rvalue" << std::endl;
   return *this;
 }
//...snip
};     

The constructor and assignment operators have been overloaded with versions that take rvalue references. Rvalue references allow a function to branch at compile time (via overload resolution) on the condition "Am I being called on an lvalue or an rvalue?". This allowed us to create more efficient constructor and assignment operators above that move resources rather copy them.

The compiler automatically branches at compile time (depending on the whether it is being invoked for an lvalue or an rvalue) choosing whether the move constructor or move assignment operator should be called.

Summing up: rvalue references allow move semantics (and perfect forwarding, discussed in the article link below).

One practical easy-to-understand example is the class template std::unique_ptr. Since a unique_ptr maintains exclusive ownership of its underlying raw pointer, unique_ptr's can't be copied. That would violate their invariant of exclusive ownership. So they do not have copy constructors. But they do have move constructors:

template<class T> class unique_ptr {
  //...snip
 unique_ptr(unique_ptr&& __u) noexcept; // move constructor
};

 std::unique_ptr<int[] pt1{new int[10]};  
 std::unique_ptr<int[]> ptr2{ptr1};// compile error: no copy ctor.  

 // So we must first cast ptr1 to an rvalue 
 std::unique_ptr<int[]> ptr2{std::move(ptr1)};  

std::unique_ptr<int[]> TakeOwnershipAndAlter(std::unique_ptr<int[]> param,\
 int size)      
{
  for (auto i = 0; i < size; ++i) {
     param[i] += 10;
  }
  return param; // implicitly calls unique_ptr(unique_ptr&&)
}

// Now use function     
unique_ptr<int[]> ptr{new int[10]};

// first cast ptr from lvalue to rvalue
unique_ptr<int[]> new_owner = TakeOwnershipAndAlter(\
           static_cast<unique_ptr<int[]>&&>(ptr), 10);

cout << "output:\n";

for(auto i = 0; i< 10; ++i) {
   cout << new_owner[i] << ", ";
}

output:
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 

static_cast<unique_ptr<int[]>&&>(ptr) is usually done using std::move

// first cast ptr from lvalue to rvalue
unique_ptr<int[]> new_owner = TakeOwnershipAndAlter(std::move(ptr),0);

An excellent article explaining all this and more (like how rvalues allow perfect forwarding and what that means) with lots of good examples is Thomas Becker's C++ Rvalue References Explained. This post relied heavily on his article.

A shorter introduction is A Brief Introduction to Rvalue References by Stroutrup, et. al

How to add MVC5 to Visual Studio 2013?

Go File -> New Project.

Select Web under Visual C#.

Select ASP.NET Web Application

select mvc

when solution is created, you will find resources getting added in solution in status bar of vs 2013.

Check property of Dll file --> system.web.mvc, it shows latest version (5.2.2.0)

but depending on your OS runtime version will be decided.

Python dictionary : TypeError: unhashable type: 'list'

This is indeed rather odd.

If aSourceDictionary were a dictionary, I don't believe it is possible for your code to fail in the manner you describe.

This leads to two hypotheses:

  1. The code you're actually running is not identical to the code in your question (perhaps an earlier or later version?)

  2. aSourceDictionary is in fact not a dictionary, but is some other structure (for example, a list).

What is the difference between Document style and RPC style communication?

Document
Document style messages can be validated against predefined schema. In document style, SOAP message is sent as a single document. Example of schema:

  <types>  
   <xsd:schema> <xsd:import namespace="http://example.com/" 
    schemaLocation="http://localhost:8080/ws/hello?xsd=1"/>  
   </xsd:schema>  
  </types>

Example of document style soap body message

  <message name="getHelloWorldAsString">   
     <part name="parameters" element="tns:getHelloWorldAsString"/>   
  </message> 
  <message name="getHelloWorldAsStringResponse">  
     <part name="parameters"> element="tns:getHelloWorldAsStringResponse"/>   
  </message>

Document style message is loosely coupled.

RPC RPC style messages use method name and parameters to generate XML structure. messages are difficult to be validated against schema. In RPC style, SOAP message is sent as many elements.

  <message name="getHelloWorldAsString">
    <part name="arg0"> type="xsd:string"/>   
   </message> 
  <message name="getHelloWorldAsStringResponse">   
    <part name="return"
   > type="xsd:string"/>   
  </message>

Here each parameters are discretely specified, RPC style message is tightly coupled, is typically static, requiring changes to the client when the method signature changes The rpc style is limited to very simple XSD types such as String and Integer, and the resulting WSDL will not even have a types section to define and constrain the parameters

Literal By default style. Data is serialized according to a schema, data type not specified in messages but a reference to schema(namespace) is used to build soap messages.

   <soap:body>
     <myMethod>
        <x>5</x>
        <y>5.0</y>
     </myMethod>
   </soap:body>

Encoded Datatype specified in each parameter

   <soap:body>
     <myMethod>
         <x xsi:type="xsd:int">5</x>
         <y xsi:type="xsd:float">5.0</y>
     </myMethod>
   </soap:body>

Schema free

How to delete node from XML file using C#

It may be easier to use XPath to locate the nodes that you wish to delete. This stackoverflow thread might give you some ideas.

In your case you will find the four nodes that you want using this expression:

XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");

READ_EXTERNAL_STORAGE permission for Android

I also had a similar error log and here's what I did-

  1. In onCreate method we request a Dialog Box for checking permissions

    ActivityCompat.requestPermissions(MainActivity.this,
    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
    
  2. Method to check for the result

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission granted and now can proceed
             mymethod(); //a sample method called
    
            } else {
    
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        // add other cases for more permissions
        }
    }
    

The official documentation to Requesting Runtime Permissions

scp copy directory to another server with private key auth

The command looks quite fine. Could you try to run -v (verbose mode) and then we can figure out what it is wrong on the authentication?

Also as mention in the other answer, maybe could be this issue - that you need to convert the keys (answered already here): How to convert SSH keypairs generated using PuttyGen(Windows) into key-pairs used by ssh-agent and KeyChain(Linux) OR http://winscp.net/eng/docs/ui_puttygen (depending what you need)

Scrollview can host only one direct child

Wrap all the children inside of another LinearLayout with wrap_content for both the width and the height as well as the vertical orientation.

Multiple types were found that match the controller named 'Home'

Other variation of this error is when you use resharper and you use some "auto" refactor options that include namespace name changing. This is what happen to me. To solve issue with this kind of scenario delete folderbin

MacOSX homebrew mysql root password

Since the question was asked/answered long time ago, those top answers do not work for me. Here's my solution, in 2020.

Background: Fresh mysql/mariadb installed by homebrew.

Problem: The password for root is not empty and unknown.

The fix:

  1. mysql -u YOUR-SYSTEM-USERNAME -p
  2. The password is empty (press enter)
  3. ALTER USER 'root'@'localhost' IDENTIFIED BY 'NEW-ROOT-PASSWORD';
  4. FLUSH PRIVILEGES;

The reason:

  1. Homebrew will create a user with root privileges named by the current MacOS username.
  2. it has no password
  3. Since it has all privileges, just reset the root password with that user.
  4. The initial password for root was randomly generated.

How do I center text horizontally and vertically in a TextView?

You can also use the combination:

android:gravity="left|center"

Then, if textview width is more than "fill_parent" the text will still be aligned to left (not centered as with gravity set only to "center").

Reading InputStream as UTF-8

Solved my own problem. This line:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

needs to be:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

or since Java 7:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

Setting selected option in laravel form

Everybody talking about you go using {!! Form::select() !!} but, if all you need is to use plain simple HTML.. here is another way to do it.

<select name="myselect">
@foreach ($options as $key => $value)
    <option value="{{ $key }}"
    @if ($key == old('myselect', $model->option))
        selected="selected"
    @endif
    >{{ $value }}</option>
@endforeach
</select>

the old() function is useful when you submit the form and the validation fails. So that, old() returns the previously selected value.

How to check a string starts with numeric number?

I think you ought to use a regex:


import java.util.regex.*;

public class Test {
  public static void main(String[] args) {
    String neg = "-123abc";
    String pos = "123abc";
    String non = "abc123";
        /* I'm not sure if this regex is too verbose, but it should be
         * clear. It checks that the string starts with either a series
         * of one or more digits... OR a negative sign followed by 1 or
         * more digits. Anything can follow the digits. Update as you need
         * for things that should not follow the digits or for floating
         * point numbers.
         */
    Pattern pattern = Pattern.compile("^(\\d+.*|-\\d+.*)");
    Matcher matcher = pattern.matcher(neg);
    if(matcher.matches()) {
        System.out.println("matches negative number");
    }
    matcher = pattern.matcher(pos);
    if (matcher.matches()) {
        System.out.println("positive matches");
    }
    matcher = pattern.matcher(non);
    if (!matcher.matches()) {
        System.out.println("letters don't match :-)!!!");
    }
  }
}

You may want to adjust this to accept floating point numbers, but this will work for negatives. Other answers won't work for negatives because they only check the first character! Be more specific about your needs and I can help you adjust this approach.

PHP display current server path

here is a test script to run on your server to see what is reliabel.

<?php
$host = gethostname();
$ip = gethostbyname($host);
echo "gethostname and gethostbyname: $host at $ip<br>";
$server = $_SERVER['SERVER_ADDR'];
echo "_SERVER[SERVER_ADDR]: $server<br>";
$my_current_ip=exec("ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'");
echo "exec ifconfig ... : $my_current_ip<br>";
$external_ip = file_get_contents("http://ipecho.net/plain");
echo "get contents ipecho.net: $external_ip<br>";
?>

The only different option in there is using fiel_get_contents rather than curl for the extrernal website lookup.

This is the result of hitting the web page on a shared hosting, free account. (actual server name and IP changed)

gethostname and gethostbyname: freesites.servercluster.com at 345.27.413.51
_SERVER[SERVER_ADDR]: 127.0.0.7
exec ifconfig ... :
get contents ipecho.net: 345.27.413.51

Why needed this? Decided to point A record at server to see if it opens the web page. Later ran script to save ip and update on ghost site on same server to lookup IP and alert if changed.

In this case, good results optained by:

gethostname() & 
gethostbyname($host)
or 
file_get_contents("http://ipecho.net/plain")

What is the "hasClass" function with plain JavaScript?

I use a simple/minimal solution, one line, cross browser, and works with legacy browsers as well:

/\bmyClass/.test(document.body.className) // notice the \b command for whole word 'myClass'

This method is great because does not require polyfills and if you use them for classList it's much better in terms of performance. At least for me.

Update: I made a tiny polyfill that's an all round solution I use now:

function hasClass(element,testClass){
  if ('classList' in element) { return element.classList.contains(testClass);
} else { return new Regexp(testClass).exec(element.className); } // this is better

//} else { return el.className.indexOf(testClass) != -1; } // this is faster but requires indexOf() polyfill
  return false;
}

For the other class manipulation, see the complete file here.

Javascript/jQuery: Set Values (Selection) in a multiple Select

Iterate through the loop using the value in a dynamic selector that utilizes the attribute selector.

var values="Test,Prof,Off";
$.each(values.split(","), function(i,e){
    $("#strings option[value='" + e + "']").prop("selected", true);
});

Working Example http://jsfiddle.net/McddQ/1/

How to check if a scope variable is undefined in AngularJS template?

You can use the double pipe operation to check if the value is undefined the after statement:

<div ng-show="foo || false">
    Show this if foo is defined!
</div>
<div ng-show="boo || true">
    Show this if boo is undefined!
</div>

Check JSFiddle for demo

For technical explanation for the double pipe, I prefer to take a look on this link: https://stackoverflow.com/a/34707750/6225126

Display Records From MySQL Database using JTable in Java

this is the easy way to do that you just need to download the jar file "rs2xml.jar" add it to your project and do that : 1- creat a connection 2- statment and resultset 3- creat a jtable 4- give the result set to DbUtils.resultSetToTableModel(rs) as define in this methode you well get your jtable so easy.

public void afficherAll(String tableName){
        String sql="select * from "+tableName;
        try {
            stmt=con.createStatement();
            rs=stmt.executeQuery(sql);
            tbContTable.setModel(DbUtils.resultSetToTableModel(rs));
        } catch (SQLException e) {
            // TODO Auto-generated catch block
             JOptionPane.showMessageDialog(null, e);
        }       
    }

Convert ArrayList to String array in Android

String[] array = new String[items2.size()];
items2.toArray(array);

Is there a way to use two CSS3 box shadows on one element?

Box shadows can use commas to have multiple effects, just like with background images (in CSS3).

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

How to get the string size in bytes?

You can use strlen. Size is determined by the terminating null-character, so passed string should be valid.

If you want to get size of memory buffer, that contains your string, and you have pointer to it:

  • If it is dynamic array(created with malloc), it is impossible to get it size, since compiler doesn't know what pointer is pointing at. (check this)
  • If it is static array, you can use sizeof to get its size.

If you are confused about difference between dynamic and static arrays, check this.

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

I don't think other answers explained the key part: why "COUNT(*)" returns more than one result?

I just encountered the same issue today, and what I found out is that if you have another class extending the target mapped class (here "CustomerData"), Hibernate will do this magic.

Hope this will save some time for other unfortunate guys.

How to get jQuery to wait until an effect is finished?

You can specify a callback function:

$(selector).fadeOut('slow', function() {
    // will be called when the element finishes fading out
    // if selector matches multiple elements it will be called once for each
});

Documentation here.

Where does this come from: -*- coding: utf-8 -*-

This is so called file local variables, that are understood by Emacs and set correspondingly. See corresponding section in Emacs manual - you can define them either in header or in footer of file

Copy Image from Remote Server Over HTTP

PHP has a built-in function file_get_contents(), which reads the content of a file into a string.

<?php
//Get the file
$content = file_get_contents("http://example.com/image.jpg");

//Store in the filesystem. $fp = fopen("/location/to/save/image.jpg", "w"); fwrite($fp, $content); fclose($fp); ?>

If you wish to store the file in a database, simply use the $content variable and don't save the file to disk.

Preventing SQL injection in Node.js

The library has a section in the readme about escaping. It's Javascript-native, so I do not suggest switching to node-mysql-native. The documentation states these guidelines for escaping:

Edit: node-mysql-native is also a pure-Javascript solution.

  • Numbers are left untouched
  • Booleans are converted to true / false strings
  • Date objects are converted to YYYY-mm-dd HH:ii:ss strings
  • Buffers are converted to hex strings, e.g. X'0fa5'
  • Strings are safely escaped
  • Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
  • Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')
  • Objects are turned into key = 'val' pairs. Nested objects are cast to strings.
  • undefined / null are converted to NULL
  • NaN / Infinity are left as-is. MySQL does not support these, and trying to insert them as values will trigger MySQL errors until they implement support.

This allows for you to do things like so:

var userId = 5;
var query = connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
  //query.sql returns SELECT * FROM users WHERE id = '5'
});

As well as this:

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
  //query.sql returns INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
});

Aside from those functions, you can also use the escape functions:

connection.escape(query);
mysql.escape(query);

To escape query identifiers:

mysql.escapeId(identifier);

And as a response to your comment on prepared statements:

From a usability perspective, the module is great, but it has not yet implemented something akin to PHP's Prepared Statements.

The prepared statements are on the todo list for this connector, but this module at least allows you to specify custom formats that can be very similar to prepared statements. Here's an example from the readme:

connection.config.queryFormat = function (query, values) {
  if (!values) return query;
  return query.replace(/\:(\w+)/g, function (txt, key) {
    if (values.hasOwnProperty(key)) {
      return this.escape(values[key]);
    }
    return txt;
  }.bind(this));
};

This changes the query format of the connection so you can use queries like this:

connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
//equivalent to
connection.query("UPDATE posts SET title = " + mysql.escape("Hello MySQL");

Batch not-equal (inequality) operator

Try:

if not "asdf" == "fdas" echo asdf

That works for me on Windows XP (I get the same error as you for the code you posted).

'printf' vs. 'cout' in C++

I'm surprised that everyone in this question claims that std::cout is way better than printf, even if the question just asked for differences. Now, there is a difference - std::cout is C++, and printf is C (however, you can use it in C++, just like almost anything else from C). Now, I'll be honest here; both printf and std::cout have their advantages.

Real differences

Extensibility

std::cout is extensible. I know that people will say that printf is extensible too, but such extension is not mentioned in the C standard (so you would have to use non-standard features - but not even common non-standard feature exists), and such extensions are one letter (so it's easy to conflict with an already-existing format).

Unlike printf, std::cout depends completely on operator overloading, so there is no issue with custom formats - all you do is define a subroutine taking std::ostream as the first argument and your type as second. As such, there are no namespace problems - as long you have a class (which isn't limited to one character), you can have working std::ostream overloading for it.

However, I doubt that many people would want to extend ostream (to be honest, I rarely saw such extensions, even if they are easy to make). However, it's here if you need it.

Syntax

As it could be easily noticed, both printf and std::cout use different syntax. printf uses standard function syntax using pattern string and variable-length argument lists. Actually, printf is a reason why C has them - printf formats are too complex to be usable without them. However, std::cout uses a different API - the operator << API that returns itself.

Generally, that means the C version will be shorter, but in most cases it won't matter. The difference is noticeable when you print many arguments. If you have to write something like Error 2: File not found., assuming error number, and its description is placeholder, the code would look like this. Both examples work identically (well, sort of, std::endl actually flushes the buffer).

printf("Error %d: %s.\n", id, errors[id]);
std::cout << "Error " << id << ": " << errors[id] << "." << std::endl;

While this doesn't appear too crazy (it's just two times longer), things get more crazy when you actually format arguments, instead of just printing them. For example, printing of something like 0x0424 is just crazy. This is caused by std::cout mixing state and actual values. I never saw a language where something like std::setfill would be a type (other than C++, of course). printf clearly separates arguments and actual type. I really would prefer to maintain the printf version of it (even if it looks kind of cryptic) compared to iostream version of it (as it contains too much noise).

printf("0x%04x\n", 0x424);
std::cout << "0x" << std::hex << std::setfill('0') << std::setw(4) << 0x424 << std::endl;

Translation

This is where the real advantage of printf lies. The printf format string is well... a string. That makes it really easy to translate, compared to operator << abuse of iostream. Assuming that the gettext() function translates, and you want to show Error 2: File not found., the code to get translation of the previously shown format string would look like this:

printf(gettext("Error %d: %s.\n"), id, errors[id]);

Now, let's assume that we translate to Fictionish, where the error number is after the description. The translated string would look like %2$s oru %1$d.\n. Now, how to do it in C++? Well, I have no idea. I guess you can make fake iostream which constructs printf that you can pass to gettext, or something, for purposes of translation. Of course, $ is not C standard, but it's so common that it's safe to use in my opinion.

Not having to remember/look-up specific integer type syntax

C has lots of integer types, and so does C++. std::cout handles all types for you, while printf requires specific syntax depending on an integer type (there are non-integer types, but the only non-integer type you will use in practice with printf is const char * (C string, can be obtained using to_c method of std::string)). For instance, to print size_t, you need to use %zd, while int64_t will require using %"PRId64". The tables are available at http://en.cppreference.com/w/cpp/io/c/fprintf and http://en.cppreference.com/w/cpp/types/integer.

You can't print the NUL byte, \0

Because printf uses C strings as opposed to C++ strings, it cannot print NUL byte without specific tricks. In certain cases it's possible to use %c with '\0' as an argument, although that's clearly a hack.

Differences nobody cares about

Performance

Update: It turns out that iostream is so slow that it's usually slower than your hard drive (if you redirect your program to file). Disabling synchronization with stdio may help, if you need to output lots of data. If the performance is a real concern (as opposed to writing several lines to STDOUT), just use printf.

Everyone thinks that they care about performance, but nobody bothers to measure it. My answer is that I/O is bottleneck anyway, no matter if you use printf or iostream. I think that printf could be faster from a quick look into assembly (compiled with clang using the -O3 compiler option). Assuming my error example, printf example does way fewer calls than the cout example. This is int main with printf:

main:                                   @ @main
@ BB#0:
        push    {lr}
        ldr     r0, .LCPI0_0
        ldr     r2, .LCPI0_1
        mov     r1, #2
        bl      printf
        mov     r0, #0
        pop     {lr}
        mov     pc, lr
        .align  2
@ BB#1:

You can easily notice that two strings, and 2 (number) are pushed as printf arguments. That's about it; there is nothing else. For comparison, this is iostream compiled to assembly. No, there is no inlining; every single operator << call means another call with another set of arguments.

main:                                   @ @main
@ BB#0:
        push    {r4, r5, lr}
        ldr     r4, .LCPI0_0
        ldr     r1, .LCPI0_1
        mov     r2, #6
        mov     r3, #0
        mov     r0, r4
        bl      _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
        mov     r0, r4
        mov     r1, #2
        bl      _ZNSolsEi
        ldr     r1, .LCPI0_2
        mov     r2, #2
        mov     r3, #0
        mov     r4, r0
        bl      _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
        ldr     r1, .LCPI0_3
        mov     r0, r4
        mov     r2, #14
        mov     r3, #0
        bl      _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
        ldr     r1, .LCPI0_4
        mov     r0, r4
        mov     r2, #1
        mov     r3, #0
        bl      _ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_PKS3_l
        ldr     r0, [r4]
        sub     r0, r0, #24
        ldr     r0, [r0]
        add     r0, r0, r4
        ldr     r5, [r0, #240]
        cmp     r5, #0
        beq     .LBB0_5
@ BB#1:                                 @ %_ZSt13__check_facetISt5ctypeIcEERKT_PS3_.exit
        ldrb    r0, [r5, #28]
        cmp     r0, #0
        beq     .LBB0_3
@ BB#2:
        ldrb    r0, [r5, #39]
        b       .LBB0_4
.LBB0_3:
        mov     r0, r5
        bl      _ZNKSt5ctypeIcE13_M_widen_initEv
        ldr     r0, [r5]
        mov     r1, #10
        ldr     r2, [r0, #24]
        mov     r0, r5
        mov     lr, pc
        mov     pc, r2
.LBB0_4:                                @ %_ZNKSt5ctypeIcE5widenEc.exit
        lsl     r0, r0, #24
        asr     r1, r0, #24
        mov     r0, r4
        bl      _ZNSo3putEc
        bl      _ZNSo5flushEv
        mov     r0, #0
        pop     {r4, r5, lr}
        mov     pc, lr
.LBB0_5:
        bl      _ZSt16__throw_bad_castv
        .align  2
@ BB#6:

However, to be honest, this means nothing, as I/O is the bottleneck anyway. I just wanted to show that iostream is not faster because it's "type safe". Most C implementations implement printf formats using computed goto, so the printf is as fast as it can be, even without compiler being aware of printf (not that they aren't - some compilers can optimize printf in certain cases - constant string ending with \n is usually optimized to puts).

Inheritance

I don't know why you would want to inherit ostream, but I don't care. It's possible with FILE too.

class MyFile : public FILE {}

Type safety

True, variable length argument lists have no safety, but that doesn't matter, as popular C compilers can detect problems with printf format string if you enable warnings. In fact, Clang can do that without enabling warnings.

$ cat safety.c

#include <stdio.h>

int main(void) {
    printf("String: %s\n", 42);
    return 0;
}

$ clang safety.c

safety.c:4:28: warning: format specifies type 'char *' but the argument has type 'int' [-Wformat]
    printf("String: %s\n", 42);
                    ~~     ^~
                    %d
1 warning generated.
$ gcc -Wall safety.c
safety.c: In function ‘main’:
safety.c:4:5: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
     printf("String: %s\n", 42);
     ^

How to get a string after a specific substring?

s1 = "hello python world , i'm a beginner "
s2 = "world"

print s1[s1.index(s2) + len(s2):]

If you want to deal with the case where s2 is not present in s1, then use s1.find(s2) as opposed to index. If the return value of that call is -1, then s2 is not in s1.

How to open a txt file and read numbers in Java

File file = new File("file.txt");   
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
    if (scanner.hasNextInt()) {
        integers.add(scanner.nextInt());
    } 
    else {
        scanner.next();
    }
}
System.out.println(integers);

How can I toggle word wrap in Visual Studio?

In Visual Studio 2008 it is Ctrl + E + W.

Making a Bootstrap table column fit to content

You can wrap your table around the div tag like this as it helped me too.

<div class="col-md-3">

<table>
</table>

</div>

Why do we use volatile keyword?

In computer programming, particularly in the C, C++, and C# programming languages, a variable or object declared with the volatile keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own." (c) Wikipedia

http://en.wikipedia.org/wiki/Volatile_variable

Convert base64 string to ArrayBuffer

Async solution, it's better when the data is big:

// base64 to buffer
function base64ToBufferAsync(base64) {
  var dataUrl = "data:application/octet-binary;base64," + base64;

  fetch(dataUrl)
    .then(res => res.arrayBuffer())
    .then(buffer => {
      console.log("base64 to buffer: " + new Uint8Array(buffer));
    })
}

// buffer to base64
function bufferToBase64Async( buffer ) {
    var blob = new Blob([buffer], {type:'application/octet-binary'});    
    console.log("buffer to blob:" + blob)

    var fileReader = new FileReader();
    fileReader.onload = function() {
      var dataUrl = fileReader.result;
      console.log("blob to dataUrl: " + dataUrl);

      var base64 = dataUrl.substr(dataUrl.indexOf(',')+1)      
      console.log("dataUrl to base64: " + base64);
    };
    fileReader.readAsDataURL(blob);
}

How to read a local text file?

Provably you already try it, type "false" as follows:

 rawFile.open("GET", file, false);

Axios Delete request with body and headers?

To send an HTTP DELETE with some headers via axios I've done this:

  const deleteUrl = "http//foo.bar.baz";
  const httpReqHeaders = {
    'Authorization': token,
    'Content-Type': 'application/json'
  };
  // check the structure here: https://github.com/axios/axios#request-config
  const axiosConfigObject = {headers: httpReqHeaders}; 

  axios.delete(deleteUrl, axiosConfigObject);

The axios syntax for different HTTP verbs (GET, POST, PUT, DELETE) is tricky because sometimes the 2nd parameter is supposed to be the HTTP body, some other times (when it might not be needed) you just pass the headers as the 2nd parameter.

However let's say you need to send an HTTP POST request without an HTTP body, then you need to pass undefined as the 2nd parameter.

Bare in mind that according to the definition of the configuration object (https://github.com/axios/axios#request-config) you can still pass an HTTP body in the HTTP call via the data field when calling axios.delete, however for the HTTP DELETE verb it will be ignored.

This confusion between the 2nd parameter being sometimes the HTTP body and some other time the whole config object for axios is due to how the HTTP rules have been implemented. Sometimes an HTTP body is not needed for an HTTP call to be considered valid.

How to check if a windows form is already open, and close it if it is?

This is what I used to close all open forms (except for the main form)

    private void CloseOpenForms()
    {

           // Close all open forms - except for the main form.  (This is usually OpenForms[0].
           // Closing a form decrmements the OpenForms count
           while (Application.OpenForms.Count > 1)
           {
               Application.OpenForms[Application.OpenForms.Count-1].Close();
           }
    }

Convert xlsx file to csv using batch

Get all file item and filter them by suffix and then use PowerShell Excel VBA object to save the excel files to csv files.

$excelApp = New-Object -ComObject Excel.Application 
$excelApp.DisplayAlerts = $false 

$ExcelFiles | ForEach-Object { 
    $workbook = $excelApp.Workbooks.Open($_.FullName) 
    $csvFilePath = $_.FullName -replace "\.xlsx$", ".csv" 
    $workbook.SaveAs($csvFilePath, [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSV) 
    $workbook.Close() 
} 

You can find the complete sample here How to convert Excel xlsx file to csv file in batch by PowerShell

jQuery UI Accordion Expand/Collapse All

I found AlecRust's solution quite helpful, but I add something to resolve one problem: When you click on a single accordion to expand it and then you click on the button to expand, they will all be opened. But, if you click again on the button to collapse, the single accordion expand before won't be collapse.

I've used imageButton, but you can also apply that logic to buttons.

/*** Expand all ***/
$(".expandAll").click(function (event) {
    $('.accordion .ui-accordion-header:not(.ui-state-active)').next().slideDown();

    return false;
});

/*** Collapse all ***/
$(".collapseAll").click(function (event) {
    $('.accordion').accordion({
        collapsible: true,
        active: false
    });

    $('.accordion .ui-accordion-header').next().slideUp();

    return false;
});

Also, if you have accordions inside an accordion and you want to expand all only on that second level, you can add a query:

/*** Expand all Second Level ***/
$(".expandAll").click(function (event) {
    $('.accordion .ui-accordion-header:not(.ui-state-active)').nextAll(':has(.accordion .ui-accordion-header)').slideDown();

    return false;
});

Update multiple columns in SQL

The Update table1 set (a,b,c) = (select x,y,x) syntax is an example of the use of row-value constructors, Oracle supports this, MSSQL does not. (Connect item)

A valid provisioning profile for this executable was not found for debug mode

One of the solution can be,Your provisioning profile does not include your iPhone's UDID. For that You need to register UDID first and then regenerate provisioning profile from developer account.

How to empty a list in C#?

If by "list" you mean a List<T>, then the Clear method is what you want:

List<string> list = ...;
...
list.Clear();

You should get into the habit of searching the MSDN documentation on these things.

Here's how to quickly search for documentation on various bits of that type:

All of these Google queries lists a bundle of links, but typically you want the first one that google gives you in each case.

Add Header and Footer for PDF using iTextsharp

Easy codes that work successfully:

protected void Page_Load(object sender, EventArgs e)
{
 .
 .       
 using (MemoryStream ms = new MemoryStream())
 {
  .
  .
  iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 36, 36, 54, 54);
  iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, ms);
  writer.PageEvent = new HeaderFooter();
  doc.Open();
  .
  .
  // make your document content..
  .
  .                   
  doc.Close();
  writer.Close();

  // output
  Response.ContentType = "application/pdf;";
  Response.AddHeader("Content-Disposition", "attachment; filename=clientfilename.pdf");
  byte[] pdf = ms.ToArray();
  Response.OutputStream.Write(pdf, 0, pdf.Length);
 }
 .
 .
 .
}
class HeaderFooter : PdfPageEventHelper
{
public override void OnEndPage(PdfWriter writer, Document document)
{

    // Make your table header using PdfPTable and name that tblHeader
    .
    . 
    tblHeader.WriteSelectedRows(0, -1, page.Left + document.LeftMargin, page.Top, writer.DirectContent);
    .
    .
    // Make your table footer using PdfPTable and name that tblFooter
    .
    . 
    tblFooter.WriteSelectedRows(0, -1, page.Left + document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent);
}
}

SCRIPT438: Object doesn't support property or method IE

I had the following

document.getElementById("search-button") != null

which worked fine in all browsers except ie8. ( I didnt check ie6 or ie7)

I changed it to

document.getElementById("searchBtn") != null

and updated the id attribute on the field in my html and it now works in ie8

Git: How to remove proxy

You config proxy settings for some network and now you connect another network. Now have to remove the proxy settings. For that use these commands:

git config --global --unset https.proxy
git config --global --unset http.proxy

Now you can push too. (If did not remove proxy configuration still you can use git commands like add , commit and etc)

Uncaught ReferenceError: $ is not defined

I had this problem but the cause was very different to scenarios reported above. My site was working everywhere except on my older Android (2.2). Turned out this device was rejecting the https certificate at the code.jquery.com CDN, so it was not loading JQuery. The fix was to load JQuery resources from the https Google CDN instead (using URLs named by others above).

How do I schedule a task to run at periodic intervals?

public void schedule(TimerTask task,long delay)

Schedules the specified task for execution after the specified delay.

you want:

public void schedule(TimerTask task, long delay, long period)

Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.

Adding/removing items from a JavaScript object with jQuery

If you are using jQuery you can use the extend function to add new items.

var olddata = {"fruit":{"apples":10,"pears":21}};

var newdata = {};
newdata['vegetables'] = {"carrots": 2, "potatoes" : 5};

$.extend(true, olddata, newdata);

This will generate:

{"fruit":{"apples":10,"pears":21}, "vegetables":{"carrots":2,"potatoes":5}};

Change Row background color based on cell value DataTable

DataTables has functionality for this since v 1.10

https://datatables.net/reference/option/createdRow

Example:

$('#tid_css').DataTable({
  // ...
  "createdRow": function(row, data, dataIndex) {
    if (data["column_index"] == "column_value") {
      $(row).css("background-color", "Orange");
      $(row).addClass("warning");
    }
  },
  // ...
});

How to Refresh a Component in Angular

This can be achieved via a hack, Navigate to some sample component and then navigate to the component that you want to reload.

this.router.navigateByUrl('/SampleComponent', { skipLocationChange: true });
this.router.navigate(["yourLandingComponent"]);

HttpContext.Current.User.Identity.Name is Empty

These might resolve the issue(It did for me). In IIS Express change the project property values, "Anonymous Authentication" and "Windows Authentication". To do this, when project is selected, press F4 and then change these properties.

enter image description here

In case you are deploying it on IIS locally, make sure local machines "Windows Authentication" feature is enabled and "Anonymous Authentication" is disabled.

Refer to

https://grekai.wordpress.com/2011/03/31/httpcontext-current-user-identity-name-is-empty/

Automatic vertical scroll bar in WPF TextBlock?

I tried to to get these suggestions to work for a textblock, but couldn't get it to work. I even tried to get it to work from the designer. (Look in Layout and expand the list by clicking the down-arrow "V" at the bottom) I tried setting the scrollviewer to Visible and then Auto, but it still wouldn't work.

I eventually gave up and changed the TextBlock to a TextBox with the Readonly attribute set, and it worked like a charm.

Simplest two-way encryption using PHP

Edited:

You should really be using openssl_encrypt() & openssl_decrypt()

As Scott says, Mcrypt is not a good idea as it has not been updated since 2007.

There is even an RFC to remove Mcrypt from PHP - https://wiki.php.net/rfc/mcrypt-viking-funeral

Apply vs transform on a group object

Two major differences between apply and transform

There are two major differences between the transform and apply groupby methods.

  • Input:
  • apply implicitly passes all the columns for each group as a DataFrame to the custom function.
  • while transform passes each column for each group individually as a Series to the custom function.
  • Output:
  • The custom function passed to apply can return a scalar, or a Series or DataFrame (or numpy array or even list).
  • The custom function passed to transform must return a sequence (a one dimensional Series, array or list) the same length as the group.

So, transform works on just one Series at a time and apply works on the entire DataFrame at once.

Inspecting the custom function

It can help quite a bit to inspect the input to your custom function passed to apply or transform.

Examples

Let's create some sample data and inspect the groups so that you can see what I am talking about:

import pandas as pd
import numpy as np
df = pd.DataFrame({'State':['Texas', 'Texas', 'Florida', 'Florida'], 
                   'a':[4,5,1,3], 'b':[6,10,3,11]})

     State  a   b
0    Texas  4   6
1    Texas  5  10
2  Florida  1   3
3  Florida  3  11

Let's create a simple custom function that prints out the type of the implicitly passed object and then raised an error so that execution can be stopped.

def inspect(x):
    print(type(x))
    raise

Now let's pass this function to both the groupby apply and transform methods to see what object is passed to it:

df.groupby('State').apply(inspect)

<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
RuntimeError

As you can see, a DataFrame is passed into the inspect function. You might be wondering why the type, DataFrame, got printed out twice. Pandas runs the first group twice. It does this to determine if there is a fast way to complete the computation or not. This is a minor detail that you shouldn't worry about.

Now, let's do the same thing with transform

df.groupby('State').transform(inspect)
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
RuntimeError

It is passed a Series - a totally different Pandas object.

So, transform is only allowed to work with a single Series at a time. It is impossible for it to act on two columns at the same time. So, if we try and subtract column a from b inside of our custom function we would get an error with transform. See below:

def subtract_two(x):
    return x['a'] - x['b']

df.groupby('State').transform(subtract_two)
KeyError: ('a', 'occurred at index a')

We get a KeyError as pandas is attempting to find the Series index a which does not exist. You can complete this operation with apply as it has the entire DataFrame:

df.groupby('State').apply(subtract_two)

State     
Florida  2   -2
         3   -8
Texas    0   -2
         1   -5
dtype: int64

The output is a Series and a little confusing as the original index is kept, but we have access to all columns.


Displaying the passed pandas object

It can help even more to display the entire pandas object within the custom function, so you can see exactly what you are operating with. You can use print statements by I like to use the display function from the IPython.display module so that the DataFrames get nicely outputted in HTML in a jupyter notebook:

from IPython.display import display
def subtract_two(x):
    display(x)
    return x['a'] - x['b']

Screenshot: enter image description here


Transform must return a single dimensional sequence the same size as the group

The other difference is that transform must return a single dimensional sequence the same size as the group. In this particular instance, each group has two rows, so transform must return a sequence of two rows. If it does not then an error is raised:

def return_three(x):
    return np.array([1, 2, 3])

df.groupby('State').transform(return_three)
ValueError: transform must return a scalar value for each group

The error message is not really descriptive of the problem. You must return a sequence the same length as the group. So, a function like this would work:

def rand_group_len(x):
    return np.random.rand(len(x))

df.groupby('State').transform(rand_group_len)

          a         b
0  0.962070  0.151440
1  0.440956  0.782176
2  0.642218  0.483257
3  0.056047  0.238208

Returning a single scalar object also works for transform

If you return just a single scalar from your custom function, then transform will use it for each of the rows in the group:

def group_sum(x):
    return x.sum()

df.groupby('State').transform(group_sum)

   a   b
0  9  16
1  9  16
2  4  14
3  4  14

View's getWidth() and getHeight() returns 0

Height and width are zero because view has not been created by the time you are requesting it's height and width . One simplest solution is

view.post(new Runnable() {
        @Override
        public void run() {
            view.getHeight(); //height is ready
            view.getWidth(); //width is ready
        }
    });

This method is good as compared to other methods as it is short and crisp.

How do I include a file over 2 directories back?

You can do ../../directory/file.txt - This goes two directories back.

../../../ - this goes three. etc

How is a non-breaking space represented in a JavaScript string?

&nbsp; is a HTML entity. When doing .text(), all HTML entities are decoded to their character values.

Instead of comparing using the entity, compare using the actual raw character:

var x = td.text();
if (x == '\xa0') { // Non-breakable space is char 0xa0 (160 dec)
  x = '';
}

Or you can also create the character from the character code manually it in its Javascript escaped form:

var x = td.text();
if (x == String.fromCharCode(160)) { // Non-breakable space is char 160
  x = '';
}

More information about String.fromCharCode is available here:

fromCharCode - MDC Doc Center

More information about character codes for different charsets are available here:

Windows-1252 Charset
UTF-8 Charset

Xcode 9 error: "iPhone has denied the launch request"

It's an intermittent bug in Xcode - I just stopped and started all my devices and it magically worked (after messing about for 1/2 hour) I had upgraded MacOS overnight to 10.13.04 which obviously upset something! Xcode 9.3, iOS 11.3 watchOS 4.3

How do I undo 'git add' before commit?

To reset every file in a particular folder (and its subfolders), you can use the following command:

git reset *

Call a url from javascript

If you need to be checking external pages, you won't be able to get away with a pure javascript solution, since any requests to external URLs are blocked. You can get away with it by using JSONP, but that won't work unless the page you're requesting only serves up JSON.

You need to have a proxy on your own server to get the external links for you. This is actually rather simple with any server-side language.

<?php
$contents = file_get_contents($_GET['url']); // please do some sanitation here...
                                             // i'm just showing an example.
echo $contents;
?>

If you needed to check server response codes (eg: 404, 301, etc), then using a library such as cURL in your server-side script could retrieve that information and then pass it onto your javascript app.

Thinking about it now, there probably could be JSONP-enabled proxies out there for you to use, should the "setting up my own proxy" option not be viable.

How do I find the mime-type of a file with php?

mime_content_type() is deprecated, so you won't be able to count on it working in the future. There is a "fileinfo" PECL extension, but I haven't heard good things about it.

If you are running on a *nix server, you can do the following, which has worked fine for me:

$file = escapeshellarg( $filename );
$mime = shell_exec("file -bi " . $file);
$filename should probably include the absolute path.

How do I initialize a TypeScript Object with a JSON-Object?

The 4th option described above is a simple and nice way to do it, which has to be combined with the 2nd option in the case where you have to handle a class hierarchy like for instance a member list which is any of a occurences of subclasses of a Member super class, eg Director extends Member or Student extends Member. In that case you have to give the subclass type in the json format

Jenkins: Is there any way to cleanup Jenkins workspace?

Assuming the question is about cleaning the workspace of the current job, you can run:

test -n "$WORKSPACE" && rm -rf "$WORKSPACE"/*

Using the GET parameter of a URL in JavaScript

Here's some sample code for that.

<script>
var param1var = getQueryVariable("param1");

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  alert('Query Variable ' + variable + ' not found');
}
</script>

Selenium using Python - Geckodriver executable needs to be in PATH

For Windows users

Use the original code as it's:

from selenium import webdriver
browser = webdriver.Firefox()
driver.get("https://www.google.com")

Then download the driver from: mozilla/geckodriver

Place it in a fixed path (permanently)... As an example, I put it in:

C:\Python35

Then go to the environment variables of the system. In the grid of "System variables" look for the Path variable and add:

;C:\Python35\geckodriver

geckodriver, not geckodriver.exe.

Unit test naming best practices

Kent Beck suggests:

  • One test fixture per 'unit' (class of your program). Test fixtures are classes themselves. The test fixture name should be:

    [name of your 'unit']Tests
    
  • Test cases (the test fixture methods) have names like:

    test[feature being tested]
    

For example, having the following class:

class Person {
    int calculateAge() { ... }

    // other methods and properties
}

A test fixture would be:

class PersonTests {

    testAgeCalculationWithNoBirthDate() { ... }

    // or

    testCalculateAge() { ... }
}

Determine a user's timezone

JavaScript:

function maketimus(timestampz)
{
    var linktime = new Date(timestampz * 1000);
    var linkday = linktime.getDate();
    var freakingmonths = new Array();

    freakingmonths[0]  = "jan";
    freakingmonths[1]  = "feb";
    freakingmonths[2]  = "mar";
    freakingmonths[3]  = "apr";
    freakingmonths[4]  = "may";
    freakingmonths[5]  = "jun";
    freakingmonths[6]  = "jul";
    freakingmonths[7]  = "aug";
    freakingmonths[8]  = "sep";
    freakingmonths[9]  = "oct";
    freakingmonths[10] = "nov";
    freakingmonths[11] = "dec";

    var linkmonthnum = linktime.getMonth();
    var linkmonth = freakingmonths[linkmonthnum];
    var linkyear = linktime.getFullYear();
    var linkhour = linktime.getHours();
    var linkminute = linktime.getMinutes();

    if (linkminute < 10)
    {
        linkminute = "0" + linkminute;
    }

    var fomratedtime = linkday + linkmonth + linkyear + " " +
                       linkhour + ":" + linkminute + "h";
    return fomratedtime;
}

Simply provide your times in Unix timestamp format to this function; JavaScript already knows the timezone of the user.

Like this:

PHP:

echo '<script type="text/javascript">
var eltimio = maketimus('.$unix_timestamp_ofshiz.');
document.write(eltimio);
</script><noscript>pls enable javascript</noscript>';

This will always show the times correctly based on the timezone the person has set on his/her computer clock. There is no need to ask anything to anyone and save it into places, thank god!

When do I use path params vs. query params in a RESTful API?

Example URL: /rest/{keyword}

This URL is an example for path parameters. We can get this URL data by using @PathParam.

Example URL: /rest?keyword=java&limit=10

This URL is an example for query parameters. We can get this URL data by using @Queryparam.

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

A bit late to the game, but non of the above solutions pointed me in the direction of a pure and simple .NET, no json.net solution. So here it is, ended up being very simple. Below a full running example of how it is done with standard .NET Json serialization, the example has dictionary both in the root object and in the child objects.

The golden bullet is this cat, parse the settings as second parameter to the serializer:

DataContractJsonSerializerSettings settings =
                       new DataContractJsonSerializerSettings();
                    settings.UseSimpleDictionaryFormat = true;

Full code below:

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

    namespace Kipon.dk
    {
        public class JsonTest
        {
            public const string EXAMPLE = @"{
                ""id"": ""some id"",
                ""children"": {
                ""f1"": {
                    ""name"": ""name 1"",
                    ""subs"": {
                    ""1"": { ""name"": ""first sub"" },
                    ""2"": { ""name"": ""second sub"" }
                    }
                },
                ""f2"": {
                    ""name"": ""name 2"",
                    ""subs"": {
                    ""37"": { ""name"":  ""is 37 in key""}
                    }
                }
                }
            }
            ";

            [DataContract]
            public class Root
            {
                [DataMember(Name ="id")]
                public string Id { get; set; }

                [DataMember(Name = "children")]
                public Dictionary<string,Child> Children { get; set; }
            }

            [DataContract]
            public class Child
            {
                [DataMember(Name = "name")]
                public string Name { get; set; }

                [DataMember(Name = "subs")]
                public Dictionary<int, Sub> Subs { get; set; }
            }

            [DataContract]
            public class Sub
            {
                [DataMember(Name = "name")]
                public string Name { get; set; }
            }

            public static void Test()
            {
                var array = System.Text.Encoding.UTF8.GetBytes(EXAMPLE);
                using (var mem = new System.IO.MemoryStream(array))
                {
                    mem.Seek(0, System.IO.SeekOrigin.Begin);
                    DataContractJsonSerializerSettings settings =
                       new DataContractJsonSerializerSettings();
                    settings.UseSimpleDictionaryFormat = true;

                    var ser = new DataContractJsonSerializer(typeof(Root), settings);
                    var data = (Root)ser.ReadObject(mem);
                    Console.WriteLine(data.Id);
                    foreach (var childKey in data.Children.Keys)
                    {
                        var child = data.Children[childKey];
                        Console.WriteLine(" Child: " + childKey + " " + child.Name);
                        foreach (var subKey in child.Subs.Keys)
                        {
                            var sub = child.Subs[subKey];
                            Console.WriteLine("   Sub: " + subKey + " " + sub.Name);
                        }
                    }
                }
            }
        }
    }

How to add an image to a JPanel?

You can avoid rolling your own Component subclass completely by using the JXImagePanel class from the free SwingX libraries.

Download

Manifest merger failed : uses-sdk:minSdkVersion 14

I also had the same issue and changing following helped me:

from:

dependencies {
    compile 'com.android.support:support-v4:+'

to:

dependencies {
 compile 'com.android.support:support-v4:20.0.0'
}

map vs. hash_map in C++

The C++ spec doesn't say exactly what algorithm you must use for the STL containers. It does, however, put certain constraints on their performance, which rules out the use of hash tables for map and other associative containers. (They're most commonly implemented with red/black trees.) These constraints require better worst-case performance for these containers than hash tables can deliver.

Many people really do want hash tables, however, so hash-based STL associative containers have been a common extension for years. Consequently, they added unordered_map and such to later versions of the C++ standard.

Detect Click into Iframe using JavaScript

This definitely works if the iframe is from the same domain as your parent site. I have not tested it for cross-domain sites.

$(window.frames['YouriFrameId']).click(function(event){  /* do something here  */ });
$(window.frames['YouriFrameId']).mousedown(function(event){ /* do something here */ });
$(window.frames['YouriFrameId']).mouseup(function(event){ /* do something here */ });

Without jQuery you could try something like this, but again I have not tried this.

window.frames['YouriFrameId'].onmousedown = function() { do something here }

You can even filter your results:

$(window.frames['YouriFrameId']).mousedown(function(event){   
  var eventId = $(event.target).attr('id');      
  if (eventId == 'the-id-you-want') {
   //  do something
  }
});

How to label scatterplot points by name?

Another convoluted answer which should technically work and is ok for a small number of data points is to plot all your data points as 1 series in order to get your connecting line. Then plot each point as its own series. Then format data labels to display series name for each of the individual data points.

In short it works ok for a small data set or just key points from a data set.

Section vs Article HTML5

I like to stick with the standard meaning of the words used: An article would apply to, well, articles. I would define blog posts, documents, and news articles as articles. Sections on the other hand, would refer to layout/ux items: sidebar, header, footer would be sections. However this is all my own personal interpretation -- as you pointed out, the specification for these elements are not well defined.

Supporting this, the w3c defines an article element as a section of content that can independently stand on its own. A blog post could stand on it's own as a valuable and consumable item of content. However, a header would not.

Here is an interesting article about one mans madness in trying to differenciate between the two new elements. The basic point of the article, that I also feel is correct, is to try and use what ever element you feel best actually represents what it contains.

What’s more problematic is that article and section are so very similar. All that separates them is the word “self-contained”. Deciding which element to use would be easy if there were some hard and fast rules. Instead, it’s a matter of interpretation. You can have multiple articles within a section, you can have multiple sections within and article, you can nest sections within sections and articles within sections. It’s up to you to decide which element is the most semantically appropriate in any given situation.

Here is a very good answer to the same question here on SO

Remove URL parameters without refreshing page

a single line solution :

history.replaceState && history.replaceState(
  null, '', location.pathname + location.search.replace(/[\?&]my_parameter=[^&]+/, '').replace(/^&/, '?')
);

credits : https://gist.github.com/simonw/9445b8c24ddfcbb856ec

iOS Swift - Get the Current Local Time and Date Timestamp

If you code for iOS 13.0 or later and want a timestamp, then you can use:

let currentDate = NSDate.now

JavaScript: get code to run every minute

Using setInterval:

setInterval(function() {
    // your code goes here...
}, 60 * 1000); // 60 * 1000 milsec

The function returns an id you can clear your interval with clearInterval:

var timerID = setInterval(function() {
    // your code goes here...
}, 60 * 1000); 

clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.

A "sister" function is setTimeout/clearTimeout look them up.


If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:

function fn60sec() {
    // runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);

How to SELECT in Oracle using a DBLINK located in a different schema?

I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).

A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.

Do like this:

create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;

Windows task scheduler error 101 launch failure code 2147943785

I have the same today on Win7.x64, this solve it.

Right Click MyComputer > Manage > Local Users and Groups > Groups > Administrators double click > your name should be there, if not press add...

How to check if a folder exists

You need to transform your Path into a File and test for existence:

for(Path entry: stream){
  if(entry.toFile().exists()){
    log.info("working on file " + entry.getFileName());
  }
}

MySQL Event Scheduler on a specific time everyday

DROP EVENT IF EXISTS xxxEVENTxxx;
CREATE EVENT xxxEVENTxxx
  ON SCHEDULE
    EVERY 1 DAY
    STARTS (TIMESTAMP(CURRENT_DATE) + INTERVAL 1 DAY + INTERVAL 1 HOUR)
  DO
    --process;

¡IMPORTANT!->

SET GLOBAL event_scheduler = ON;

jQuery check if <input> exists and has a value

I would do something like this: $('input[value]').something . This finds all inputs that have value and operates something onto them.

How to create image slideshow in html?

  1. Set var step=1 as global variable by putting it above the function call
  2. put semicolons

It will look like this

<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "images/pentagg.jpg"
var image2 = new Image()
image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
        var step=1;
        function slideit()
        {
            document.images.slide.src = eval("image"+step+".src");
            if(step<2)
                step++;
            else
                step=1;
            setTimeout("slideit()",2500);
        }
        slideit();
</script>
</body>

How does true/false work in PHP?

think of operator as unary function: is_false(type value) which returns true or false, depending on the exact implementation for specific type and value. Consider if statement to invoke such function implicitly, via syntactic sugar.

other possibility is that type has cast operator, which turns type into another type implicitly, in this case string to Boolean.

PHP does not expose such details, but C++ allows operator overloading which exposes fine details of operator implementation.

How to post data in PHP using file_get_contents?

An alternative, you can also use fopen

$params = array('http' => array(
    'method' => 'POST',
    'content' => 'toto=1&tata=2'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if ($response === false) 
{
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}

How to use the TextWatcher class in Android?

Using TextWatcher in Android

Here is a sample code. Try using addTextChangedListener method of TextView

addTextChangedListener(new TextWatcher() {

        BigDecimal previousValue;
        BigDecimal currentValue;

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int
                count) {
            if (isFirstTimeChange) {
                return;
            }
            if (s.toString().length() > 0) {
                try {
                    currentValue = new BigDecimal(s.toString().replace(".", "").replace(',', '.'));
                } catch (Exception e) {
                    currentValue = new BigDecimal(0);
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            if (isFirstTimeChange) {
                return;
            }
            if (s.toString().length() > 0) {
                try {
                    previousValue = new BigDecimal(s.toString().replace(".", "").replace(',', '.'));
                } catch (Exception e) {
                    previousValue = new BigDecimal(0);
                }
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (isFirstTimeChange) {
                isFirstTimeChange = false;
                return;
            }
            if (currentValue != null && previousValue != null) {
                if ((currentValue.compareTo(previousValue) > 0)) {
                    //setBackgroundResource(R.color.devises_overview_color_green);
                    setBackgroundColor(flashOnColor);
                } else if ((currentValue.compareTo(previousValue) < 0)) {
                    //setBackgroundResource(R.color.devises_overview_color_red);

                    setBackgroundColor(flashOffColor);
                } else {
                    //setBackgroundColor(textColor);
                }
                handler.removeCallbacks(runnable);
                handler.postDelayed(runnable, 1000);
            }
        }
    });

How to prevent a dialog from closing when a button is clicked

It could be built with easiest way:

Alert Dialog with Custom View and with two Buttons (Positive & Negative).

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setTitle(getString(R.string.select_period));
builder.setPositiveButton(getString(R.string.ok), null);

 builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {

    // Click of Cancel Button

   }
 });

  LayoutInflater li = LayoutInflater.from(getActivity());
  View promptsView = li.inflate(R.layout.dialog_date_picker, null, false);
  builder.setView(promptsView);

  DatePicker startDatePicker = (DatePicker)promptsView.findViewById(R.id.startDatePicker);
  DatePicker endDatePicker = (DatePicker)promptsView.findViewById(R.id.endDatePicker);

  final AlertDialog alertDialog = builder.create();
  alertDialog.show();

  Button theButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
  theButton.setOnClickListener(new CustomListener(alertDialog, startDatePicker, endDatePicker));

CustomClickLister of Positive Button of Alert Dailog:

private class CustomListener implements View.OnClickListener {
        private final Dialog dialog;
        private DatePicker mStartDp, mEndDp;
    public CustomListener(Dialog dialog, DatePicker dS, DatePicker dE) {
        this.dialog = dialog;
        mStartDp = dS;
        mEndDp = dE;
    }

    @Override
    public void onClick(View v) {

        int day1  = mStartDp.getDayOfMonth();
        int month1= mStartDp.getMonth();
        int year1 = mStartDp.getYear();
        Calendar cal1 = Calendar.getInstance();
        cal1.set(Calendar.YEAR, year1);
        cal1.set(Calendar.MONTH, month1);
        cal1.set(Calendar.DAY_OF_MONTH, day1);


        int day2  = mEndDp.getDayOfMonth();
        int month2= mEndDp.getMonth();
        int year2 = mEndDp.getYear();
        Calendar cal2 = Calendar.getInstance();
        cal2.set(Calendar.YEAR, year2);
        cal2.set(Calendar.MONTH, month2);
        cal2.set(Calendar.DAY_OF_MONTH, day2);

        if(cal2.getTimeInMillis()>=cal1.getTimeInMillis()){
            dialog.dismiss();
            Log.i("Dialog", "Dismiss");
            // Condition is satisfied so do dialog dismiss
            }else {
            Log.i("Dialog", "Do not Dismiss");
            // Condition is not satisfied so do not dialog dismiss
        }

    }
}

Done

Android TabLayout Android Design

So easy way :

XML:

<android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fff"/>
<android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

Java code:

private ViewPager viewPager;

private String[] PAGE_TITLES = new String[]{
        "text1",
        "text1",
        "text3"
};
private final Fragment[] PAGES = new Fragment[]{
        new fragment1(), 
        new fragment2(),
        new fragment3()

};

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

    /**TODO ***************tebLayout*************************/
    viewPager = findViewById(R.id.viewpager);
    viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
    TabLayout tabLayout = findViewById(R.id.tab_layout);
    tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#1f57ff"));
    tabLayout.setSelectedTabIndicatorHeight((int) (4 * 
    getResources().getDisplayMetrics().density));
    tabLayout.setTabTextColors(Color.parseColor("#9d9d9d"), 
    Color.parseColor("#0d0e10"));
    tabLayout.setupWithViewPager(viewPager);
    /***************************************************************************/
    }

How to enable C++11 in Qt Creator?

As an alternative for handling both cases addressed in Ali's excellent answer, I usually add

# With C++11 support
greaterThan(QT_MAJOR_VERSION, 4){    
CONFIG += c++11
} else {
QMAKE_CXXFLAGS += -std=c++0x
}

to my project files. This can be handy when you don't really care much about which Qt version is people using in your team, but you want them to have C++11 enabled in any case.

Get a random boolean in python?

u could try this it produces randomly generated array of true and false :

a=[bool(i) for i in np.array(np.random.randint(0,2,10))]

out: [True, True, True, True, True, False, True, False, True, False]

How to redirect both stdout and stderr to a file

Use:

command >>log_file 2>>log_file

How to use split?

Look in JavaScript split() Method

Usage:

"something -- something_else".split(" -- ") 

How to get class object's name as a string in Javascript?

This is pretty old, but I ran across this question via Google, so perhaps this solution might be useful to others.

function GetObjectName(myObject){
    var objectName=JSON.stringify(myObject).match(/"(.*?)"/)[1];
    return objectName;
}

It just uses the browser's JSON parser and regex without cluttering up the DOM or your object too much.

Find and kill a process in one line using bash and regex

I use gkill processname, where gkill is the following script:

cnt=`ps aux|grep $1| grep -v "grep" -c`
if [ "$cnt" -gt 0 ]
then
    echo "Found $cnt processes - killing them"
    ps aux|grep $1| grep -v "grep"| awk '{print $2}'| xargs kill
else
    echo "No processes found"
fi

NOTE: it will NOT kill processes that have "grep" in their command lines.

How to calculate age (in years) based on Date of Birth and getDate()

After trying MANY methods, this works 100% of the time using the modern MS SQL FORMAT function instead of convert to style 112. Either would work but this is the least code.

Can anyone find a date combination which does not work? I don't think there is one :)

--Set parameters, or choose from table.column instead:

DECLARE @DOB    DATE = '2000/02/29' -- If @DOB is a leap day...
       ,@ToDate DATE = '2018/03/01' --...there birthday in this calculation will be 

--0+ part tells SQL to calc the char(8) as numbers:
SELECT [Age] = (0+ FORMAT(@ToDate,'yyyyMMdd') - FORMAT(@DOB,'yyyyMMdd') ) /10000

Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.

Add the below line in your app.gradle file before depencencies block.

configurations.all {
    resolutionStrategy {
        force 'com.android.support:support-annotations:26.1.0'
    }
}

There's also screenshot below for a better understanding.

Configurations.all block

  1. the configurations.all block will only be helpful if you want your target sdk to be 26. If you can change it to 27 the error will be gone without adding the configuration block in app.gradle file.

  2. There is one more way if you would remove all the test implementation from app.gradle file it would resolve the error and in this also you dont need to add the configuration block nor you need to change the targetsdk version.

Hope that helps.

Can I replace groups in Java regex?

replace the password fields from the input:

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



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

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

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

np.mean() vs np.average() in Python NumPy?

In addition to the differences already noted, there's another extremely important difference that I just now discovered the hard way: unlike np.mean, np.average doesn't allow the dtype keyword, which is essential for getting correct results in some cases. I have a very large single-precision array that is accessed from an h5 file. If I take the mean along axes 0 and 1, I get wildly incorrect results unless I specify dtype='float64':

>T.shape
(4096, 4096, 720)
>T.dtype
dtype('<f4')

m1 = np.average(T, axis=(0,1))                #  garbage
m2 = np.mean(T, axis=(0,1))                   #  the same garbage
m3 = np.mean(T, axis=(0,1), dtype='float64')  # correct results

Unfortunately, unless you know what to look for, you can't necessarily tell your results are wrong. I will never use np.average again for this reason but will always use np.mean(.., dtype='float64') on any large array. If I want a weighted average, I'll compute it explicitly using the product of the weight vector and the target array and then either np.sum or np.mean, as appropriate (with appropriate precision as well).

Filename timestamp in Windows CMD batch script getting truncated

It wants the full time in DD-MM-YYYY_HH-MM-SS.TT where TT is the ticks. The exception says it all.

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Remove leading zeros from a number in Javascript

It is not clear why you want to do this. If you want to get the correct numerical value, you could use unary + [docs]:

value = +value;

If you just want to format the text, then regex could be better. It depends on the values you are dealing with I'd say. If you only have integers, then

input.value = +input.value;

is fine as well. Of course it also works for float values, but depending on how many digits you have after the point, converting it to a number and back to a string could (at least for displaying) remove some.

Using jq to parse and display multiple fields in a json serially

I got pretty close to what I wanted by doing something like this

cat my.json | jq '.my.prefix[] | .primary_key + ":", (.sub.prefix[] | "    - " + .sub_key)' | tr -d '"' 

The output of which is close enough to yaml for me to usually import it into other tools without much problem. (I am still looking for a way to basicallt export a subset of the input json)

Can't import org.apache.http.HttpResponse in Android Studio

Main build.gradle - /build.gradle

buildscript {
    ...
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.1' 
        // Versions: http://jcenter.bintray.com/com/android/tools/build/gradle/
    }
    ...
}

Module specific build.gradle - /app/build.gradle

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    ...
    useLibrary 'org.apache.http.legacy'
    ...
}

TABLOCK vs TABLOCKX

Quite an old article on mssqlcity attempts to explain the types of locks:

Shared locks are used for operations that do not change or update data, such as a SELECT statement.

Update locks are used when SQL Server intends to modify a page, and later promotes the update page lock to an exclusive page lock before actually making the changes.

Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or DELETE.

What it doesn't discuss are Intent (which basically is a modifier for these lock types). Intent (Shared/Exclusive) locks are locks held at a higher level than the real lock. So, for instance, if your transaction has an X lock on a row, it will also have an IX lock at the table level (which stops other transactions from attempting to obtain an incompatible lock at a higher level on the table (e.g. a schema modification lock) until your transaction completes or rolls back).


The concept of "sharing" a lock is quite straightforward - multiple transactions can have a Shared lock for the same resource, whereas only a single transaction may have an Exclusive lock, and an Exclusive lock precludes any transaction from obtaining or holding a Shared lock.

Rotate label text in seaborn factorplot

For a seaborn.heatmap, you can rotate these using (based on @Aman's answer)

pandas_frame = pd.DataFrame(data, index=names, columns=names)
heatmap = seaborn.heatmap(pandas_frame)
loc, labels = plt.xticks()
heatmap.set_xticklabels(labels, rotation=45)
heatmap.set_yticklabels(labels[::-1], rotation=45) # reversed order for y

receiving error: 'Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN' while using npm

Putting this before the command seems to work NODE_TLS_REJECT_UNAUTHORIZED=0. ex: NODE_TLS_REJECT_UNAUTHORIZED=0 npm ...

It would be best to figure out how to make node see self signed certificate as valid. strict-ssl suggestion above didn't work for me for some reason. If you understand the security implications and need a temporary quick fix, this is what I found in some random github issues during Google search of the error.

How to PUT a json object with an array using curl

Try using a single quote instead of double quotes along with -g

Following scenario worked for me

curl -g -d '{"collection":[{"NumberOfParcels":1,"Weight":1,"Length":1,"Width":1,"Height":1}]}" -H "Accept: application/json" -H "Content-Type: application/json" --user [email protected]:123456 -X POST  https://yoururl.com

WITH

curl -g -d "{'collection':[{'NumberOfParcels':1,'Weight':1,'Length':1,'Width':1,'Height':1}]}" -H "Accept: application/json" -H "Content-Type: application/json" --user [email protected]:123456 -X POST  https://yoururl.com

This especially resolved my error curl command error : bad url colon is first character

Add a custom attribute to a Laravel / Eloquent model on load?

you can use setAttribute function in Model to add a custom attribute

Highlight a word with jQuery

Is it possible to get this above example:

jQuery.fn.highlight = function (str, className)
{
    var regex = new RegExp(str, "g");

    return this.each(function ()
    {
        this.innerHTML = this.innerHTML.replace(
            regex,
            "<span class=\"" + className + "\">" + str + "</span>"
        );
    });
};

not to replace text inside html-tags like , this otherwise breakes the page.

How to increase memory limit for PHP over 2GB?

You should have 64-bit OS on hardware that supports 64-bit OS, 64-bit Apache version and the same for PHP. But this does not guarantee that functions that are work with PDF can use such big sizes of memory. You'd better not load the whole file into memory, split it into chunks or use file functions to seek on it without loading to RAM.

Exit a while loop in VBS/VBA

While Loop is an obsolete structure, I would recommend you to replace "While loop" to "Do While..loop", and you will able to use Exit clause.

check = 0 

Do while not rs.EOF 
   if rs("reg_code") = rcode then 
      check = 1 
      Response.Write ("Found") 
      Exit do
   else 
      rs.MoveNext 
    end if 
Loop 

if check = 0 then 
   Response.Write "Not Found" 
end if}

Disable LESS-CSS Overwriting calc()

Apart from using an escaped value as described in my other answer, it is also possible to fix this issue by enabling the Strict Math setting.

With strict math on, only maths that are inside unnecessary parentheses will be processed, so your code:

width: calc(100% - 200px);

Would work as expected with the strict math option enabled.

However, note that Strict Math is applied globally, not only inside calc(). That means, if you have:

font-size: 12px + 2px;

The math will no longer be processed by Less -- it will output font-size: 12px + 2px which is, obviously, invalid CSS. You'd have to wrap all maths that should be processed by Less in (previously unnecessary) parentheses:

font-size: (12px + 2px);

Strict Math is a nice option to consider when starting a new project, otherwise you'd possibly have to rewrite a good part of the code base. For the most common use cases, the escaped string approach described in the other answer is more suitable.

Cannot find control with name: formControlName in angular reactive form

you're missing group nested controls with formGroupName directive

<div class="panel-body" formGroupName="address">
  <div class="form-group">
    <label for="address" class="col-sm-3 control-label">Business Address</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="street" placeholder="Business Address">
    </div>
  </div>
  <div class="form-group">
    <label for="website" class="col-sm-3 control-label">Website</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="website" placeholder="website">
    </div>
  </div>
  <div class="form-group">
    <label for="telephone" class="col-sm-3 control-label">Telephone</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="mobile" placeholder="telephone">
    </div>
  </div>
  <div class="form-group">
    <label for="email" class="col-sm-3 control-label">Email</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="email" placeholder="email">
    </div>
  </div>
  <div class="form-group">
    <label for="page id" class="col-sm-3 control-label">Facebook Page ID</label>
    <div class="col-sm-8">
      <input type="text" class="form-control" formControlName="pageId" placeholder="facebook page id">
    </div>
  </div>
  <div class="form-group">
    <label for="about" class="col-sm-3  control-label"></label>
    <div class="col-sm-3">
      <!--span class="btn btn-success form-control" (click)="openGeneralPanel()">Back</span-->
    </div>
    <label for="about" class="col-sm-2  control-label"></label>
    <div class="col-sm-3">
      <button class="btn btn-success form-control" [disabled]="companyCreatForm.invalid" (click)="openContactInfo()">Continue</button>
    </div>
  </div>
</div>

Good beginners tutorial to socket.io?

To start with Socket.IO I suggest you read first the example on the main page:

http://socket.io/

On the server side, read the "How to use" on the GitHub source page:

https://github.com/Automattic/socket.io

And on the client side:

https://github.com/Automattic/socket.io-client

Finally you need to read this great tutorial:

http://howtonode.org/websockets-socketio

Hint: At the end of this blog post, you will have some links pointing on source code that could be some help.

Is there a way to get the git root directory in one command?

To write a simple answer here, so that we can use

git root

to do the job, simply configure your git by using

git config --global alias.root "rev-parse --show-toplevel"

and then you might want to add the following to your ~/.bashrc:

alias cdroot='cd $(git root)'

so that you can just use cdroot to go to the top of your repo.

java.lang.RuntimeException: Uncompilable source code - what can cause this?

I had the same problem. My error was the packaging. So I would suggest you first check the package name and if the class is in the correct package.

A generic error occurred in GDI+, JPEG Image to MemoryStream

You'll also get this exception if you try to save to an invalid path or if there's a permissions issue.

If you're not 100% sure that the file path is available and permissions are correct then try writing a to a text file. This takes just a few seconds to rule out what would be a very simple fix.

var img = System.Drawing.Image.FromStream(incomingStream);

// img.Save(path);
System.IO.File.WriteAllText(path, "Testing valid path & permissions.");

And don't forget to clean up your file.

How do I export an Android Studio project?

Windows:

First Open Command Window and set location of your android studio project folder like:

D:\MyApplication>

then type below command in it:

gradlew clean

then wait for complete clean process. after complete it now zip your project like below:

  • right click on your project folder
  • then select send to option now
  • select compressed via zip

How to fill Dataset with multiple tables?

DataSet ds = new DataSet();
using (var reader = cmd.ExecuteReader())
{
    while (!reader.IsClosed)
         {
              ds.Tables.Add().Load(reader);
         }
}
return ds;

How can I get the number of records affected by a stored procedure?

For Microsoft SQL Server you can return the @@ROWCOUNT variable to return the number of rows affected by the last statement in the stored procedure.

jQuery How to Get Element's Margin and Padding?

var bordT = $('img').outerWidth() - $('img').innerWidth();
var paddT = $('img').innerWidth() - $('img').width();
var margT = $('img').outerWidth(true) - $('img').outerWidth();

var formattedBord = bordT + 'px';
var formattedPadd = paddT + 'px';
var formattedMarg = margT + 'px';

Check the jQuery API docs for information on each:

Here's the edited jsFiddle showing the result.

You can perform the same type of operations for the Height to get its margin, border, and padding.

Use jQuery to get the file input's selected filename without the path

You just need to do the code below. The first [0] is to access the HTML element and second [0] is to access the first file of the file upload (I included a validation in case that there is no file):

    var filename = $('input[type=file]')[0].files.length ? ('input[type=file]')[0].files[0].name : "";

What are the differences between "git commit" and "git push"?

Well, basically git commit puts your changes into your local repo, while git push sends your changes to the remote location.

WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?

TODO:

  1. Have Apache 2.4 installed (doesn't work with 2.2), a2enmod proxy and a2enmod proxy_wstunnel.load

  2. Do this in the Apache config
    just add two line in your file where 8080 is your tomcat running port

    <VirtualHost *:80>
    ProxyPass "/ws2/" "ws://localhost:8080/" 
    ProxyPass "/wss2/" "wss://localhost:8080/"
    
    </VirtualHost *:80>
    

Django URLs TypeError: view must be a callable or a list/tuple in the case of include()

Your code is

urlpatterns = [
    url(r'^$', 'myapp.views.home'),
    url(r'^contact/$', 'myapp.views.contact'),
    url(r'^login/$', 'django.contrib.auth.views.login'),
]

change it to following as you're importing include() function :

urlpatterns = [
    url(r'^$', views.home),
    url(r'^contact/$', views.contact),
    url(r'^login/$', views.login),
]

How to convert a DataFrame back to normal RDD in pyspark?

Answer given by kennyut/Kistian works very well but to get exact RDD like output when RDD consist of list of attributes e.g. [1,2,3,4] we can use flatmap command as below,

rdd = df.rdd.flatMap(list)
or 
rdd = df.rdd.flatmap(lambda x: list(x))

How to calculate a mod b in Python?

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

output:

1
1
0
0

How to get a file or blob from an object URL?

Using fetch for example like below:

 fetch(<"yoururl">, {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + <your access token if need>
    },
       })
.then((response) => response.blob())
.then((blob) => {
// 2. Create blob link to download
 const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `sample.xlsx`);
 // 3. Append to html page
 document.body.appendChild(link);
 // 4. Force download
 link.click();
 // 5. Clean up and remove the link
 link.parentNode.removeChild(link);
})

You can paste in on Chrome console to test. the file with download with 'sample.xlsx' Hope it can help!

How do I make the scrollbar on a div only visible when necessary?

You can try with below one:

  <div style="width: 100%; height: 100%; overflow-x: visible; overflow-y: scroll;">Text</div>

Unable to install packages in latest version of RStudio and R Version.3.1.1

Based on answers from the community, there appear to be several ways that might solve this:

  1. From the official FAQ and support forums and this answer, you may have have a firewall or proxy issue that is blocking RStudio from connecting to the internet:
  • Disable any firewalls
  • Tools -> Global Options -> Packages and unchecking the "Use Internet Explorer library/proxy for HTTP" option and restart R (#1, #2, #3)
  • Flag R with --internet2
  • On CentOS it was suggested to try the following: install.packages('package_name', dependencies=TRUE, repos='http://cran.rstudio.com/')
  1. Several answers suggest using an alternate mirror (#1, #2, #3):
  • Preferences > General > Default working directory > Browse and switch your mirror from local/global (whichever is unchecked)
  1. On Windows you can start the application with http_proxy=http://host:port/:
  • "C:\Program Files\RStudio\bin\rstudio.exe" http_proxy=http://host:port/
  1. Shut down and restart. Needed after many of the above operations, and suggested standalone.

How to know whether refresh button or browser back button is clicked in Firefox

For Back Button in jquery // http://code.jquery.com/jquery-latest.js

 jQuery(window).bind("unload", function() { //

and in html5 there is an event The event is called 'popstate'

window.onpopstate = function(event) {
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

and for refresh please check Check if page gets reloaded or refreshed in Javascript

In Mozilla Client-x and client-y is inside document area https://developer.mozilla.org/en-US/docs/Web/API/event.clientX

How to change CSS using jQuery?

$(".radioValue").css({"background-color":"-webkit-linear-gradient(#e9e9e9,rgba(255, 255, 255, 0.43137254901960786),#e9e9e9)","color":"#454545", "padding": "8px"});

How to make flutter app responsive according to different screen size?

check out this page from flutter wiki :

Creating Responsive Apps

Use the LayoutBuilder class: From its builder property, you get a BoxConstraints. Examine the constraint's properties to decide what to display. For example, if your maxWidth is greater than your width breakpoint, return a Scaffold object with a row that has a list on the left. If it's narrower, return a Scaffold object with a drawer containing that list. You can also adjust your display based on the device's height, the aspect ratio, or some other property. When the constraints change (e.g. the user rotates the phone, or puts your app into a tile UI in Nougat), the build function will rerun.

How do I convert uint to int in C#?

Assuming you want to simply lift the 32bits from one type and dump them as-is into the other type:

uint asUint = unchecked((uint)myInt);
int asInt = unchecked((int)myUint);

The destination type will blindly pick the 32 bits and reinterpret them.

Conversely if you're more interested in keeping the decimal/numerical values within the range of the destination type itself:

uint asUint = checked((uint)myInt);
int asInt = checked((int)myUint);

In this case, you'll get overflow exceptions if:

  • casting a negative int (eg: -1) to an uint
  • casting a positive uint between 2,147,483,648 and 4,294,967,295 to an int

In our case, we wanted the unchecked solution to preserve the 32bits as-is, so here are some examples:

Examples

int => uint

int....: 0000000000 (00-00-00-00)
asUint.: 0000000000 (00-00-00-00)
------------------------------
int....: 0000000001 (01-00-00-00)
asUint.: 0000000001 (01-00-00-00)
------------------------------
int....: -0000000001 (FF-FF-FF-FF)
asUint.: 4294967295 (FF-FF-FF-FF)
------------------------------
int....: 2147483647 (FF-FF-FF-7F)
asUint.: 2147483647 (FF-FF-FF-7F)
------------------------------
int....: -2147483648 (00-00-00-80)
asUint.: 2147483648 (00-00-00-80)

uint => int

uint...: 0000000000 (00-00-00-00)
asInt..: 0000000000 (00-00-00-00)
------------------------------
uint...: 0000000001 (01-00-00-00)
asInt..: 0000000001 (01-00-00-00)
------------------------------
uint...: 2147483647 (FF-FF-FF-7F)
asInt..: 2147483647 (FF-FF-FF-7F)
------------------------------
uint...: 4294967295 (FF-FF-FF-FF)
asInt..: -0000000001 (FF-FF-FF-FF)
------------------------------

Code

int[] testInts = { 0, 1, -1, int.MaxValue, int.MinValue };
uint[] testUints = { uint.MinValue, 1, uint.MaxValue / 2, uint.MaxValue };

foreach (var Int in testInts)
{
    uint asUint = unchecked((uint)Int);
    Console.WriteLine("int....: {0:D10} ({1})", Int, BitConverter.ToString(BitConverter.GetBytes(Int)));
    Console.WriteLine("asUint.: {0:D10} ({1})", asUint, BitConverter.ToString(BitConverter.GetBytes(asUint)));
    Console.WriteLine(new string('-',30));
}
Console.WriteLine(new string('=', 30));
foreach (var Uint in testUints)
{
    int asInt = unchecked((int)Uint);
    Console.WriteLine("uint...: {0:D10} ({1})", Uint, BitConverter.ToString(BitConverter.GetBytes(Uint)));
    Console.WriteLine("asInt..: {0:D10} ({1})", asInt, BitConverter.ToString(BitConverter.GetBytes(asInt)));
    Console.WriteLine(new string('-', 30));
}  

Create tap-able "links" in the NSAttributedString of a UILabel?

(My answer builds on @NAlexN's excellent answer. I won't duplicate his detailed explanation of each step here.)

I found it most convenient and straightforward to add support for tap-able UILabel text as a category to UITapGestureRecognizer. (You don't have to use UITextView's data detectors, as some answers suggest.)

Add the following method to your UITapGestureRecognizer category:

/**
 Returns YES if the tap gesture was within the specified range of the attributed text of the label.
 */
- (BOOL)didTapAttributedTextInLabel:(UILabel *)label inRange:(NSRange)targetRange {
    NSParameterAssert(label != nil);

    CGSize labelSize = label.bounds.size;
    // create instances of NSLayoutManager, NSTextContainer and NSTextStorage
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeZero];
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:label.attributedText];

    // configure layoutManager and textStorage
    [layoutManager addTextContainer:textContainer];
    [textStorage addLayoutManager:layoutManager];

    // configure textContainer for the label
    textContainer.lineFragmentPadding = 0.0;
    textContainer.lineBreakMode = label.lineBreakMode;
    textContainer.maximumNumberOfLines = label.numberOfLines;
    textContainer.size = labelSize;

    // find the tapped character location and compare it to the specified range
    CGPoint locationOfTouchInLabel = [self locationInView:label];
    CGRect textBoundingBox = [layoutManager usedRectForTextContainer:textContainer];
    CGPoint textContainerOffset = CGPointMake((labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,
                                              (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y);
    CGPoint locationOfTouchInTextContainer = CGPointMake(locationOfTouchInLabel.x - textContainerOffset.x,
                                                         locationOfTouchInLabel.y - textContainerOffset.y);
    NSInteger indexOfCharacter = [layoutManager characterIndexForPoint:locationOfTouchInTextContainer
                                                            inTextContainer:textContainer
                                   fractionOfDistanceBetweenInsertionPoints:nil];
    if (NSLocationInRange(indexOfCharacter, targetRange)) {
        return YES;
    } else {
        return NO;
    }
}

Example Code

// (in your view controller)    
// create your label, gesture recognizer, attributed text, and get the range of the "link" in your label
myLabel.userInteractionEnabled = YES;
[myLabel addGestureRecognizer:
   [[UITapGestureRecognizer alloc] initWithTarget:self 
                                           action:@selector(handleTapOnLabel:)]]; 

// create your attributed text and keep an ivar of your "link" text range
NSAttributedString *plainText;
NSAttributedString *linkText;
plainText = [[NSMutableAttributedString alloc] initWithString:@"Add label links with UITapGestureRecognizer"
                                                   attributes:nil];
linkText = [[NSMutableAttributedString alloc] initWithString:@" Learn more..."
                                                  attributes:@{
                                                      NSForegroundColorAttributeName:[UIColor blueColor]
                                                  }];
NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] init];
[attrText appendAttributedString:plainText];
[attrText appendAttributedString:linkText];

// ivar -- keep track of the target range so you can compare in the callback
targetRange = NSMakeRange(plainText.length, linkText.length);

Gesture Callback

// handle the gesture recognizer callback and call the category method
- (void)handleTapOnLabel:(UITapGestureRecognizer *)tapGesture {
    BOOL didTapLink = [tapGesture didTapAttributedTextInLabel:myLabel
                                            inRange:targetRange];
    NSLog(@"didTapLink: %d", didTapLink);

}

Use "ENTER" key on softkeyboard instead of clicking button

We can also use Kotlin lambda

editText.setOnKeyListener { _, keyCode, keyEvent ->
        if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
            Log.d("Android view component", "Enter button was pressed")
            return@setOnKeyListener true
        }
        return@setOnKeyListener false
    }

C99 stdint.h header and MS Visual Studio

Just define them yourself.

#ifdef _MSC_VER

typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;

#else
#include <stdint.h>
#endif

iOS: set font size of UILabel Programmatically

If you are looking for swift code:

var titleLabel = UILabel()
titleLabel.font = UIFont(name: "HelveticaNeue-UltraLight",
                         size: 20.0)

How can I switch my signed in user in Visual Studio 2013?

You don't need to reset all your user data to switch users. Try clicking on your name in the upper right corner then click on "Account settings". There you will get an option to sign out of the IDE. Once signed out you can sign back in as another Microsoft account.

Alert handling in Selenium WebDriver (selenium 2) with Java

Alert alert = driver.switchTo().alert();

alert.accept();

You can also decline the alert box:


Alert alert = driver.switchTo().alert();

alert().dismiss();