Programs & Examples On #Compiler as a service

Future managed C# and VB compiler and language services API from Microsoft

How to provide password to a command that prompts for one in bash?

Secure commands will not allow this, and rightly so, I'm afraid - it's a security hole you could drive a truck through.

If your command does not allow it using input redirection, or a command-line parameter, or a configuration file, then you're going to have to resort to serious trickery.

Some applications will actually open up /dev/tty to ensure you will have a hard time defeating security. You can get around them by temporarily taking over /dev/tty (creating your own as a pipe, for example) but this requires serious privileges and even it can be defeated.

Border length smaller than div width?

I have case to have some bottom border between pictures in div container and the best one line code was - border-bottom-style: inset;

Is it possible to decompile a compiled .pyc file into a .py file?

Yes.

I use uncompyle6 decompile (even support latest Python 3.8.0):

uncompyle6 utils.cpython-38.pyc > utils.py

and the origin python and decompiled python comparing look like this:

pyc uncompile utils

so you can see, ALMOST same, decompile effect is VERY GOOD.

Change the Theme in Jupyter Notebook?

conda install jupyterthemes

did not worked for me in Windows. I am using Anaconda.

But,

pip install jupyterthemes

worked in Anaconda Prompt.

Find unique rows in numpy.array

I've compared the suggested alternative for speed and found that, surprisingly, the void view unique solution is even a bit faster than numpy's native unique with the axis argument. If you're looking for speed, you'll want

numpy.unique(
    a.view(numpy.dtype((numpy.void, a.dtype.itemsize*a.shape[1])))
).view(a.dtype).reshape(-1, a.shape[1])

There is a bug report on GitHub for this, too.

enter image description here


Code to reproduce the plot:

import numpy
import perfplot


def unique_void_view(a):
    return (
        numpy.unique(a.view(numpy.dtype((numpy.void, a.dtype.itemsize * a.shape[1]))))
        .view(a.dtype)
        .reshape(-1, a.shape[1])
    )


def lexsort(a):
    ind = numpy.lexsort(a.T)
    return a[
        ind[numpy.concatenate(([True], numpy.any(a[ind[1:]] != a[ind[:-1]], axis=1)))]
    ]


def vstack(a):
    return numpy.vstack([tuple(row) for row in a])


def unique_axis(a):
    return numpy.unique(a, axis=0)


perfplot.show(
    setup=lambda n: numpy.random.randint(2, size=(n, 20)),
    kernels=[unique_void_view, lexsort, vstack, unique_axis],
    n_range=[2 ** k for k in range(15)],
    xlabel="len(a)",
    equality_check=None,
)

How to call function that takes an argument in a Django template?

By design, Django templates cannot call into arbitrary Python code. This is a security and safety feature for environments where designers write templates, and it also prevents business logic migrating into templates.

If you want to do this, you can switch to using Jinja2 templates (http://jinja.pocoo.org/docs/), or any other templating system you like that supports this. No other part of django will be affected by the templates you use, because it is intentionally a one-way process. You could even use many different template systems in the same project if you wanted.

Accessing nested JavaScript objects and arrays by string path

This is the solution I use:

function resolve(path, obj=self, separator='.') {
    var properties = Array.isArray(path) ? path : path.split(separator)
    return properties.reduce((prev, curr) => prev && prev[curr], obj)
}

Example usage:

// accessing property path on global scope
resolve("document.body.style.width")
// or
resolve("style.width", document.body)

// accessing array indexes
// (someObject has been defined in the question)
resolve("part3.0.size", someObject) // returns '10'

// accessing non-existent properties
// returns undefined when intermediate properties are not defined:
resolve('properties.that.do.not.exist', {hello:'world'})

// accessing properties with unusual keys by changing the separator
var obj = { object: { 'a.property.name.with.periods': 42 } }
resolve('object->a.property.name.with.periods', obj, '->') // returns 42

// accessing properties with unusual keys by passing a property name array
resolve(['object', 'a.property.name.with.periods'], obj) // returns 42

Limitations:

  • Can't use brackets ([]) for array indices—though specifying array indices between the separator token (e.g., .) works fine as shown above.

Setting size for icon in CSS

None of those work for me.

.fa-volume-down {
    color: white;
    width: 50% !important;
    height: 50% !important;
    margin-top: 8%;
    margin-left: 7.5%;
    font-size: 1em;
    background-size: 120%;
}

conversion from infix to prefix

If there's something about what infix and prefix mean that you don't quite understand, I'd highly suggest you reread that section of your textbook. You aren't doing yourself any favors if you come out of this with the right answer for this one problem, but still don't understand the concept.

Algorithm-wise, its pretty darn simple. You just act like a computer yourself a bit. Start by puting parens around every calculation in the order it would be calculated. Then (again in order from first calculation to last) just move the operator in front of the expression on its left hand side. After that, you can simplify by removing parens.

Converting java date to Sql timestamp

Take a look at SimpleDateFormat:

java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());  

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
System.out.println(sdf.format(sq));

Remove ALL styling/formatting from hyperlinks

You can just use an a selector in your stylesheet to define all states of an anchor/hyperlink. For example:

a {
    color: blue;
}

Would override all link styles and make all the states the colour blue.

How to press back button in android programmatically?

Call onBackPressed after overriding it in your activity.

how to pass parameters to query in SQL (Excel)

It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)

The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.

When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.

When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.

I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.

curl : (1) Protocol https not supported or disabled in libcurl

Solved this problem with flag --with-darwinssl

Go to folder with curl source code

Download it here https://curl.haxx.se/download.html

sudo ./configure --with-darwinssl
make
make install

restart your console and it is done!

How to download Javadoc to read offline?

JAVA Fax Api documentation

You could download the mac 2.2 preview release from here and unzip it.

http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html

The javadoc won't quite match 2.1, but it will be close and if you use the preview instead, it will match exactly.

I think this would help you :)

How do I iterate over a range of numbers defined by variables in Bash?

If you need it prefix than you might like this

 for ((i=7;i<=12;i++)); do echo `printf "%2.0d\n" $i |sed "s/ /0/"`;done

that will yield

07
08
09
10
11
12

Can promises have multiple arguments to onFulfilled?

The fulfillment value of a promise parallels the return value of a function and the rejection reason of a promise parallels the thrown exception of a function. Functions cannot return multiple values so promises must not have more than 1 fulfillment value.

Generating sql insert into for Oracle

You might execute something like this in the database:

select "insert into targettable(field1, field2, ...) values(" || field1 || ", " || field2 || ... || ");"
from targettable;

Something more sophisticated is here.

How to create a static library with g++?

You can create a .a file using the ar utility, like so:

ar crf lib/libHeader.a header.o

lib is a directory that contains all your libraries. it is good practice to organise your code this way and separate the code and the object files. Having everything in one directory generally looks ugly. The above line creates libHeader.a in the directory lib. So, in your current directory, do:

mkdir lib

Then run the above ar command.

When linking all libraries, you can do it like so:

g++ test.o -L./lib -lHeader -o test  

The -L flag will get g++ to add the lib/ directory to the path. This way, g++ knows what directory to search when looking for libHeader. -llibHeader flags the specific library to link.

where test.o is created like so:

g++ -c test.cpp -o test.o 

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

How to find if a given key exists in a C++ std::map

map<string, string> m;

check key exist or not, and return number of occurs(0/1 in map):

int num = m.count("f");  
if (num>0) {    
    //found   
} else {  
    // not found  
}

check key exist or not, and return iterator:

map<string,string>::iterator mi = m.find("f");  
if(mi != m.end()) {  
    //found  
    //do something to mi.  
} else {  
    // not found  
}  

in your question, the error caused by bad operator<< overload, because p.first is map<string, string>, you can not print it out. try this:

if(p.first != p.second) {
    cout << p.first->first << " " << p.first->second << endl;
}

How to output (to a log) a multi-level array in a format that is human-readable?

Simple stuff:

Using print_r, var_dump or var_export should do it pretty nicely if you look at the result in view-source mode not in HTML mode or as @Joel Larson said if you wrap everything in a <pre> tag.

print_r is best for readability but it doesn't print null/false values.

var_dump is best for checking types of values and lengths and null/false values.

var_export is simmilar to var_dump but it can be used to get the dumped string.

The format returned by any of these is indented correctly in the source code and var_export can be used for logging since it can be used to return the dumped string.

Advanced stuff:

Use the xdebug plug-in for PHP this prints var_dumps as HTML formatted strings not as raw dump format and also allows you to supply a custom function you want to use for formatting.

Increasing Heap Size on Linux Machines

Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.

Look here for permanently changing the heap size.

How to break line in JavaScript?

alert("I will get back to you soon\nThanks and Regards\nSaurav Kumar");

or %0D%0A in a url

How to import or copy images to the "res" folder in Android Studio?

If you want to do this easily from within Android Studio then on the left side, right above your file directory you will see a dropdown with options on how to view your files like:

Project, Android, and Packages, plus a list of Scopes.

If you are on Android it makes it hard to see when you add new folders or assets to your project - BUT if you change the dropdown to PROJECT then the file directory will match the file system on your computer, then go to:

app > src > main > res

From here you can find the conventional Eclipse type files like drawable/drawable-hdpi/drawable-mdpi and so on where you can easily drag and drop files into or import into and instantly see them. As soon as you see your files here they will be available when going to assign image src's and so on.

Good luck Android Warriors in a strange new world!

What is the best way to test for an empty string with jquery-out-of-the-box?

Based on David's answer I personally like to check the given object first if it is a string at all. Otherwise calling .trim() on a not existing object would throw an exception:

function isEmpty(value) {
  return typeof value == 'string' && !value.trim() || typeof value == 'undefined' || value === null;
}

Usage:

isEmpty(undefined); // true
isEmpty(null); // true
isEmpty(''); // true
isEmpty('foo'); // false
isEmpty(1); // false
isEmpty(0); // false

How to change maven logging level to display only warning and errors?

Answering your question

I made a small investigation because I am also interested in the solution.

Maven command line verbosity options

According to http://books.sonatype.com/mvnref-book/reference/running-sect-options.html#running-sect-verbose-option

  • -e for error
  • -X for debug
  • -q for only error

Maven logging config file

Currently maven 3.1.x uses SLF4J to log to the System.out . You can modify the logging settings at the file:

${MAVEN_HOME}/conf/logging/simplelogger.properties

According to the page : http://maven.apache.org/maven-logging.html

Command line setup

I think you should be able to setup the default Log level of the simple logger via a command line parameter, like this:

$ mvn clean package -Dorg.slf4j.simpleLogger.defaultLogLevel=debug

But I could not get it to work. I guess the only problem with this is, maven picks up the default level from the config file on the classpath. I also tried a couple of other settings via System.properties, but all of them were unsuccessful.

Appendix

You can find the source of slf4j on github here : slf4j github

The source of the simplelogger here : slf4j/jcl-over-slf4j/src/main/java/org/apache/commons/logging/impl/SimpleLog.java

The plexus loader loads the simplelogger.properties.

Regular expression to allow spaces between words

This does not allow space in the beginning. But allowes spaces in between words. Also allows for special characters between words. A good regex for FirstName and LastName fields.

\w+.*$

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

Rails Root directory path?

In some cases you may want the Rails root without having to load Rails.

For example, you get a quicker feedback cycle when TDD'ing models that do not depend on Rails by requiring spec_helper instead of rails_helper.

# spec/spec_helper.rb

require 'pathname'

rails_root = Pathname.new('..').expand_path(File.dirname(__FILE__))

[
  rails_root.join('app', 'models'),
  # Add your decorators, services, etc.
].each do |path|
  $LOAD_PATH.unshift path.to_s
end

Which allows you to easily load Plain Old Ruby Objects from their spec files.

# spec/models/poro_spec.rb

require 'spec_helper'

require 'poro'

RSpec.describe ...

2D Euclidean vector rotations

You're calculating the y-part of your new coordinate based on the 'new' x-part of the new coordinate. Basically this means your calculating the new output in terms of the new output...

Try to rewrite in terms of input and output:

vector2<double> multiply( vector2<double> input, double cs, double sn ) {
  vector2<double> result;
  result.x = input.x * cs - input.y * sn;
  result.y = input.x * sn + input.y * cs;
  return result;
}

Then you can do this:

vector2<double> input(0,1);
vector2<double> transformed = multiply( input, cs, sn );

Note how choosing proper names for your variables can avoid this problem alltogether!

Using SQL LOADER in Oracle to import CSV file

-- Step 1: Create temp table. create table Billing ( TAP_ID char(10), ACCT_NUM char(10));

SELECT * FROM BILLING;

-- Step 2: Create Control file.

load data infile IN_DATA.txt into table Billing fields terminated by ',' (TAP_ID, ACCT_NUM)

-- Step 3: Create input data file. IN_DATA.txt file content: 100,15678966

-- Step 4: Execute command from run: .. client\bin>sqlldr username@db-sis__id/password control='Billing.ctl'

Center button under form in bootstrap

It's working completely try this:

<div class="button pull-left" style="padding-left:40%;" >

Lombok is not generating getter and setter

If you are using maven , Go to maven dependencies in your project structure then run lombok jar as java project it will install it then exit and start eclipse

How to insert a new key value pair in array in php?

If you are creating new array then try this :

$arr = ['key' => 'value'];

And if array is already created then try this :

$arr['key'] = 'value';

How to disable Home and other system buttons in Android?

You can use Android-HomeKey-Locker to disable HOME KEY and other system keys(such as BACK KEY and MENU KEY)

Hope this will help you in your application. Thanks.

How does one set up the Visual Studio Code compiler/debugger to GCC?

For Windows:

  1. Install MinGW or Dev C++
  2. Open Environment Variables
  3. In System Variable select Path -> Edit -> New
  4. Copy this C:\Program Files (x86)\Dev-Cpp\MinGW64\bin to the New window. (If you have MinGW installed copy its /bin path).
  5. To check if you have added it successfully: Open CMD -> Type "gcc" and it should return: gcc: fatal error: no input files compilation terminated.
  6. Install C/C++ for Visual Studio Code && C/C++ Compile Run || Code Runner
  7. If you installed only C/C++ Compile Run extension you can compile your program using F6/F7
  8. If you installed the second extension you can compile your program using the button in the top bar.

Screenshot: Hello World compiled in VS Code

Java way to check if a string is palindrome

Using reverse is overkill because you don't need to generate an extra string, you just need to query the existing one. The following example checks the first and last characters are the same, and then walks further inside the string checking the results each time. It returns as soon as s is not a palindrome.

The problem with the reverse approach is that it does all the work up front. It performs an expensive action on a string, then checks character by character until the strings are not equal and only then returns false if it is not a palindrome. If you are just comparing small strings all the time then this is fine, but if you want to defend yourself against bigger input then you should consider this algorithm.

boolean isPalindrome(String s) {
  int n = s.length();
  for (int i = 0; i < (n/2); ++i) {
     if (s.charAt(i) != s.charAt(n - i - 1)) {
         return false;
     }
  }

  return true;
}

Yahoo Finance API

Yahoo is very easy to use and provides customized data. Use the following page to learn more.

finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT=pder=.csv

WARNING - there are a few tutorials out there on the web that show you how to do this, but the region where you put in the stock symbols causes an error if you use it as posted. You will get a "MISSING FORMAT VALUE". The tutorials I found omits the commentary around GOOG.

Example URL for GOOG: http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EDJI,GOOG&f=nsl1op&e=.csv

Error: Unexpected value 'undefined' imported by the module

Make sure you should not import a module/component like this:

import { YOUR_COMPONENT } from './';

But it should be

import { YOUR_COMPONENT } from './YOUR_COMPONENT.ts';

How can I get current date in Android?

Works like a charm and converts to String as a bonus ;)

SimpleDateFormat currentDate = new SimpleDateFormat("dd/MM/yyyy");
      Date todayDate = new Date();
    String thisDate = currentDate.format(todayDate);

What does "make oldconfig" do exactly in the Linux kernel makefile?

Before you run make oldconfig, you need to copy a kernel configuration file from an older kernel into the root directory of the new kernel.

You can find a copy of the old kernel configuration file on a running system at /boot/config-3.11.0. Alternatively, kernel source code has configs in linux-3.11.0/arch/x86/configs/{i386_defconfig / x86_64_defconfig}

If your kernel source is located at /usr/src/linux:

cd /usr/src/linux
cp /boot/config-3.9.6-gentoo .config
make oldconfig

What does @@variable mean in Ruby?

The answers are partially correct because @@ is actually a class variable which is per class hierarchy meaning it is shared by a class, its instances and its descendant classes and their instances.

class Person
  @@people = []

  def initialize
    @@people << self
  end

  def self.people
    @@people
  end
end

class Student < Person
end

class Graduate < Student
end

Person.new
Student.new

puts Graduate.people

This will output

#<Person:0x007fa70fa24870>
#<Student:0x007fa70fa24848>

So there is only one same @@variable for Person, Student and Graduate classes and all class and instance methods of these classes refer to the same variable.

There is another way of defining a class variable which is defined on a class object (Remember that each class is actually an instance of something which is actually the Class class but it is another story). You use @ notation instead of @@ but you can't access these variables from instance methods. You need to have class method wrappers.

class Person

  def initialize
    self.class.add_person self
  end

  def self.people
    @people
  end

  def self.add_person instance
    @people ||= []
    @people << instance
  end
end

class Student < Person
end

class Graduate < Student
end

Person.new
Person.new
Student.new
Student.new
Graduate.new
Graduate.new

puts Student.people.join(",")
puts Person.people.join(",")
puts Graduate.people.join(",")

Here, @people is single per class instead of class hierarchy because it is actually a variable stored on each class instance. This is the output:

#<Student:0x007f8e9d2267e8>,#<Student:0x007f8e9d21ff38>
#<Person:0x007f8e9d226158>,#<Person:0x007f8e9d226608>
#<Graduate:0x007f8e9d21fec0>,#<Graduate:0x007f8e9d21fdf8> 

One important difference is that, you cannot access these class variables (or class instance variables you can say) directly from instance methods because @people in an instance method would refer to an instance variable of that specific instance of the Person or Student or Graduate classes.

So while other answers correctly state that @myvariable (with single @ notation) is always an instance variable, it doesn't necessarily mean that it is not a single shared variable for all instances of that class.

Dynamically fill in form values with jQuery

If you need to hit the database, you need to hit the web server again (for the most part).

What you can do is use AJAX, which makes a request to another script on your site to retrieve data, gets the data, and then updates the input fields you want.

AJAX calls can be made in jquery with the $.ajax() function call, so this will happen

User's browser enters input that fires a trigger that makes an AJAX call

$('input .callAjax').bind('change', function() { 
  $.ajax({ url: 'script/ajax', 
           type: json
           data: $foo,  
           success: function(data) {
             $('input .targetAjax').val(data.newValue);
           });
  );

Now you will need to point that AJAX call at script (sounds like you're working PHP) that will do the query you want and send back data.

You will probably want to use the JSON object call so you can pass back a javascript object, that will be easier to use than return XML etc.

The php function json_encode($phpobj); will be useful.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Uninstall completely MySQL

sudo apt-get remove --purge mysql\*

reinstall it

sudo apt install mysql-server mysql-client

test if it run

sudo mysql

Install php drivers

sudo apt install php7.4 php7.4-fpm php7.4-mysql php7.4-cgi php7.4-cli php7.4-common

Very nice !

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

>>> 2 == 2.0
True
>>> 2 is 2.0
False

Use ==

How to stop EditText from gaining focus at Activity startup in Android

Is the actual problem that you just don't want it to have focus at all? Or you don't want it to show the virtual keyboard as a result of focusing the EditText? I don't really see an issue with the EditText having focus on start, but it's definitely a problem to have the softInput window open when the user did not explicitly request to focus on the EditText (and open the keyboard as a result).

If it's the problem of the virtual keyboard, see the AndroidManifest.xml <activity> element documentation.

android:windowSoftInputMode="stateHidden" - always hide it when entering the activity.

or android:windowSoftInputMode="stateUnchanged" - don't change it (e.g. don't show it if it isn't already shown, but if it was open when entering the activity, leave it open).

Remove duplicate elements from array in Ruby

array = array.uniq

uniq removes all duplicate elements and retains all unique elements in the array.

This is one of many beauties of the Ruby language.

Windows Bat file optional argument parsing

If you want to use optional arguments, but not named arguments, then this approach worked for me. I think this is much easier code to follow.

REM Get argument values.  If not specified, use default values.
IF "%1"=="" ( SET "DatabaseServer=localhost" ) ELSE ( SET "DatabaseServer=%1" )
IF "%2"=="" ( SET "DatabaseName=MyDatabase" ) ELSE ( SET "DatabaseName=%2" )

REM Do work
ECHO Database Server = %DatabaseServer%
ECHO Database Name   = %DatabaseName%

How to clear all input fields in a specific div with jQuery?

Here is Beena's answer in ES6 Sans the JQuery dependency.. Thank's Beena!

let resetFormObject = (elementID)=> {
        document.getElementById(elementID).getElementsByTagName('input').forEach((input)=>{
            switch(input.type) {
                case 'password':
                case 'text':
                case 'textarea':
                case 'file':
                case 'select-one':
                case 'select-multiple':
                case 'date':
                case 'number':
                case 'tel':
                case 'email':
                    input.value = '';
                    break;
                case 'checkbox':
                case 'radio':
                    input.checked = false;
                    break;
            }
        }); 
    }

How do I find what Java version Tomcat6 is using?

After installing tomcat, you can choose "configure tomcat" by search in "search programs and files". After clicking on "configure Tomcat", you should give admin permissions and the window opens. Then click on "java" tab. There you can see the JVM and JAVA classpath.

In Java, what does NaN mean?

NaN = Not a Number.

How do you automatically set the focus to a textbox when a web page loads?

You need to use javascript:

<BODY onLoad="document.getElementById('myButton').focus();">

@Ben notes that you should not add event handlers like this. While that is another question, he recommends that you use this function:

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

And then put a call to addLoadEvent on your page and reference a function the sets the focus to you desired textbox.

Loop and get key/value pair for JSON array using jQuery

The best and perfect solution for this issue:

I tried the jQuery with the Ajax success responses, but it doesn't work so I invented my own and finally it works!

Click here to see the full solution

var rs = '{"test" : "Got it perfect!","message" : "Got it!"}';
eval("var toObject = "+ rs + ";");
alert(toObject.message);

how to call scalar function in sql server 2008

For some reason I was not able to use my scalar function until I referenced it using brackets, like so:

select [dbo].[fun_functional_score]('01091400003')

Querying Datatable with where condition

Something like this...

var res = from row in myDTable.AsEnumerable()
where row.Field<int>("EmpID") == 5 &&
(row.Field<string>("EmpName") != "abc" ||
row.Field<string>("EmpName") != "xyz")
select row;

See also LINQ query on a DataTable

How to map with index in Ruby?

Over the top obfuscation:

arr = ('a'..'g').to_a
indexes = arr.each_index.map(&2.method(:+))
arr.zip(indexes)

Java Spring Boot: How to map my app root (“/”) to index.html?

Inside Spring Boot, I always put the webpages inside a folder like public or webapps or views and place it inside src/main/resources directory as you can see in application.properties also.

Spring_Boot-Project-Explorer-View

and this is my application.properties:

server.port=15800
spring.mvc.view.prefix=/public/
spring.mvc.view.suffix=.html
spring.datasource.url=jdbc:mysql://localhost:3306/hibernatedb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.format_sql = true

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

as soon you put the url like servername:15800 and this request received by Spring Boot occupied Servlet dispatcher it will exactly search the index.html and this name will in case sensitive as the spring.mvc.view.suffix which would be html, jsp, htm etc.

Hope it would help manyone.

Google Maps V3 marker with label

The way to do this without use of plugins is to make a subclass of google's OverlayView() method.

https://developers.google.com/maps/documentation/javascript/reference?hl=en#OverlayView

You make a custom function and apply it to the map.

function Label() { 
    this.setMap(g.map);
};

Now you prototype your subclass and add HTML nodes:

Label.prototype = new google.maps.OverlayView; //subclassing google's overlayView
Label.prototype.onAdd = function() {
        this.MySpecialDiv               = document.createElement('div');
        this.MySpecialDiv.className     = 'MyLabel';
        this.getPanes().overlayImage.appendChild(this.MySpecialDiv); //attach it to overlay panes so it behaves like markers

}

you also have to implement remove and draw functions as stated in the API docs, or this won't work.

Label.prototype.onRemove = function() {
... // remove your stuff and its events if any
}
Label.prototype.draw = function() {
      var position = this.getProjection().fromLatLngToDivPixel(this.get('position')); // translate map latLng coords into DOM px coords for css positioning
var pos = this.get('position');
            $('.myLabel')
            .css({
                'top'   : position.y + 'px',
                'left'  : position.x + 'px'
            })
        ;
}

That's the gist of it, you'll have to do some more work in your specific implementation.

Laravel Check If Related Model Exists

I prefer to use exists method:

RepairItem::find($id)->option()->exists()

to check if related model exists or not. It's working fine on Laravel 5.2

How to escape apostrophe (') in MySql?

In PHP I like using mysqli_real_escape_string() which escapes special characters in a string for use in an SQL statement.

see https://www.php.net/manual/en/mysqli.real-escape-string.php

Graph visualization library in JavaScript

In a commercial scenario, a serious contestant for sure is yFiles for HTML:

It offers:

  • Easy import of custom data (this interactive online demo seems to pretty much do exactly what the OP was looking for)
  • Interactive editing for creating and manipulating the diagrams through user gestures (see the complete editor)
  • A huge programming API for customizing each and every aspect of the library
  • Support for grouping and nesting (both interactive, as well as through the layout algorithms)
  • Does not depend on a specfic UI toolkit but supports integration into almost any existing Javascript toolkit (see the "integration" demos)
  • Automatic layout (various styles, like "hierarchic", "organic", "orthogonal", "tree", "circular", "radial", and more)
  • Automatic sophisticated edge routing (orthogonal and organic edge routing with obstacle avoidance)
  • Incremental and partial layout (adding and removing elements and only slightly or not at all changing the rest of the diagram)
  • Support for grouping and nesting (both interactive, as well as through the layout algorithms)
  • Implementations of graph analysis algorithms (paths, centralities, network flows, etc.)
  • Uses HTML 5 technologies like SVG+CSS and Canvas and modern Javascript leveraging properties and other more ES5 and ES6 features (but for the same reason will not run in IE versions 8 and lower).
  • Uses a modular API that can be loaded on-demand using UMD loaders

Here is a sample rendering that shows most of the requested features:

Screenshot of a sample rendering created by the BPMN demo.

Full disclosure: I work for yWorks, but on Stackoverflow I do not represent my employer.

Aligning rotated xticklabels with their respective xticks

If you dont want to modify the xtick labels, you can just use:

plt.xticks(rotation=45)

Write HTML string in JSON

You should escape the characters like double quotes in the html string by adding "\"

eg: <h2 class=\"fg-white\">

How do I comment out a block of tags in XML?

You can easily comment out the data using this:

<!-- 
 <data>
        <data-field1></data-field1>
        <data-field2></data-field2>
        <data-field3></data-field3>
 </data>
-->

method of commenting in xml.

github: server certificate verification failed

Make sure first that you have certificates installed on your Debian in /etc/ssl/certs.

If not, reinstall them:

sudo apt-get install --reinstall ca-certificates

Since that package does not include root certificates, add:

sudo mkdir /usr/local/share/ca-certificates/cacert.org
sudo wget -P /usr/local/share/ca-certificates/cacert.org http://www.cacert.org/certs/root.crt http://www.cacert.org/certs/class3.crt
sudo update-ca-certificates

Make sure your git does reference those CA:

git config --global http.sslCAinfo /etc/ssl/certs/ca-certificates.crt

Jason C mentions another potential cause (in the comments):

It was the clock. The NTP server was down, the system clock wasn't set properly, I didn't notice or think to check initially, and the incorrect time was causing verification to fail.

Certificates are time sensitive.

What's the difference between Sender, From and Return-Path?

The official RFC which defines this specification could be found here:

http://tools.ietf.org/html/rfc4021#section-2.1.2 (look at paragraph 2.1.2. and the following)

2.1.2. Header Field: From

Description:  
    Mailbox of message author  
[...]  
Related information:
    Specifies the author(s) of the message; that is, the mailbox(es)
    of the person(s) or system(s) responsible for the writing of the
    message. Defined as standard by RFC 822.

2.1.3. Header Field: Sender

Description:  
    Mailbox of message sender  
[...]  
Related information:
    Specifies the mailbox of the agent responsible for the actual
    transmission of the message.  Defined as standard by RFC 822.

2.1.22. Header Field: Return-Path

Description:
    Message return path
[...]  
Related information:
    Return path for message response diagnostics. See also RFC 2821
    [17]. Defined as standard by RFC 822.

laravel collection to array

Use collect($comments_collection).

Else, try json_encode($comments_collection) to convert to json.

MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?

That directory is part of your user data and you can delete any user data without affecting Xcode seriously. You can delete the whole CoreSimulator/ directory. Xcode will recreate fresh instances there for you when you do your next simulator run. If you can afford losing any previous simulator data of your apps this is the easy way to get space.

Update: A related useful app is "DevCleaner for Xcode" https://apps.apple.com/app/devcleaner-for-xcode/id1388020431

What is the difference between map and flatMap and a good use case for each?

It boils down to your initial question: what you mean by flattening ?

When you use flatMap, a "multi-dimensional" collection becomes "one-dimensional" collection.

val array1d = Array ("1,2,3", "4,5,6", "7,8,9")  
//array1d is an array of strings

val array2d = array1d.map(x => x.split(","))
//array2d will be : Array( Array(1,2,3), Array(4,5,6), Array(7,8,9) )

val flatArray = array1d.flatMap(x => x.split(","))
//flatArray will be : Array (1,2,3,4,5,6,7,8,9)

You want to use a flatMap when,

  • your map function results in creating multi layered structures
  • but all you want is a simple - flat - one dimensional structure, by removing ALL the internal groupings

PHP "php://input" vs $_POST

The reason is that php://input returns all the raw data after the HTTP-headers of the request, regardless of the content type.

The PHP superglobal $_POST, only is supposed to wrap data that is either

  • application/x-www-form-urlencoded (standard content type for simple form-posts) or
  • multipart/form-data (mostly used for file uploads)

This is because these are the only content types that must be supported by user agents. So the server and PHP traditionally don't expect to receive any other content type (which doesn't mean they couldn't).

So, if you simply POST a good old HTML form, the request looks something like this:

POST /page.php HTTP/1.1

key1=value1&key2=value2&key3=value3

But if you are working with Ajax a lot, this probaby also includes exchanging more complex data with types (string, int, bool) and structures (arrays, objects), so in most cases JSON is the best choice. But a request with a JSON-payload would look something like this:

POST /page.php HTTP/1.1

{"key1":"value1","key2":"value2","key3":"value3"}

The content would now be application/json (or at least none of the above mentioned), so PHP's $_POST-wrapper doesn't know how to handle that (yet).

The data is still there, you just can't access it through the wrapper. So you need to fetch it yourself in raw format with file_get_contents('php://input') (as long as it's not multipart/form-data-encoded).

This is also how you would access XML-data or any other non-standard content type.

How to perform a for-each loop over all the files under a specified path?

The for-loop will iterate over each (space separated) entry on the provided string.

You do not actually execute the find command, but provide it is as string (which gets iterated by the for-loop). Instead of the double quotes use either backticks or $():

for line in $(find . -iname '*.txt'); do 
     echo "$line"
     ls -l "$line"
done

Furthermore, if your file paths/names contains spaces this method fails (since the for-loop iterates over space separated entries). Instead it is better to use the method described in dogbanes answer.


To clarify your error:

As said, for line in "find . -iname '*.txt'"; iterates over all space separated entries, which are:

  • find
  • .
  • -iname
  • '*.txt' (I think...)

The first two do not result in an error (besides the undesired behavior), but the third is problematic as it executes:

ls -l -iname

A lot of (bash) commands can combine single character options, so -iname is the same as -i -n -a -m -e. And voila: your invalid option -- 'e' error!

Changing Placeholder Text Color with Swift

In my case, I have done following:

extension UITextField {
    @IBInspectable var placeHolderColor: UIColor? {
        get {
            if let color = self.attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor {
                return color
            }
            return nil
        }
        set (setOptionalColor) {
            if let setColor = setOptionalColor {
                let string = self.placeholder ?? ""
                self.attributedPlaceholder = NSAttributedString(string: string , attributes:[NSAttributedString.Key.foregroundColor: setColor])
            }
        }
    }
}

How do I use JDK 7 on Mac OSX?

Now, Use command

Update 2020: 04

To install Java7 with homebrew run:

brew tap homebrew/cask-versions
brew cask install java7

Hope this help.

How to base64 encode image in linux bash / shell

Base 64 for html:

file="DSC_0251.JPG"
type=$(identify -format "%m" "$file" | tr '[A-Z]' '[a-z]')
echo "data:image/$type;base64,$(base64 -w 0 "$file")"

Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?

Both Activity and View have method dispatchTouchEvent() and onTouchEvent.The ViewGroup have this methods too, but have another method called onInterceptTouchEvent. The return type of those methods are boolean, you can control the dispatch route through the return value.

The event dispatch in Android starts from Activity->ViewGroup->View.

Getting multiple values with scanf()

int a[1000] ;
for(int i = 0 ; i <= 3 , i++)
scanf("%d" , &a[i]) ;

How to Fill an array from user input C#?

Add the input values to a List and when you are done use List.ToArray() to get an array with the values.

JUnit tests pass in Eclipse but fail in Maven Surefire

This has helped me in troubleshooting my problem. I had a similar symptoms in that maven would fail however running junit tests runs fine.

As it turns out my parent pom.xml contains the following definition:

    <plugin>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.9</version>
      <configuration>
        <forkMode>pertest</forkMode>
        <argLine>-Xverify:none</argLine>
      </configuration>
    </plugin>

And in my project I override it to remove the argLine:

    <plugin>
       <artifactId>maven-surefire-plugin</artifactId>
       <configuration>
            <forkMode>pertest</forkMode>
            <argLine combine.self="override"></argLine>
          </configuration>
    </plugin>

Hopefully this will help someone in troubleshooting surefire plugin.

HTML: Select multiple as dropdown

It's quite unpractical to make multiple select with size 1. think about it. I made a fiddle here: https://jsfiddle.net/wqd0yd5m/2/

<select name="test" multiple>
    <option>123</option>
    <option>456</option>
    <option>789</option>
</select>

Try to explore other options such as using checkboxes to achieve your goal.

BULK INSERT with identity (auto-increment) column

You have to do bulk insert with format file:

   BULK INSERT Employee FROM 'path\tempFile.csv ' 
   WITH (FORMATFILE = 'path\tempFile.fmt');

where format file (tempFile.fmt) looks like this:

11.0
2
1 SQLCHAR 0 50 "\t"  2  Name   SQL_Latin1_General_CP1_CI_AS
2 SQLCHAR 0 50 "\r\n" 3  Address  SQL_Latin1_General_CP1_CI_AS

more details here - http://msdn.microsoft.com/en-us/library/ms179250.aspx

What exactly is RESTful programming?

RESTful programming is about:

  • resources being identified by a persistent identifier: URIs are the ubiquitous choice of identifier these days
  • resources being manipulated using a common set of verbs: HTTP methods are the commonly seen case - the venerable Create, Retrieve, Update, Delete becomes POST, GET, PUT, and DELETE. But REST is not limited to HTTP, it is just the most commonly used transport right now.
  • the actual representation retrieved for a resource is dependent on the request and not the identifier: use Accept headers to control whether you want XML, HTTP, or even a Java Object representing the resource
  • maintaining the state in the object and representing the state in the representation
  • representing the relationships between resources in the representation of the resource: the links between objects are embedded directly in the representation
  • resource representations describe how the representation can be used and under what circumstances it should be discarded/refetched in a consistent manner: usage of HTTP Cache-Control headers

The last one is probably the most important in terms of consequences and overall effectiveness of REST. Overall, most of the RESTful discussions seem to center on HTTP and its usage from a browser and what not. I understand that R. Fielding coined the term when he described the architecture and decisions that lead to HTTP. His thesis is more about the architecture and cache-ability of resources than it is about HTTP.

If you are really interested in what a RESTful architecture is and why it works, read his thesis a few times and read the whole thing not just Chapter 5! Next look into why DNS works. Read about the hierarchical organization of DNS and how referrals work. Then read and consider how DNS caching works. Finally, read the HTTP specifications (RFC2616 and RFC3040 in particular) and consider how and why the caching works the way that it does. Eventually, it will just click. The final revelation for me was when I saw the similarity between DNS and HTTP. After this, understanding why SOA and Message Passing Interfaces are scalable starts to click.

I think that the most important trick to understanding the architectural importance and performance implications of a RESTful and Shared Nothing architectures is to avoid getting hung up on the technology and implementation details. Concentrate on who owns resources, who is responsible for creating/maintaining them, etc. Then think about the representations, protocols, and technologies.

Get $_POST from multiple checkboxes

you have to name your checkboxes accordingly:

<input type="checkbox" name="check_list[]" value="…" />

you can then access all checked checkboxes with

// loop over checked checkboxes
foreach($_POST['check_list'] as $checkbox) {
   // do something
}

ps. make sure to properly escape your output (htmlspecialchars())

jquery animate background position

You don't need to use the background animate plugin if you just use separate values like this:

$('.pop').animate({
  'background-position-x': '10%',
  'background-position-y': '20%'
}, 10000, 'linear');

Is there any option to limit mongodb memory usage?

There is no reason to limit MongoDB cache as by default the mongod process will take 1/2 of the memory on the machine and no more. The default storage engine is WiredTiger. "With WiredTiger, MongoDB utilizes both the WiredTiger internal cache and the filesystem cache."

You are probably looking at top and assuming that Mongo is using all the memory on your machine. That is virtual memory. Use free -m:

              total        used        free      shared  buff/cache   available
Mem:           7982        1487        5601           8         893        6204
Swap:             0           0           0

Only when the available metric goes to zero is your computer swapping memory out to disk. In that case your database is too large for your machine. Add another mongodb instance to your cluster.

Use these two commands in the mongod console to get information about how much virtual and physical memory Mongodb is using:

var mem = db.serverStatus().tcmalloc;

mem.tcmalloc.formattedString

------------------------------------------------
MALLOC:      360509952 (  343.8 MiB) Bytes in use by application
MALLOC: +    477704192 (  455.6 MiB) Bytes in page heap freelist
MALLOC: +     33152680 (   31.6 MiB) Bytes in central cache freelist
MALLOC: +      2684032 (    2.6 MiB) Bytes in transfer cache freelist
MALLOC: +      3508952 (    3.3 MiB) Bytes in thread cache freelists
MALLOC: +      6349056 (    6.1 MiB) Bytes in malloc metadata
MALLOC:   ------------
MALLOC: =    883908864 (  843.0 MiB) Actual memory used (physical + swap)
MALLOC: +     33611776 (   32.1 MiB) Bytes released to OS (aka unmapped)
MALLOC:   ------------
MALLOC: =    917520640 (  875.0 MiB) Virtual address space used
MALLOC:
MALLOC:          26695              Spans in use
MALLOC:             22              Thread heaps in use
MALLOC:           4096              Tcmalloc page size

How to run .jar file by double click on Windows 7 64-bit?

If you try unpopular's answer:

For Windows 7:

  1. Start "Control Panel"
  2. Click "Default Programs"
  3. Click "Associate a file type or protocol with a specific program"
  4. Double click .jar
  5. Browse C:\Program Files\Java\jre7\bin\javaw.exe
  6. Click the button Open
  7. Click the button OK

And jar files still fail to open (in my case it was like I never double clicked):
open the Command Prompt (to be safe with admin rights enabled) and type the following commands:

java -version This should return a version so you can safely assume java is installed.

Then run

java -jar "PATHTOFILE\FILENAME.JAR"

Read through the output generated. You may discover an error message.

AlertDialog styling - how to change style (color) of title, message, etc

It depends how much you want to customize the alert dialog. I have different steps in order to customize the alert dialog. Please visit: https://stackoverflow.com/a/33439849/5475941

enter image description here enter image description here enter image description here enter image description here

Best C# API to create PDF

My work uses Winnovative's PDF generator (We've used it mainly to convert HTML to PDF, but you can generate it other ways as well)

ngrok command not found

  • Download the zip file.
  • Unzip it.
  • Open The terminal in the current location (inside unzip folder) where you unzip the file.
  • Execute the following command into the terminal :

    sudo cp ngrok /usr/local/bin          
    

    Now your ngrok execuatable file is successfully copied to the /usr/local/bin directory. Now you are able to run the ngrok command in the terminal

Why should hash functions use a prime number modulus?

Copying from my other answer https://stackoverflow.com/a/43126969/917428. See it for more details and examples.

I believe that it just has to do with the fact that computers work with in base 2. Just think at how the same thing works for base 10:

  • 8 % 10 = 8
  • 18 % 10 = 8
  • 87865378 % 10 = 8

It doesn't matter what the number is: as long as it ends with 8, its modulo 10 will be 8.

Picking a big enough, non-power-of-two number will make sure the hash function really is a function of all the input bits, rather than a subset of them.

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Using a RegEx to match IP addresses in Python

You have to modify your regex in the following way

pat = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")

that's because . is a wildcard that stands for "every character"

Horizontal list items

You could also use inline blocks to avoid floating elements

<ul>
    <li>
        <a href="#">some item</a>
    </li>
    <li>
        <a href="#">another item</a>
   </li>
</ul>

and then style as:

li{
    /* with fix for IE */
    display:inline;
    display:inline-block;
    zoom:1;
    /*
    additional styles to make it look nice
    */
 }

that way you wont need to float anything, eliminating the need for clearfixes

How to convert Nonetype to int or string?

In some situations it is helpful to have a function to convert None to int zero:

def nz(value):

    '''
    Convert None to int zero else return value.
    '''

    if value == None:
        return 0
    return value

mysql.h file can't be found

You probably don't included the path to mysql headers, which can be found at /usr/include/mysql, on several unix systems I think. See this post, it may be helpfull.

By the way, related with the question of that guy above, about syntastic configuration. One can add the following to your ~/.vimrc:

let b:syntastic_c_cflags = '-I/usr/include/mysql'

and you can always check the wiki page of the developers on github. Enjoy!

escaping question mark in regex javascript

You can delimit your regexp with slashes instead of quotes and then a single backslash to escape the question mark. Try this:

var gent = /I like your Apartment. Could we schedule a viewing\?/g;

GSON - Date format

I'm on Gson 2.8.6 and discovered this bug today.

My approach allows all our existing clients (mobile/web/etc) to continue functioning as they were, but adds some handling for those using 24h formats and allows millis too, for good measure.

Gson rawGson = new Gson();
SimpleDateFormat fmt = new SimpleDateFormat("MMM d, yyyy HH:mm:ss")
private class DateDeserializer implements JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        try {
            return new rawGson.fromJson(json, Date.class);
        } catch (JsonSyntaxException e) {}
        String timeString = json.getAsString();
        log.warning("Standard date deserialization didn't work:" + timeString);
        try {
            return fmt.parse(timeString);
        } catch (ParseException e) {}
        log.warning("Parsing as json 24 didn't work:" + timeString);
        return new Date(json.getAsLong());
    }
}

Gson gson = new GsonBuilder()
    .registerTypeAdapter(Date.class, new DateDeserializer())
    .create();

I kept serialization the same as all clients understand the standard json date format.

Ordinarily, I don't think it's good practice to use try/catch blocks, but this should be a fairly rare case.

linking jquery in html

Add your test.js file after the jQuery libraries. This way your test.js file can use the libraries.

Whoops, looks like something went wrong. Laravel 5.0

Go to project directory then follow below steps.

step 1: rename file .env.example `to .env

mv .env.example .env (for linux)

step 2: php artisan key:generate

mysql datatype for telephone number and address

i would use a varchar for telephone numbers. that way you can also store + and (), which is sometimes seen in tel numbers (as you mentioned yourself). and you don't have to worry about using up all bits in integers.

Create a one to many relationship using SQL Server

This is a simple example of a classic Order example. Each Customer can have multiple Orders, and each Order can consist of multiple OrderLines.

You create a relation by adding a foreign key column. Each Order record has a CustomerID in it, that points to the ID of the Customer. Similarly, each OrderLine has an OrderID value. This is how the database diagram looks:

enter image description here

In this diagram, there are actual foreign key constraints. They are optional, but they ensure integrity of your data. Also, they make the structure of your database clearer to anyone using it.

I assume you know how to create the tables themselves. Then you just need to define the relationships between them. You can of course define constraints in T-SQL (as posted by several people), but they're also easily added using the designer. Using SQL Management Studio, you can right-click the Order table, click Design (I think it may be called Edit under 2005). Then anywhere in the window that opens right-click and select Relationships.

You will get another dialog, on the right there should be a grid view. One of the first lines reads "Tables and Columns Specification". Click that line, then click again on the little [...] button that appears on the right. You will get this dialog:

Foreign key constraint

The Order table should already be selected on the right. Select the Customer table on the left dropdown. Then in the left grid, select the ID column. In the right grid, select the CustomerID column. Close the dialog, and the next. Press Ctrl+S to save.

Having this constraint will ensure that no Order records can exist without an accompanying Customer record.

To effectively query a database like this, you might want to read up on JOINs.

How do I trim a file extension from a String in Java?

String fileName="foo.bar";
int dotIndex=fileName.lastIndexOf('.');
if(dotIndex>=0) { // to prevent exception if there is no dot
  fileName=fileName.substring(0,dotIndex);
}

Is this a trick question? :p

I can't think of a faster way atm.

Set height 100% on absolute div

http://jsbin.com/ubalax/1/edit .You can see the results here

body {
    position: relative;
    float: left;
    height: 3000px;
    width: 100%;
}
body div {
    position: absolute;
    height: 100%;
    width: 100%;
    top:0;
    left:0;
    background-color: yellow;
}

Sample database for exercise

You want huge?

Here's a small table: create table foo (id int not null primary key auto_increment, crap char(2000));

insert into foo(crap) values ('');

-- each time you run the next line, the number of rows in foo doubles. insert into foo( crap ) select * from foo;

run it twenty more times, you have over a million rows to play with.

Yes, if he's looking for looks of relations to navigate, this is not the answer. But if by huge he means to test performance and his ability to optimize, this will do it. I did exactly this (and then updated with random values) to test an potential answer I had for another question. (And didn't answer it, because I couldn't come up with better performance than what that asker had.)

Had he asked for "complex", I'd have gien a differnt answer. To me,"huge" implies "lots of rows".

Because you don't need huge to play with tables and relations. Consider a table, by itself, with no nullable columns. How many different kinds of rows can there be? Only one, as all columns must have some value as none can be null.

Every nullable column multiples by two the number of different kinds of rows possible: a row where that column is null, an row where it isn't null.

Now consider the table, not in isolation. Consider a table that is a child table: for every child that has an FK to the parent, that, is a many-to-one, there can be 0, 1 or many children. So we multiply by three times the count we got in the previous step (no rows for zero, one for exactly one, two rows for many). For any grandparent to which the parent is a many, another three.

For many-to-many relations, we can have have no relation, a one-to-one, a one-to-many, many-to-one, or a many-to-many. So for each many-to-many we can reach in a graph from the table, we multiply the rows by nine -- or just like two one-to manys. If the many-to-many also has data, we multiply by the nullability number.

Tables that we can't reach in our graph -- those that we have no direct or indirect FK to, don't multiply the rows in our table.

By recursively multiplying the each table we can reach, we can come up with the number of rows needed to provide one of each "kind", and we need no more than those to test every possible relation in our schema. And we're nowhere near huge.

Why did I get the compile error "Use of unassigned local variable"?

Local variables are not automatically initialized. That only happens with instance-level variables.

You need to explicitly initialize local variables if you want them to be initialized. In this case, (as the linked documentation explains) either by setting the value of 0 or using the new operator.

The code you've shown does indeed attempt to use the value of the variable tmpCnt before it is initialized to anything, and the compiler rightly warns about it.

Active Menu Highlight CSS

add simply way

<div id='cssmenu'>
<ul>
<li class=''><a href='1.html'><span>1</span></a></li>
<li class=''><a href='2.html'><span>2</span></a></li>
<li class='' style="float:right;"><a href='3.html'><span>3</span></a></li>
</ul>
</div>

$("document").ready(function(){
$(function() {
$('.cssmenu a[href="' + location.pathname.split("/")[location.pathname.split("/").length-1] + '"]').parent().addClass('active');
});

});

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

A solution that helped me: Go to Tools > NuGet Package Manager > Manage NuGet Packaged for Solution... > Browse > Search for System.IO.Compression.ZipFile and install it

What is the difference between a field and a property?

Though fields and properties look to be similar to each other, they are 2 completely different language elements.

  1. Fields are the only mechanism how to store data on class level. Fields are conceptually variables at class scope. If you want to store some data to instances of your classes (objects) you need to use fields. There is no other choice. Properties can't store any data even though, it may look they are able to do so. See bellow.

  2. Properties on the other hand never store data. They are just the pairs of methods (get and set) that can be syntactically called in a similar way as fields and in most cases they access (for read or write) fields, which is the source of some confusion. But because property methods are (with some limitations like fixed prototype) regular C# methods they can do whatever regular methods can do. It means they can have 1000 lines of code, they can throw exceptions, call another methods, can be even virtual, abstract or overridden. What makes properties special, is the fact that C# compiler stores some extra metadata into assemblies that can be used to search for specific properties - widely used feature.

Get and set property methods has the following prototypes.

PROPERTY_TYPE get();

void set(PROPERTY_TYPE value);

So it means that properties can be 'emulated' by defining a field and 2 corresponding methods.

class PropertyEmulation
{
    private string MSomeValue;

    public string GetSomeValue()
    {
        return(MSomeValue);
    }

    public void SetSomeValue(string value)
    {
        MSomeValue=value;
    }
}

Such property emulation is typical for programming languages that don't support properties - like standard C++. In C# there you should always prefer properties as the way how to access to your fields.

Because only the fields can store a data, it means that more fields class contains, more memory objects of such class will consume. On the other hand, adding new properties into a class doesn't make objects of such class bigger. Here is the example.

class OneHundredFields
{
        public int Field1;
        public int Field2;
        ...
        public int Field100;
}

OneHundredFields Instance=new OneHundredFields() // Variable 'Instance' consumes 100*sizeof(int) bytes of memory.

class OneHundredProperties
{
    public int Property1
    {
        get
        {
            return(1000);
        }
        set
        {
            // Empty.
        }
    }

    public int Property2
    {
        get
        {
            return(1000);
        }
        set
        {
            // Empty.
        }
    }

    ...

    public int Property100
    {
        get
        {
            return(1000);
        }
        set
        {
            // Empty.
        }
    }
}

OneHundredProperties Instance=new OneHundredProperties() // !!!!! Variable 'Instance' consumes 0 bytes of memory. (In fact a some bytes are consumed becasue every object contais some auxiliarity data, but size doesn't depend on number of properties).

Though property methods can do anything, in most cases they serve as a way how to access objects' fields. If you want to make a field accessible to other classes you can do by 2 ways.

  1. Making fields as public - not advisable.
  2. Using properties.

Here is a class using public fields.

class Name
{
    public string FullName;
    public int YearOfBirth;
    public int Age;
}

Name name=new Name();

name.FullName="Tim Anderson";
name.YearOfBirth=1979;
name.Age=40;

While the code is perfectly valid, from design point of view, it has several drawbacks. Because fields can be both read and written, you can't prevent user from writing to fields. You can apply readonly keyword, but in this way, you have to initialize readonly fields only in constructor. What's more, nothing prevents you to store invalid values into your fields.

name.FullName=null;
name.YearOfBirth=2200;
name.Age=-140;

The code is valid, all assignments will be executed though they are illogical. Age has a negative value, YearOfBirth is far in future and doesn't correspond to Age and FullName is null. With fields you can't prevent users of class Name to make such mistakes.

Here is a code with properties that fixes these issues.

class Name
{
    private string MFullName="";
    private int MYearOfBirth;

    public string FullName
    {
        get
        {
            return(MFullName);
        }
        set
        {
            if (value==null)
            {
                throw(new InvalidOperationException("Error !"));
            }

            MFullName=value;
        }
    }

    public int YearOfBirth
    {
        get
        {
            return(MYearOfBirth);
        }
        set
        {
            if (MYearOfBirth<1900 || MYearOfBirth>DateTime.Now.Year)
            {
                throw(new InvalidOperationException("Error !"));
            }

            MYearOfBirth=value;
        }
    }

    public int Age
    {
        get
        {
            return(DateTime.Now.Year-MYearOfBirth);
        }
    }

    public string FullNameInUppercase
    {
        get
        {
            return(MFullName.ToUpper());
        }
    }
}

The updated version of class has the following advantages.

  1. FullName and YearOfBirth are checked for invalid values.
  2. Age is not writtable. It's callculated from YearOfBirth and current year.
  3. A new property FullNameInUppercase converts FullName to UPPER CASE. This is a little contrived example of property usage, where properties are commonly used to present field values in the format that is more appropriate for user - for instance using current locale on specific numeric of DateTime format.

Beside this, properties can be defined as virtual or overridden - simply because they are regular .NET methods. The same rules applies for such property methods as for regular methods.

C# also supports indexers which are the properties that have an index parameter in property methods. Here is the example.

class MyList
{
    private string[]                 MBuffer;

    public MyList()
    {
        MBuffer=new string[100];
    }

    public string this[int Index]
    {
        get
        {
            return(MBuffer[Index]);
        }
        set
        {
            MBuffer[Index]=value;
        }
    }
}

MyList   List=new MyList();

List[10]="ABC";
Console.WriteLine(List[10]);

Since C# 3.0 allows you to define automatic properties. Here is the example.

class AutoProps
{
    public int Value1
    {
        get;
        set;
    }

    public int Value2
    {
        get;
        set;
    }
}

Even though class AutoProps contains only properties (or it looks like), it can store 2 values and size of objects of this class is equal to sizeof(Value1)+sizeof(Value2)=4+4=8 bytes.

The reason for this is simple. When you define an automatic property, C# compiler generates automatic code that contains hidden field and a property with property methods accessing this hidden field. Here is the code compiler produces.

Here is a code generated by the ILSpy from compiled assembly. Class contains generated hidden fields and properties.

internal class AutoProps
{
    [CompilerGenerated]
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private int <Value1>k__BackingField;

    [CompilerGenerated]
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private int <Value2>k__BackingField;

    public int Value1
    {
        [CompilerGenerated]
        get
        {
            return <Value1>k__BackingField;
        }
        [CompilerGenerated]
        set
        {
            <Value1>k__BackingField = value;
        }
    }

    public int Value2
    {
        [CompilerGenerated]
        get
        {
            return <Value2>k__BackingField;
        }
        [CompilerGenerated]
        set
        {
            <Value2>k__BackingField = value;
        }
    }
}

So, as you can see, the compiler still uses the fields to store the values - since fields are the only way how to store values into objects.

So as you can see, though properties and fields have similar usage syntax they are very different concepts. Even if you use automatic properties or events - hidden fields are generated by compiler where the real data are stored.

If you need to make a field value accessible to the outside world (users of your class) don't use public or protected fields. Fields always should be marked as private. Properties allow you to make value checks, formatting, conversions etc. and generally make your code safer, more readable and more extensible for future modifications.

How to know what the 'errno' means?

You can use strerror() to get a human-readable string for the error number. This is the same string printed by perror() but it's useful if you're formatting the error message for something other than standard error output.

For example:

#include <errno.h>
#include <string.h>

/* ... */

if(read(fd, buf, 1)==-1) {
    printf("Oh dear, something went wrong with read()! %s\n", strerror(errno));
}

Linux also supports the explicitly-threadsafe variant strerror_r().

Android Spinner: Get the selected item change event

spinner1.setOnItemSelectedListener(
    new AdapterView.OnItemSelectedListener() {
        //add some code here
    }
);

Access the css ":after" selector with jQuery

You can add style for :after a like html code.
For example:

var value = 22;
body.append('<style>.wrapper:after{border-top-width: ' + value + 'px;}</style>');

jQuery - Appending a div to body, the body is the object?

jQuery methods returns the set they were applied on.

Use .appendTo:

var $div = $('<div />').appendTo('body');
$div.attr('id', 'holdy');

How to fix IndexError: invalid index to scalar variable

Basically, 1 is not a valid index of y. If the visitor is comming from his own code he should check if his y contains the index which he tries to access (in this case the index is 1).

Error when deploying an artifact in Nexus

Just to create a separate answer. The answer is actually found in a comment for the accepted answer.

Try changing the version of your artefact to end with -SNAPSHOT.

How are VST Plugins made?

If you know a .NET language (C#/VB.NET etc) then checkout VST.NET. This framework allows you to create (unmanaged) VST 2.4 plugins in .NET. It comes with a framework that structures and simplifies the creation of a VST Plugin with support for Parameters, Programs and Persistence.

There are several samples that demonstrate the typical plugin scenarios. There's also documentation that explains how to get started and some of the concepts behind VST.NET.

Hope it helps. Marc Jacobi

How can I upgrade NumPy?

When you already have an older version of NumPy, use this:

pip install numpy --upgrade

If it still doesn't work, try:

pip install numpy --upgrade --ignore-installed

Iterate over object keys in node.js

For simple iteration of key/values, sometimes libraries like underscorejs can be your friend.

const _ = require('underscore');

_.each(a, function (value, key) {
    // handle
});

just for reference

how to install Lex and Yacc in Ubuntu?

Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:

sudo apt-get install bison flex

There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.

How to count the number of letters in a string without the spaces?

I found this is working perfectly

str = "count a character occurance"
str = str.replace(' ', '')
print (str)
print (len(str))

Why doesn't C++ have a garbage collector?

One of the biggest reasons that C++ doesn't have built in garbage collection is that getting garbage collection to play nice with destructors is really, really hard. As far as I know, nobody really knows how to solve it completely yet. There are alot of issues to deal with:

  • deterministic lifetimes of objects (reference counting gives you this, but GC doesn't. Although it may not be that big of a deal).
  • what happens if a destructor throws when the object is being garbage collected? Most languages ignore this exception, since theres really no catch block to be able to transport it to, but this is probably not an acceptable solution for C++.
  • How to enable/disable it? Naturally it'd probably be a compile time decision but code that is written for GC vs code that is written for NOT GC is going to be very different and probably incompatible. How do you reconcile this?

These are just a few of the problems faced.

Group by multiple field names in java 8

Define a class for key definition in your group.

class KeyObj {

    ArrayList<Object> keys;

    public KeyObj( Object... objs ) {
        keys = new ArrayList<Object>();

        for (int i = 0; i < objs.length; i++) {
            keys.add( objs[i] );
        }
    }

    // Add appropriate isEqual() ... you IDE should generate this

}

Now in your code,

peopleByManyParams = people
            .collect(Collectors.groupingBy(p -> new KeyObj( p.age, p.other1, p.other2 ), Collectors.mapping((Person p) -> p, toList())));

How do I find out my root MySQL password?

You can reset the root password by running the server with --skip-grant-tables and logging in without a password by running the following as root (or with sudo):

# service mysql stop
# mysqld_safe --skip-grant-tables &
$ mysql -u root
mysql> use mysql;
mysql> update user set authentication_string=PASSWORD("YOUR-NEW-ROOT-PASSWORD") where User='root';
mysql> flush privileges;
mysql> quit
# service mysql stop
# service mysql start
$ mysql -u root -p

Now you should be able to login as root with your new password.

It is also possible to find the query that reset the password in /home/$USER/.mysql_history or /root/.mysql_history of the user who reset the password, but the above will always work.

Note: prior to MySQL 5.7 the column was called password instead of authentication_string. Replace the line above with

mysql> update user set password=PASSWORD("YOUR-NEW-ROOT-PASSWORD") where User='root';

Min width in window resizing

Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:

#container {
    min-width:800px;
    width: auto !important;
    width:800px;
}

That will effectively give you 800px min-width in IE6 and any up-to-date browsers.

Convert Bitmap to File

Try this:

bitmap.compress(Bitmap.CompressFormat.PNG, quality, outStream);

See this

notifyDataSetChange not working from custom adapter

My case was different but it might be the same case for others

for those who still couldn't find a solution and tried everything above, if you're using the adapter inside fragment then the reason it's not working fragment could be recreating so the adapter is recreating everytime the fragment recreate

you should verify if the adapter and objects list are null before initializing

_x000D_
_x000D_
if(adapter == null){_x000D_
  adapter = new CustomListAdapter(...);_x000D_
}_x000D_
..._x000D_
_x000D_
if(objects == null){_x000D_
  objects = new ArrayList<>();_x000D_
}
_x000D_
_x000D_
_x000D_

Why maven settings.xml file is not there?

You can verify where your Setting.xml is by pressing shortcut Ctrl+3, you will see Quick Access on top right side of Eclipse, then search setting.xml in searchbox. If you got setting.xml it will show up in search. Click that, and it will open the window showing directory path wherever it is stored. Your Maven Global Settings should be as such:

Global Setting C:\maven\apache-maven-3.5.0\conf\settings.xml
User Setting %userprofile%\\.m2\setting.xml
You can use global setting usually and leave the second option user setting untouched. Store your setting.xml in Global Setting

PHP not displaying errors even though display_errors = On

I had the same problem but I used ini_set('display_errors', '1'); inside the faulty script itself so it never fires on fatal / syntax errors. Finally I solved it by adding this to my .htaccess:

php_value auto_prepend_file /usr/www/{YOUR_PATH}/display_errors.php

display_errors.php:

<?php
ini_set('display_errors', 1);
error_reporting(-1);
?>

By that I was not forced to change the php.ini, use it for specific subfolders and could easily disable it again.

How can I convert a string with dot and comma into a float in Python

If you have a comma as decimals separator and the dot as thousands separator, you can do:

s = s.replace('.','').replace(',','.')
number = float(s)

Hope it will help

Execute bash script from URL

This way is good and conventional:

17:04:59@itqx|~
qx>source <(curl -Ls http://192.168.80.154/cent74/just4Test) Lord Jesus Loves YOU
Remote script test...
Param size: 4

---------
17:19:31@node7|/var/www/html/cent74
arch>cat just4Test
echo Remote script test...
echo Param size: $#

How do I add a new sourceset to Gradle?

This was once written for Gradle 2.x / 3.x in 2016 and is far outdated!! Please have a look at the documented solutions in Gradle 4 and up


To sum up both old answers (get best and minimum viable of both worlds):

some warm words first:

  1. first, we need to define the sourceSet:

    sourceSets {
        integrationTest
    }
    
  2. next we expand the sourceSet from test, therefor we use the test.runtimeClasspath (which includes all dependenciess from test AND test itself) as classpath for the derived sourceSet:

    sourceSets {
        integrationTest {
            compileClasspath += sourceSets.test.runtimeClasspath
            runtimeClasspath += sourceSets.test.runtimeClasspath // ***)
        }
    }
    
    • note) somehow this redeclaration / extend for sourceSets.integrationTest.runtimeClasspath is needed, but should be irrelevant since runtimeClasspath always expands output + runtimeSourceSet, don't get it
  3. we define a dedicated task for just running integration tests:

    task integrationTest(type: Test) {
    }
    
  4. Configure the integrationTest test classes and classpaths use. The defaults from the java plugin use the test sourceSet

    task integrationTest(type: Test) {
        testClassesDir = sourceSets.integrationTest.output.classesDir
        classpath = sourceSets.integrationTest.runtimeClasspath
    }
    
  5. (optional) auto run after test

    integrationTest.dependsOn test
    

  6. (optional) add dependency from check (so it always runs when build or check are executed)

    tasks.check.dependsOn(tasks.integrationTest)
    
  7. (optional) add java,resources to the sourceSet to support auto-detection and create these "partials" in your IDE. i.e. IntelliJ IDEA will auto create sourceSet directories java and resources for each set if it doesn't exist:

    sourceSets {
         integrationTest {
             java
             resources
         }
    }
    

tl;dr

apply plugin: 'java'

// apply the runtimeClasspath from "test" sourceSet to the new one
// to include any needed assets: test, main, test-dependencies and main-dependencies
sourceSets {
    integrationTest {
        // not necessary but nice for IDEa's
        java
        resources

        compileClasspath += sourceSets.test.runtimeClasspath
        // somehow this redeclaration is needed, but should be irrelevant
        // since runtimeClasspath always expands compileClasspath
        runtimeClasspath += sourceSets.test.runtimeClasspath
    }
}

// define custom test task for running integration tests
task integrationTest(type: Test) {
    testClassesDir = sourceSets.integrationTest.output.classesDir
    classpath = sourceSets.integrationTest.runtimeClasspath
}
tasks.integrationTest.dependsOn(tasks.test)

referring to:

Unfortunatly, the example code on github.com/gradle/gradle/subprojects/docs/src/samples/java/customizedLayout/build.gradle or …/gradle/…/withIntegrationTests/build.gradle seems not to handle this or has a different / more complex / for me no clearer solution anyway!

Creating new database from a backup of another Database on the same server?

I think that is easier than this.

  • First, create a blank target database.
  • Then, in "SQL Server Management Studio" restore wizard, look for the option to overwrite target database. It is in the 'Options' tab and is called 'Overwrite the existing database (WITH REPLACE)'. Check it.
  • Remember to select target files in 'Files' page.

You can change 'tabs' at left side of the wizard (General, Files, Options)

What's the difference between a word and byte?

BYTE

I am trying to answer this question from C++ perspective.

The C++ standard defines ‘byte’ as “Addressable unit of data large enough to hold any member of the basic character set of the execution environment.”

What this means is that the byte consists of at least enough adjacent bits to accommodate the basic character set for the implementation. That is, the number of possible values must equal or exceed the number of distinct characters. In the United States, the basic character sets are usually the ASCII and EBCDIC sets, each of which can be accommodated by 8 bits. Hence it is guaranteed that a byte will have at least 8 bits.

In other words, a byte is the amount of memory required to store a single character.

If you want to verify ‘number of bits’ in your C++ implementation, check the file ‘limits.h’. It should have an entry like below.

#define CHAR_BIT      8         /* number of bits in a char */

WORD

A Word is defined as specific number of bits which can be processed together (i.e. in one attempt) by the machine/system. Alternatively, we can say that Word defines the amount of data that can be transferred between CPU and RAM in a single operation.

The hardware registers in a computer machine are word sized. The Word size also defines the largest possible memory address (each memory address points to a byte sized memory).

Note – In C++ programs, the memory addresses points to a byte of memory and not to a word.

Set background color in PHP?

You better use CSS for that, after all, this is what CSS is for. If you don't want to do that, go with Dorwand's answer.

How to read a PEM RSA private key from .NET

I solved, thanks. In case anyone's interested, bouncycastle did the trick, just took me some time due to lack of knowledge from on my side and documentation. This is the code:

var bytesToDecrypt = Convert.FromBase64String("la0Cz.....D43g=="); // string to decrypt, base64 encoded

AsymmetricCipherKeyPair keyPair; 

using (var reader = File.OpenText(@"c:\myprivatekey.pem")) // file containing RSA PKCS1 private key
    keyPair = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject(); 

var decryptEngine = new Pkcs1Encoding(new RsaEngine());
decryptEngine.Init(false, keyPair.Private); 

var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length)); 

How to write a:hover in inline CSS?

You can use the pseudo-class a:hover in external style sheets only. Therefore I recommend using an external style sheet. The code is:

a:hover {color:#FF00FF;}   /* Mouse-over link */

Displaying output of a remote command with Ansible

I'm not sure about the syntax of your specific commands (e.g., vagrant, etc), but in general...

Just register Ansible's (not-normally-shown) JSON output to a variable, then display each variable's stdout_lines attribute:

- name: Generate SSH keys for vagrant user
  user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048
  register: vagrant
- debug: var=vagrant.stdout_lines

- name: Show SSH public key
  command: /bin/cat $home_directory/.ssh/id_rsa.pub
  register: cat
- debug: var=cat.stdout_lines

- name: Wait for user to copy SSH public key
  pause: prompt="Please add the SSH public key above to your GitHub account"
  register: pause
- debug: var=pause.stdout_lines

Convert javascript array to string

You shouldn't confuse arrays with lists.

This is a list: {...}. It has no length or other Array properties.

This is an array: [...]. You can use array functions, methods and so, like someone suggested here: someArray.toString();

someObj.toString(); will not work on any other object types, like lists.

Get GMT Time in Java

The following code will get the date minus timezone offset:

protected Date toGmt0(ZonedDateTime time) {
    ZonedDateTime gmt0 = time.minusSeconds(time.getOffset().getTotalSeconds());
    return Date.from(gmt0.toInstant());
}

@Test
public void test() {

    ZonedDateTime now = ZonedDateTime.now();
    Date dateAtSystemZone = Date.from(now.toInstant());
    Date dateAtGmt0 = toGmt0(now);

    SimpleDateFormat sdfWithoutZone = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    SimpleDateFormat sdfWithZoneGmt0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ITALIAN);
    sdfWithZoneGmt0.setTimeZone(TimeZone.getTimeZone("GMT"));

    System.out.println(""
            + "\ndateAtSystemZone          = " + dateAtSystemZone
            + "\ndateAtGmt0                = " + dateAtGmt0
            + "\ndiffInMillis              = " + (dateAtSystemZone.getTime() - dateAtGmt0.getTime())
            + "\n"
            + "\ndateWithSystemZone.format = " + sdfWithoutZone.format(dateAtSystemZone)
            + "\ndateAtGmt0.format         = " + sdfWithoutZone.format(dateAtGmt0)
            + "\n"
            + "\ndateFormatWithGmt0        = " + sdfWithZoneGmt0.format(dateAtSystemZone)
    );

output :

dateAtSystemZone          = Thu Apr 23 14:03:36 CST 2020
dateAtGmt0                = Thu Apr 23 06:03:36 CST 2020
diffInMillis              = 28800000

dateWithSystemZone.format = 2020-04-23 14:03:36.140
dateAtGmt0.format         = 2020-04-23 06:03:36.140

dateFormatWithGmt0        = 2020-04-23 06:03:36.140

My system is at GMT+8, so diffInMillis = 28800000 = 8 * 60 * 60 * 1000?

How can I enable auto complete support in Notepad++?

Open Notepad++ and Settings -> Preferences -> Auto-Completion -> Check the Auto-insert options you want. this link will help alot: http://docs.notepad-plus-plus.org/index.php/Auto_Completion

How to hide elements without having them take space on the page?

To use display:none is a good option just to removing an element BUT it will be also removed for screenreaders. There are also discussions if it effects SEO. There's a good, short article on that topic on A List Apart

If you really just want hide and not remove an element, better use:

div {
  position: absolute; 
  left: -999em;
}

Like this it can be also read by screen readers.

The only disadvantage of this method is, that this DIV is actually rendered and it might effect the performance, especially on mobile phones.

Argument of type 'X' is not assignable to parameter of type 'X'

I was getting this one on this case

...
.then((error: any, response: any) => {
  console.info('document error: ', error);
  console.info('documenr response: ', response);
  return new MyModel();
})
...

on this case making parameters optional would make ts stop complaining

.then((error?: any, response?: any) => {

Initializing a struct to 0

See §6.7.9 Initialization:

21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

So, yes both of them work. Note that in C99 a new way of initialization, called designated initialization can be used too:

myStruct _m1 = {.c2 = 0, .c1 = 1};

DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view

Try @ sign at start of expression. So you wont need to type escape characters just copy paste the regular expression in "" and put @ sign. Like so:

[RegularExpression(@"([a-zA-Z\d]+[\w\d]*|)[a-zA-Z]+[\w\d.]*", ErrorMessage = "Invalid username")]
public string Username { get; set; }

GCC fatal error: stdio.h: No such file or directory

Mac OS X

I had this problem too (encountered through Macports compilers). Previous versions of Xcode would let you install command line tools through xcode/Preferences, but xcode5 doesn't give a command line tools option in the GUI, that so I assumed it was automatically included now. Try running this command:

xcode-select --install

Ubuntu

(as per this answer)

sudo apt-get install libc6-dev

Alpine Linux

(as per this comment)

apk add libc-dev

Minimal web server using netcat

Add -q 1 to the netcat command line:

while true; do 
  echo -e "HTTP/1.1 200 OK\n\n $(date)" | nc -l -p 1500 -q 1
done

Mocking methods of local scope objects with Mockito

If you really want to avoid touching this code, you can use Powermockito (PowerMock for Mockito).

With this, amongst many other things, you can mock the construction of new objects in a very easy way.

html <input type="text" /> onchange event not working

HTML5 defines an oninput event to catch all direct changes. it works for me.

Confused about UPDLOCK, HOLDLOCK

UPDLOCK is used when you want to lock a row or rows during a select statement for a future update statement. The future update might be the very next statement in the transaction.

Other sessions can still see the data. They just cannot obtain locks that are incompatiable with the UPDLOCK and/or HOLDLOCK.

You use UPDLOCK when you wan to keep other sessions from changing the rows you have locked. It restricts their ability to update or delete locked rows.

You use HOLDLOCK when you want to keep other sessions from changing any of the data you are looking at. It restricts their ability to insert, update, or delete the rows you have locked. This allows you to run the query again and see the same results.

Git will not init/sync/update new submodules

Same as you I found that git submodule sync does not do what you expect it to do. Only after doing an explicit git submodule add again does a submodule url change.

So, I put this script in ~/bin/git-submodule-sync.rb:

https://gist.github.com/frimik/5125436

And I also use the same logic on a few post-receive git deploy scripts.

All I need to do now is edit .gitmodules, then run this script and it finally works like I thought git submodule sync was supposed to.

Check if a string is a date value

SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
sdf.setLenient(false);

By default this is set to TRUE. So even strings of wrong format return good values.

I have used it something like this :

SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
formatter.setLenient(false);
String value = "1990/13/23"; 

try {
      Date date = formatter.parse(value);
      System.out.println(date);
    }catch (ParseException e) 
  {
    System.out.println("its bad");
  }

CSS Transition doesn't work with top, bottom, left, right

I ran into this issue today. Here is my hacky solution.

I needed a fixed position element to transition up by 100 pixels as it loaded.

var delay = (ms) => new Promise(res => setTimeout(res, ms));
async function animateView(startPosition,elm){
  for(var i=0; i<101; i++){
    elm.style.top = `${(startPosition-i)}px`;
    await delay(1);
  }
}

Is it possible to insert multiple rows at a time in an SQLite database?

Start from version 2012-03-20 (3.7.11), sqlite support the following INSERT syntax:

INSERT INTO 'tablename' ('column1', 'column2') VALUES
  ('data1', 'data2'),
  ('data3', 'data4'),
  ('data5', 'data6'),
  ('data7', 'data8');

Read documentation: http://www.sqlite.org/lang_insert.html

PS: Please +1 to Brian Campbell's reply/answer. not mine! He presented the solution first.

How to properly apply a lambda function into a pandas data frame column

You need mask:

sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)

Another solution with loc and boolean indexing:

sample.loc[sample['PR'] < 90, 'PR'] = np.nan

Sample:

import pandas as pd
import numpy as np

sample = pd.DataFrame({'PR':[10,100,40] })
print (sample)
    PR
0   10
1  100
2   40

sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)
print (sample)
      PR
0    NaN
1  100.0
2    NaN
sample.loc[sample['PR'] < 90, 'PR'] = np.nan
print (sample)
      PR
0    NaN
1  100.0
2    NaN

EDIT:

Solution with apply:

sample['PR'] = sample['PR'].apply(lambda x: np.nan if x < 90 else x)

Timings len(df)=300k:

sample = pd.concat([sample]*100000).reset_index(drop=True)

In [853]: %timeit sample['PR'].apply(lambda x: np.nan if x < 90 else x)
10 loops, best of 3: 102 ms per loop

In [854]: %timeit sample['PR'].mask(sample['PR'] < 90, np.nan)
The slowest run took 4.28 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 3.71 ms per loop

What is .htaccess file?

You are allow to use php_value to change php setting in .htaccess file. Same like how php.ini did.

Example:

php_value date.timezone Asia/Kuala_Lumpur

For other php setting, please read http://www.php.net/manual/en/ini.list.php

Get value from SimpleXMLElement Object

$codeZero = null;
foreach ($xml->code->children() as $child) {
   $codeZero = $child;
}

$lat = null;
foreach ($codeZero->children() as $child) {
   if (isset($child->lat)) {
      $lat = $child->lat;
   }
}

Convert HTML Character Back to Text Using Java Standard Library

As @jem suggested, it is possible to use jsoup.

With jSoup 1.8.3 it il possible to use the method Parser.unescapeEntities that retain the original html.

import org.jsoup.parser.Parser;
...
String html = Parser.unescapeEntities(original_html, false);

It seems that in some previous release this method is not present.

How to set RelativeLayout layout params in code not in xml?

Something like this..

 RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.widget43);
                // ListView listView = (ListView) findViewById(R.id.ListView01);

                LayoutInflater inflater = (LayoutInflater) this
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                // View footer = inflater.inflate(R.layout.footer, null);
                View footer = LayoutInflater.from(this).inflate(R.layout.footer,
                        null);
                final RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.FILL_PARENT,
                        RelativeLayout.LayoutParams.FILL_PARENT);
                layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1);
footer.setLayoutParams(layoutParams);

jquery AJAX and json format

$.ajax({
   type: "POST",
   url: hb_base_url + "consumer",
   contentType: "application/json",
   dataType: "json",
   data: {
       data__value = JSON.stringify(
       {
           first_name: $("#namec").val(),
           last_name: $("#surnamec").val(),
           email: $("#emailc").val(),
           mobile: $("#numberc").val(),
           password: $("#passwordc").val()
       })
   },
   success: function(response) {
       console.log(response);
   },
   error: function(response) {
       console.log(response);
   }
});

(RU) ?? ??????? ???? ?????? ????? ???????? ??? - $_POST['data__value']; ???????? ??? ????????? ???????? first_name ?? ???????, ????? ????????:

(EN) On the server, you can get your data as - $_POST ['data__value']; For example, to get the first_name value on the server, write:

$test = json_decode( $_POST['data__value'] );
echo $test->first_name;

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

After clicking on Properties of any installer(.exe) which block your application to install (Windows Defender SmartScreen prevented an unrecognized app ) for that issue i found one solution

  1. Right click on installer(.exe)
  2. Select properties option.
  3. Click on checkbox to check Unblock at the bottom of Properties.

This solution work for Heroku CLI (heroku-x64) installer(.exe)

Create a Bitmap/Drawable from file path

static ArrayList< Drawable>  d;
d = new ArrayList<Drawable>();
for(int i=0;i<MainActivity.FilePathStrings1.size();i++) {
  myDrawable =  Drawable.createFromPath(MainActivity.FilePathStrings1.get(i));
  d.add(myDrawable);
}

How to remove all whitespace from a string?

Use [[:blank:]] to match any kind of horizontal white_space characters.

gsub("[[:blank:]]", "", " xx yy 11 22  33 ")
# [1] "xxyy112233"

Can't find System.Windows.Media namespace?

You should add reference to PresentationCore.dll.

Why does 'git commit' not save my changes?

Maybe an obvious thing, but...

If you have problem with the index, use git-gui. You get a very good view how the index (staging area) actually works.

Another source of information that helped me understand the index was Scott Chacons "Getting Git" page 259 and forward.

I started off using the command line because most documentation only showed that...

I think git-gui and gitk actually make me work faster, and I got rid of bad habits like "git pull" for example... Now I always fetch first... See what the new changes really are before I merge.

Attach IntelliJ IDEA debugger to a running Java process

It's possible, but you have to add some JVM flags when you start your application.

You have to add remote debug configuration: Edit configuration -> Remote.

Then you'lll find in displayed dialog window parametrs that you have to add to program execution, like:

-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005

Then when your application is launched you can attach your debugger. If you want your application to wait until debugger is connected just change suspend flag to y (suspend=y)

What does $_ mean in PowerShell?

$_ is an alias for automatic variable $PSItem (introduced in PowerShell V3.0; Usage information found here) which represents the current item from the pipe.

PowerShell (v6.0) online documentation for automatic variables is here.

Convert YYYYMMDD to DATE

I was also facing the same issue where I was receiving the Transaction_Date as YYYYMMDD in bigint format. So I converted it into Datetime format using below query and saved it in new column with datetime format. I hope this will help you as well.

SELECT
convert( Datetime, STUFF(STUFF(Transaction_Date, 5, 0, '-'), 8, 0, '-'), 120) As [Transaction_Date_New]
FROM mydb

ng-if, not equal to?

It is better to use ng-switch

<div ng-switch on="details.Payment[0].Status">
    <div ng-switch-when="1">
        <!-- code to render a large video block-->
    </div>
    <div ng-switch-default>
        <!-- code to render the regular video block -->
    </div>
</div>

git stash -> merge stashed change with current changes

you can easily

  1. Commit your current changes
  2. Unstash your stash and resolve conflicts
  3. Commit changes from stash
  4. Soft reset to commit you are comming from (last correct commit)

Laravel: Auth::user()->id trying to get a property of a non-object

Your question and code sample are a little vague, and I believe the other developers are focusing on the wrong thing. I am making an application in Laravel, have used online tutorials for creating a new user and authentication, and seemed to have noticed that when you create a new user in Laravel, no Auth object is created - which you use to get the (new) logged-in user's ID in the rest of the application. This is a problem, and I believe what you may be asking. I did this kind of cludgy hack in userController::store :

$user->save();

Session::flash('message','Successfully created user!');

//KLUDGE!! rest of site depends on user id in auth object - need to force/create it here
Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')), true);

Redirect::to('users/' . Auth::user()->id);

Shouldn't have to create and authenticate, but I didn't know what else to do.

How to capitalize the first character of each word in a string

I use wordUppercase(String s) from the Raindrop-Library. Because this is my library, here the single method:

 /**
  * Set set first letter from every word uppercase.
  *
  * @param s - The String wich you want to convert.
  * @return The string where is the first letter of every word uppercase.
  */
 public static String wordUppercase(String s){
   String[] words = s.split(" ");
   for (int i = 0; i < words.length; i++) words[i] = words[i].substring(0, 1).toUpperCase() + words[i].substring(1).toLowerCase();
   return String.join(" ", words);
 }

Hope it helps :)

Open URL in same window and in same tab

Do you have to use window.open? What about using window.location="http://example.com"?

Override default Spring-Boot application.properties settings in Junit Test

TLDR:

So what I did was to have the standard src/main/resources/application.properties and also a src/test/resources/application-default.properties where i override some settings for ALL my tests.

Whole Story

I ran into the same problem and was not using profiles either so far. It seemed to be bothersome to have to do it now and remember declaring the profile -- which can be easily forgotten.

The trick is, to leverage that a profile specific application-<profile>.properties overrides settings in the general profile. See https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties.

How to use if-else logic in Java 8 stream forEach

Just put the condition into the lambda itself, e.g.

animalMap.entrySet().stream()
        .forEach(
                pair -> {
                    if (pair.getValue() != null) {
                        myMap.put(pair.getKey(), pair.getValue());
                    } else {
                        myList.add(pair.getKey());
                    }
                }
        );

Of course, this assumes that both collections (myMap and myList) are declared and initialized prior to the above piece of code.


Update: using Map.forEach makes the code shorter, plus more efficient and readable, as Jorn Vernee kindly suggested:

    animalMap.forEach(
            (key, value) -> {
                if (value != null) {
                    myMap.put(key, value);
                } else {
                    myList.add(key);
                }
            }
    );

Placeholder in UITextView


Simulating Native Placeholders


A common gripe is that iOS doesn't provide a native placeholder feature for textviews. The UITextView extension below attempts to address that concern by offering the convenience one would expect from a native feature, requiring only one line of code to add a placeholder to a textview instance.

The downside of this solution is, because it daisy chains delegate calls, it is vulnerable to (unlikely) changes to the UITextViewDelegate protocol in an iOS update. Specifically, if iOS adds new protocol methods and you implement any of them in the delegate for a text view with a placeholder, those methods won't be called unless you've also updated the extension to forward those calls.

Alternatively, the Inline Placeholder answer is a rock-solid and about as simple as can be.


Usage examples:


   • If the text view gaining the placeholder doesn't use a UITextViewDelegate:

    /* Swift 3 */

    class NoteViewController : UIViewController {
        @IBOutlet weak var noteView: UITextView!
        override func viewDidLoad() {
            noteView.addPlaceholder("Enter some text...",  color: UIColor.lightGray)
        }
    }

                                            -- OR --

   • If the text view gaining the placeholder does use a UITextViewDelegate:

    /* Swift 3 */

    class NoteViewController : UIViewController, UITextViewDelegate {
        @IBOutlet weak var noteView: UITextView!
        override func viewDidLoad() {
            noteView.addPlaceholder("Phone #", color: UIColor.lightGray, delegate: self)
        }
    }

Implementation (UITextView extension):


/* Swift 3 */

extension UITextView: UITextViewDelegate
{

    func addPlaceholder(_ placeholderText : String, 
                      color : UIColor? = UIColor.lightGray,
                      delegate : UITextViewDelegate? = nil) {

        self.delegate = self             // Make receiving textview instance a delegate
        let placeholder = UITextView()   // Need delegate storage ULabel doesn't provide
        placeholder.isUserInteractionEnabled = false  //... so we *simulate* UILabel
        self.addSubview(placeholder)     // Add to text view instance's view tree               
        placeholder.sizeToFit()          // Constrain to fit inside parent text view
        placeholder.tintColor = UIColor.clear // Unused in textviews. Can host our 'tag'
        placeholder.frame.origin = CGPoint(x: 5, y: 0) // Don't cover I-beam cursor
        placeholder.delegate = delegate  // Use as cache for caller's delegate 
        placeholder.font = UIFont.italicSystemFont(ofSize: (self.font?.pointSize)!)
        placeholder.text = placeholderText
        placeholder.textColor = color
    }

      
    func findPlaceholder() -> UITextView? { // find placeholder by its tag 
        for subview in self.subviews {
            if let textview = subview as? UITextView {
                if textview.tintColor == UIColor.clear { // sneaky tagging scheme
                    return textview
                }
            }
        }
        return nil
    }
     
    /* 
     * Safely daisychain to caller delegate methods as appropriate...
     */

    public func textViewDidChange(_ textView: UITextView) { // ?  need this delegate method
        if let placeholder = findPlaceholder() {
            placeholder.isHidden = !self.text.isEmpty // ? ... to do this
            placeholder.delegate?.textViewDidChange?(textView)
        } 
    }

    /* 
     * Since we're becoming a delegate on behalf of this placeholder-enabled
     * text view instance, we must forward *all* that protocol's activity expected
     * by the instance, not just the particular optional protocol method we need to
     * intercept, above.
     */

    public func textViewDidEndEditing(_ textView: UITextView) {
        if let placeholder = findPlaceholder() {
            placeholder.delegate?.textViewDidEndEditing?(textView)
        } 
    }

    public func textViewDidBeginEditing(_ textView: UITextView) {
        if let placeholder = findPlaceholder() {
            placeholder.delegate?.textViewDidBeginEditing?(textView)
        } 
    }

    public  func textViewDidChangeSelection(_ textView: UITextView) {
        if let placeholder = findPlaceholder() {
            placeholder.delegate?.textViewDidChangeSelection?(textView)
        } 
    }

    public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
        if let placeholder = findPlaceholder() {
            guard let retval = placeholder.delegate?.textViewShouldEndEditing?(textView) else {
                return true
            }
            return retval
        }
        return true
    }

    public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        if let placeholder = findPlaceholder() {
            guard let retval = placeholder.delegate?.textViewShouldBeginEditing?(textView) else {
                return true
            }
            return retval
        } 
        return true
    }

    public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if let placeholder = findPlaceholder() {
            guard let retval = placeholder.delegate?.textView?(textView, shouldChangeTextIn: range, replacementText: text) else {
                return true
            }
            return retval
        } 
        return true
    }

    public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if let placeholder = findPlaceholder() {
                guard let retval = placeholder.delegate?.textView?(textView, shouldInteractWith: URL, in: characterRange, interaction:
                    interaction) else {
                        return true
            }
            return retval
        }
        return true
    }

    public func textView(_ textView: UITextView, shouldInteractWith textAttachment: NSTextAttachment, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        if let placeholder = findPlaceholder() {
            guard let retval = placeholder.delegate?.textView?(textView, shouldInteractWith: textAttachment, in: characterRange, interaction: interaction) else {
                return true
            }
            return retval
        }
        return true
    }
}

1. As an extension of an essential iOS class like UITextView, it's important to know that this code has no interaction with any textviews that don't activate a placeholder, e.g textview instances that haven't been initialized with a call addPlaceholder()

2. Placeholder-enabled text views transparently become a UITextViewDelegate to track character count, in order to control placeholder visibility. If a delegate is passed to addPlaceholder(), this code daisy-chains (i.e. forwards) delegate callbacks to that delegate.

3. The author is investigating ways to inspect the UITextViewDelegate protocol and proxy it automatically without having to hardcode each method. That would inoculate the code from method signature changes and new methods being added to the protocol.

HTML5 iFrame Seamless Attribute

Updated: October 2016

The seamless attribute no longer exists. It was originally pitched to be included in the first HTML5 spec, but subsequently dropped. An unrelated attribute of the same name made a brief cameo in the HTML5.1 draft, but that too was ditched mid-2016:

So I think the gist of it all both from the implementor side and the web-dev side is that seamless as-specced doesn’t seem to be what anybody wanted to begin with. Or at least it’s more than anybody actually wanted. And anyway like @annevk says, it’s seems a lot of it’s since been “overcome by events” in light of Shadow DOM.

In other words: purge the seamless attribute from your memory, and pretend it never existed.

For posterity's sake, here's my original answer from five years ago:

Original answer: April 2011

The attribute is in draft mode at the moment. For that reason, none of the current browsers are supporting it yet (as the implementation is subject to change). In the meantime, it's best just to use CSS to strip the borders/scrollbars from the iframe:

iframe[seamless]{
    background-color: transparent;
    border: 0px none transparent;
    padding: 0px;
    overflow: hidden;
}

There's more to the seamless attribute than what can be added with CSS: part of the reasoning behind the attribute was to allow nested content to inherit the same styles applied to the iframe (acting as though the embedded document was one big nested inside the element, for example).

Lastly, versions of Internet Explorer (8 and earlier) require additional attributes in order to remove the borders, scrollbars and background colour:

<iframe frameborder="0" allowtransparency="true" scrolling="no" src="..."></iframe>

Naturally, this doesn't validate. So it's up to you how to handle it. My (picky) approach would be to sniff the agent string and add the attributes for IE versions earlier than 9.

Hope that helps. :)

How to read a file into a variable in shell?

In cross-platform, lowest-common-denominator sh you use:

#!/bin/sh
value=`cat config.txt`
echo "$value"

In bash or zsh, to read a whole file into a variable without invoking cat:

#!/bin/bash
value=$(<config.txt)
echo "$value"

Invoking cat in bash or zsh to slurp a file would be considered a Useless Use of Cat.

Note that it is not necessary to quote the command substitution to preserve newlines.

See: Bash Hacker's Wiki - Command substitution - Specialities.

JavaScript getElementByID() not working

At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload maybe. Something like this:

<html>
<head>
    <title></title>
    <script type="text/javascript">
        window.onload = function(){
           var refButton = document.getElementById("btnButton");

            refButton.onclick = function() {
                alert('I am clicked!');
            }
        };
    </script>
</head>
<body>
    <form id="form1">
    <div>
        <input id="btnButton" type="button" value="Click me"/>
    </div>
    </form>
</body>
</html>

How to specify preference of library path?

Add the path to where your new library is to LD_LIBRARY_PATH (it has slightly different name on Mac ...)

Your solution should work with using the -L/my/dir -lfoo options, at runtime use LD_LIBRARY_PATH to point to the location of your library.

Careful with using LD_LIBRARY_PATH - in short (from link):

..implications..:
Security: Remember that the directories specified in LD_LIBRARY_PATH get searched before(!) the standard locations? In that way, a nasty person could get your application to load a version of a shared library that contains malicious code! That’s one reason why setuid/setgid executables do neglect that variable!
Performance: The link loader has to search all the directories specified, until it finds the directory where the shared library resides – for ALL shared libraries the application is linked against! This means a lot of system calls to open(), that will fail with “ENOENT (No such file or directory)”! If the path contains many directories, the number of failed calls will increase linearly, and you can tell that from the start-up time of the application. If some (or all) of the directories are in an NFS environment, the start-up time of your applications can really get long – and it can slow down the whole system!
Inconsistency: This is the most common problem. LD_LIBRARY_PATH forces an application to load a shared library it wasn’t linked against, and that is quite likely not compatible with the original version. This can either be very obvious, i.e. the application crashes, or it can lead to wrong results, if the picked up library not quite does what the original version would have done. Especially the latter is sometimes hard to debug.

OR

Use the rpath option via gcc to linker - runtime library search path, will be used instead of looking in standard dir (gcc option):

-Wl,-rpath,$(DEFAULT_LIB_INSTALL_PATH)

This is good for a temporary solution. Linker first searches the LD_LIBRARY_PATH for libraries before looking into standard directories.

If you don't want to permanently update LD_LIBRARY_PATH you can do it on the fly on command line:

LD_LIBRARY_PATH=/some/custom/dir ./fooo

You can check what libraries linker knows about using (example):

/sbin/ldconfig -p | grep libpthread
        libpthread.so.0 (libc6, OS ABI: Linux 2.6.4) => /lib/libpthread.so.0

And you can check which library your application is using:

ldd foo
        linux-gate.so.1 =>  (0xffffe000)
        libpthread.so.0 => /lib/libpthread.so.0 (0xb7f9e000)
        libxml2.so.2 => /usr/lib/libxml2.so.2 (0xb7e6e000)
        librt.so.1 => /lib/librt.so.1 (0xb7e65000)
        libm.so.6 => /lib/libm.so.6 (0xb7d5b000)
        libc.so.6 => /lib/libc.so.6 (0xb7c2e000)
        /lib/ld-linux.so.2 (0xb7fc7000)
        libdl.so.2 => /lib/libdl.so.2 (0xb7c2a000)
        libz.so.1 => /lib/libz.so.1 (0xb7c18000)

What regular expression will match valid international phone numbers?

You can use the library libphonenumber from Google.

PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
String decodedNumber = null;
PhoneNumber number;
    try {
        number = phoneNumberUtil.parse(encodedHeader, null);
        decodedNumber = phoneNumberUtil.format(number, PhoneNumberFormat.E164);
    } catch (NumberParseException e) {
        e.printStackTrace();
    }

Java - Abstract class to contain variables?

Of course. The whole idea of abstract classes is that they can contain some behaviour or data which you require all sub-classes to contain. Think of the simple example of WheeledVehicle - it should have a numWheels member variable. You want all sub classes to have this variable. Remember that abstract classes are a very useful feature when developing APIs, as they can ensure that people who extend your API won't break it.

What's the default password of mariadb on fedora?

mariadb uses by defaults UNIX_SOCKET plugin to authenticate user root. https://mariadb.com/kb/en/mariadb/unix_socket-authentication-plugin/

"Because he has identified himself to the operating system, he does not need to do it again for the database"

so you need to login as the root user on unix to login as root in mysql/mariadb:

sudo mysql

if you want to login with root from your normal unix user, you can disable the authentication plugin for root.

Beforehand you can set the root password with mysql_secure_installation (default password is blank), then to let every user authenticate as root login with:

shell$ sudo mysql -u root
[mysql] use mysql;
[mysql] update user set plugin='' where User='root';
[mysql] flush privileges;
[mysql] \q

What is the meaning of Bus: error 10 in C

Your code attempts to overwrite a string literal. This is undefined behaviour.

There are several ways to fix this:

  1. use malloc() then strcpy() then free();
  2. turn str into an array and use strcpy();
  3. use strdup().

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

I recently had this problem as I was moving from Putty for Linux to Remmina for Linux. So I have a lot of PPK files for Putty in my .putty directory as I've been using it's for 8 years. For this I used a simple for command for bash shell to do all files:

cd ~/.putty
for X in *.ppk; do puttygen $X -L > ~/.ssh/$(echo $X | sed 's,./,,' | sed 's/.ppk//g').pub; puttygen $X -O private-openssh -o ~/.ssh/$(echo $X | sed 's,./,,' | sed 's/.ppk//g').pvk; done;

Very quick and to the point, got the job done for all files that putty had. If it finds a key with a password it will stop and ask for the password for that key first and then continue.

How to set JAVA_HOME in Mac permanently?

Declare two export inside your .bashrc or .zshrc:

export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8) 
export JAVA_11_HOME=$(/usr/libexec/java_home -v11)

Add alias for quick change:

alias java8='export JAVA_HOME=$JAVA_8_HOME'
alias java11='export JAVA_HOME=$JAVA_11_HOME'

set default to Java 11

java11

export PATH

export PATH=$JAVA_HOME/bin:$PATH

you could change java11 by java8 inside your .bashrc/zshrc file to change permanently your java version

Get image dimensions

You can use the getimagesize function like this:

list($width, $height) = getimagesize('path to image');
echo "width: " . $width . "<br />";
echo "height: " .  $height;

OAuth2 and Google API: access token expiration time?

The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time

Convert XML String to Object

Simply Run Your Visual Studio 2013 as Administration ... Copy the content of your Xml file.. Go to Visual Studio 2013 > Edit > Paste Special > Paste Xml as C# Classes It will create your c# classes according to your Xml file content.

C++ printing spaces or tabs given a user input integer

cout << "Enter amount of spaces you would like (integer)" << endl; 
cin >> n;
//print n spaces
for (int i = 0; i < n; ++i)
{
   cout << " " ;
}
cout <<endl;

Get the data received in a Flask request

Here's an example of posting form data to add a user to a database. Check request.method == "POST" to check if the form was submitted. Use keys from request.form to get the form data. Render an HTML template with a <form> otherwise. The fields in the form should have name attributes that match the keys in request.form.

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route("/user/add", methods=["GET", "POST"])
def add_user():
    if request.method == "POST":
        user = User(
            username=request.form["username"],
            email=request.form["email"],
        )
        db.session.add(user)
        db.session.commit()
        return redirect(url_for("index"))

    return render_template("add_user.html")
<form method="post">
    <label for="username">Username</label>
    <input type="text" name="username" id="username">
    <label for="email">Email</label>
    <input type="email" name="email" id="email">
    <input type="submit">
</form>

How to hide Soft Keyboard when activity starts

If your application is targeting Android API Level 21 or more than there is a default method available.

editTextObj.setShowSoftInputOnFocus(false);

Make sure you have set below code in EditText XML tag.

<EditText  
    ....
    android:enabled="true"
    android:focusable="true" />

Get Application Directory

There is a simpler way to get the application data directory with min API 4+. From any Context (e.g. Activity, Application):

getApplicationInfo().dataDir

http://developer.android.com/reference/android/content/Context.html#getApplicationInfo()

Pandas - Compute z-score for all columns

The almost one-liner solution:

df2 = (df.ix[:,1:] - df.ix[:,1:].mean()) / df.ix[:,1:].std()
df2['ID'] = df['ID']

converting Java bitmap to byte array

Try this to convert String-Bitmap or Bitmap-String

/**
 * @param bitmap
 * @return converting bitmap and return a string
 */
public static String BitMapToString(Bitmap bitmap){
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
    byte [] b=baos.toByteArray();
    String temp=Base64.encodeToString(b, Base64.DEFAULT);
    return temp;
}

/**
 * @param encodedString
 * @return bitmap (from given string)
 */
public static Bitmap StringToBitMap(String encodedString){
    try{
        byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
        Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        return bitmap;
    }catch(Exception e){
        e.getMessage();
        return null;
    }
}

SQL: how to use UNION and order by a specific select?

@Adrien's answer is not working. It gives an ORA-01791.

The correct answer (for the question that is asked) should be:

select id
from 
 (SELECT id, 2 as ordered FROM a -- returns 1,4,2,3
  UNION ALL
  SELECT id, 1 as ordered FROM b -- returns 2,1
  )
group by id
order by min(ordered)

Explanation:

  1. The "UNION ALL" is combining the 2 sets. A "UNION" is wastefull because the 2 sets could not be the same, because the ordered field is different.
  2. The "group by" is then eliminating duplicates
  3. The "order by min (ordered)" is assuring the elements of table b are first

This solves all the cases, even when table b has more or different elements then table a

is of a type that is invalid for use as a key column in an index

Noting klaisbyskov's comment about your key length needing to be gigabytes in size, and assuming that you do in fact need this, then I think your only options are:

  1. use a hash of the key value
    • Create a column on nchar(40) (for a sha1 hash, for example),
    • put a unique key on the hash column.
    • generate the hash when saving or updating the record
  2. triggers to query the table for an existing match on insert or update.

Hashing comes with the caveat that one day, you might get a collision.

Triggers will scan the entire table.

Over to you...

Attribute Error: 'list' object has no attribute 'split'

I think you've actually got a wider confusion here.

The initial error is that you're trying to call split on the whole list of lines, and you can't split a list of strings, only a string. So, you need to split each line, not the whole thing.

And then you're doing for points in Type, and expecting each such points to give you a new x and y. But that isn't going to happen. Types is just two values, x and y, so first points will be x, and then points will be y, and then you'll be done. So, again, you need to loop over each line and get the x and y values from each line, not loop over a single Types from a single line.

So, everything has to go inside a loop over every line in the file, and do the split into x and y once for each line. Like this:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")

    for line in readfile:
        Type = line.split(",")
        x = Type[1]
        y = Type[2]
        print(x,y)

getQuakeData()

As a side note, you really should close the file, ideally with a with statement, but I'll get to that at the end.


Interestingly, the problem here isn't that you're being too much of a newbie, but that you're trying to solve the problem in the same abstract way an expert would, and just don't know the details yet. This is completely doable; you just have to be explicit about mapping the functionality, rather than just doing it implicitly. Something like this:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")
    readlines = readfile.readlines()
    Types = [line.split(",") for line in readlines]
    xs = [Type[1] for Type in Types]
    ys = [Type[2] for Type in Types]
    for x, y in zip(xs, ys):
        print(x,y)

getQuakeData()

Or, a better way to write that might be:

def getQuakeData():
    filename = input("Please enter the quake file: ")
    # Use with to make sure the file gets closed
    with open(filename, "r") as readfile:
        # no need for readlines; the file is already an iterable of lines
        # also, using generator expressions means no extra copies
        types = (line.split(",") for line in readfile)
        # iterate tuples, instead of two separate iterables, so no need for zip
        xys = ((type[1], type[2]) for type in types)
        for x, y in xys:
            print(x,y)

getQuakeData()

Finally, you may want to take a look at NumPy and Pandas, libraries which do give you a way to implicitly map functionality over a whole array or frame of data almost the same way you were trying to.

Difference between HttpModule and HttpClientModule

This is a good reference, it helped me switch my http requests to httpClient.

It compares the two in terms of differences and gives code examples.

This is just a few differences I dealt with while changing services to httpclient in my project (borrowing from the article I mentioned) :

Importing

import {HttpModule} from '@angular/http';
import {HttpClientModule} from '@angular/common/http';

Requesting and parsing response:

@angular/http

 this.http.get(url)
      // Extract the data in HTTP Response (parsing)
      .map((response: Response) => response.json() as GithubUser)
      .subscribe((data: GithubUser) => {
        // Display the result
        console.log('TJ user data', data);
      });

@angular/common/http

 this.http.get(url)
      .subscribe((data: GithubUser) => {
        // Data extraction from the HTTP response is already done
        // Display the result
        console.log('TJ user data', data);
      });

Note: You no longer have to extract the returned data explicitly; by default, if the data you get back is type of JSON, then you don't have to do anything extra.

But, if you need to parse any other type of response like text or blob, then make sure you add the responseType in the request. Like so:

Making the GET HTTP request with responseType option:

 this.http.get(url, {responseType: 'blob'})
      .subscribe((data) => {
        // Data extraction from the HTTP response is already done
        // Display the result
        console.log('TJ user data', data);
      });

Adding Interceptor

I also used interceptors for adding the token for my authorization to every request, reference.

like so:

@Injectable()
export class MyFirstInterceptor implements HttpInterceptor {

    constructor(private currentUserService: CurrentUserService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        // get the token from a service
        const token: string = this.currentUserService.token;

        // add it if we have one
        if (token) {
            req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
        }

        // if this is a login-request the header is 
        // already set to x/www/formurl/encoded. 
        // so if we already have a content-type, do not 
        // set it, but if we don't have one, set it to 
        // default --> json
        if (!req.headers.has('Content-Type')) {
            req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
        }

        // setting the accept header
        req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
        return next.handle(req);
    }
}

Its a pretty nice upgrade!