Programs & Examples On #On the fly

How do I set adaptive multiline UILabel text?

With Graphical User Interface (GUI) in Xcode, you can do the following:

  • Go to "Attribute Inspector" and set Lines value to 0. By default, it is set to 1.
  • The Label text can be written in multi-line by hitting option + return.

enter image description here

  • Now, go to "Size Inspector" and set the width, height, X & Y position of the Label.

enter image description here

That's all.

What is the "proper" way to cast Hibernate Query.list() to List<Type>?

Only way that work for me was with an Iterator.

Iterator iterator= query.list().iterator();
Destination dest;
ArrayList<Destination> destinations= new ArrayList<>();
Iterator iterator= query.list().iterator();
    while(iterator.hasNext()){
        Object[] tuple= (Object[]) iterator.next();
        dest= new Destination();
        dest.setId((String)tuple[0]);
        dest.setName((String)tuple[1]);
        dest.setLat((String)tuple[2]);
        dest.setLng((String)tuple[3]);
        destinations.add(dest);
    }

With other methods that I found, I had cast problems

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

Why is my CSS bundling not working with a bin deployed MVC4 app?

css names must be consistent.

Names of jqueryUI css are not "jquery.ui.XXX" in Contents/themes/base folder .

so it should be :

wrong:

            bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                                    "~/Content/themes/base/jquery.ui.core.css",
                                    "~/Content/themes/base/jquery.ui.resizable.css",
                                    "~/Content/themes/base/jquery.ui.selectable.css",
                                    "~/Content/themes/base/jquery.ui.accordion.css",
                                    "~/Content/themes/base/jquery.ui.autocomplete.css",
                                    "~/Content/themes/base/jquery.ui.button.css",
                                    "~/Content/themes/base/jquery.ui.dialog.css",
                                    "~/Content/themes/base/jquery.ui.slider.css",
                                    "~/Content/themes/base/jquery.ui.tabs.css",
                                    "~/Content/themes/base/jquery.ui.datepicker.css",
                                    "~/Content/themes/base/jquery.ui.progressbar.css",
                                    "~/Content/themes/base/jquery.ui.theme.css"));

correct :

            bundles.Add(new StyleBundle("~/Bundles/themes/base/css").Include(
                                    "~/Content/themes/base/core.css",
                                    "~/Content/themes/base/resizable.css",
                                    "~/Content/themes/base/selectable.css",
                                    "~/Content/themes/base/accordion.css",
                                    "~/Content/themes/base/autocomplete.css",
                                    "~/Content/themes/base/button.css",
                                    "~/Content/themes/base/dialog.css",
                                    "~/Content/themes/base/slider.css",
                                    "~/Content/themes/base/tabs.css",
                                    "~/Content/themes/base/datepicker.css",
                                    "~/Content/themes/base/progressbar.css",
                                    "~/Content/themes/base/theme.css"));

I tried in MVC5 and worked successfully.

wkhtmltopdf: cannot connect to X server

Just made it:

1- To download wkhtmltopdf dependencies

# apt-get install wkhtmltopdf

2- Download from source

# wget http://downloads.sourceforge.net/project/wkhtmltopdf/xxx.deb

# dpkg -i xxx.deb

3- Try

# wkhtmltopdf http://google.com google.pdf

Its working fine

It works!

Getting strings recognized as variable names in R

You found one answer, i.e. eval(parse()) . You can also investigate do.call() which is often simpler to implement. Keep in mind the useful as.name() tool as well, for converting strings to variable names.

Datatables on-the-fly resizing

What is happening is that DataTables is setting the CSS width of the table when it is initialised to a calculated value - that value is in pixels, hence why it won't resize with your dragging. The reason it does this is to stop the table and the columns (the column widths are also set) jumping around in width when you change pagination.

What you can do to stop this behaviour in DataTables is set the autoWidth parameter to false.

$('#example').dataTable( {
  "autoWidth": false
} );

That will stop DataTables adding its calculated widths to the table, leaving your (presumably) width:100% alone and allowing it to resize. Adding a relative width to the columns would also help stop the columns bouncing.

One other option that is built into DataTables is to set the sScrollX option to enable scrolling, as DataTables will set the table to be 100% width of the scrolling container. But you might not want scrolling.

The prefect solution would be if I could get the CSS width of the table (assuming one is applied - i.e. 100%), but without parsing the stylesheets, I don't see a way of doing that (i.e. basically I want $().css('width') to return the value from the stylesheet, not the pixel calculated value).

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

For Win7 Acrobat Pro X

Since I did all these without rechecking to see if the problem still existed afterwards, I am not sure which on of these actually fixed the problem, but one of them did. In fact, after doing the #3 and rebooting, it worked perfectly.

FYI: Below is the order in which I stepped through the repair.

  1. Go to Control Panel > folders options under each of the General, View and Search Tabs click the Restore Defaults button and the Reset Folders button

  2. Go to Internet Explorer, Tools > Options > Advanced > Reset ( I did not need to delete personal settings)

  3. Open Acrobat Pro X, under Edit > Preferences > General.
    At the bottom of page select Default PDF Handler. I chose Adobe Pro X, and click Apply.

You may be asked to reboot (I did).

Best Wishes

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

I know that you can modify a javascript file when using Google Chrome.

  1. Open up Chrome Inspector, go to the "Scripts" tab.
  2. Press the drop-down menu and select the javascript file that you want to edit.
  3. Double click in the text field, type in what ever you want and delete whatever you want.
  4. Then all you have to do is press Ctrl + S to save the file.

Warning: If you refresh the page, all changes will go back to original file. I recommend to copy/paste the code somewhere else if you want to use it again.

Hope this helps!

PHP prepend leading zero before single digit number, on-the-fly

You can use sprintf: http://php.net/manual/en/function.sprintf.php

<?php
$num = 4;
$num_padded = sprintf("%02d", $num);
echo $num_padded; // returns 04
?>

It will only add the zero if it's less than the required number of characters.

Edit: As pointed out by @FelipeAls:

When working with numbers, you should use %d (rather than %s), especially when there is the potential for negative numbers. If you're only using positive numbers, either option works fine.

For example:

sprintf("%04s", 10); returns 0010
sprintf("%04s", -10); returns 0-10

Where as:

sprintf("%04d", 10); returns 0010
sprintf("%04d", -10); returns -010

Create a text file for download on-the-fly

Check out this SO question's accepted solution. Substitute your own filename for basename($File) and change filesize($File) to strlen($your_string). (You may want to use mb_strlen just in case the string contains multibyte characters.)

How to flush output after each `echo` call?

This works fine for me (Apache 2.4/PHP 7.0):

@ob_end_clean();
echo "lorem ipsum...";
flush();
sleep(5);
echo "<br>dolor...";
flush();
sleep(5);
echo "<br>sit amet";

jQuery UI Slider (setting programmatically)

For me this perfectly triggers slide event on UI Slider :

hs=$('#height_slider').slider();
hs.slider('option', 'value',h);
hs.slider('option','slide')
       .call(hs,null,{ handle: $('.ui-slider-handle', hs), value: h });

Don't forget to set value by hs.slider('option', 'value',h); before the trigger. Else slider handler will not be in sync with value.

One thing to note here is that h is index/position (not value) in case you are using html select.

How to call a Web Service Method?

write return(secondmethod) inside of the first method

enter image description here

Showing the stack trace from a running Python application

Take a look at the faulthandler module, new in Python 3.3. A faulthandler backport for use in Python 2 is available on PyPI.

What is the difference between field, variable, attribute, and property in Java POJOs?

Yes, there is.

Variable can be local, field, or constant (although this is technically wrong). It's vague like attribute. Also, you should know that some people like to call final non-static (local or instance) variables

"Values". This probably comes from emerging JVM FP languages like Scala.

Field is generally a private variable on an instance class. It does not mean there is a getter and a setter.

Attribute is a vague term. It can easily be confused with XML or Java Naming API. Try to avoid using that term.

Property is the getter and setter combination.

Some examples below

public class Variables {

    //Constant
    public final static String MY_VARIABLE = "that was a lot for a constant";

    //Value
    final String dontChangeMeBro = "my god that is still long for a val";

    //Field
    protected String flipMe = "wee!!!";

    //Property
    private String ifYouThoughtTheConstantWasVerboseHaHa;

    //Still the property
    public String getIfYouThoughtTheConstantWasVerboseHaHa() {
        return ifYouThoughtTheConstantWasVerboseHaHa;
    }

    //And now the setter
    public void setIfYouThoughtTheConstantWasVerboseHaHa(String ifYouThoughtTheConstantWasVerboseHaHa) {
        this.ifYouThoughtTheConstantWasVerboseHaHa = ifYouThoughtTheConstantWasVerboseHaHa;
    }

}

There are many more combinations, but my fingers are getting tired :)

Enter key in textarea

You could do something like this:

<body>

<textarea id="txtArea" onkeypress="onTestChange();"></textarea>

<script>
function onTestChange() {
    var key = window.event.keyCode;

    // If the user has pressed enter
    if (key === 13) {
        document.getElementById("txtArea").value = document.getElementById("txtArea").value + "\n*";
        return false;
    }
    else {
        return true;
    }
}
</script>

</body>

Although the new line character feed from pressing enter will still be there, but its a start to getting what you want.

CodeIgniter - accessing $config variable in view

$config['cricket'] = 'bat'; in config.php file

$this->config->item('cricket') use this in view

How can I display a messagebox in ASP.NET?

This code will help you add a MsgBox in your asp.net file. You can change the function definition to your requirements. Hope this helps!

protected void Addstaff_Click(object sender, EventArgs e)    
    {   
 if (intClassCapcity < intCurrentstaffNumber)     
                {                  
            MsgBox("Record cannot be added because max seats available for the " + (string)Session["course_name"] + " training has been reached");    
        }    
else    
    {   
            sqlClassList.Insert();    
    }    
}

private void MsgBox(string sMessage)    
    {    
        string msg = "<script language=\"javascript\">";    
        msg += "alert('" + sMessage + "');";    
        msg += "</script>";    
        Response.Write(msg);    
    }

PDF to byte array and vice versa

Calling toString() on an InputStream doesn't do what you think it does. Even if it did, a PDF contains binary data, so you wouldn't want to convert it to a string first.

What you need to do is read from the stream, write the results into a ByteArrayOutputStream, then convert the ByteArrayOutputStream into an actual byte array by calling toByteArray():

InputStream inputStream = new FileInputStream(sourcePath);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

int data;
while( (data = inputStream.read()) >= 0 ) {
    outputStream.write(data);
}

inputStream.close();
return outputStream.toByteArray();

What is attr_accessor in Ruby?

Another way to understand it is to figure out what error code it eliminates by having attr_accessor.

Example:

class BankAccount    
  def initialize( account_owner )
    @owner = account_owner
    @balance = 0
  end

  def deposit( amount )
    @balance = @balance + amount
  end

  def withdraw( amount )
    @balance = @balance - amount
  end
end

The following methods are available:

$ bankie = BankAccout.new("Iggy")
$ bankie 
$ bankie.deposit(100)
$ bankie.withdraw(5)

The following methods throws error:

$ bankie.owner     #undefined method `owner'... 
$ bankie.balance   #undefined method `balance'...

owner and balance are not, technically, a method, but an attribute. BankAccount class does not have def owner and def balance. If it does, then you can use the two commands below. But those two methods aren't there. However, you can access attributes as if you'd access a method via attr_accessor!! Hence the word attr_accessor. Attribute. Accessor. It accesses attributes like you would access a method.

Adding attr_accessor :balance, :owner allows you to read and write balance and owner "method". Now you can use the last 2 methods.

$ bankie.balance
$ bankie.owner

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

Center align a column in twitter bootstrap

I tried the approaches given above, but these methods fail when dynamically the height of the content in one of the cols increases, it basically pushes the other cols down.

for me the basic table layout solution worked.

// Apply this to the enclosing row
.row-centered {
  text-align: center;
  display: table-row;
}
// Apply this to the cols within the row
.col-centered {
  display: table-cell;
  float: none;
  vertical-align: top;
}

Merge PDF files

from PyPDF2 import PdfFileMerger
import webbrowser
import os
dir_path = os.path.dirname(os.path.realpath(__file__))

def list_files(directory, extension):
    return (f for f in os.listdir(directory) if f.endswith('.' + extension))

pdfs = list_files(dir_path, "pdf")

merger = PdfFileMerger()

for pdf in pdfs:
    merger.append(open(pdf, 'rb'))

with open('result.pdf', 'wb') as fout:
    merger.write(fout)

webbrowser.open_new('file://'+ dir_path + '/result.pdf')

Git Repo: https://github.com/mahaguru24/Python_Merge_PDF.git

How can I set Image source with base64

Try using setAttribute instead:

document.getElementById('img')
    .setAttribute(
        'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
    );

Real answer: (And make sure you remove the line-breaks in the base64.)

/etc/apt/sources.list" E212: Can't open file for writing

for me worked changing the filesystem from Read-Only before running vim:

bash-3.2# mount -o remount rw /

Adding attributes to an XML node

Well id isn't really the root node: Login is.

It should just be a case of specifying the attributes (not tags, btw) using XmlElement.SetAttribute. You haven't specified how you're creating the file though - whether you're using XmlWriter, the DOM, or any other XML API.

If you could give an example of the code you've got which isn't working, that would help a lot. In the meantime, here's some code which creates the file you described:

using System;
using System.Xml;

class Test
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        XmlElement root = doc.CreateElement("Login");
        XmlElement id = doc.CreateElement("id");
        id.SetAttribute("userName", "Tushar");
        id.SetAttribute("passWord", "Tushar");
        XmlElement name = doc.CreateElement("Name");
        name.InnerText = "Tushar";
        XmlElement age = doc.CreateElement("Age");
        age.InnerText = "24";

        id.AppendChild(name);
        id.AppendChild(age);
        root.AppendChild(id);
        doc.AppendChild(root);

        doc.Save("test.xml");
    }
}

Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

In addition to @Ivan's answer, types all need to be included

    /* Drop all Types */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sys.types where is_user_defined = 1 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP TYPE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Type: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sys.types where is_user_defined = 1 AND [name] > @name ORDER BY [name])
END
GO

cURL not working (Error #77) for SSL connections on CentOS for non-root users

Windows users, add this to PHP.ini:

curl.cainfo = "C:/cacert.pem";

Path needs to be changed to your own and you can download cacert.pem from a google search

(yes I know its a CentOS question)

How to make FileFilter in java?

From JDK8 on words it is as simple as

final String extension = ".java";
final File currentDir = new File(YOUR_DIRECTORY_PATH);
File[] files = currentDir.listFiles((File pathname) -> pathname.getName().endsWith(extension));

What is the difference between the float and integer data type when the size is the same?

  • float stores floating-point values, that is, values that have potential decimal places
  • int only stores integral values, that is, whole numbers

So while both are 32 bits wide, their use (and representation) is quite different. You cannot store 3.141 in an integer, but you can in a float.

Dissecting them both a little further:

In an integer, all bits are used to store the number value. This is (in Java and many computers too) done in the so-called two's complement. This basically means that you can represent the values of −231 to 231 − 1.

In a float, those 32 bits are divided between three distinct parts: The sign bit, the exponent and the mantissa. They are laid out as follows:

S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM

There is a single bit that determines whether the number is negative or non-negative (zero is neither positive nor negative, but has the sign bit set to zero). Then there are eight bits of an exponent and 23 bits of mantissa. To get a useful number from that, (roughly) the following calculation is performed:

M × 2E

(There is more to it, but this should suffice for the purpose of this discussion)

The mantissa is in essence not much more than a 24-bit integer number. This gets multiplied by 2 to the power of the exponent part, which, roughly, is a number between −128 and 127.

Therefore you can accurately represent all numbers that would fit in a 24-bit integer but the numeric range is also much greater as larger exponents allow for larger values. For example, the maximum value for a float is around 3.4 × 1038 whereas int only allows values up to 2.1 × 109.

But that also means, since 32 bits only have 4.2 × 109 different states (which are all used to represent the values int can store), that at the larger end of float's numeric range the numbers are spaced wider apart (since there cannot be more unique float numbers than there are unique int numbers). You cannot represent some numbers exactly, then. For example, the number 2 × 1012 has a representation in float of 1,999,999,991,808. That might be close to 2,000,000,000,000 but it's not exact. Likewise, adding 1 to that number does not change it because 1 is too small to make a difference in the larger scales float is using there.

Similarly, you can also represent very small numbers (between 0 and 1) in a float but regardless of whether the numbers are very large or very small, float only has a precision of around 6 or 7 decimal digits. If you have large numbers those digits are at the start of the number (e.g. 4.51534 × 1035, which is nothing more than 451534 follows by 30 zeroes – and float cannot tell anything useful about whether those 30 digits are actually zeroes or something else), for very small numbers (e.g. 3.14159 × 10−27) they are at the far end of the number, way beyond the starting digits of 0.0000...

PermissionError: [WinError 5] Access is denied python using moviepy to write gif

I was facing the same error while running command

pip install --upgrade pip

in a virtual venvironment (created with python -m venv venv).

using the --user flag fixed the problem for me

pip install --upgrade pip --user

If the problem not resolved use --user flag in a command prompt with admin rights.

How can I rotate an HTML <div> 90 degrees?

Use following in your CSS

div {
    -webkit-transform: rotate(90deg); /* Safari and Chrome */
    -moz-transform: rotate(90deg);   /* Firefox */
    -ms-transform: rotate(90deg);   /* IE 9 */
    -o-transform: rotate(90deg);   /* Opera */
    transform: rotate(90deg);
} 

Maven- No plugin found for prefix 'spring-boot' in the current project and in the plugin groups

You should run the $ mvn spring-boot:run from the folder where your pom.xml file is located and refer to this answer https://stackoverflow.com/a/33602837/4918021

How to SHA1 hash a string in Android?

If you can get away with using Guava it is by far the simplest way to do it, and you don't have to reinvent the wheel:

final HashCode hashCode = Hashing.sha1().hashString(yourValue, Charset.defaultCharset());

You can then take the hashed value and get it as a byte[], as an int, or as a long.

No wrapping in a try catch, no shenanigans. And if you decide you want to use something other than SHA-1, Guava also supports sha256, sha 512, and a few I had never even heard about like adler32 and murmur3.

How to write a std::string to a UTF-8 text file

There is nice tiny library to work with utf8 from c++: utfcpp

how to count length of the JSON array element

First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :

obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;

Where are static methods and static variables stored in Java?

This is a question with a simple answer and a long-winded answer.

The simple answer is the heap. Classes and all of the data applying to classes (not instance data) is stored in the Permanent Generation section of the heap.

The long answer is already on stack overflow:

There is a thorough description of memory and garbage collection in the JVM as well as an answer that talks more concisely about it.

Enabling SSL with XAMPP

For XAMPP, do the following steps:

  1. G:\xampp\apache\conf\extra\httpd-ssl.conf"

  2. Search 'DocumentRoot' text.

  3. Change DocumentRoot DocumentRoot "G:/xampp/htdocs" to DocumentRoot "G:/xampp/htdocs/project name".

Reading Data From Database and storing in Array List object

 while (rs.next()) {

            customer.setId(rs.getInt("id"));
            customer.setName(rs.getString("name"));

            customer.setAddress(rs.getString("address"));
            customer.setPhone(rs.getString("phone"));
            customer.setEmail(rs.getString("email"));
            customer.setBountPoints(rs.getInt("bonuspoint"));
            customer.setTotalsale(rs.getInt("totalsale"));

            customers.add(customer);
             customer = null;
        }

Try replacing your while loop code with above mentioned code. Here what we have done is after doing customers.add(customer) we are doing customer = null;`

z-index issue with twitter bootstrap dropdown menu

I had the same problem, in my case because i forgot this in my NavBar style: overflow: hidden;

Sort array by firstname (alphabetically) in Javascript

In case we are sorting names or something with special characters, like ñ or áéíóú (commons in Spanish) we could use the params locales (es for spanish in this case ) and options like this:

_x000D_
_x000D_
let user = [{'firstname': 'Az'},{'firstname': 'Áb'},{'firstname':'ay'},{'firstname': 'Ña'},{'firstname': 'Nz'},{'firstname': 'ny'}];_x000D_
_x000D_
_x000D_
user.sort((a, b) => a.firstname.localeCompare(b.firstname, 'es', {sensitivity: 'base'}))_x000D_
_x000D_
_x000D_
console.log(user)
_x000D_
_x000D_
_x000D_

The oficial locale options could be found here in iana, es (spanish), de (German), fr (French). About sensitivity base means:

Only strings that differ in base letters compare as unequal. Examples: a ? b, a = á, a = A.

How do I select an element in jQuery by using a variable for the ID?

There are two problems with your code

  1. To find an element by ID you must prefix it with a "#"
  2. You are attempting to pass a Number to the find function when a String is required (passing "#" + 5 would fix this as it would convert the 5 to a "5" first)

What is the difference between npm install and npm run build?

NPM in 2019

npm build no longer exists. You must call npm run build now. More info below.

TLDR;

npm install: installs dependencies, then calls the install from the package.json scripts field.

npm run build: runs the build field from the package.json scripts field.


NPM Scripts Field

https://docs.npmjs.com/misc/scripts

There are many things you can put into the npm package.json scripts field. Check out the documentation link above more above the lifecycle of the scripts - most have pre and post hooks that you can run scripts before/after install, publish, uninstall, test, start, stop, shrinkwrap, version.


To Complicate Things

  • npm install is not the same as npm run install
  • npm install installs package.json dependencies, then runs the package.json scripts.install
    • (Essentially calls npm run install after dependencies are installed.
  • npm run install only runs the package.json scripts.install, it will not install dependencies.
  • npm build used to be a valid command (used to be the same as npm run build) but it no longer is; it is now an internal command. If you run it you'll get: npm WARN build npm build called with no arguments. Did you mean to npm run-script build? You can read more on the documentation: https://docs.npmjs.com/cli/build

Extra Notes

There are still two top level commands that will run scripts, they are:

  • npm start which is the same as npm run start
  • npm test ==> npm run test

Difference between the Apache HTTP Server and Apache Tomcat?

If you are using java technology(Servlet/JSP) for making web application you will probably use Apache Tomcat. However, if you are using other technologies like Perl, PHP or ruby, its better(easier) to use Apache HTTP Server.

A TypeScript GUID class?

There is an implementation in my TypeScript utilities based on JavaScript GUID generators.

Here is the code:

_x000D_
_x000D_
class Guid {_x000D_
  static newGuid() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
      var r = Math.random() * 16 | 0,_x000D_
        v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
      return v.toString(16);_x000D_
    });_x000D_
  }_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
  var id = Guid.newGuid();_x000D_
  console.log(id);_x000D_
}
_x000D_
_x000D_
_x000D_

Please note the following:

C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.

JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).

Float a div above page content

You want to use absolute positioning.

An absolute position element is positioned relative to the first parent element that has a position other than static. If no such element is found, the containing block is html

For instance :

.yourDiv{
  position:absolute;
  top: 123px;
}

To get it to work, the parent needs to be relative (position:relative)

In your case this should do the trick:

.suggestionsBox{position:absolute; top:40px;}
#specific_locations_add{position:relative;}

Angular 2: import external js file into component

Let's say you have added a file "xyz.js" under assets/js folder in some Angular project in Visual-Studio, then the easiest way to include that file is to add it to .angular-cli.json

"scripts": [ "assets/js/xyz.js" ],

You should be able to use this JS file's functionality in your component or .ts files.

Can't find android device using "adb devices" command

You will need USB driver installed correctly and have debugging enabled in settings. if these dont work there could be something wrong with your device.

Also see this.

grep a file, but show several surrounding lines?

ack works with similar arguments as grep, and accepts -C. But it's usually better for searching through code.

Java equivalent of unsigned long long?

The org.apache.axis.types package has a

UnsignedLong class.

for maven:

<dependency>
    <groupId>org.apache.axis</groupId>
    <artifactId>axis</artifactId>
    <version>1.4</version>
</dependency>

Can you hide the controls of a YouTube embed without enabling autoplay?

If you add this ?showinfo=0&iv_load_policy=3&controls=0 before the end of your src, it will take out everything but the bottom right YouTube logo
working example: http://jsfiddle.net/42gxdf0f/1/

docker mounting volumes on host

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

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

Explode string by one or more spaces or tabs

$parts = preg_split('/\s+/', $str);

How many socket connections possible?

This depends not only on the operating system in question, but also on configuration, potentially real-time configuration.

For Linux:

cat /proc/sys/fs/file-max

will show the current maximum number of file descriptors total allowed to be opened simultaneously. Check out http://www.cs.uwaterloo.ca/~brecht/servers/openfiles.html

In LINQ, select all values of property X where X != null

You can use the OfType operator. It ignores null values in the source sequence. Just use the same type as MyProperty and it won't filter out anything else.

// given:
// public T MyProperty { get; }
var nonNullItems = list.Select(x => x.MyProperty).OfType<T>();

I would advise against this though. If you want to pick non-null values, what can be more explicit than saying you want "the MyProperties from the list that are not null"?

Internal vs. Private Access Modifiers

Private members are accessible only within the body of the class or the struct in which they are declared.

Internal types or members are accessible only within files in the same assembly

Hive insert query like SQL

You can use below approach. With this, You don't need to create temp table OR txt/csv file for further select and load respectively.

INSERT INTO TABLE tablename SELECT value1,value2 FROM tempTable_with_atleast_one_records LIMIT 1.

Where tempTable_with_atleast_one_records is any table with atleast one record.

But problem with this approach is that If you have INSERT statement which inserts multiple rows like below one.

INSERT INTO yourTable values (1 , 'value1') , (2 , 'value2') , (3 , 'value3') ;

Then, You need to have separate INSERT hive statement for each rows. See below.

INSERT INTO TABLE yourTable SELECT 1 , 'value1' FROM tempTable_with_atleast_one_records LIMIT 1;
INSERT INTO TABLE yourTable SELECT 2 , 'value2' FROM tempTable_with_atleast_one_records LIMIT 1;
INSERT INTO TABLE yourTable SELECT 3 , 'value3' FROM tempTable_with_atleast_one_records LIMIT 1;

How to get the previous url using PHP

But you could make an own link for every from url.

Example: http://example.com?auth=holasite

In this example your site is: example.com

If somebody open that link it's give you the holasite value for the auth variable.

Then just $_GET['auth'] and you have the variable. But you should have a database to store it, and to authorize.

Like: $holasite = http://holasite.com (You could use mysql too..)

And just match it, and you have the url.

This method is a little bit more complicated, but it works. This method is good for a referral system authentication. But where is the site name, you should write an id, and works with that id.

How can I programmatically get the MAC address of an iphone

It's not possible anymore on devices running iOS 7.0 or later, thus unavailable to get MAC address in Swift.

As Apple stated:

In iOS 7 and later, if you ask for the MAC address of an iOS device, the system returns the value 02:00:00:00:00:00. If you need to identify the device, use the identifierForVendor property of UIDevice instead. (Apps that need an identifier for their own advertising purposes should consider using the advertisingIdentifier property of ASIdentifierManager instead.)

Laravel migration: unique key is too long, even if specified

If anyone else stumbles upon this answer like I did but for a different reason, you may check your Laravel DB charset/collation.

I was installing an application (Snipe-IT) and had configured the Laravel database config to use the following:

'charset' => 'utf8mb4',
'collation' => 'utf8mb4_general_ci',

Removing mb4 from both strings fixed the issue, although I believe Antonio's answer is the real solution to the problem.

Spark DataFrame groupBy and sort in the descending order (pyspark)

By far the most convenient way is using this:

df.orderBy(df.column_name.desc())

Doesn't require special imports.

Implement an input with a mask

Use this to implement mask:

https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js

<input id="phn-number" class="ant-input" type="text" placeholder="(XXX) XXX-XXXX" data-inputmask-mask="(999) 999-9999">


jQuery( '#phn-number[data-inputmask-mask]' ).inputmask();

Get current NSDate in timestamp format

If you need time stamp as a string.

time_t result = time(NULL);                
NSString *timeStampString = [@(result) stringValue];

How to Create simple drag and Drop in angularjs

I just posted this to my brand spanking new blog: http://jasonturim.wordpress.com/2013/09/01/angularjs-drag-and-drop/

Code here: https://github.com/logicbomb/lvlDragDrop

Demo here: http://logicbomb.github.io/ng-directives/drag-drop.html

Here are the directives these rely on a UUID service which I've included below:

var module = angular.module("lvl.directives.dragdrop", ['lvl.services']);

module.directive('lvlDraggable', ['$rootScope', 'uuid', function($rootScope, uuid) {
        return {
            restrict: 'A',
            link: function(scope, el, attrs, controller) {
                console.log("linking draggable element");

                angular.element(el).attr("draggable", "true");
                var id = attrs.id;
                if (!attrs.id) {
                    id = uuid.new()
                    angular.element(el).attr("id", id);
                }

                el.bind("dragstart", function(e) {
                    e.dataTransfer.setData('text', id);

                    $rootScope.$emit("LVL-DRAG-START");
                });

                el.bind("dragend", function(e) {
                    $rootScope.$emit("LVL-DRAG-END");
                });
            }
        }
    }]);

module.directive('lvlDropTarget', ['$rootScope', 'uuid', function($rootScope, uuid) {
        return {
            restrict: 'A',
            scope: {
                onDrop: '&'
            },
            link: function(scope, el, attrs, controller) {
                var id = attrs.id;
                if (!attrs.id) {
                    id = uuid.new()
                    angular.element(el).attr("id", id);
                }

                el.bind("dragover", function(e) {
                  if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                  }

                  e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.
                  return false;
                });

                el.bind("dragenter", function(e) {
                  // this / e.target is the current hover target.
                  angular.element(e.target).addClass('lvl-over');
                });

                el.bind("dragleave", function(e) {
                  angular.element(e.target).removeClass('lvl-over');  // this / e.target is previous target element.
                });

                el.bind("drop", function(e) {
                  if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                  }

                  if (e.stopPropagation) {
                    e.stopPropagation(); // Necessary. Allows us to drop.
                  }
                    var data = e.dataTransfer.getData("text");
                    var dest = document.getElementById(id);
                    var src = document.getElementById(data);

                    scope.onDrop({dragEl: src, dropEl: dest});
                });

                $rootScope.$on("LVL-DRAG-START", function() {
                    var el = document.getElementById(id);
                    angular.element(el).addClass("lvl-target");
                });

                $rootScope.$on("LVL-DRAG-END", function() {
                    var el = document.getElementById(id);
                    angular.element(el).removeClass("lvl-target");
                    angular.element(el).removeClass("lvl-over");
                });
            }
        }
    }]);

UUID service

angular
.module('lvl.services',[])
.factory('uuid', function() {
    var svc = {
        new: function() {
            function _p8(s) {
                var p = (Math.random().toString(16)+"000000000").substr(2,8);
                return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ;
            }
            return _p8() + _p8(true) + _p8(true) + _p8();
        },

        empty: function() {
          return '00000000-0000-0000-0000-000000000000';
        }
    };

    return svc;
});

Dead simple example of using Multiprocessing Queue, Pool and Locking

This might be not 100% related to the question, but on my search for an example of using multiprocessing with a queue this shows up first on google.

This is a basic example class that you can instantiate and put items in a queue and can wait until queue is finished. That's all I needed.

from multiprocessing import JoinableQueue
from multiprocessing.context import Process


class Renderer:
    queue = None

    def __init__(self, nb_workers=2):
        self.queue = JoinableQueue()
        self.processes = [Process(target=self.upload) for i in range(nb_workers)]
        for p in self.processes:
            p.start()

    def render(self, item):
        self.queue.put(item)

    def upload(self):
        while True:
            item = self.queue.get()
            if item is None:
                break

            # process your item here

            self.queue.task_done()

    def terminate(self):
        """ wait until queue is empty and terminate processes """
        self.queue.join()
        for p in self.processes:
            p.terminate()

r = Renderer()
r.render(item1)
r.render(item2)
r.terminate()

How can I display a list view in an Android Alert Dialog?

According to the documentation, there are three kinds of lists that can be used with an AlertDialog:

  1. Traditional single-choice list
  2. Persistent single-choice list (radio buttons)
  3. Persistent multiple-choice list (checkboxes)

I will give an example of each below.

Traditional single-choice list

The way to make a traditional single-choice list is to use setItems.

enter image description here

Java version

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");

// add a list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
builder.setItems(animals, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case 0: // horse
            case 1: // cow
            case 2: // camel
            case 3: // sheep
            case 4: // goat
        }
    }
});

// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();

There is no need for an OK button because as soon as the user clicks on a list item control is returned to the OnClickListener.

Kotlin version

// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose an animal")

// add a list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
builder.setItems(animals) { dialog, which ->
    when (which) {
        0 -> { /* horse */ }
        1 -> { /* cow   */ }
        2 -> { /* camel */ }
        3 -> { /* sheep */ }
        4 -> { /* goat  */ }
    }
}

// create and show the alert dialog
val dialog = builder.create()
dialog.show()

Radio button list

enter image description here

The advantage of the radio button list over the traditional list is that the user can see what the current setting is. The way to make a radio button list is to use setSingleChoiceItems.

Java version

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");

// add a radio button list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
int checkedItem = 1; // cow
builder.setSingleChoiceItems(animals, checkedItem, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // user checked an item
    }
});

// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // user clicked OK
    }
});
builder.setNegativeButton("Cancel", null);

// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();

I hard coded the chosen item here, but you could keep track of it with a class member variable in a real project.

Kotlin version

// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose an animal")

// add a radio button list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
val checkedItem = 1 // cow
builder.setSingleChoiceItems(animals, checkedItem) { dialog, which ->
    // user checked an item
}


// add OK and Cancel buttons
builder.setPositiveButton("OK") { dialog, which ->
    // user clicked OK
}
builder.setNegativeButton("Cancel", null)

// create and show the alert dialog
val dialog = builder.create()
dialog.show()

Checkbox list

enter image description here

The way to make a checkbox list is to use setMultiChoiceItems.

Java version

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose some animals");

// add a checkbox list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
boolean[] checkedItems = {true, false, false, true, false};
builder.setMultiChoiceItems(animals, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
        // user checked or unchecked a box
    }
});

// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // user clicked OK
    }
});
builder.setNegativeButton("Cancel", null);

// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();

Here I hard coded the the which items in the list were already checked. It is more likely that you would want to keep track of them in an ArrayList<Integer>. See the documentation example for more details. You can also set the checked items to null if you always want everything to start unchecked.

Kotlin version

// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose some animals")

// add a checkbox list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
val checkedItems = booleanArrayOf(true, false, false, true, false)
builder.setMultiChoiceItems(animals, checkedItems) { dialog, which, isChecked ->
    // user checked or unchecked a box
}

// add OK and Cancel buttons
builder.setPositiveButton("OK") { dialog, which ->
    // user clicked OK
}
builder.setNegativeButton("Cancel", null)

// create and show the alert dialog
val dialog = builder.create()
dialog.show()

Notes

  • For the context in the code above, don't use getApplicationContext() or you will get an IllegalStateException (see here for why). Instead, get a reference to the activity context, such as with this.
  • You can also populate the list items from a database or another source using setAdapter or setCursor or passing in a Cursor or ListAdapter into the setSingleChoiceItems or setMultiChoiceItems.
  • If the list is longer than will fit on the screen then the dialog will automatically scroll it. If you have a really long list, though, I'm guessing that you should probably make a custom dialog with a RecyclerView.
  • To test all of the examples above I just had a simple project with a single button than showed the dialog when clicked:

    import android.support.v7.app.AppCompatActivity;
    
    public class MainActivity extends AppCompatActivity {
    
        Context context;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            context = this;
        }
    
        public void showAlertDialogButtonClicked(View view) {
    
            // example code to create alert dialog lists goes here
        }
    }
    

Related

What is the point of "final class" in Java?

First of all, I recommend this article: Java: When to create a final class


If they do, when do they use it so I can understand it better and know when to use it.

A final class is simply a class that can't be extended.

(It does not mean that all references to objects of the class would act as if they were declared as final.)

When it's useful to declare a class as final is covered in the answers of this question:

If Java is object oriented, and you declare a class final, doesn't it stop the idea of class having the characteristics of objects?

In some sense yes.

By marking a class as final you disable a powerful and flexible feature of the language for that part of the code. Some classes however, should not (and in certain cases can not) be designed to take subclassing into account in a good way. In these cases it makes sense to mark the class as final, even though it limits OOP. (Remember however that a final class can still extend another non-final class.)

Python 3 Float Decimal Points/Precision

The simple way to do this is by using the round buit-in.

round(2.6463636263,2) would be displayed as 2.65.

How to get query parameters from URL in Angular 5?

/*
Example below url with two param (type and name) 
URL : http://localhost:4200/updatePolicy?type=Medicare%20Insurance&name=FutrueInsurance
*/ 
  constructor(private route: ActivatedRoute) {
    //Read url query parameter `enter code here`
  this.route.queryParams.subscribe(params => {
    this.name= params['type'];
    this.type= params['name'];
    alert(this.type);
    alert(this.name);

 });

  }

css padding is not working in outlook

Avoid paddings and margins in newsletters, some email clients will ignore this properties.

You can use empty tr and td as was suggested (but this will result in a lot of html), or you can use borders with the same border color as the background of the email. so, instead of padding-top: 40px you can use border-top: 40px solid #ffffff (assuming that the background color of the email is #ffffff)

I've tested this solution in gmail (and gmail for business), yahoo mail, outlook web, outlook desktop, thunderbird, apple mail and more. As far as I can tell, border property is pretty safe to use everywhere.

Example:


<!-- With paddings: WON'T WORK IN ALL EMAIL CLIENTS! -->
<table>

    <tr>

        <td style="padding: 10px 10px 10px 10px">
            <!-- Content goes here -->
        </td>

    </tr>

</table>


<!-- Same result with borders and same border color of the background -->
<table>

    <tr>

        <td style="border: solid 10px #ffffff">
           <!-- Content goes here -->
        </td>

    </tr>

</table>


<!-- Same result using empty td/tr. (A lot more html than borders, get messy on large emails) -->
<table>

    <tr>
        <td colspan="3" height="10" style="height: 10px; line-height: 1px">&nbsp;</td>
    </tr>


    <tr>

        <td width="10" style="width: 10px; line-height: 1px">&nbsp;</td>

        <td><!--Content goes here--></td>

        <td width="10" style="width: 10px; line-height: 1px">&nbsp;</td>

    </tr>


    <tr>
        <td colspan="3" height="10" style="height: 10px; line-height: 1px">&nbsp;</td>
    </tr>

</table>
<!-- With tr/td every property is needed. height must be setted both as attribute and style, same with width, line-height must be setted JIC default value is greater than actual height and without the &nbsp; some email clients won't render the column because is empty. You can remove the colspan and still will work, but is annoying when inspecting the element in browser not to see a perfect square table -->

In addition, here is an excelent guide to make responsive newsletters without mediaqueries. The emails really works everywhere:

https://webdesign.tutsplus.com/tutorials/creating-a-future-proof-responsive-email-without-media-queries--cms-23919

And always remember to make styles inline:

https://inliner.cm/

To test emails, here is a good resource:

https://putsmail.com/

Finally, for doubts about css support in email clients you can go here:

https://templates.mailchimp.com/resources/email-client-css-support/

or here:

https://www.campaignmonitor.com/css/

How to open URL in Microsoft Edge from the command line?

Windows 10: Create a shortcut with this destination:

%windir%\system32\cmd.exe /c "start microsoft-edge:https://twitter.com"

How to select the comparison of two columns as one column in Oracle

select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;

HTH

SSH library for Java

I just discovered sshj, which seems to have a much more concise API than JSCH (but it requires Java 6). The documentation is mostly by examples-in-the-repo at this point, and usually that's enough for me to look elsewhere, but it seems good enough for me to give it a shot on a project I just started.

Why not use tables for layout in HTML?

I'm going to go through your arguments one after another and try to show the errors in them.

It's good to separate content from layout But this is a fallacious argument; Cliché Thinking.

It's not fallacious at all because HTML was designed intentionally. Misuse of an element might not be completely out of question (after all, new idioms have developed in other languages, as well) but possible negative implications have to be counterbalanced. Additionally, even if there were no arguments against misusing the <table> element today, there might be tomorrow because of the way browser vendors apply special treatment to the element. After all, they know that “<table> elements are for tabular data only” and might use this fact to improve the rendering engine, in the process subtly changing how <table>s behave, and thus breaking cases where it was previously misused.

So what? Does my boss care? Do my users care?

Depends. Is your boss pointy-haired? Then he might not care. If she's competent, then she will care, because the users will.

Perhaps me or my fellow developers who have to maintain a web page care... Is a table less maintainable? I think using a table is easier than using divs and css.

The majority of professional web developers seem to oppose you[citation needed]. That tables are in fact less maintainable should be obvious. Using tables for layout means that changing the corporate layout will in fact mean changing every single page. This can be very expensive. On the other hand, judicious use of semantically meaningful HTML combined with CSS might confine such changes to the CSS and the pictures used.

By the way... why is using a div or a span good separation of content from layout and a table not? Getting a good layout with only divs often requires a lot of nested divs.

Deeply nested <div>s are an anti-pattern just as table layouts. Good web designers don't need many of them. On the other hand, even such deep-nested divs don't have many of the problems of table layouts. In fact, they can even contribute to a semantic structure by logically dividing the content in parts.

Readability of the code I think it's the other way around. Most people understand html, little understand css. It's simpler.

“Most people” don't matter. Professionals matter. For professionals, table layouts create many more problems than HTML + CSS. This is like saying I shouldn't use GVim or Emacs because Notepad is simpler for most people. Or that I shouldn't use LaTeX because MS Word is simpler for most people.

It's better for SEO not to use tables

I don't know if this is true and wouldn't use this as an argument but it would be logical. Search engines search for relevant data. While tabular data could of course be relevant, it's rarely what users search for. Users search for terms used in the page title or similarly prominent positions. It would therefore be logical to exclude tabular content from filtering and thus cutting the processing time (and costs!) by a large factor.

Tables are slower. An extra tbody element has to be inserted. This is peanuts for modern web browsers.

The extra element has got nothing to do with tables being slower. On the other hand, the layout algorithm for tables is much harder, the browser often has to wait for the whole table to load before it can begin to layout the content. Additionally, caching of the layout won't work (CSS can easily be cached). All this has been mentioned before.

Show me some benchmarks where the use of a table significantly slows down a page.

Unfortunately, I don't have any benchmark data. I would be interested in it myself because it's right that this argument lacks a certain scientific rigour.

Most web sites that need an upgrade need new content (html) as well. Scenarios where a new version of a web site only needs a new css file are not very likely.

Not at all. I've worked on several cases where changing the design was simplified by a separation of content and design. It's often still necessary to change some HTML code but the changes will always be much more confined. Additionally, design changes must on occasion be made dynamically. Consider template engines such as the one used by the WordPress blogging system. Table layouts would literally kill this system. I've worked on a similar case for a commercial software. Being able to change the design without changing the HTML code was one of the business requirements.

Another thing. Table layout makes automated parsing of websites (screen scraping) much harder. This might sound trivial because, after all, who does it? I was surprised myself. Screen scraping can help a lot if the service in question doesn't offer a WebService alternative to access its data. I'm working in bioinformatics where this is a sad reality. Modern web techniques and WebServices have not reached most developers and often, screen scraping is the only way to automate the process of getting data. No wonder that many biologists still perform such tasks manually. For thousands of data sets.

Inline list initialization in VB.NET

Use this syntax for VB.NET 2005/2008 compatibility:

Dim theVar As New List(Of String)(New String() {"one", "two", "three"})

Although the VB.NET 2010 syntax is prettier.

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

Is using System.Threading.Timer mandatory?

If not, System.Timers.Timer has handy Start() and Stop() methods (and an AutoReset property you can set to false, so that the Stop() is not needed and you simply call Start() after executing).

What is C# analog of C++ std::pair?

I created a C# implementation of Tuples, which solves the problem generically for between two and five values - here's the blog post, which contains a link to the source.

Service located in another namespace

To access services in two different namespaces you can use url like this:

HTTP://<your-service-name>.<namespace-with-that-service>.svc.cluster.local

To list out all your namespaces you can use:

kubectl get namespace

And for service in that namespace you can simply use:

kubectl get services -n <namespace-name>

this will help you.

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

  1. First of all, there is no difference between View.OnClickListener and OnClickListener. If you just use View.OnClickListener directly, then you don't need to write-

    import android.view.View.OnClickListener

  2. You set an OnClickListener instance (e.g. myListener named object)as the listener to a view via setOnclickListener(). When a click event is fired, that myListener gets notified and it's onClick(View view) method is called. Thats where we do our own task. Hope this helps you.

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

Complete class to download a file while printing status to console.

using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Threading;

class FileDownloader
{
    private readonly string _url;
    private readonly string _fullPathWhereToSave;
    private bool _result = false;
    private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0);

    public FileDownloader(string url, string fullPathWhereToSave)
    {
        if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url");
        if (string.IsNullOrEmpty(fullPathWhereToSave)) throw new ArgumentNullException("fullPathWhereToSave");

        this._url = url;
        this._fullPathWhereToSave = fullPathWhereToSave;
    }

    public bool StartDownload(int timeout)
    {
        try
        {
            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(_fullPathWhereToSave));

            if (File.Exists(_fullPathWhereToSave))
            {
                File.Delete(_fullPathWhereToSave);
            }
            using (WebClient client = new WebClient())
            {
                var ur = new Uri(_url);
                // client.Credentials = new NetworkCredential("username", "password");
                client.DownloadProgressChanged += WebClientDownloadProgressChanged;
                client.DownloadFileCompleted += WebClientDownloadCompleted;
                Console.WriteLine(@"Downloading file:");
                client.DownloadFileAsync(ur, _fullPathWhereToSave);
                _semaphore.Wait(timeout);
                return _result && File.Exists(_fullPathWhereToSave);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Was not able to download file!");
            Console.Write(e);
            return false;
        }
        finally
        {
            this._semaphore.Dispose();
        }
    }

    private void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        Console.Write("\r     -->    {0}%.", e.ProgressPercentage);
    }

    private void WebClientDownloadCompleted(object sender, AsyncCompletedEventArgs args)
    {
        _result = !args.Cancelled;
        if (!_result)
        {
            Console.Write(args.Error.ToString());
        }
        Console.WriteLine(Environment.NewLine + "Download finished!");
        _semaphore.Release();
    }

    public static bool DownloadFile(string url, string fullPathWhereToSave, int timeoutInMilliSec)
    {
        return new FileDownloader(url, fullPathWhereToSave).StartDownload(timeoutInMilliSec);
    }
}

Usage:

static void Main(string[] args)
{
    var success = FileDownloader.DownloadFile(fileUrl, fullPathWhereToSave, timeoutInMilliSec);
    Console.WriteLine("Done  - success: " + success);
    Console.ReadLine();
}

Display all views on oracle database

SELECT * 
FROM DBA_OBJECTS  
WHERE OBJECT_TYPE = 'VIEW'

How to capitalize the first letter of a String in Java?

Here is my detailed article on the topic for all possible options Capitalize First Letter of String in Android

Method to Capitalize First Letter of String in Java

public static String capitalizeString(String str) {
        String retStr = str;
        try { // We can face index out of bound exception if the string is null
            retStr = str.substring(0, 1).toUpperCase() + str.substring(1);
        }catch (Exception e){}
        return retStr;
}

Method to Capitalize First Letter of String in KOTLIN

fun capitalizeString(str: String): String {
        var retStr = str
        try { // We can face index out of bound exception if the string is null
            retStr = str.substring(0, 1).toUpperCase() + str.substring(1)
        } catch (e: Exception) {
        }
        return retStr
}

"unable to locate adb" using Android Studio

Else this will helps you

The ADB is now located in the Android SDK platform-tools.

Check your [sdk directory]/platform-tools directory and if it does not exist, then open the SDK manager in the Android Studio (a button somewhere in the top menu, android logo with a down arrow), switch to SDK tools tab and and select/install the Android SDK Platform-tools.

Alternatively, you can try the standalone SDK Manager: Open the SDK manager and you should see a "Launch Standalone SDK manager" link somewhere at the bottom of the settings window. Click and open the standalone SDK manager, then install/update the

"Tools > Android SDK platform tools". If the above does not solve the problem, try reinstalling the tools: open the "Standalone SDK manager" and uninstall the Android SDK platform-tools, delete the [your sdk directory]/platform-tools directory completely and install it again using the SDK manager.

Hope this helps!

Convert float to double without losing precision

I find converting to the binary representation easier to grasp this problem.

float f = 0.27f;
double d2 = (double) f;
double d3 = 0.27d;

System.out.println(Integer.toBinaryString(Float.floatToRawIntBits(f)));
System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d2)));
System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d3)));

You can see the float is expanded to the double by adding 0s to the end, but that the double representation of 0.27 is 'more accurate', hence the problem.

   111110100010100011110101110001
11111111010001010001111010111000100000000000000000000000000000
11111111010001010001111010111000010100011110101110000101001000

Render HTML to an image

You could use PhantomJS, which is a headless webkit (the rendering engine in safari and (up until recently) chrome) driver. You can learn how to do screen capture of pages here. Hope that helps!

Switch on Enum in Java

Actually you can use a switch statement with Strings in Java...unfortunately this is a new feature of Java 7, and most people are not using Java 7 yet because it's so new.

What REALLY happens when you don't free after malloc?

I typically free every allocated block once I'm sure that I'm done with it. Today, my program's entry point might be main(int argc, char *argv[]) , but tomorrow it might be foo_entry_point(char **args, struct foo *f) and typed as a function pointer.

So, if that happens, I now have a leak.

Regarding your second question, if my program took input like a=5, I would allocate space for a, or re-allocate the same space on a subsequent a="foo". This would remain allocated until:

  1. The user typed 'unset a'
  2. My cleanup function was entered, either servicing a signal or the user typed 'quit'

I can not think of any modern OS that does not reclaim memory after a process exits. Then again, free() is cheap, why not clean up? As others have said, tools like valgrind are great for spotting leaks that you really do need to worry about. Even though the blocks you example would be labeled as 'still reachable' , its just extra noise in the output when you're trying to ensure you have no leaks.

Another myth is "If its in main(), I don't have to free it", this is incorrect. Consider the following:

char *t;

for (i=0; i < 255; i++) {
    t = strdup(foo->name);
    let_strtok_eat_away_at(t);
}

If that came prior to forking / daemonizing (and in theory running forever), your program has just leaked an undetermined size of t 255 times.

A good, well written program should always clean up after itself. Free all memory, flush all files, close all descriptors, unlink all temporary files, etc. This cleanup function should be reached upon normal termination, or upon receiving various kinds of fatal signals, unless you want to leave some files laying around so you can detect a crash and resume.

Really, be kind to the poor soul who has to maintain your stuff when you move on to other things .. hand it to them 'valgrind clean' :)

Insert new column into table in sqlite?

ALTER TABLE {tableName} ADD COLUMN COLNew {type};
UPDATE {tableName} SET COLNew = {base on {type} pass value here};

This update is required to handle the null value, inputting a default value as you require. As in your case, you need to call the SELECT query and you will get the order of columns, as paxdiablo already said:

SELECT name, colnew, qty, rate FROM{tablename}

and in my opinion, your column name to get the value from the cursor:

private static final String ColNew="ColNew";
String val=cursor.getString(cursor.getColumnIndex(ColNew));

so if the index changes your application will not face any problems.

This is the safe way in the sense that otherwise, if you are using CREATE temptable or RENAME table or CREATE, there would be a high chance of data loss if not handled carefully, for example in the case where your transactions occur while the battery is running out.

Email Address Validation for ASP.NET

Here is a basic email validator I just created based on Simon Johnson's idea. It just needs the extra functionality of DNS lookup being added if it is required.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Web.UI;

namespace CompanyName.Library.Web.Controls
{
    [ToolboxData("<{0}:EmailValidator runat=server></{0}:EmailValidator>")]
    public class EmailValidator : BaseValidator
    {

        protected override bool EvaluateIsValid()
        {
            string val = this.GetControlValidationValue(this.ControlToValidate);
            string pattern = @"^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$";
            Match match = Regex.Match(val.Trim(), pattern, RegexOptions.IgnoreCase);

            if (match.Success)
                return true;
            else
                return false;
        }

    }
}

Update: Please don't use the original Regex. Seek out a newer more complete sample.

Can you do a For Each Row loop using MySQL?

In the link you provided, thats not a loop in sql...

thats a loop in programming language

they are first getting list of all distinct districts, and then for each district executing query again.

How the int.TryParse actually works

TryParse is the best way for parse or validate in single line:

int nNumber = int.TryParse("InputString", out nNumber) ? nNumber : 1;

Short description:

  1. nNumber will initialize with zero,
  2. int.TryParse() try parse "InputString" and validate it, if succeed set into nNumber.
  3. short if ?: checking int.TryParse() result, that return nNumber or 1 as default value.

make UITableViewCell selectable only while editing

Have you tried setting the selection properties of your tableView like this:

tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

You can have this method return nil in cases where you don't want the selection to happen.

Place a button right aligned

To keep the button in the page flow:

<input type="button" value="Click Me" style="margin-left: auto; display: block;" />

(put that style in a .css file, do not use this html inline, for better maintenance)

Angular 2 How to redirect to 404 or other path if the path does not exist

As shaishab roy says, in the cheat sheet you can find the answer.

But in his answer, the given response was :

{path: '/home/...', name: 'Home', component: HomeComponent}
{path: '/', redirectTo: ['Home']},
{path: '/user/...', name: 'User', component: UserComponent},
{path: '/404', name: 'NotFound', component: NotFoundComponent},

{path: '/*path', redirectTo: ['NotFound']}

For some reasons, it doesn't works on my side, so I tried instead :

{path: '/**', redirectTo: ['NotFound']}

and it works. Be careful and don't forget that you need to put it at the end, or else you will often have the 404 error page ;).

What is `git push origin master`? Help with git's refs, heads and remotes

Or as a single command:

git push -u origin master:my_test

Pushes the commits from your local master branch to a (possibly new) remote branch my_test and sets up master to track origin/my_test.

How to remove all of the data in a table using Django

You can use the Django-Truncate library to delete all data of a table without destroying the table structure.

Example:

  1. First, install django-turncate using your terminal/command line:
pip install django-truncate
  1. Add "django_truncate" to your INSTALLED_APPS in the settings.py file:
INSTALLED_APPS = [
    ...
    'django_truncate',
]
  1. Use this command in your terminal to delete all data of the table from the app.
python manage.py truncate --apps app_name --models table_name

module.exports vs. export default in Node.js and ES6

Felix Kling did a great comparison on those two, for anyone wondering how to do an export default alongside named exports with module.exports in nodejs

module.exports = new DAO()
module.exports.initDAO = initDAO // append other functions as named export

// now you have
let DAO = require('_/helpers/DAO');
// DAO by default is exported class or function
DAO.initDAO()

Javascript: console.log to html

You can override the default implementation of console.log()

(function () {
    var old = console.log;
    var logger = document.getElementById('log');
    console.log = function (message) {
        if (typeof message == 'object') {
            logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(message) : message) + '<br />';
        } else {
            logger.innerHTML += message + '<br />';
        }
    }
})();

Demo: Fiddle

grep using a character vector with multiple patterns

To add to Brian Diggs answer.

another way using grepl will return a data frame containing all your values.

toMatch <- myfile$Letter

matches <- myfile[grepl(paste(toMatch, collapse="|"), myfile$Letter), ]

matches

Letter Firstname
1     A1      Alex 
2     A6      Alex 
4     A1       Bob 
5     A9     Chris 
6     A6     Chris

Maybe a bit cleaner... maybe?

Changing an element's ID with jQuery

I'm not sure what your goal is, but might it be better to use addClass instead? I mean an objects ID in my opinion should be static and specific to that object. If you are just trying to change it from showing on the page or something like that I would put those details in a class and then add it to the object rather then trying to change it's ID. Again, I'm saying that without understand your underlining goal.

How to fix the session_register() deprecated issue?

To complement Felix Kling's answer, I was studying a codebase that used to have the following code:

if (is_array($start_vars)) {
    foreach ($start_vars as $var) {
        session_register($var);
    }
} else if (!(empty($start_vars))) {
    session_register($start_vars);
}

In order to not use session_register they made the following adjustments:

if (is_array($start_vars)) {
    foreach ($start_vars as $var) {
        $_SESSION[$var] =  $GLOBALS[$var];
    }
} else if (!(empty($start_vars))) {
    $_SESSION[$start_vars] =  $GLOBALS[$start_vars];
}

Git: Merge a Remote branch locally

If you already fetched your remote branch and do git branch -a,
you obtain something like :

* 8.0
  xxx
  remotes/origin/xxx
  remotes/origin/8.0
  remotes/origin/HEAD -> origin/8.0
  remotes/rep_mirror/8.0

After that, you can use rep_mirror/8.0 to designate locally your remote branch.

The trick is that remotes/rep_mirror/8.0 doesn't work but rep_mirror/8.0 does.

So, a command like git merge -m "my msg" rep_mirror/8.0 do the merge.

(note : this is a comment to @VonC answer. I put it as another answer because code blocks don't fit into the comment format)

Gerrit error when Change-Id in commit messages are missing

You might be an admin doing a one-off push directly into refs/changes/<change_number>.

For example, once a commit without Change-Id landed into Subversion, you pull it out of Subversion using git-svn, and you'd like to archive it as a Gerrit patchset into a Gerrit change.

If so, you can go to project settings page (http://[installation-path]/#/admin/projects/[project-id]) and temporarily change "Require Change-Id in commit message" value to False.

Don't forget to afterwards change it back to Inherit or True!

$watch an object

For anyone that wants to watch for a change to an object within an array of objects, this seemed to work for me (as the other solutions on this page didn't):

function MyController($scope) {

    $scope.array = [
        data1: {
            name: 'name',
            surname: 'surname'
        },
        data2: {
            name: 'name',
            surname: 'surname'
        },
    ]


    $scope.$watch(function() {
        return $scope.data,
    function(newVal, oldVal){
        console.log(newVal, oldVal);
    }, true);

How to create an XML document using XmlDocument?

Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here

and edited my code: (xmlDoc.DocumentElement.AppendChild(body))

//a dictionary:
Dictionary<string, string> Level2Data 
{
    {"level2", "text"},
    {"level2", "other text"},
    {"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR



foreach (KeyValuePair<string, string> entry in Level2Data)
{
    //write to xml: - it works version 1.
    XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
    keyNode.InnerText = entry.Value;
    body.AppendChild(keyNode); //close TAB

    //Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
    //XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
    //XmlText value = xmlDoc.CreateTextNode(entry.Value);
    //key.AppendChild(value);
    //body.AppendChild(key);
}

Both versions (1 and 2 inside foreach loop) give the output:

<?xml version="1.0" encoding="UTF-8"?>
<body>
    <level1>
        <level2>text</level2>
        <level2>ther text</level2>
         <same_level2>more text</same_level2>
    </level1>
</body>

(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.

checked = "checked" vs checked = true

The element has both an attribute and a property named checked. The property determines the current state.

The attribute is a string, and the property is a boolean. When the element is created from the HTML code, the attribute is set from the markup, and the property is set depending on the value of the attribute.

If there is no value for the attribute in the markup, the attribute becomes null, but the property is always either true or false, so it becomes false.

When you set the property, you should use a boolean value:

document.getElementById('myRadio').checked = true;

If you set the attribute, you use a string:

document.getElementById('myRadio').setAttribute('checked', 'checked');

Note that setting the attribute also changes the property, but setting the property doesn't change the attribute.

Note also that whatever value you set the attribute to, the property becomes true. Even if you use an empty string or null, setting the attribute means that it's checked. Use removeAttribute to uncheck the element using the attribute:

document.getElementById('myRadio').removeAttribute('checked');

How to require a controller in an angularjs directive

There is a good stackoverflow answer here by Mark Rajcok:

AngularJS directive controllers requiring parent directive controllers?

with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/

<div ng-controller="MyCtrl">
    <div screen>
        <div component>
            <div widget>
                <button ng-click="widgetIt()">Woo Hoo</button>
            </div>
        </div>
    </div>
</div>

JavaScript

var myApp = angular.module('myApp',[])

.directive('screen', function() {
    return {
        scope: true,
        controller: function() {
            this.doSomethingScreeny = function() {
                alert("screeny!");
            }
        }
    }
})

.directive('component', function() {
    return {
        scope: true,
        require: '^screen',
        controller: function($scope) {
            this.componentFunction = function() {
                $scope.screenCtrl.doSomethingScreeny();
            }
        },
        link: function(scope, element, attrs, screenCtrl) {
            scope.screenCtrl = screenCtrl
        }
    }
})

.directive('widget', function() {
    return {
        scope: true,
        require: "^component",
        link: function(scope, element, attrs, componentCtrl) {
            scope.widgetIt = function() {
                componentCtrl.componentFunction();
            };
        }
    }
})


//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
}

How to disable Google asking permission to regularly check installed apps on my phone?

In Nexus 5, Go to Settings -> Google -> Security and uncheck "Scan device for Security threats" and "Improve harmful app detection".

TestNG ERROR Cannot find class in classpath

I had to make a jar file from my test classes and add it to my class path. Previously I added my test class file to class path and then I got above error. So I created a jar and added to classpath.

e.g

java -cp "my_jars/*" org.testng.TestNG testing.xml

if else in a list comprehension

you can do this

row = [unicode(x.strip()) if x != None else '' for x in row]

Some Syntax for List comprehension :

[item if condition else item for item in items]
[f(item) if condition else value for item in items]
[item if condition for item in items]
[value if condition else value1 if condition1 else value2]

WAITING at sun.misc.Unsafe.park(Native Method)

unsafe.park is pretty much the same as thread.wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits. It's used a lot for thread pooling.

So, to answer your question, all the thread is doing is waiting for something, it's not really using any CPU. Considering that your original stack trace shows that you're using a lock I would assume a deadlock is going on in your case.

Yes I know you have almost certainly already solved this issue by now. However, you're one of the top results if someone googles sun.misc.unsafe.park. I figure answering the question may help others trying to understand what this method that seems to be using all their CPU is.

Permutation of array

There are n! total permutations for the given array size n. Here is code written in Java using DFS.

public List<List<Integer>> permute(int[] nums) {
    List<List<Integer>> results = new ArrayList<List<Integer>>();
    if (nums == null || nums.length == 0) {
        return results;
    }
    List<Integer> result = new ArrayList<>();
    dfs(nums, results, result);
    return results;
}

public void dfs(int[] nums, List<List<Integer>> results, List<Integer> result) {
    if (nums.length == result.size()) {
        List<Integer> temp = new ArrayList<>(result);
        results.add(temp);
    }        
    for (int i=0; i<nums.length; i++) {
        if (!result.contains(nums[i])) {
            result.add(nums[i]);
            dfs(nums, results, result);
            result.remove(result.size() - 1);
        }
    }
}

For input array [3,2,1,4,6], there are totally 5! = 120 possible permutations which are:

[[3,4,6,2,1],[3,4,6,1,2],[3,4,2,6,1],[3,4,2,1,6],[3,4,1,6,2],[3,4,1,2,6],[3,6,4,2,1],[3,6,4,1,2],[3,6,2,4,1],[3,6,2,1,4],[3,6,1,4,2],[3,6,1,2,4],[3,2,4,6,1],[3,2,4,1,6],[3,2,6,4,1],[3,2,6,1,4],[3,2,1,4,6],[3,2,1,6,4],[3,1,4,6,2],[3,1,4,2,6],[3,1,6,4,2],[3,1,6,2,4],[3,1,2,4,6],[3,1,2,6,4],[4,3,6,2,1],[4,3,6,1,2],[4,3,2,6,1],[4,3,2,1,6],[4,3,1,6,2],[4,3,1,2,6],[4,6,3,2,1],[4,6,3,1,2],[4,6,2,3,1],[4,6,2,1,3],[4,6,1,3,2],[4,6,1,2,3],[4,2,3,6,1],[4,2,3,1,6],[4,2,6,3,1],[4,2,6,1,3],[4,2,1,3,6],[4,2,1,6,3],[4,1,3,6,2],[4,1,3,2,6],[4,1,6,3,2],[4,1,6,2,3],[4,1,2,3,6],[4,1,2,6,3],[6,3,4,2,1],[6,3,4,1,2],[6,3,2,4,1],[6,3,2,1,4],[6,3,1,4,2],[6,3,1,2,4],[6,4,3,2,1],[6,4,3,1,2],[6,4,2,3,1],[6,4,2,1,3],[6,4,1,3,2],[6,4,1,2,3],[6,2,3,4,1],[6,2,3,1,4],[6,2,4,3,1],[6,2,4,1,3],[6,2,1,3,4],[6,2,1,4,3],[6,1,3,4,2],[6,1,3,2,4],[6,1,4,3,2],[6,1,4,2,3],[6,1,2,3,4],[6,1,2,4,3],[2,3,4,6,1],[2,3,4,1,6],[2,3,6,4,1],[2,3,6,1,4],[2,3,1,4,6],[2,3,1,6,4],[2,4,3,6,1],[2,4,3,1,6],[2,4,6,3,1],[2,4,6,1,3],[2,4,1,3,6],[2,4,1,6,3],[2,6,3,4,1],[2,6,3,1,4],[2,6,4,3,1],[2,6,4,1,3],[2,6,1,3,4],[2,6,1,4,3],[2,1,3,4,6],[2,1,3,6,4],[2,1,4,3,6],[2,1,4,6,3],[2,1,6,3,4],[2,1,6,4,3],[1,3,4,6,2],[1,3,4,2,6],[1,3,6,4,2],[1,3,6,2,4],[1,3,2,4,6],[1,3,2,6,4],[1,4,3,6,2],[1,4,3,2,6],[1,4,6,3,2],[1,4,6,2,3],[1,4,2,3,6],[1,4,2,6,3],[1,6,3,4,2],[1,6,3,2,4],[1,6,4,3,2],[1,6,4,2,3],[1,6,2,3,4],[1,6,2,4,3],[1,2,3,4,6],[1,2,3,6,4],[1,2,4,3,6],[1,2,4,6,3],[1,2,6,3,4],[1,2,6,4,3]]

Hope this helps.

How to scale a BufferedImage

scale(..) works a bit differently. You can use bufferedImage.getScaledInstance(..)

How do I fix certificate errors when running wget on an HTTPS URL in Cygwin?

If the problem is that a known root CA is missing and when you are using ubuntu or debian, then you can solve the problem with this one line:

sudo apt-get install ca-certificates

Mysql - How to quit/exit from stored procedure

To handle this situation in a portable way (ie will work on all databases because it doesn’t use MySQL label Kung fu), break the procedure up into logic parts, like this:

CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
     IF tablename IS NOT NULL THEN
         CALL SP_Reporting_2(tablename);
     END IF;
END;

CREATE PROCEDURE SP_Reporting_2(IN tablename VARCHAR(20))
BEGIN
     #proceed with code
END;

How do I import a pre-existing Java project into Eclipse and get up and running?

This assumes Eclipse and an appropriate JDK are installed on your system

  1. Open Eclipse and create a new Workspace by specifying an empty directory.
  2. Make sure you're in the Java perspective by selecting Window -> Open Perspective ..., select Other... and then Java
  3. Right click anywhere in the Package Explorer pane and select New -> Java Project
  4. In the dialog that opens give the project a name and then click the option that says "Crate project from existing sources."
  5. In the text box below the option you selected in Step 4 point to the root directory where you checked out the project. This should be the directory that contains "com"
  6. Click Finish. For this particular project you don't need to do any additional setup for your classpath since it only depends on classes that are part of the Java SE API.

Making an asynchronous task in Flask

Threading is another possible solution. Although the Celery based solution is better for applications at scale, if you are not expecting too much traffic on the endpoint in question, threading is a viable alternative.

This solution is based on Miguel Grinberg's PyCon 2016 Flask at Scale presentation, specifically slide 41 in his slide deck. His code is also available on github for those interested in the original source.

From a user perspective the code works as follows:

  1. You make a call to the endpoint that performs the long running task.
  2. This endpoint returns 202 Accepted with a link to check on the task status.
  3. Calls to the status link returns 202 while the taks is still running, and returns 200 (and the result) when the task is complete.

To convert an api call to a background task, simply add the @async_api decorator.

Here is a fully contained example:

from flask import Flask, g, abort, current_app, request, url_for
from werkzeug.exceptions import HTTPException, InternalServerError
from flask_restful import Resource, Api
from datetime import datetime
from functools import wraps
import threading
import time
import uuid

tasks = {}

app = Flask(__name__)
api = Api(app)


@app.before_first_request
def before_first_request():
    """Start a background thread that cleans up old tasks."""
    def clean_old_tasks():
        """
        This function cleans up old tasks from our in-memory data structure.
        """
        global tasks
        while True:
            # Only keep tasks that are running or that finished less than 5
            # minutes ago.
            five_min_ago = datetime.timestamp(datetime.utcnow()) - 5 * 60
            tasks = {task_id: task for task_id, task in tasks.items()
                     if 'completion_timestamp' not in task or task['completion_timestamp'] > five_min_ago}
            time.sleep(60)

    if not current_app.config['TESTING']:
        thread = threading.Thread(target=clean_old_tasks)
        thread.start()


def async_api(wrapped_function):
    @wraps(wrapped_function)
    def new_function(*args, **kwargs):
        def task_call(flask_app, environ):
            # Create a request context similar to that of the original request
            # so that the task can have access to flask.g, flask.request, etc.
            with flask_app.request_context(environ):
                try:
                    tasks[task_id]['return_value'] = wrapped_function(*args, **kwargs)
                except HTTPException as e:
                    tasks[task_id]['return_value'] = current_app.handle_http_exception(e)
                except Exception as e:
                    # The function raised an exception, so we set a 500 error
                    tasks[task_id]['return_value'] = InternalServerError()
                    if current_app.debug:
                        # We want to find out if something happened so reraise
                        raise
                finally:
                    # We record the time of the response, to help in garbage
                    # collecting old tasks
                    tasks[task_id]['completion_timestamp'] = datetime.timestamp(datetime.utcnow())

                    # close the database session (if any)

        # Assign an id to the asynchronous task
        task_id = uuid.uuid4().hex

        # Record the task, and then launch it
        tasks[task_id] = {'task_thread': threading.Thread(
            target=task_call, args=(current_app._get_current_object(),
                               request.environ))}
        tasks[task_id]['task_thread'].start()

        # Return a 202 response, with a link that the client can use to
        # obtain task status
        print(url_for('gettaskstatus', task_id=task_id))
        return 'accepted', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
    return new_function


class GetTaskStatus(Resource):
    def get(self, task_id):
        """
        Return status about an asynchronous task. If this request returns a 202
        status code, it means that task hasn't finished yet. Else, the response
        from the task is returned.
        """
        task = tasks.get(task_id)
        if task is None:
            abort(404)
        if 'return_value' not in task:
            return '', 202, {'Location': url_for('gettaskstatus', task_id=task_id)}
        return task['return_value']


class CatchAll(Resource):
    @async_api
    def get(self, path=''):
        # perform some intensive processing
        print("starting processing task, path: '%s'" % path)
        time.sleep(10)
        print("completed processing task, path: '%s'" % path)
        return f'The answer is: {path}'


api.add_resource(CatchAll, '/<path:path>', '/')
api.add_resource(GetTaskStatus, '/status/<task_id>')


if __name__ == '__main__':
    app.run(debug=True)

MySql sum elements of a column

select
  sum(a) as atotal,
  sum(b) as btotal,
  sum(c) as ctotal
from
  yourtable t
where
  t.id in (1, 2, 3)

Sending event when AngularJS finished loading

i observe DOM manipulation of angular with JQuery and i did set a finish for my app (some sort of predefined and satisfactory situation that i need for my app-abstract) for example i expect my ng-repeater to produce 7 result and there for i will set an observation function with the help of setInterval for this purpose .

$(document).ready(function(){

  var interval = setInterval(function(){

  if($("article").size() == 7){
     myFunction();
     clearInterval(interval);
  }

  },50);

});

How do I add space between items in an ASP.NET RadioButtonList

Even though, the best approach for this situation is set custom CSS styles - an alternative could be:

  • Use Width property and set the percentaje as you see more suitable for your purposes.

In my desired scenario, I need set (2) radiobuttons/items as follows:

o Item 1 o Item 2

Example:

<asp:RadioButtonList ID="rbtnLstOptionsGenerateCertif" runat="server" 
    BackColor="Transparent" BorderColor="Transparent" RepeatDirection="Horizontal" 
    EnableTheming="False" Width="40%">
    <asp:ListItem Text="Item 1" Value="0" />
    <asp:ListItem Text="Item 2" Value="1" />
</asp:RadioButtonList>

Rendered result:

_x000D_
_x000D_
<table id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif" class="chxbx2" border="0" style="background-color:Transparent;border-color:Transparent;width:40%;">
  <tbody>
    <tr>
      <td>
        <input id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_0" type="radio" name="ctl00$ContentPlaceHolder$rbtnLstOptionsGenerateCertif" value="0" checked="checked">
        <label for="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_0">Item 1</label>
      </td>
      <td>
        <input id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_1" type="radio" name="ctl00$ContentPlaceHolder$rbtnLstOptionsGenerateCertif" value="1">
        <label for="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_1">Item 2</label>
      </td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

IIS_IUSRS and IUSR permissions in IIS8

When I added IIS_IUSRS permission to site folder - resources, like js and css, still were unaccessible (error 401, forbidden). However, when I added IUSR - it became ok. So for sure "you CANNOT remove the permissions for IUSR without worrying", dear @Travis G@

Convert String to System.IO.Stream

System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( contents));

How do I apply a perspective transform to a UIView?

Swift 5.0

func makeTransform(horizontalDegree: CGFloat, verticalDegree: CGFloat, maxVertical: CGFloat,rotateDegree: CGFloat, maxHorizontal: CGFloat) -> CATransform3D {
    var transform = CATransform3DIdentity
           
    transform.m34 = 1 / -500
    
    let xAnchor = (horizontalDegree / (2 * maxHorizontal)) + 0.5
    let yAnchor = (verticalDegree / (-2 * maxVertical)) + 0.5
    let anchor = CGPoint(x: xAnchor, y: yAnchor)
    
    setAnchorPoint(anchorPoint: anchor, forView: self.imgView)
    let hDegree  = (CGFloat(horizontalDegree) * .pi)  / 180
    let vDegree  = (CGFloat(verticalDegree) * .pi)  / 180
    let rDegree  = (CGFloat(rotateDegree) * .pi)  / 180
    transform = CATransform3DRotate(transform, vDegree , 1, 0, 0)
    transform = CATransform3DRotate(transform, hDegree , 0, 1, 0)
    transform = CATransform3DRotate(transform, rDegree , 0, 0, 1)
    
    return transform
}

func setAnchorPoint(anchorPoint: CGPoint, forView view: UIView) {
    var newPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x, y: view.bounds.size.height * anchorPoint.y)
    var oldPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x, y: view.bounds.size.height * view.layer.anchorPoint.y)
    
    newPoint = newPoint.applying(view.transform)
    oldPoint = oldPoint.applying(view.transform)
    
    var position = view.layer.position
    position.x -= oldPoint.x
    position.x += newPoint.x
    
    position.y -= oldPoint.y
    position.y += newPoint.y
    
    print("Anchor: \(anchorPoint)")
    
    view.layer.position = position
    view.layer.anchorPoint = anchorPoint
}

you only need to call the function with your degree. for example:

var transform = makeTransform(horizontalDegree: 20.0 , verticalDegree: 25.0, maxVertical: 25, rotateDegree: 20, maxHorizontal: 25)
imgView.layer.transform = transform

Nested jQuery.each() - continue/break

return true not work

return false working

found = false;
query = "foo";

$('.items').each(function()
{
  if($(this).text() == query)
  {
    found = true;
    return false;
  }
});

ERROR 1049 (42000): Unknown database 'mydatabasename'

La Chi's answer works for me.

You can view his/her answer in the comment of zessx answer in this page. But I initially have a problem with it if you also do just tweak his/her answer like this: mysql -h localhost -u root -p -D mydatabase < mydatabase.sql.

Also I would suggest that in the mydatabase.sql portion you include the direct location of it in your computer like "C:\Users\username\desktop".

Thank you.

How do you format code in Visual Studio Code (VSCode)

Just install Visual Studio Keymap (Visual Studio Keymap for Visual Studio Code) by Microsoft. Problem Solved. :p

Change the borderColor of the TextBox

This is an ultimate solution to set the border color of a TextBox:

public class BorderedTextBox : UserControl
{
    TextBox textBox;

    public BorderedTextBox()
    {
        textBox = new TextBox()
        {
            BorderStyle = BorderStyle.FixedSingle,
            Location = new Point(-1, -1),
            Anchor = AnchorStyles.Top | AnchorStyles.Bottom |
                     AnchorStyles.Left | AnchorStyles.Right
        };
        Control container = new ContainerControl()
        {
            Dock = DockStyle.Fill,
            Padding = new Padding(-1)
        };
        container.Controls.Add(textBox);
        this.Controls.Add(container);

        DefaultBorderColor = SystemColors.ControlDark;
        FocusedBorderColor = Color.Red;
        BackColor = DefaultBorderColor;
        Padding = new Padding(1);
        Size = textBox.Size;
    }

    public Color DefaultBorderColor { get; set; }
    public Color FocusedBorderColor { get; set; }

    public override string Text
    {
        get { return textBox.Text; }
        set { textBox.Text = value; }
    }

    protected override void OnEnter(EventArgs e)
    {
        BackColor = FocusedBorderColor;
        base.OnEnter(e);
    }

    protected override void OnLeave(EventArgs e)
    {
        BackColor = DefaultBorderColor;
        base.OnLeave(e);
    }

    protected override void SetBoundsCore(int x, int y,
        int width, int height, BoundsSpecified specified)
    {
        base.SetBoundsCore(x, y, width, textBox.PreferredHeight, specified);
    }
}

HTML/Javascript change div content

Assuming you're not using jQuery or some other library that makes this sort of thing easier for you, you can just use the element's innerHTML property.

document.getElementById("content").innerHTML = "whatever";

Detect application heap size in Android

Asus Nexus 7 (2013) 32Gig: getMemoryClass()=192 maxMemory()=201326592

I made the mistake of prototyping my game on the Nexus 7, and then discovering it ran out of memory almost immediately on my wife's generic 4.04 tablet (memoryclass 48, maxmemory 50331648)

I'll need to restructure my project to load fewer resources when I determine memoryclass is low.
Is there a way in Java to see the current heap size? (I can see it clearly in the logCat when debugging, but I'd like a way to see it in code to adapt, like if currentheap>(maxmemory/2) unload high quality bitmaps load low quality

Dynamically add properties to a existing object

Consider using the decorator pattern http://en.wikipedia.org/wiki/Decorator_pattern

You can change the decorator at runtime with one that has different properties when an event occurs.

Align DIV's to bottom or baseline

this works (i only tested ie & ff):

<html>
<head>
    <style type="text/css">
        #parent {
            height: 300px;
            width: 300px;
            background-color: #ccc;
            border: 1px solid red;
            position: relative;
        }
        #child  {
            height: 100px;
            width: 30px;
            background-color: #eee;
            border: 1px solid green;
            position: absolute;
            bottom: 0;
            left: 0;
        }
    </style>
</head>
<body>
    <div id="parent">parent
        <div id="child">child</div>
    </div>
    outside
</body>
</html>

hope that helps.

XML Carriage return encoding

xml:space="preserve" has to work for all compliant XML parsers.

However, note that in HTML the line break is just whitespace and NOT a line break (this is represented with the <br /> (X)HTML tag, maybe this is the problem which you are facing.

You can also add &#10; and/or &#13; to insert CR/LF characters.

How to Customize a Progress Bar In Android

in your xml

<ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        style="@style/CustomProgressBar" 
        android:layout_margin="5dip" />

And in res/values/styles.xml:

<resources> 
        <style name="CustomProgressBar" parent="android:Widget.ProgressBar.Horizontal">
          <item name="android:indeterminateOnly">false</item>
          <item name="android:progressDrawable">@drawable/custom_progress_bar_horizontal</item>
          <item name="android:minHeight">10dip</item>
          <item name="android:maxHeight">20dip</item>
        </style>       
    <style name="AppTheme" parent="android:Theme.Light" />
</resources>

And custom_progress_bar_horizontal is a xml stored in drawable folder which defines your custom progress bar. For more detail see this blog.

I hope this will help you.

Symfony 2 EntityManager injection in service

Since 2017 and Symfony 3.3 you can register Repository as service, with all its advantages it has.

Check my post How to use Repository with Doctrine as Service in Symfony for more general description.


To your specific case, original code with tuning would look like this:

1. Use in your services or Controller

<?php

namespace Test\CommonBundle\Services;

use Doctrine\ORM\EntityManagerInterface;

class UserService
{
    private $userRepository;

    // use custom repository over direct use of EntityManager
    // see step 2
    public function __constructor(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function getUser($userId)
    {
        return $this->userRepository->find($userId);
    }
}

2. Create new custom repository

<?php

namespace Test\CommonBundle\Repository;

use Doctrine\ORM\EntityManagerInterface;

class UserRepository
{
    private $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(UserEntity::class);
    }

    public function find($userId)
    {
        return  $this->repository->find($userId);
    }
}

3. Register services

# app/config/services.yml
services:
    _defaults:
        autowire: true

    Test\CommonBundle\:
       resource: ../../Test/CommonBundle

System.IO.IOException: file used by another process

After coming across this error and not finding anything on the web that set me right, I thought I'd add another reason for getting this Exception - namely that the source and destination paths in the File Copy command are the same. It took me a while to figure it out, but it may help to add code somewhere to throw an exception if source and destination paths are pointing to the same file.

Good luck!

Make 2 functions run at the same time

This can be done elegantly with Ray, a system that allows you to easily parallelize and distribute your Python code.

To parallelize your example, you'd need to define your functions with the @ray.remote decorator, and then invoke them with .remote.

import ray

ray.init()

# Define functions you want to execute in parallel using 
# the ray.remote decorator.
@ray.remote
def func1():
    print("Working")

@ray.remote
def func2():
    print("Working")

# Execute func1 and func2 in parallel.
ray.get([func1.remote(), func2.remote()])

If func1() and func2() return results, you need to rewrite the above code a bit, by replacing ray.get([func1.remote(), func2.remote()]) with:

ret_id1 = func1.remote()
ret_id2 = func1.remote()
ret1, ret2 = ray.get([ret_id1, ret_id2])

There are a number of advantages of using Ray over the multiprocessing module or using multithreading. In particular, the same code will run on a single machine as well as on a cluster of machines.

For more advantages of Ray see this related post.

Format output string, right alignment

I really enjoy a new literal string interpolation in Python 3.6+:

line_new = f'{word[0]:>12}  {word[1]:>12}  {word[2]:>12}'

Reference: PEP 498 -- Literal String Interpolation

number_format() with MySQL

http://blogs.mysql.com/peterg/2009/04/

In Mysql 6.1 you will be able to do FORMAT(X,D [,locale_name] )

As in

 SELECT format(1234567,2,’de_DE’);

For now this ability does not exist, though you MAY be able to set your locale in your database my.ini check it out.

Making href (anchor tag) request POST instead of GET?

To do POST you'll need to have a form.

<form action="employee.action" method="post">
    <input type="submit" value="Employee1" />
</form>

There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.

Some tricks: Make a link use POST instead of GET and How do you post data with a link

Edit: to load response on a frame you can target your form to your frame:

<form action="employee.action" method="post" target="myFrame">

What is the significance of load factor in HashMap?

If the buckets get too full, then we have to look through

a very long linked list.

And that's kind of defeating the point.

So here's an example where I have four buckets.

I have elephant and badger in my HashSet so far.

This is a pretty good situation, right?

Each element has zero or one elements.

Now we put two more elements into our HashSet.

     buckets      elements
      -------      -------
        0          elephant
        1          otter
         2          badger
         3           cat

This isn't too bad either.

Every bucket only has one element . So if I wanna know, does this contain panda?

I can very quickly look at bucket number 1 and it's not

there and

I known it's not in our collection.

If I wanna know if it contains cat, I look at bucket

number 3,

I find cat, I very quickly know if it's in our

collection.

What if I add koala, well that's not so bad.

             buckets      elements
      -------      -------
        0          elephant
        1          otter -> koala 
         2          badger
         3           cat

Maybe now instead of in bucket number 1 only looking at

one element,

I need to look at two.

But at least I don't have to look at elephant, badger and

cat.

If I'm again looking for panda, it can only be in bucket

number 1 and

I don't have to look at anything other then otter and

koala.

But now I put alligator in bucket number 1 and you can

see maybe where this is going.

That if bucket number 1 keeps getting bigger and bigger and

bigger, then I'm basically having to look through all of

those elements to find

something that should be in bucket number 1.

            buckets      elements
      -------      -------
        0          elephant
        1          otter -> koala ->alligator
         2          badger
         3           cat

If I start adding strings to other buckets,

right, the problem just gets bigger and bigger in every

single bucket.

How do we stop our buckets from getting too full?

The solution here is that

          "the HashSet can automatically

        resize the number of buckets."

There's the HashSet realizes that the buckets are getting

too full.

It's losing this advantage of this all of one lookup for

elements.

And it'll just create more buckets(generally twice as before) and

then place the elements into the correct bucket.

So here's our basic HashSet implementation with separate

chaining. Now I'm going to create a "self-resizing HashSet".

This HashSet is going to realize that the buckets are

getting too full and

it needs more buckets.

loadFactor is another field in our HashSet class.

loadFactor represents the average number of elements per

bucket,

above which we want to resize.

loadFactor is a balance between space and time.

If the buckets get too full then we'll resize.

That takes time, of course, but

it may save us time down the road if the buckets are a

little more empty.

Let's see an example.

Here's a HashSet, we've added four elements so far.

Elephant, dog, cat and fish.

          buckets      elements
      -------      -------
        0          
        1          elephant
         2          cat ->dog
         3           fish
          4         
           5

At this point, I've decided that the loadFactor, the

threshold,

the average number of elements per bucket that I'm okay

with, is 0.75.

The number of buckets is buckets.length, which is 6, and

at this point our HashSet has four elements, so the

current size is 4.

We'll resize our HashSet, that is we'll add more buckets,

when the average number of elements per bucket exceeds

the loadFactor.

That is when current size divided by buckets.length is

greater than loadFactor.

At this point, the average number of elements per bucket

is 4 divided by 6.

4 elements, 6 buckets, that's 0.67.

That's less than the threshold I set of 0.75 so we're

okay.

We don't need to resize.

But now let's say we add woodchuck.

                  buckets      elements
      -------      -------
        0          
        1          elephant
         2        woodchuck-> cat ->dog
         3           fish
          4         
           5

Woodchuck would end up in bucket number 3.

At this point, the currentSize is 5.

And now the average number of elements per bucket

is the currentSize divided by buckets.length.

That's 5 elements divided by 6 buckets is 0.83.

And this exceeds the loadFactor which was 0.75.

In order to address this problem, in order to make the

buckets perhaps a little

more empty so that operations like determining whether a

bucket contains

an element will be a little less complex, I wanna resize

my HashSet.

Resizing the HashSet takes two steps.

First I'll double the number of buckets, I had 6 buckets,

now I'm going to have 12 buckets.

Note here that the loadFactor which I set to 0.75 stays the same.

But the number of buckets changed is 12,

the number of elements stayed the same, is 5.

5 divided by 12 is around 0.42, that's well under our

loadFactor,

so we're okay now.

But we're not done because some of these elements are in

the wrong bucket now.

For instance, elephant.

Elephant was in bucket number 2 because the number of

characters in elephant

was 8.

We have 6 buckets, 8 minus 6 is 2.

That's why it ended up in number 2.

But now that we have 12 buckets, 8 mod 12 is 8, so

elephant does not belong in bucket number 2 anymore.

Elephant belongs in bucket number 8.

What about woodchuck?

Woodchuck was the one that started this whole problem.

Woodchuck ended up in bucket number 3.

Because 9 mod 6 is 3.

But now we do 9 mod 12.

9 mod 12 is 9, woodchuck goes to bucket number 9.

And you see the advantage of all this.

Now bucket number 3 only has two elements whereas before it had 3.

So here's our code,

where we had our HashSet with separate chaining that

didn't do any resizing.

Now, here's a new implementation where we use resizing.

Most of this code is the same,

we're still going to determine whether it contains the

value already.

If it doesn't, then we'll figure it out which bucket it

should go into and

then add it to that bucket, add it to that LinkedList.

But now we increment the currentSize field.

currentSize was the field that kept track of the number

of elements in our HashSet.

We're going to increment it and then we're going to look

at the average load,

the average number of elements per bucket.

We'll do that division down here.

We have to do a little bit of casting here to make sure

that we get a double.

And then, we'll compare that average load to the field

that I've set as

0.75 when I created this HashSet, for instance, which was

the loadFactor.

If the average load is greater than the loadFactor,

that means there's too many elements per bucket on

average, and I need to reinsert.

So here's our implementation of the method to reinsert

all the elements.

First, I'll create a local variable called oldBuckets.

Which is referring to the buckets as they currently stand

before I start resizing everything.

Note I'm not creating a new array of linked lists just yet.

I'm just renaming buckets as oldBuckets.

Now remember buckets was a field in our class, I'm going

to now create a new array

of linked lists but this will have twice as many elements

as it did the first time.

Now I need to actually do the reinserting,

I'm going to iterate through all of the old buckets.

Each element in oldBuckets is a LinkedList of strings

that is a bucket.

I'll go through that bucket and get each element in that

bucket.

And now I'm gonna reinsert it into the newBuckets.

I will get its hashCode.

I will figure out which index it is.

And now I get the new bucket, the new LinkedList of

strings and

I'll add it to that new bucket.

So to recap, HashSets as we've seen are arrays of Linked

Lists, or buckets.

A self resizing HashSet can realize using some ratio or

How to redirect to a different domain using NGINX?

Why use the rewrite module if you can do return? Technically speaking, return is part of the rewrite module as you can read here but this snippet is easier to read imho.

server {
    server_name  .domain.com;

    return 302 $scheme://forwarded-domain.com;
}

You can also give it a 301 redirect.

Spring data JPA query with parameter properties

Are you working with a @Service too? Because if you are, then you can @Autowired your PersonRepository to the @Service and then in the service just invoke the Name class and use the form that @CuriosMind... proposed:

@Query(select p from Person p where p.forename = :forename and p.surname = :surname)
User findByForenameAndSurname(@Param("surname") String lastname,
                         @Param("forename") String firstname);
}

and when invoking the method from the repository in the service, you can then pass those parameters.

Calculate difference between 2 date / times in Oracle SQL

If You want get date defer from using table and column.

SELECT TO_DATE( TO_CHAR(COLUMN_NAME_1, 'YYYY-MM-DD'), 'YYYY-MM-DD') - 
       TO_DATE(TO_CHAR(COLUMN_NAME_2, 'YYYY-MM-DD') , 'YYYY-MM-DD')  AS DATEDIFF       
FROM TABLE_NAME;

converting Java bitmap to byte array

In order to avoid OutOfMemory error for bigger files, I would solve the task by splitting a bitmap into several parts and merging their parts' bytes.

private byte[] getBitmapBytes(Bitmap bitmap)
{
    int chunkNumbers = 10;
    int bitmapSize = bitmap.getRowBytes() * bitmap.getHeight();
    byte[] imageBytes = new byte[bitmapSize];
    int rows, cols;
    int chunkHeight, chunkWidth;
    rows = cols = (int) Math.sqrt(chunkNumbers);
    chunkHeight = bitmap.getHeight() / rows;
    chunkWidth = bitmap.getWidth() / cols;

    int yCoord = 0;
    int bitmapsSizes = 0;

    for (int x = 0; x < rows; x++)
    {
        int xCoord = 0;
        for (int y = 0; y < cols; y++)
        {
            Bitmap bitmapChunk = Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkWidth, chunkHeight);
            byte[] bitmapArray = getBytesFromBitmapChunk(bitmapChunk);
            System.arraycopy(bitmapArray, 0, imageBytes, bitmapsSizes, bitmapArray.length);
            bitmapsSizes = bitmapsSizes + bitmapArray.length;
            xCoord += chunkWidth;

            bitmapChunk.recycle();
            bitmapChunk = null;
        }
        yCoord += chunkHeight;
    }

    return imageBytes;
}


private byte[] getBytesFromBitmapChunk(Bitmap bitmap)
{
    int bitmapSize = bitmap.getRowBytes() * bitmap.getHeight();
    ByteBuffer byteBuffer = ByteBuffer.allocate(bitmapSize);
    bitmap.copyPixelsToBuffer(byteBuffer);
    byteBuffer.rewind();
    return byteBuffer.array();
}

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The server at x3.chatforyoursite.com needs to output the following header:

Access-Control-Allow-Origin: http://www.example.com

Where http://www.example.com is your website address. You should check your settings on chatforyoursite.com to see if you can enable this - if not their technical support would probably be the best way to resolve this. However to answer your question, you need the remote site to allow your site to access AJAX responses client side.

Eclipse "Invalid Project Description" when creating new project from existing source

Go into your workspace, and move your project source code folder to another area outside of your workspace (like the desktop). Make sure the project is deleted in eclipse, then create a new project from source from that directory.

Another thing you could do is try creating a project of a different name (from the first project's source), so that the workspace will contain the new project as a functional project. Then, go into your workspace directory and absolutely delete the folder that contained the original project, or move it. Try loading the project from source again, this time using the second project, by naming it with the correct name. Or, you could try refactoring the second project back to the first's name.

Jquery submit form

Use the following jquery to submit a selectbox with out a submit button. Use "change" instead of click as shown above.

$("selectbox").change(function() { 
   document.forms["form"].submit();
});

Cheers!

Passing variables to the next middleware using next() in Express.js

Attach your variable to the req object, not res.

Instead of

res.somevariable = variable1;

Have:

req.somevariable = variable1;

As others have pointed out, res.locals is the recommended way of passing data through middleware.

\r\n, \r and \n what is the difference between them?

  • \r = CR (Carriage Return) → Used as a new line character in Mac OS before X
  • \n = LF (Line Feed) → Used as a new line character in Unix/Mac OS X
  • \r\n = CR + LF → Used as a new line character in Windows

Undefined index error PHP

Try:

<?php

if (isset($_POST['name'])) {
    $name = $_POST['name'];
}

if (isset($_POST['price'])) {
    $price = $_POST['price'];
}

if (isset($_POST['description'])) {
    $description = $_POST['description'];
}

?>

Using set_facts and with_items together in Ansible

I was hunting around for an answer to this question. I found this helpful. The pattern wasn't apparent in the documentation for with_items.

https://github.com/ansible/ansible/issues/39389

- hosts: localhost
  connection: local
  gather_facts: no

  tasks:
    - name: set_fact
      set_fact:
        foo: "{{ foo }} + [ '{{ item }}' ]"
      with_items:
        - "one"
        - "two"
        - "three"
      vars:
        foo: []

    - name: Print the var
      debug:
        var: foo

How do I replace NA values with zeros in an R dataframe?

Another dplyr pipe compatible option with tidyrmethod replace_na that works for several columns:

require(dplyr)
require(tidyr)

m <- matrix(sample(c(NA, 1:10), 100, replace = TRUE), 10)
d <- as.data.frame(m)

myList <- setNames(lapply(vector("list", ncol(d)), function(x) x <- 0), names(d))

df <- d %>% replace_na(myList)

You can easily restrict to e.g. numeric columns:

d$str <- c("string", NA)

myList <- myList[sapply(d, is.numeric)]

df <- d %>% replace_na(myList)

What does 'public static void' mean in Java?

Considering the typical top-level class. Only public and no modifier access modifiers may be used at the top level so you'll either see public or you won't see any access modifier at all.

`static`` is used because you may not have a need to create an actual object at the top level (but sometimes you will want to so you may not always see/use static. There are other reasons why you wouldn't include static too but this is the typical one at the top level.)

void is used because usually you're not going to be returning a value from the top level (class). (sometimes you'll want to return a value other than NULL so void may not always be used either especially in the case when you have declared, initialized an object at the top level that you are assigning some value to).

Disclaimer: I'm a newbie myself so if this answer is wrong in any way please don't hang me. By day I'm a tech recruiter not a developer; coding is my hobby. Also, I'm always open to constructive criticism and love to learn so please feel free to point out any errors.

How can you determine a point is between two other points on a line segment?

Ok, lots of mentions of linear algebra (cross product of vectors) and this works in a real (ie continuous or floating point) space but the question specifically stated that the two points were expressed as integers and thus a cross product is not the correct solution although it can give an approximate solution.

The correct solution is to use Bresenham's Line Algorithm between the two points and to see if the third point is one of the points on the line. If the points are sufficiently distant that calculating the algorithm is non-performant (and it'd have to be really large for that to be the case) I'm sure you could dig around and find optimisations.

How do I start a program with arguments when debugging?

I came to this page because I have sensitive information in my command line parameters, and didn't want them stored in the code repository. I was using System Environment variables to hold the values, which could be set on each build or development machine as needed for each purpose. Environment Variable Expansion works great in Shell Batch processes, but not Visual Studio.

Visual Studio Start Options:

Visual Studio Start Options

However, Visual Studio wouldn't return the variable value, but the name of the variable.

Example of Issue:

Example of Error in Visual Studio

My final solution after trying several here on S.O. was to write a quick lookup for the Environment variable in my Argument Processor. I added a check for % in the incoming variable value, and if it's found, lookup the Environment Variable and replace the value. This works in Visual Studio, and in my Build Environment.

foreach (string thisParameter in args)
            {
                if (thisParameter.Contains("="))
                {
                    string parameter = thisParameter.Substring(0, thisParameter.IndexOf("="));
                    string value = thisParameter.Substring(thisParameter.IndexOf("=") + 1);

                    if (value.Contains("%"))
                    {   //Workaround for VS not expanding variables in debug
                        value = Environment.GetEnvironmentVariable(value.Replace("%", ""));
                    }

This allows me to use the same syntax in my sample batch files, and in debugging with Visual Studio. No account information or URLs saved in GIT.

Example Use in Batch

Batch File Example

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

Maybe this can help:

swagger: '2.0'
info:
  version: 1.0.0
  title: Based on "Basic Auth Example"
  description: >
    An example for how to use Auth with Swagger.

host: basic-auth-server.herokuapp.com
schemes:
  - http
  - https
securityDefinitions:
  Bearer:
    type: apiKey
    name: Authorization
    in: header
paths:
  /:
    get:
      security:
        - Bearer: []
      responses:
        '200':
          description: 'Will send `Authenticated`'
        '403': 
          description: 'You do not have necessary permissions for the resource'

You can copy&paste it out here: http://editor.swagger.io/#/ to check out the results.

There are also several examples in the swagger editor web with more complex security configurations which could help you.

Add custom headers to WebView resource requests - android

You will need to intercept each request using WebViewClient.shouldInterceptRequest

With each interception, you will need to take the url, make this request yourself, and return the content stream:

WebViewClient wvc = new WebViewClient() {
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

        try {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("MY-CUSTOM-HEADER", "header value");
            httpGet.setHeader(HttpHeaders.USER_AGENT, "custom user-agent");
            HttpResponse httpReponse = client.execute(httpGet);

            Header contentType = httpReponse.getEntity().getContentType();
            Header encoding = httpReponse.getEntity().getContentEncoding();
            InputStream responseInputStream = httpReponse.getEntity().getContent();

            String contentTypeValue = null;
            String encodingValue = null;
            if (contentType != null) {
                contentTypeValue = contentType.getValue();
            }
            if (encoding != null) {
                encodingValue = encoding.getValue();
            }
            return new WebResourceResponse(contentTypeValue, encodingValue, responseInputStream);
        } catch (ClientProtocolException e) {
            //return null to tell WebView we failed to fetch it WebView should try again.
            return null;
        } catch (IOException e) {
             //return null to tell WebView we failed to fetch it WebView should try again.
            return null;
        }
    }
}

Webview wv = new WebView(this);
wv.setWebViewClient(wvc);

If your minimum API target is level 21, you can use the new shouldInterceptRequest which gives you additional request information (such as headers) instead of just the URL.

How to execute python file in linux

yes there is. add

#!/usr/bin/env python

to the beginning of the file and do

chmod u+rx <file>

assuming your user owns the file, otherwise maybe adjust the group or world permissions.

.py files under windows are associated with python as the program to run when opening them just like MS word is run when opening a .docx for example.

Excel formula to display ONLY month and year?

Very easy, trial and error. Go to the cell you want the month in. Type the Month, go to the next cell and type the year, something weird will come up but then go to your number section click on the little arrow in the right bottom and highlight text and it will change to the year you originally typed

How do I put a border around an Android textview?

You can set the border by two methods. One is by drawable and the second is programmatic.

Using Drawable

<shape>
    <solid android:color="@color/txt_white"/>
    <stroke android:width="1dip" android:color="@color/border_gray"/>
    <corners android:bottomLeftRadius="10dp"
             android:bottomRightRadius="0dp"
             android:topLeftRadius="10dp"
             android:topRightRadius="0dp"/>
    <padding android:bottom="0dip"
             android:left="0dip"
             android:right="0dip"
             android:top="0dip"/>
</shape>

Programmatic


public static GradientDrawable backgroundWithoutBorder(int color) {

    GradientDrawable gdDefault = new GradientDrawable();
    gdDefault.setColor(color);
    gdDefault.setCornerRadii(new float[] { radius, radius, 0, 0, 0, 0,
                                           radius, radius });
    return gdDefault;
}

Excel VBA, How to select rows based on data in a column?

Yes using Option Explicit is a good habit. Using .Select however is not :) it reduces the speed of the code. Also fully justify sheet names else the code will always run for the Activesheet which might not be what you actually wanted.

Is this what you are trying?

Option Explicit

Sub Sample()
    Dim lastRow As Long, i As Long
    Dim CopyRange As Range

    '~~> Change Sheet1 to relevant sheet name
    With Sheets("Sheet1")
        lastRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 2 To lastRow
            If Len(Trim(.Range("A" & i).Value)) <> 0 Then
                If CopyRange Is Nothing Then
                    Set CopyRange = .Rows(i)
                Else
                    Set CopyRange = Union(CopyRange, .Rows(i))
                End If
            Else
                Exit For
            End If
        Next

        If Not CopyRange Is Nothing Then
            '~~> Change Sheet2 to relevant sheet name
            CopyRange.Copy Sheets("Sheet2").Rows(1)
        End If
    End With
End Sub

NOTE

If if you have data from Row 2 till Row 10 and row 11 is blank and then you have data again from Row 12 then the above code will only copy data from Row 2 till Row 10

If you want to copy all rows which have data then use this code.

Option Explicit

Sub Sample()
    Dim lastRow As Long, i As Long
    Dim CopyRange As Range

    '~~> Change Sheet1 to relevant sheet name
    With Sheets("Sheet1")
        lastRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 2 To lastRow
            If Len(Trim(.Range("A" & i).Value)) <> 0 Then
                If CopyRange Is Nothing Then
                    Set CopyRange = .Rows(i)
                Else
                    Set CopyRange = Union(CopyRange, .Rows(i))
                End If
            End If
        Next

        If Not CopyRange Is Nothing Then
            '~~> Change Sheet2 to relevant sheet name
            CopyRange.Copy Sheets("Sheet2").Rows(1)
        End If
    End With
End Sub

Hope this is what you wanted?

Sid

What is define([ , function ]) in JavaScript?

define() is part of the AMD spec of js

See:

Edit: Also see Claudio's answer below. Likely the more relevant explanation.

How to take character input in java

you can use a Scanner to read from input :

Scanner scanner = new Scanner(System.in); 
char c = scanner.next().charAt(0); //charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.

c# Image resizing to different size while preserving aspect ratio

Here's a less specific extension method that works with Image rather than doing the loading and saving for you. It also allows you to specify interpolation method and correctly renders edges when you use NearestNeighbour interpolation.

The image will be rendered within the bounds of the area you specify so you always know your output width and height. e.g:

Scaled within bounds

namespace YourApp
{
    #region Namespaces
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Drawing.Drawing2D;
    #endregion

    /// <summary>Generic helper functions related to graphics.</summary>
    public static class ImageExtensions
    {
        /// <summary>Resizes an image to a new width and height value.</summary>
        /// <param name="image">The image to resize.</param>
        /// <param name="newWidth">The width of the new image.</param>
        /// <param name="newHeight">The height of the new image.</param>
        /// <param name="mode">Interpolation mode.</param>
        /// <param name="maintainAspectRatio">If true, the image is centered in the middle of the returned image, maintaining the aspect ratio of the original image.</param>
        /// <returns>The new image. The old image is unaffected.</returns>
        public static Image ResizeImage(this Image image, int newWidth, int newHeight, InterpolationMode mode = InterpolationMode.Default, bool maintainAspectRatio = false)
        {
            Bitmap output = new Bitmap(newWidth, newHeight, image.PixelFormat);

            using (Graphics gfx = Graphics.FromImage(output))
            {
                gfx.Clear(Color.FromArgb(0, 0, 0, 0));
                gfx.InterpolationMode = mode;
                if (mode == InterpolationMode.NearestNeighbor)
                {
                    gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    gfx.SmoothingMode = SmoothingMode.HighQuality;
                }

                double ratioW = (double)newWidth / (double)image.Width;
                double ratioH = (double)newHeight / (double)image.Height;
                double ratio = ratioW < ratioH ? ratioW : ratioH;
                int insideWidth = (int)(image.Width * ratio);
                int insideHeight = (int)(image.Height * ratio);

                gfx.DrawImage(image, new Rectangle((newWidth / 2) - (insideWidth / 2), (newHeight / 2) - (insideHeight / 2), insideWidth, insideHeight));
            }

            return output;
        }
    }
}

Compiling C++ on remote Linux machine - "clock skew detected" warning

Make checks if the result of the compilation, e.g. somefile.o, is older than the source, e.g. somefile.c. The warning above means that something about the timestaps of the files is strange. Probably the system clocks of the University server differs from your clock and you e.g. push at 1 pm a file with modification date 2 pm. You can see the time at the console by typing date.

Get the previous month's first and last day dates in c#

An approach using extension methods:

class Program
{
    static void Main(string[] args)
    {
        DateTime t = DateTime.Now;

        DateTime p = t.PreviousMonthFirstDay();
        Console.WriteLine( p.ToShortDateString() );

        p = t.PreviousMonthLastDay();
        Console.WriteLine( p.ToShortDateString() );


        Console.ReadKey();
    }
}


public static class Helpers
{
    public static DateTime PreviousMonthFirstDay( this DateTime currentDate )
    {
        DateTime d = currentDate.PreviousMonthLastDay();

        return new DateTime( d.Year, d.Month, 1 );
    }

    public static DateTime PreviousMonthLastDay( this DateTime currentDate )
    {
        return new DateTime( currentDate.Year, currentDate.Month, 1 ).AddDays( -1 );
    }
}

See this link http://www.codeplex.com/fluentdatetime for some inspired DateTime extensions.

Cast object to interface in TypeScript

If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:

Didn't pass linting

const x = new Obj(a as b);

The linter was complaining that a was missing properties that existed on b. In other words, a had some properties and methods of b, but not all. To work around this, I followed VS Code's suggestion:

Passed linting and testing

const x = new Obj(a as unknown as b);

Note that if your code attempts to call one of the properties that exists on type b that is not implemented on type a, you should realize a runtime fault.

Passing javascript variable to html textbox

You could also use to localStorage feature of HTML5 to store your test value and then access it at any other point in your website by using the localStorage.getItem() method. To see how this works you should look at the w3schools explanation or the explanation from the Opera Developer website. Hope this helps.

Convert Map to JSON using Jackson

Using jackson, you can do it as follows:

    ObjectMapper mapper = new ObjectMapper();
    String clientFilterJson = "";
    try {
        clientFilterJson = mapper.writeValueAsString(filterSaveModel);
    } catch (IOException e) {
        e.printStackTrace();
    }

How to decrypt hash stored by bcrypt

To answer the original posters question.... to 'decrypt' the password, you have to do what a password cracker would do.

In other words, you'd run a program to read from a large list of potential passwords (a password dictionary) and you'd hash each one using bcrypt and the salt and complexity from the password you're trying to decipher. If you're lucky you'll find a match, but if the password is a strong one then you likely won't find a match.

Bcrypt has the added security characteristic of being a slow hash. If your password had been hashed with md5 (terrible choice) then you'd be able to check billions of passwords per second, but since it's hashed using bcrypt you will be able to check far fewer per second.

The fact that bcrypt is slow to hash and salted is what makes it a good choice for password storage even today. That being said I believe NIST recommends the PBKDF2 for password hashing.

initialize a numpy array

The way I usually do that is by creating a regular list, then append my stuff into it, and finally transform the list to a numpy array as follows :

import numpy as np
big_array = [] #  empty regular list
for i in range(5):
    arr = i*np.ones((2,4)) # for instance
    big_array.append(arr)
big_np_array = np.array(big_array)  # transformed to a numpy array

of course your final object takes twice the space in the memory at the creation step, but appending on python list is very fast, and creation using np.array() also.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

I'm developing a simple JavaFX11 application with SQLite Database in Eclipse IDE. To generate report I added Jasper jars. Suddenly it throws "THIS" error.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

It was running good (BEFORE THIS ADDITION). But suddenly!

I'm not using maven or other managers for this simple application. I'm adding jars manually.

I created "User Library" and added my jars from external folders.

PROBLEM OCCURING AREA: My "User Library" are marked as system library. I just removed the marking. Now its not a system library. "NOW MY PROJECT WORKING GOOD".

DEBUG MYSELF: Tried other things: AT RUN CONFIGURATION: Try, removing library and add jars one-by-one and see. - here you have to delete all jars one by one, there is no select all and remove in eclipse right now in run configuration. So the error messages changes form one jars to another.

Hope this helps someone.

Cannot make Project Lombok work on Eclipse

I am on Eclipse Neon, and after following the above steps, it still didnt work. import lombok.Data; was not being recognized.

After about an hour of looking around, i switched the version to 1.16.14 and it worked.

Now my thought is, whether the 1 hour spent will be a good investment for long term :-)

Python 3 print without parenthesis

No. That will always be a syntax error in Python 3. Consider using 2to3 to translate your code to Python 3

How to get thread id of a pthread in linux c program?

There is also another way of getting thread id. While creating threads with

int pthread_create(pthread_t * thread, const pthread_attr_t * attr, void * (*start_routine)(void *), void *arg);

function call; the first parameter pthread_t * thread is actually a thread id (that is an unsigned long int defined in bits/pthreadtypes.h). Also, the last argument void *arg is the argument that is passed to void * (*start_routine) function to be threaded.

You can create a structure to pass multiple arguments and send a pointer to a structure.

typedef struct thread_info {
    pthread_t thread;
    //...
} thread_info;
//...
tinfo = malloc(sizeof(thread_info) * NUMBER_OF_THREADS);
//...
pthread_create (&tinfo[i].thread, NULL, handler, (void*)&tinfo[i]);
//...
void *handler(void *targs) {
    thread_info *tinfo = targs;
    // here you get the thread id with tinfo->thread
}

Creating email templates with Django

Django Mail Templated is a feature-rich Django application to send emails with Django template system.

Installation:

pip install django-mail-templated

Configuration:

INSTALLED_APPS = (
    ...
    'mail_templated'
)

Template:

{% block subject %}
Hello {{ user.name }}
{% endblock %}

{% block body %}
{{ user.name }}, this is the plain text part.
{% endblock %}

Python:

from mail_templated import send_mail
send_mail('email/hello.tpl', {'user': user}, from_email, [user.email])

More info: https://github.com/artemrizhov/django-mail-templated

Read a file in Node.js

If you want to know how to read a file, within a directory, and do something with it, here you go. This also shows you how to run a command through the power shell. This is in TypeScript! I had trouble with this, so I hope this helps someone one day. Feel free to down vote me if you think its THAT unhelpful. What this did for me was webpack all of my .ts files in each of my directories within a certain folder to get ready for deployment. Hope you can put it to use!

import * as fs from 'fs';
let path = require('path');
let pathDir = '/path/to/myFolder';
const execSync = require('child_process').execSync;

let readInsideSrc = (error: any, files: any, fromPath: any) => {
    if (error) {
        console.error('Could not list the directory.', error);
        process.exit(1);
    }

    files.forEach((file: any, index: any) => {
        if (file.endsWith('.ts')) {
            //set the path and read the webpack.config.js file as text, replace path
            let config = fs.readFileSync('myFile.js', 'utf8');
            let fileName = file.replace('.ts', '');
            let replacedConfig = config.replace(/__placeholder/g, fileName);

            //write the changes to the file
            fs.writeFileSync('myFile.js', replacedConfig);

            //run the commands wanted
            const output = execSync('npm run scriptName', { encoding: 'utf-8' });
            console.log('OUTPUT:\n', output);

            //rewrite the original file back
            fs.writeFileSync('myFile.js', config);
        }
    });
};

// loop through all files in 'path'
let passToTest = (error: any, files: any) => {
    if (error) {
        console.error('Could not list the directory.', error);
        process.exit(1);
    }

    files.forEach(function (file: any, index: any) {
        let fromPath = path.join(pathDir, file);
        fs.stat(fromPath, function (error2: any, stat: any) {
            if (error2) {
                console.error('Error stating file.', error2);
                return;
            }

            if (stat.isDirectory()) {
                fs.readdir(fromPath, (error3: any, files1: any) => {
                    readInsideSrc(error3, files1, fromPath);
                });
            } else if (stat.isFile()) {
                //do nothing yet
            }

        });
    });
};

//run the bootstrap
fs.readdir(pathDir, passToTest);

How to create EditText accepts Alphabets only in android?

For spaces, you can add single space in the digits. If you need any special characters like the dot, a comma also you can add to this list

android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "

Swift performSelector:withObject:afterDelay: is unavailable

Swift is statically typed so the performSelector: methods are to fall by the wayside.

Instead, use GCD to dispatch a suitable block to the relevant queue — in this case it'll presumably be the main queue since it looks like you're doing UIKit work.

EDIT: the relevant performSelector: is also notably missing from the Swift version of the NSRunLoop documentation ("1 Objective-C symbol hidden") so you can't jump straight in with that. With that and its absence from the Swiftified NSObject I'd argue it's pretty clear what Apple is thinking here.

How to update Python?

I have always just installed the new version on top and never had any issues. Do make sure that your path is updated to point to the new version though.

Setting CSS pseudo-class rules from JavaScript

Just place the css in a template string.

const cssTemplateString = `.foo:[psuedoSelector]{prop: value}`;

Then create a style element and place the string in the style tag and attach it to the document.

const styleTag = document.createElement("style");
styleTag.innerHTML = cssTemplateString;
document.head.insertAdjacentElement('beforeend', styleTag);

Specificity will take care of the rest. Then you can remove and add style tags dynamically. This is a simple alternative to libraries and messing with the stylesheet array in the DOM. Happy Coding!

Autoreload of modules in IPython

As mentioned above, you need the autoreload extension. If you want it to automatically start every time you launch ipython, you need to add it to the ipython_config.py startup file:

It may be necessary to generate one first:

ipython profile create

Then include these lines in ~/.ipython/profile_default/ipython_config.py:

c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')

As well as an optional warning in case you need to take advantage of compiled Python code in .pyc files:

c.InteractiveShellApp.exec_lines.append('print "Warning: disable autoreload in ipython_config.py to improve performance." ')

edit: the above works with version 0.12.1 and 0.13

how to check if input field is empty

use .val(), it will return the value of the <input>

$("#spa").val().length > 0

And you had a typo, length not lenght.

How to escape a while loop in C#

If you need to continue with additional logic use...

break;

or if you have a value to return...

return my_value_to_be_returned;

However, looking at your code, I believe you will control the loop with the revised example below without using a break or return...

private void CheckLog()
        {
            bool continueLoop = true;
            while (continueLoop)
            {
                Thread.Sleep(5000);
                if (!System.IO.File.Exists("Command.bat")) continue;
                using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
                {
                    string s = "";
                    while (continueLoop && (s = sr.ReadLine()) != null)
                    {
                        if (s.Contains("mp4:production/CATCHUP/"))
                        {
                            RemoveEXELog();

                            Process p = new Process();
                            p.StartInfo.WorkingDirectory = "dump";
                            p.StartInfo.FileName = "test.exe"; 
                            p.StartInfo.Arguments = s; 
                            p.Start();
                            continueLoop = false;
                        }
                    }
                }
            }
        }

How do I POST a x-www-form-urlencoded request using Fetch?

Just set the body as the following

var reqBody = "username="+username+"&password="+password+"&grant_type=password";

then

fetch('url', {
      method: 'POST',
      headers: {
          //'Authorization': 'Bearer token',
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      },
      body: reqBody
  }).then((response) => response.json())
      .then((responseData) => {
          console.log(JSON.stringify(responseData));
      }).catch(err=>{console.log(err)})

Sorting arrays in NumPy by column

It is an old question but if you need to generalize this to a higher than 2 dimension arrays, here is the solution than can be easily generalized:

np.einsum('ij->ij', a[a[:,1].argsort(),:])

This is an overkill for two dimensions and a[a[:,1].argsort()] would be enough per @steve's answer, however that answer cannot be generalized to higher dimensions. You can find an example of 3D array in this question.

Output:

[[7 0 5]
 [9 2 3]
 [4 5 6]]

CSS - center two images in css side by side

I've just done this for a project, and achieved it by using the h6 tag which I wasn't using for anything else:

in html code:

<h6><img alt="small drawing" src="../Images/image1.jpg" width="50%"/> <img alt="small drawing" src="../Images/image2.jpg" width="50%"/><br/>Optional caption text</h6>

The space between the image tags puts a vertical gap between the images. The width argument in each img tag is optional, but it neatly sizes the images to fill the width of the page. Notice that each image must be set to take up only 50% of the width. (Or 33% if you're using 3 images.) The width argument must come after the alt and src arguments or it won't work.

in css code:

/* h6: set presentation of images */
h6
  {
  font-family: "Franklin Gothic Demi", serif;
  font-size: 1.0em;
  font-weight: normal;
  line-height: 1.25em;
  text-align: center;
  }

The text items set the look of the caption text, and the text-align property centers both the images and the caption text.

What are Bearer Tokens and token_type in OAuth 2?

From RFC 6750, Section 1.2:

Bearer Token

A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer Token or Refresh token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for your a Bearer Token (refresh token) which you can then use to get an access token.

The Bearer Token is normally some kind of cryptic value created by the authentication server, it isn't random it is created based upon the user giving you access and the client your application getting access.

See also: Mozilla MDN Header Information.

How to print a single backslash?

You should escape it with another backslash \:

print('\\')

How do I Set Background image in Flutter?

You can use DecoratedBox.

@override
Widget build(BuildContext context) {
  return DecoratedBox(
    decoration: BoxDecoration(
      image: DecorationImage(image: AssetImage("your_asset"), fit: BoxFit.cover),
    ),
    child: Center(child: FlutterLogo(size: 300)),
  );
}

Output:

enter image description here

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

Please incre max_iter to 10000 as default value is 1000. Possibly, increasing no. of iterations will help algorithm to converge. For me it converged and solver was -'lbfgs'

log_reg = LogisticRegression(solver='lbfgs',class_weight='balanced', max_iter=10000)

Can I use tcpdump to get HTTP requests, response header and response body?

There are tcpdump filters for HTTP GET & HTTP POST (or for both plus message body):

  • Run man tcpdump | less -Ip examples to see some examples

  • Here’s a tcpdump filter for HTTP GET (GET = 0x47, 0x45, 0x54, 0x20):

    sudo tcpdump -s 0 -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'
    
  • Here’s a tcpdump filter for HTTP POST (POST = 0x50, 0x4f, 0x53, 0x54):

    sudo tcpdump -s 0 -A 'tcp dst port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)'
    
  • Monitor HTTP traffic including request and response headers and message body (source):

    tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
    tcpdump -X -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
    

For more information on the bit-twiddling in the TCP header see: String-Matching Capture Filter Generator (link to Sake Blok's explanation).

How to use "raise" keyword in Python

Besides raise Exception("message") and raise Python 3 introduced a new form, raise Exception("message") from e. It's called exception chaining, it allows you to preserve the original exception (the root cause) with its traceback.

It's very similar to inner exceptions from C#.

More info: https://www.python.org/dev/peps/pep-3134/

Getting multiple selected checkbox values in a string in javascript and PHP

var checkboxes = document.getElementsByName('location[]');
var vals = "";
for (var i=0, n=checkboxes.length;i<n;i++) 
{
    if (checkboxes[i].checked) 
    {
        vals += ","+checkboxes[i].value;
    }
}
if (vals) vals = vals.substring(1);

How to link a folder with an existing Heroku app

Two things to take care while setting up a new deployment System for old App

1. To check your app access to Heroku (especially the app)

heroku apps

it will list the apps you have access to if you set up for the first time, you probably need to

heroku keys:add

2. Then set up your git remote

For already created Heroku app, you can easily add a remote to your local repository with the heroku git: remote command. All you need is your Heroku app’s name:

heroku git:remote -a appName

you can also rename your remotes with the git remote rename command:

git remote rename heroku heroku-dev(you desired app name)

then You can use the git remote command to confirm that a remote been set for your app

 git remote -v

How to read and write xml files?

The above answer only deal with DOM parser (that normally reads the entire file in memory and parse it, what for a big file is a problem), you could use a SAX parser that uses less memory and is faster (anyway that depends on your code).

SAX parser callback some functions when it find a start of element, end of element, attribute, text between elements, etc, so it can parse the document and at the same time you get what you need.

Some example code:

http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error

Main two reasons only as mentioned in above comments

  1. NetworkCredentials you set should be correct. Verify with try actually signing into the account.
  2. You need to set UseDefaultCredentials to false first and then set Credentials Or Put smtp.UseDefaultCredentials = false; above the smtp.Credentials assignment.

Json.net serialize/deserialize derived types?

Since the question is so popular, it may be useful to add on what to do if you want to control the type property name and its value.

The long way is to write custom JsonConverters to handle (de)serialization by manually checking and setting the type property.

A simpler way is to use JsonSubTypes, which handles all the boilerplate via attributes:

[JsonConverter(typeof(JsonSubtypes), "Sound")]
[JsonSubtypes.KnownSubType(typeof(Dog), "Bark")]
[JsonSubtypes.KnownSubType(typeof(Cat), "Meow")]
public class Animal
{
    public virtual string Sound { get; }
    public string Color { get; set; }
}

public class Dog : Animal
{
    public override string Sound { get; } = "Bark";
    public string Breed { get; set; }
}

public class Cat : Animal
{
    public override string Sound { get; } = "Meow";
    public bool Declawed { get; set; }
}

from jquery $.ajax to angular $http

you can use $.param to assign data :

 $http({
  url: "http://example.appspot.com/rest/app",
  method: "POST",
  data: $.param({"foo":"bar"})
  }).success(function(data, status, headers, config) {
   $scope.data = data;
  }).error(function(data, status, headers, config) {
   $scope.status = status;
 });

look at this : AngularJS + ASP.NET Web API Cross-Domain Issue

How can I define an array of objects?

What you have above is an object, not an array.

To make an array use [ & ] to surround your objects.

userTestStatus = [
  { "id": 0, "name": "Available" },
  { "id": 1, "name": "Ready" },
  { "id": 2, "name": "Started" }
];

Aside from that TypeScript is a superset of JavaScript so whatever is valid JavaScript will be valid TypeScript so no other changes are needed.

Feedback clarification from OP... in need of a definition for the model posted

You can use the types defined here to represent your object model:

type MyType = {
    id: number;
    name: string;
}

type MyGroupType = {
    [key:string]: MyType;
}

var obj: MyGroupType = {
    "0": { "id": 0, "name": "Available" },
    "1": { "id": 1, "name": "Ready" },
    "2": { "id": 2, "name": "Started" }
};
// or if you make it an array
var arr: MyType[] = [
    { "id": 0, "name": "Available" },
    { "id": 1, "name": "Ready" },
    { "id": 2, "name": "Started" }
];

Import SQL file into mysql

mysql>c:/nitm.sql;

That would write the output of the mysql command to 'nitm.sql;' (What's the ';' supposed to do?) Assuming you've got a copy of the original file (before you overwrote it) then:

mysql < c:/nitm.sql

Is it possible to install iOS 6 SDK on Xcode 5?

Linking the 6.1 SDK into Xcode 5 as described in the other answers is one step. However this still doesn't solve the problem that running on iOS 7 new UI elements are taken, view controllers are made full-size etc.

As described in this answer it is also required to switch the UI into legacy mode on iOS 7:

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"UIUseLegacyUI"];
[[NSUserDefaults standardUserDefaults] synchronize];

Beware: This is an undocumented key and not recommended for App Store builds!

Also, in my experience while testing on the device I found that it only works the second time I launch the app even though I'm running the code fairly early in the app launch, in +[AppDelegate initialize]. Also there are subtle differences to a version built using Xcode 4.6. For instance, transparent navigation bars behave differently (causing the view to be full-size).

However, since Xcode 4.6.3 crashes on Mavericks (at least for me, see rdar://15318883), this is at least a solution to continue using Xcode 5 for debugging.

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

If you're triggering your code from Jenkins, enabling the option "Start Xvfb before the build, and shut it down after" might help. It helped me.

How to Decrease Image Brightness in CSS

try this if you need to convert black image into white:

.classname{
    filter: brightness(0) invert(1);
}

How to extract text from a PDF file?

Use textract.

It supports many types of files including PDFs

import textract
text = textract.process("path/to/file.extension")

Check if element is clickable in Selenium Java

the class attribute contains disabled when the element is not clickable.

WebElement webElement = driver.findElement(By.id("elementId"));
if(!webElement.getAttribute("class").contains("disabled")){
    webElement.click();
}

CUDA incompatible with my gcc version

On most distributions you have the possibility to install another gcc and g++ version beside a most recent compiler like gcc-4.7. In addition most build systems are aware of the CC and CXX environment variables, which let specify you other C and C++ compilers respectively. SO I suggest something like:

CC=gcc-4.4 CXX=g++-4.4 cmake path/to/your/CMakeLists.txt

For Makefiles there should be a similar way. I do not recommend setting custom symlinks within /usr/local unless you know what you are doing.

How do I programmatically click on an element in JavaScript?

Are you trying to actually follow the link or trigger the onclick? You can trigger an onclick with something like this:

var link = document.getElementById(linkId);
link.onclick.call(link);

Parsing JSON array with PHP foreach

You need to tell it which index in data to use, or double loop through all.

E.g., to get the values in the 4th index in the outside array.:

foreach($user->data[3]->values as $values)
{
     echo $values->value . "\n";
}

To go through all:

foreach($user->data as $mydata)
{
    foreach($mydata->values as $values) {
        echo $values->value . "\n";
    }

}   

How do I get the current year using SQL on Oracle?

Yet another option would be:

SELECT * FROM mytable
 WHERE TRUNC(mydate, 'YEAR') = TRUNC(SYSDATE, 'YEAR');

MySQL, Concatenate two columns

In query, CONCAT_WS() function.

This function not only add multiple string values and makes them a single string value. It also let you define separator ( ” “, ” , “, ” – “,” _ “, etc.).

Syntax –

CONCAT_WS( SEPERATOR, column1, column2, ... )

Example

SELECT 
topic, 
CONCAT_WS( " ", subject, year ) AS subject_year 
FROM table