Programs & Examples On #Mysql5

The MySQL™ software delivers a very fast, multi-threaded, multi-user, and robust SQL (Structured Query Language) database server.

Can't connect to MySQL server on 'localhost' (10061)

Edit your 'my-default.ini' file (by default it comes with commented properties)as below ie.

basedir=D:/D_Drive/mysql-5.6.20-win32
datadir=D:/D_Drive/mysql-5.6.20-win32/data
port=8888

There is very good article present that dictates commands to create user, browse tables etc ie.

http://www.ntu.edu.sg/home/ehchua/programming/sql/MySQL_HowTo.html#zz-3.1

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

Set your PRIMARY KEY as AUTO_INCREMENT.

How to get a list of user accounts using the command line in MySQL?

Peter and Jesse are correct but just make sure you first select the mysql DB.

use mysql;
select User from mysql.user;

that should do your trick

Are table names in MySQL case sensitive?

  1. Locate the file at /etc/mysql/my.cnf

  2. Edit the file by adding the following lines:

     [mysqld]
    
     lower_case_table_names=1
    
  3. sudo /etc/init.d/mysql restart

  4. Run mysqladmin -u root -p variables | grep table to check that lower_case_table_names is 1 now

You might need to recreate these tables to make it work.

Javascript reduce() on Object

You can use a generator expression (supported in all browsers for years now, and in Node) to get the key-value pairs in a list you can reduce on:

>>> a = {"b": 3}
Object { b=3}

>>> [[i, a[i]] for (i in a) if (a.hasOwnProperty(i))]
[["b", 3]]

Change the location of an object programmatically

You need to pass the whole point to location

var point = new Point(50, 100);
this.balancePanel.Location = point;

Get name of current script in Python

My fast dirty solution:

__file__.split('/')[-1:][0]

jQuery selector for inputs with square brackets in the name attribute

Just separate it with different quotes:

<input name="myName[1][data]" value="myValue">

JQuery:

var value = $('input[name="myName[1][data]"]').val();

Deleting specific rows from DataTable

DataRow[] dtr=dtPerson.select("name=Joe");
foreach(var drow in dtr)
{
   drow.delete();
}
dtperson.AcceptChanges();

I hope it will help you

Retrofit and GET using parameters

Complete working example in Kotlin, I have replaced my API keys with 1111...

        val apiService = API.getInstance().retrofit.create(MyApiEndpointInterface::class.java)
        val params = HashMap<String, String>()
        params["q"] =  "munich,de"
        params["APPID"] = "11111111111111111"

        val call = apiService.getWeather(params)

        call.enqueue(object : Callback<WeatherResponse> {
            override fun onFailure(call: Call<WeatherResponse>?, t: Throwable?) {
                Log.e("Error:::","Error "+t!!.message)
            }

            override fun onResponse(call: Call<WeatherResponse>?, response: Response<WeatherResponse>?) {
                if (response != null && response.isSuccessful && response.body() != null) {
                    Log.e("SUCCESS:::","Response "+ response.body()!!.main.temp)

                    temperature.setText(""+ response.body()!!.main.temp)

                }
            }

        })

jQuery: Selecting by class and input type

Try this:

$("input:checkbox").hasClass("myClass");

Scale Image to fill ImageView width and keep aspect ratio

This will not be applicable if you set image as background in ImageView, need to set at src(android:src).

Thanks.

How do I round a double to two decimal places in Java?

You can't 'round a double to [any number of] decimal places', because doubles don't have decimal places. You can convert a double to a base-10 String with N decimal places, because base-10 does have decimal places, but when you convert it back you are back in double-land, with binary fractional places.

addEventListener vs onclick

As far as I know, the DOM "load" event still does only work very limited. That means it'll only fire for the window object, images and <script> elements for instance. The same goes for the direct onload assignment. There is no technical difference between those two. Probably .onload = has a better cross-browser availabilty.

However, you cannot assign a load event to a <div> or <span> element or whatnot.

How to access session variables from any class in ASP.NET?

In asp.net core this works differerently:

public class SomeOtherClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private ISession _session => _httpContextAccessor.HttpContext.Session;

    public SomeOtherClass(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void TestSet()
    {
        _session.SetString("Test", "Ben Rules!");
    }

    public void TestGet()
    {
        var message = _session.GetString("Test");
    }
}

Source: https://benjii.me/2016/07/using-sessions-and-httpcontext-in-aspnetcore-and-mvc-core/

How can I include css files using node, express, and ejs?

In your app or server.js file include this line:

app.use(express.static('public'));

In your index.ejs, following line will help you:

<link rel="stylesheet" type="text/css" href="/css/style.css" />

I hope this helps, it did for me!

AttributeError: 'str' object has no attribute 'append'

What you are trying to do is add additional information to each item in the list that you already created so

    alist[ 'from form', 'stuff 2', 'stuff 3']

    for j in range( 0,len[alist]):
        temp= []
        temp.append(alist[j]) # alist[0] is 'from form' 
        temp.append('t') # slot for first piece of data 't'
        temp.append('-') # slot for second piece of data

    blist.append(temp)      # will be alist with 2 additional fields for extra stuff assocated with each item in alist  

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

What is the HTML tabindex attribute?

tabindex is a global attribute responsible for two things:

  1. it sets the order of "focusable" elements and
  2. it makes elements "focusable".

In my mind the second thing is even more important than the first one. There are very few elements that are focusable by default (e.g. <a> and form controls). Developers very often add some JavaScript event handlers (like 'onclick') on not focusable elements (<div>, <span> and so on), and the way to make your interface be responsive not only to mouse events but also to keyboard events (e.g. 'onkeypress') is to make such elements focusable. Lastly, if you don't want to set the order but just make your element focusable use tabindex="0" on all such elements:

<div tabindex="0"></div>

Also, if you don't want it to be focusable via the tab key then use tabindex="-1". For example, the below link will not be focused while using tab keys to traverse.

<a href="#" tabindex="-1">Tab key cannot reach here!</a>

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

For me it was because only Windows Authentication was enabled. To change security authentication mode. In SQL Server Management Studio Object Explorer, right-click the server, and then click Properties. On the Security page, under Server authentication, select the new server authentication mode, and then click OK. Change Server Authentication Mode - MSDN - Microsoft https://msdn.microsoft.com/en-AU/library/ms188670.aspx

Comparing Class Types in Java

As said earlier, your code will work unless you have the same classes loaded on two different class loaders. This might happen in case you need multiple versions of the same class in memory at the same time, or you are doing some weird on the fly compilation stuff (as I am).

In this case, if you want to consider these as the same class (which might be reasonable depending on the case), you can match their names to compare them.

public static boolean areClassesQuiteTheSame(Class<?> c1, Class<?> c2) {
  // TODO handle nulls maybe?
  return c1.getCanonicalName().equals(c2.getCanonicalName());
}

Keep in mind that this comparison will do just what it does: compare class names; I don't think you will be able to cast from one version of a class to the other, and before looking into reflection, you might want to make sure there's a good reason for your classloader mess.

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

I'd create a cte and do an inner join. It's not efficient but it's convenient

with table as (
SELECT DATE, STATUS, TITLE, ROW_NUMBER() 
OVER (PARTITION BY DATE, STATUS,  TITLE ORDER BY QUANTITY ASC) AS Row_Num
 FROM TABLE)

select *

from table t
join select(
max(Row_Num) as Row_Num
,DATE
,STATUS
,TITLE
from table 
group by date, status, title) t2  
on t2.Row_Num = t.Row_Num and t2
and t2.date = t.date
and t2.title = t.title

ssh: The authenticity of host 'hostname' can't be established

Ideally, you should create a self-managed certificate authority. Start with generating a key pair: ssh-keygen -f cert_signer

Then sign each server's public host key: ssh-keygen -s cert_signer -I cert_signer -h -n www.example.com -V +52w /etc/ssh/ssh_host_rsa_key.pub

This generates a signed public host key: /etc/ssh/ssh_host_rsa_key-cert.pub

In /etc/ssh/sshd_config, point the HostCertificate to this file: HostCertificate /etc/ssh/ssh_host_rsa_key-cert.pub

Restart the sshd service: service sshd restart

Then on the SSH client, add the following to ~/.ssh/known_hosts: @cert-authority *.example.com ssh-rsa AAAAB3Nz...cYwy+1Y2u/

The above contains:

  • @cert-authority
  • The domain *.example.com
  • The full contents of the public key cert_signer.pub

The cert_signer public key will trust any server whose public host key is signed by the cert_signer private key.

Although this requires a one-time configuration on the client side, you can trust multiple servers, including those that haven't been provisioned yet (as long as you sign each server, that is).

For more details, see this wiki page.

HTML img scaling

css is enough :

width : desired_width;
height: auto;/*to preserve the aspect ratio of the image*/

RecyclerView expand/collapse items

For this, just needed simple lines not complicated

in your onBindViewHolder method add below code

final boolean isExpanded = position==mExpandedPosition;
holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        mExpandedPosition = isExpanded ? -1:position;
        notifyItemChanged(position);
    }
});

mExpandedPosition is an int global variable initialized to -1

For those who want only one item expanded and others get collapsed. Use this

first declare a global variable with previousExpandedPosition = -1

then

    final boolean isExpanded = position==mExpandedPosition;
    holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
    holder.itemView.setActivated(isExpanded);

    if (isExpanded)
       previousExpandedPosition = position;

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mExpandedPosition = isExpanded ? -1:position;
            notifyItemChanged(previousExpandedPosition);
            notifyItemChanged(position);
        }
    });

Done!!!. Simple and humble .. :)

How to embed new Youtube's live video permanent URL?

Have you tried plugin called " Youtube Live Stream Auto Embed"

Its seems to be working. Check it once.

CMD: Export all the screen content to a text file

How about this:

<command> > <filename.txt> & <filename.txt>

Example:

ipconfig /all > network.txt & network.txt

This will give the results in Notepad instead of the command prompt.

Java : How to determine the correct charset encoding of a stream

You cannot determine the encoding of a arbitrary byte stream. This is the nature of encodings. A encoding means a mapping between a byte value and its representation. So every encoding "could" be the right.

The getEncoding() method will return the encoding which was set up (read the JavaDoc) for the stream. It will not guess the encoding for you.

Some streams tell you which encoding was used to create them: XML, HTML. But not an arbitrary byte stream.

Anyway, you could try to guess an encoding on your own if you have to. Every language has a common frequency for every char. In English the char e appears very often but ê will appear very very seldom. In a ISO-8859-1 stream there are usually no 0x00 chars. But a UTF-16 stream has a lot of them.

Or: you could ask the user. I've already seen applications which present you a snippet of the file in different encodings and ask you to select the "correct" one.

how to convert .java file to a .class file

To get a .class file you have to compile the .java file.

The command for this is javac. The manual for this is found here (Windows)

In short:

javac File.java

SQLite error 'attempt to write a readonly database' during insert?

I used:

echo exec('whoami');

to find out who is running the script (say username), and then gave the user permissions to the entire application directory, like:

sudo chown -R :username /var/www/html/myapp

Hope this helps someone out there.

How to use FormData for AJAX file upload?

For correct form data usage you need to do 2 steps.

Preparations

You can give your whole form to FormData() for processing

var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);

or specify exact data for FormData()

var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]); 

Sending form

Ajax request with jquery will looks like this:

$.ajax({
    url: 'Your url here',
    data: formData,
    type: 'POST',
    contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
    processData: false, // NEEDED, DON'T OMIT THIS
    // ... Other options like success and etc
});

After this it will send ajax request like you submit regular form with enctype="multipart/form-data"

Update: This request cannot work without type:"POST" in options since all files must be sent via POST request.

Note: contentType: false only available from jQuery 1.6 onwards

Get program execution time in the shell

If you only need precision to the second, you can use the builtin $SECONDS variable, which counts the number of seconds that the shell has been running.

while true; do
    start=$SECONDS
    some_long_running_command
    duration=$(( SECONDS - start ))
    echo "This run took $duration seconds"
    if some_condition; then break; fi
done

getResourceAsStream returns null

So there are several ways to get a resource from a jar and each has slightly different syntax where the path needs to be specified differently.

The best explanation I have seen is this article from InfoWorld. I'll summarize here, but if you want to know more you should check out the article.

Methods

  1. ClassLoader.getResourceAsStream().

Format: "/"-separated names; no leading "/" (all names are absolute).

Example: this.getClass().getClassLoader().getResourceAsStream("some/pkg/resource.properties");

  1. Class.getResourceAsStream()

Format: "/"-separated names; leading "/" indicates absolute names; all other names are relative to the class's package

Example: this.getClass().getResourceAsStream("/some/pkg/resource.properties");

Updated Sep 2020: Changed article link. Original article was from Javaworld, it is now hosted on InfoWorld (and has many more ads)

Subset and ggplot2

Try filter to subset only the rows of P1 and P3

df2 <- filter(df, ID == "P1" | ID == "P3")

Than yo can plot Value1. vs Value2.

Question mark characters displaying within text, why is this?

Unicode or other character set characters falling through?

I have seen similar "strange" characters show up on sites I have worked on often when the text is copied from an email or some other document format (e.g. word) into a text editor. The editor can display the non ASCII characters but the browser can't. For the website, I would suggest looking up the HTML entity code for the character and inserting that instead ... or switch to more standard ones.

Force DOM redraw/refresh on Chrome/Mac

I ran into a similar issue and this simple line of JS helped to fix it:

document.getElementsByTagName('body')[0].focus();

In my case it was a bug with a Chrome extension not redrawing the page after changing its CSS from within the extension.

How to configure socket connect timeout

There should be a ReceiveTimeout property in the Socket class.

Socket.ReceiveTimeout Property

Clearing content of text file using php

//create a file handler by opening the file
$myTextFileHandler = @fopen("filelist.txt","r+");

//truncate the file to zero
//or you could have used the write method and written nothing to it
@ftruncate($myTextFileHandler, 0);

//use location header to go back to index.html
header("Location:index.html");

I don't exactly know where u want to show the result.

Why es6 react component works only with "export default"?

Add { } while importing and exporting: export { ... }; | import { ... } from './Template';

exportimport { ... } from './Template'

export defaultimport ... from './Template'


Here is a working example:

// ExportExample.js
import React from "react";

function DefaultExport() {
  return "This is the default export";
}

function Export1() {
  return "Export without default 1";
}

function Export2() {
  return "Export without default 2";
}

export default DefaultExport;
export { Export1, Export2 };

// App.js
import React from "react";
import DefaultExport, { Export1, Export2 } from "./ExportExample";

export default function App() {
  return (
    <>
      <strong>
        <DefaultExport />
      </strong>
      <br />
      <Export1 />
      <br />
      <Export2 />
    </>
  );
}

??Working sandbox to play around: https://codesandbox.io/s/export-import-example-react-jl839?fontsize=14&hidenavigation=1&theme=dark

What is Java Servlet?

A servlet is simply a class which responds to a particular type of network request - most commonly an HTTP request. Basically servlets are usually used to implement web applications - but there are also various frameworks which operate on top of servlets (e.g. Struts) to give a higher-level abstraction than the "here's an HTTP request, write to this HTTP response" level which servlets provide.

Servlets run in a servlet container which handles the networking side (e.g. parsing an HTTP request, connection handling etc). One of the best-known open source servlet containers is Tomcat.

Using C# to read/write Excel files (.xls/.xlsx)

I'm a big fan of using EPPlus to perform these types of actions. EPPlus is a library you can reference in your project and easily create/modify spreadsheets on a server. I use it for any project that requires an export function.

Here's a nice blog entry that shows how to use the library, though the library itself should come with some samples that explain how to use it.

Third party libraries are a lot easier to use than Microsoft COM objects, in my opinion. I would suggest giving it a try.

Importing JSON into an Eclipse project

on linux pip install library_that_you_need Also on Help/Eclipse MarketPlace, i add PyDev IDE for Eclipse 7, so when i start a new project i create file/New Project/Pydev Project

How to stretch a table over multiple pages

You should \usepackage{longtable}.

Rewrite all requests to index.php with nginx

Here is what worked for me to solve part 1 of this question:

    location / {
            rewrite ^([^.]*[^/])$ $1/ permanent;
            try_files $uri $uri/ /index.php =404;
            include fastcgi_params;
            fastcgi_pass php5-fpm-sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_intercept_errors on;
    }

rewrite ^([^.]*[^/])$ $1/ permanent; rewrites non-file addresses (addresses without file extensions) to have a "/" at the end. I did this because I was running into "Access denied." message when I tried to access the folder without it.

try_files $uri $uri/ /index.php =404; is borrowed from SanjuD's answer, but with an extra 404 reroute if the location still isn't found.

fastcgi_index index.php; was the final piece of the puzzle that I was missing. The folder didn't reroute to the index.php without this line.

Android: ListView elements with multiple clickable buttons

Isn't the platform solution for this implementation to use a context menu that shows on a long press?

Is the question author aware of context menus? Stacking up buttons in a listview has performance implications, will clutter your UI and violate the recommended UI design for the platform.

On the flipside; context menus - by nature of not having a passive representation - are not obvious to the end user. Consider documenting the behaviour?

This guide should give you a good start.

http://www.mikeplate.com/2010/01/21/show-a-context-menu-for-long-clicks-in-an-android-listview/

The entity type <type> is not part of the model for the current context

For me the issue was that I had not included the Entity Class within my db set inside the context for entity framework.

public DbSet<ModelName> ModelName { get; set; }

How can I show data using a modal when clicking a table row (using bootstrap)?

One thing you can do is get rid of all those onclick attributes and do it the right way with bootstrap. You don't need to open them manually; you can specify the trigger and even subscribe to events before the modal opens so that you can do your operations and populate data in it.

I am just going to show as a static example which you can accommodate in your real world.

On each of your <tr>'s add a data attribute for id (i.e. data-id) with the corresponding id value and specify a data-target, which is a selector you specify, so that when clicked, bootstrap will select that element as modal dialog and show it. And then you need to add another attribute data-toggle=modal to make this a trigger for modal.

  <tr data-toggle="modal" data-id="1" data-target="#orderModal">
            <td>1</td>
            <td>24234234</td>
            <td>A</td>
  </tr>
  <tr data-toggle="modal" data-id="2" data-target="#orderModal">
            <td>2</td>
            <td>24234234</td>
            <td>A</td>
        </tr>
  <tr data-toggle="modal" data-id="3" data-target="#orderModal">
            <td>3</td>
            <td>24234234</td>
            <td>A</td>
  </tr>

And now in the javascript just set up the modal just once and event listen to its events so you can do your work.

$(function(){
    $('#orderModal').modal({
        keyboard: true,
        backdrop: "static",
        show:false,

    }).on('show', function(){ //subscribe to show method
          var getIdFromRow = $(event.target).closest('tr').data('id'); //get the id from tr
        //make your ajax call populate items or what even you need
        $(this).find('#orderDetails').html($('<b> Order Id selected: ' + getIdFromRow  + '</b>'))
    });
});

Demo

Do not use inline click attributes any more. Use event bindings instead with vanilla js or using jquery.

Alternative ways here:

Demo2 or Demo3

How can I convert a Unix timestamp to DateTime and vice versa?

The latest version of .NET (v4.6) has added built-in support for Unix time conversions. That includes both to and from Unix time represented by either seconds or milliseconds.

  • Unix time in seconds to UTC DateTimeOffset:

DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(1000);
  • DateTimeOffset to Unix time in seconds:

long unixTimeStampInSeconds = dateTimeOffset.ToUnixTimeSeconds();
  • Unix time in milliseconds to UTC DateTimeOffset:

DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1000000);
  • DateTimeOffset to Unix time in milliseconds:

long unixTimeStampInMilliseconds = dateTimeOffset.ToUnixTimeMilliseconds();

Note: These methods convert to and from a UTC DateTimeOffset. To get a DateTime representation simply use the DateTimeOffset.UtcDateTime or DateTimeOffset.LocalDateTime properties:

DateTime dateTime = dateTimeOffset.UtcDateTime;

Parsing HTML using Python

Compared to the other parser libraries lxml is extremely fast:

And with cssselect it’s quite easy to use for scraping HTML pages too:

from lxml.html import parse
doc = parse('http://www.google.com').getroot()
for div in doc.cssselect('a'):
    print '%s: %s' % (div.text_content(), div.get('href'))

lxml.html Documentation

how to get vlc logs?

I found the following command to run from command line:

vlc.exe --extraintf=http:logger --verbose=2 --file-logging --logfile=vlc-log.txt

How can I change or remove HTML5 form validation default error messages?

you can change them via constraint validation api: http://www.w3.org/TR/html5/constraints.html#dom-cva-setcustomvalidity

if you want an easy solution, you can rock out civem.js, Custom Input Validation Error Messages JavaScript lib download here: https://github.com/javanto/civem.js live demo here: http://jsfiddle.net/hleinone/njSbH/

How do I open a new window using jQuery?

Those are by no means the same. The first will simply send you to whatever URL you have assigned to window.location.href (in the same window you're currently in). The second makes a GET AJAX request.

Try this page: http://www.codebelt.com/jquery/open-new-browser-window-with-jquery-custom-size/

It gives a great example on how to open a new window*.

If you wish to use raw javascript then this is what you're looking for:

window.open(URL,name,specs,replace)

As seen in http://www.w3schools.com/jsref/met_win_open.asp

Iterate over values of object

It's not a map. It's simply an Object.

Edit: below code is worse than OP's, as Amit pointed out in comments.

You can "iterate over the values" by actually iterating over the keys with:

var value;
Object.keys(map).forEach(function(key) {
    value = map[key];
    console.log(value);
});

How do you close/hide the Android soft keyboard using Java?

I have tried all of solutions very much but no solution work for me, so I found my solution: You should have boolean variables like:

public static isKeyboardShowing = false;
InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
            .getSystemService(Context.INPUT_METHOD_SERVICE);

And in a touch screen event you call:

@Override
public boolean onTouchEvent(MotionEvent event) {
    if(keyboardShowing==true){
        inputMethodManager.toggleSoftInput(InputMethodManager.RESULT_UNCHANGED_HIDDEN, 0);
        keyboardShowing = false;
    }
    return super.onTouchEvent(event);
}

And in EditText is in anywhere:

yourEditText.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            yourClass.keyboardShowing = true;

        }
    });

Jquery Hide table rows

this might work for you...

$('.trhideclass1').hide();

 

<tr class="trhideclass1">
  <td>Label</td>
  <td>InputFile</td>
</tr>

Android Fragment handle back button press

I'd rather do something like this:

private final static String TAG_FRAGMENT = "TAG_FRAGMENT";

private void showFragment() {
    final Myfragment fragment = new MyFragment();
    final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment, fragment, TAG_FRAGMENT);
    transaction.addToBackStack(null);
    transaction.commit();
}

@Override
public void onBackPressed() {
    final Myfragment fragment = (Myfragment) getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);

    if (fragment.allowBackPressed()) { // and then you define a method allowBackPressed with the logic to allow back pressed or not
        super.onBackPressed();
    }
}

Append data frames together in a for loop

Here are some tidyverse and custom function options that might work depending on your needs:

library(tidyverse)

# custom function to generate, filter, and mutate the data:
combine_dfs <- function(i){
 data_frame(x = rnorm(5), y = runif(5)) %>% 
    filter(x < y) %>% 
    mutate(x_plus_y = x + y) %>% 
    mutate(i = i)
}

df <- 1:5 %>% map_df(~combine_dfs(.))
df <- map_df(1:5, ~combine_dfs(.)) # both give the same results
> df %>% head()
# A tibble: 6 x 4
       x      y x_plus_y     i
   <dbl>  <dbl>    <dbl> <int>
1 -0.973 0.673    -0.300     1
2 -0.553 0.0463   -0.507     1
3  0.250 0.716     0.967     2
4 -0.745 0.0640   -0.681     2
5 -0.736 0.228    -0.508     2
6 -0.365 0.496     0.131     3

You could do something similar if you had a directory of files that needed to be combined:

dir_path <- '/path/to/data/test_directory/'
list.files(dir_path)

combine_files <- function(path, file){
  read_csv(paste0(path, file)) %>% 
    filter(a < b) %>% 
    mutate(a_plus_b = a + b) %>% 
    mutate(file_name = file) 
}

df <- list.files(dir_path, '\\.csv$') %>% 
  map_df(~combine_files(dir_path, .))

# or if you have Excel files, using the readxl package:
combine_xl_files <- function(path, file){
  readxl::read_xlsx(paste0(path, file)) %>% 
    filter(a < b) %>% 
    mutate(a_plus_b = a + b) %>% 
    mutate(file_name = file) 
}

df <- list.files(dir_path, '\\.xlsx$') %>% 
  map_df(~combine_xl_files(dir_path, .))

check / uncheck checkbox using jquery?

You can set the state of the checkbox based on the value:

$('#your-checkbox').prop('checked', value == 1);

Post a json object to mvc controller with jquery and ajax

instead of receiving the json string a model binding is better. For example:

[HttpPost]       
public ActionResult AddUser(UserAddModel model)
{
    if (ModelState.IsValid) {
        return Json(new { Response = "Success" });
    }
    return Json(new { Response = "Error" });
}

<script>
function submitForm() {    
    $.ajax({
        type: 'POST',
        url: "@Url.Action("AddUser")",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: $("form[name=UserAddForm]").serialize(),
        success: function (data) {
            console.log(data);
        }
    });
}
</script>

Pass a data.frame column name to a function

If you are trying to build this function within an R package or simply want to reduce complexity, you can do the following:

test_func <- function(df, column) {
  if (column %in% colnames(df)) {
    return(max(df[, column, with=FALSE])) 
  } else {
    stop(cat(column, "not in data.frame columns."))
  }
}

The argument with=FALSE "disables the ability to refer to columns as if they are variables, thereby restoring the “data.frame mode” (per CRAN documentation). The if statement is a quick way to catch if the column name provided is within the data.frame. Could also use tryCatch error handling here.

RecyclerView: Inconsistency detected. Invalid item position

I had a same issue previously. Finally found a workaround for that

What i do is to notify adapter that item has removed and then notify adapter data set range changed

 public void setData(List<Data> dataList) {
      if (this.dataList.size() > 0) {
          notifyItemRangeRemoved(0, dataList.size());
          this.dataList.clear();
      }
      this.dataList.addAll(dataList)
      notifyItemRangeChanged(0, dataList.size());

 }

How to use (install) dblink in PostgreSQL?

On linux, find dblink.sql, then execute in the postgresql console something like this to create all required functions:

\i /usr/share/postgresql/8.4/contrib/dblink.sql 

you might need to install the contrib packages: sudo apt-get install postgresql-contrib

how to implement a long click listener on a listview

or try this code:

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View v,
                    int index, long arg3) {

    Toast.makeText(list.this,myList.getItemAtPosition(index).toString(), Toast.LENGTH_LONG).show();
                return false;
            }
}); 

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

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

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

Dissecting them both a little further:

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

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

S EEEEEEEE MMMMMMMMMMMMMMMMMMMMMMM

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

M × 2E

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

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

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

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

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

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

How to set .net Framework 4.5 version in IIS 7 application pool

There is no 4.5 application pool. You can use any 4.5 application in 4.0 app pool. The .NET 4.5 is "just" an in-place-update not a major new version.

.gitignore for Visual Studio Projects and Solutions

Here is what I use in my .NET Projects for my .gitignore file.

[Oo]bj/
[Bb]in/
*.suo
*.user
/TestResults
*.vspscc
*.vssscc

This is pretty much an all MS approach, that uses the built in Visual Studio tester, and a project that may have some TFS bindings in there too.

ERROR 2003 (HY000): Can't connect to MySQL server (111)

Check that your remote host (i.e. the web hosting server you're trying to connect FROM) allows OUTGOING traffic on port 3306.

I saw the (100) error in this situation. I could connect from my PC/Mac, but not from my website. The MySQL instance was accessible via the internet, but my hosting company wasn't allowing my website to connect to the database on port 3306.

Once I asked my hosting company to open my web hosting account up to outgoing traffic on port 3306, my website could connect to my remote database.

how to create insert new nodes in JsonNode?

These methods are in ObjectNode: the division is such that most read operations are included in JsonNode, but mutations in ObjectNode and ArrayNode.

Note that you can just change first line to be:

ObjectNode jNode = mapper.createObjectNode();
// version ObjectMapper has should return ObjectNode type

or

ObjectNode jNode = (ObjectNode) objectCodec.createObjectNode();
// ObjectCodec is in core part, must be of type JsonNode so need cast

How to change the size of the font of a JLabel to take the maximum size

Source Code for Label - How to change Color and Font (in Netbeans)

jLabel1.setFont(new Font("Serif", Font.BOLD, 12));


jLabel1.setForeground(Color.GREEN);

Find where java class is loaded from

Assuming that you're working with a class named MyClass, the following should work:

MyClass.class.getClassLoader();

Whether or not you can get the on-disk location of the .class file is dependent on the classloader itself. For example, if you're using something like BCEL, a certain class may not even have an on-disk representation.

How to define the css :hover state in a jQuery selector?

You can try this:

$(".myclass").mouseover(function() {
    $(this).find(" > div").css("background-color","red");
}).mouseout(function() {
    $(this).find(" > div").css("background-color","transparent");
});

DEMO

What is "Signal 15 received"

This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

If you need a quick cheatsheet of signal numbers, open a bash shell and:

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
 5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

You can determine the sender by using an appropriate signal handler like:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
  fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
      info->si_pid);
  exit(0);
}

int main (void)
{
  struct sigaction action = {
    .sa_handler = NULL,
    .sa_sigaction = sigterm_handler,
    .sa_mask = 0,
    .sa_flags = SA_SIGINFO,
    .sa_restorer = NULL
  };

  sigaction(SIGTERM, &action, NULL);
  sleep(60);

  return 0;
}

Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

Use superscripts in R axis labels

This is a quick example

plot(rnorm(30), xlab = expression(paste("4"^"th")))

SQL Query for Logins

On SQL Azure as of 2012;

logins:

SELECT * from master.sys.sql_logins

users:

SELECT * from master.sys.sysusers

var functionName = function() {} vs function functionName() {}

The two code snippets you've posted there will, for almost all purposes, behave the same way.

However, the difference in behaviour is that with the first variant (var functionOne = function() {}), that function can only be called after that point in the code.

With the second variant (function functionTwo()), the function is available to code that runs above where the function is declared.

This is because with the first variant, the function is assigned to the variable foo at run time. In the second, the function is assigned to that identifier, foo, at parse time.

More technical information

JavaScript has three ways of defining functions.

  1. Your first snippet shows a function expression. This involves using the "function" operator to create a function - the result of that operator can be stored in any variable or object property. The function expression is powerful that way. The function expression is often called an "anonymous function", because it does not have to have a name,
  2. Your second example is a function declaration. This uses the "function" statement to create a function. The function is made available at parse time and can be called anywhere in that scope. You can still store it in a variable or object property later.
  3. The third way of defining a function is the "Function()" constructor, which is not shown in your original post. It's not recommended to use this as it works the same way as eval(), which has its problems.

What is the difference between 'my' and 'our' in Perl?

Coping with Scoping is a good overview of Perl scoping rules. It's old enough that our is not discussed in the body of the text. It is addressed in the Notes section at the end.

The article talks about package variables and dynamic scope and how that differs from lexical variables and lexical scope.

Setting Curl's Timeout in PHP

Your code sets the timeout to 1000 seconds. For milliseconds, use CURLOPT_TIMEOUT_MS.

How do I localize the jQuery UI Datepicker?

just in case anyone is STILL stuck on this, despite the other answers, I solved this with:

$.datepicker.setDefaults($.datepicker.regional['en-GB']);

note the extra 'GB'. After that it worked fine.

How can I check if a file exists in Perl?

Use:

if (-f $filePath)
{
  # code
}

-e returns true even if the file is a directory. -f will only return true if it's an actual file

SQL Stored Procedure set variables using SELECT

select @currentTerm = CurrentTerm, @termID = TermID, @endDate = EndDate
    from table1
    where IsCurrent = 1

Detect the Enter key in a text input field

It may be too late to answer this question. But the following code simply prevents the enter key. Just copy and paste should work.

        <script type="text/javascript"> 
        function stopRKey(evt) { 
          var evt = (evt) ? evt : ((event) ? event : null); 
          var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
          if ((evt.keyCode == 13) && (node.type=="text"))  {return false;} 
        } 

        document.onkeypress = stopRKey; 

        </script>

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

Here a code that works with windows office 2010. This script will ask you for input filtered range of cells and then the paste range.

Please, both ranges should have the same number of cells.

Sub Copy_Filtered_Cells()

Dim from As Variant
Dim too As Variant
Dim thing As Variant
Dim cell As Range

'Selection.SpecialCells(xlCellTypeVisible).Select

    'Set from = Selection.SpecialCells(xlCellTypeVisible)
    Set temp = Application.InputBox("Copy Range :", Type:=8)
    Set from = temp.SpecialCells(xlCellTypeVisible)
    Set too = Application.InputBox("Select Paste range selected cells ( Visible cells only)", Type:=8)



    For Each cell In from
        cell.Copy
        For Each thing In too
            If thing.EntireRow.RowHeight > 0 Then
                thing.PasteSpecial
                Set too = thing.Offset(1).Resize(too.Rows.Count)
                Exit For
            End If
        Next
    Next


End Sub

Enjoy!

Does hosts file exist on the iPhone? How to change it?

No, an iPhone application can only change stuff within its own little sandbox. (And even there there are things that you can't change on the fly.)

Your best bet is probably to use the servers IP address rather than hostname. Slightly harder, but not that hard if you just need to resolve a single address, would be to put a DNS server on your Mac and configure your iPhone to use that.

Python Flask, how to set content type

Use the make_response method to get a response with your data. Then set the mimetype attribute. Finally return this response:

@app.route('/ajax_ddl')
def ajax_ddl():
    xml = 'foo'
    resp = app.make_response(xml)
    resp.mimetype = "text/xml"
    return resp

If you use Response directly, you lose the chance to customize the responses by setting app.response_class. The make_response method uses the app.responses_class to make the response object. In this you can create your own class, add make your application uses it globally:

class MyResponse(app.response_class):
    def __init__(self, *args, **kwargs):
        super(MyResponse, self).__init__(*args, **kwargs)
        self.set_cookie("last-visit", time.ctime())

app.response_class = MyResponse  

How do I calculate r-squared using Python and Numpy?

From yanl (yet-another-library) sklearn.metrics has an r2_score function;

from sklearn.metrics import r2_score

coefficient_of_dermination = r2_score(y, p(x))

Install a Nuget package in Visual Studio Code

The answers above are good, but insufficient if you have more than 1 project (.csproj) in the same folder.

First, you easily add the "PackageReference" tag to the .csproj file (either manually, by using the nuget package manager or by using the dotnet add package command).

But then, you need to run the "restore" command manually so you can tell it which project you are trying to restore (if I just clicked the restore button that popped up, nothing happened). You can do that by running:

dotnet restore Project-File-Name.csproj

And that installs the package

ISO C90 forbids mixed declarations and code in C

-Wdeclaration-after-statement minimal reproducible example

main.c

#!/usr/bin/env bash

set -eux

cat << EOF > main.c
#include <stdio.h>

int main(void) {
    puts("hello");
    int a = 1;
    printf("%d\n", a);
    return 0;
}
EOF

Give warning:

gcc -std=c89 -Wdeclaration-after-statement -Werror main.c
gcc -std=c99 -Wdeclaration-after-statement -Werror main.c
gcc -std=c89 -pedantic -Werror main.c

Don't give warning:

gcc -std=c89 -pedantic -Wno-declaration-after-statement -Werror main.c
gcc -std=c89 -Wno-declaration-after-statement -Werror main.c
gcc -std=c99 -pedantic -Werror main.c
gcc -std=c89 -Wall -Wextra -Werror main.c
# https://stackoverflow.com/questions/14737104/what-is-the-default-c-mode-for-the-current-gcc-especially-on-ubuntu/53063656#53063656
gcc -pedantic -Werror main.c

The warning:

main.c: In function ‘main’:
main.c:5:5: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]
     int a = 1;
     ^~~

Tested on Ubuntu 16.04, GCC 6.4.0.

Upload artifacts to Nexus, without Maven

For recent versions of Nexus OSS (>= 3.9.0)

https://support.sonatype.com/hc/en-us/articles/115006744008-How-can-I-programmatically-upload-files-into-Nexus-3-

Example for versions 3.9.0 to 3.13.0:

curl -D - -u user:pass -X POST "https://nexus.domain/nexus/service/rest/beta/components?repository=somerepo" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "raw.directory=/test/" -F "[email protected];type=application/json" -F "raw.asset1.filename=test.txt"

How do you post data with a link

You cannot make POST HTTP Requests by <a href="some_script.php">some_script</a>

Just open your house.php, find in it where you have $house = $_POST['houseVar'] and change it to:

isset($_POST['houseVar']) ? $house = $_POST['houseVar'] : $house = $_GET['houseVar']

And in the streeview.php make links like that:

<a href="house.php?houseVar=$houseNum"></a>

Or something else. I just don't know your files and what inside it.

How to fire an event on class change using jQuery?

There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class:

$someElement.on('event', function() {
    $('#myDiv').addClass('submission-ok').trigger('classChange');
});

// in another js file, far, far away
$('#myDiv').on('classChange', function() {
     // do stuff
});

UPDATE

This question seems to be gathering some visitors, so here is an update with an approach which can be used without having to modify existing code using the new MutationObserver:

_x000D_
_x000D_
var $div = $("#foo");_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
  mutations.forEach(function(mutation) {_x000D_
    if (mutation.attributeName === "class") {_x000D_
      var attributeValue = $(mutation.target).prop(mutation.attributeName);_x000D_
      console.log("Class attribute changed to:", attributeValue);_x000D_
    }_x000D_
  });_x000D_
});_x000D_
observer.observe($div[0], {_x000D_
  attributes: true_x000D_
});_x000D_
_x000D_
$div.addClass('red');
_x000D_
.red { color: #C00; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="foo" class="bar">#foo.bar</div>
_x000D_
_x000D_
_x000D_

Be aware that the MutationObserver is only available for newer browsers, specifically Chrome 26, FF 14, IE 11, Opera 15 and Safari 6. See MDN for more details. If you need to support legacy browsers then you will need to use the method I outlined in my first example.

How to remove responsive features in Twitter Bootstrap 3?

You can do that by using the Bootstrap 3 CSS with non-responsive features

https://github.com/bassjobsen/non-responsive-tb3

Start script missing error when running npm start

In my case, it wasn't working because I used "scripts" twice. After combining - it is ok.

"scripts": {
  "test": "make test",
  "start": "node index.js"
}

DirectX SDK (June 2010) Installation Problems: Error Code S1023

Here is the official answer from Microsoft: http://blogs.msdn.com/b/chuckw/archive/2011/12/09/known-issue-directx-sdk-june-2010-setup-and-the-s1023-error.aspx

Summary if you'd rather not click through:

  1. Remove the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1) from the system (both x86 and x64 if applicable). This can be easily done via a command-line with administrator rights:

    MsiExec.exe /passive /X{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}

    MsiExec.exe /passive /X{1D8E6291-B0D5-35EC-8441-6616F567A0F7}

  2. Install the DirectX SDK (June 2010)

  3. Reinstall the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1). On an x64 system, you should install both the x86 and x64 versions of the C++ REDIST. Be sure to install the most current version available, which at this point is the KB2565063 with a security fix.

Windows SDK: The Windows SDK 7.1 has exactly the same issue as noted in KB 2717426.

How can I get the source code of a Python function?

Please mind that the accepted answers work only if the lambda is given on a separate line. If you pass it in as an argument to a function and would like to retrieve the code of the lambda as object, the problem gets a bit tricky since inspect will give you the whole line.

For example, consider a file test.py:

import inspect

def main():
    x, f = 3, lambda a: a + 1
    print(inspect.getsource(f))

if __name__ == "__main__":
    main()

Executing it gives you (mind the indention!):

    x, f = 3, lambda a: a + 1

To retrieve the source code of the lambda, your best bet, in my opinion, is to re-parse the whole source file (by using f.__code__.co_filename) and match the lambda AST node by the line number and its context.

We had to do precisely that in our design-by-contract library icontract since we had to parse the lambda functions we pass in as arguments to decorators. It is too much code to paste here, so have a look at the implementation of this function.

json_encode() escaping forward slashes

is there a way to disable it?

Yes, you only need to use the JSON_UNESCAPED_SLASHES flag.

!important read before: https://stackoverflow.com/a/10210367/367456 (know what you're dealing with - know your enemy)

json_encode($str, JSON_UNESCAPED_SLASHES);

If you don't have PHP 5.4 at hand, pick one of the many existing functions and modify them to your needs, e.g. http://snippets.dzone.com/posts/show/7487 (archived copy).

Example Demo

<?php
/*
 * Escaping the reverse-solidus character ("/", slash) is optional in JSON.
 *
 * This can be controlled with the JSON_UNESCAPED_SLASHES flag constant in PHP.
 *
 * @link http://stackoverflow.com/a/10210433/367456
 */    

$url = 'http://www.example.com/';

echo json_encode($url), "\n";

echo json_encode($url, JSON_UNESCAPED_SLASHES), "\n";

Example Output:

"http:\/\/www.example.com\/"
"http://www.example.com/"

Resolving MSB3247 - Found conflicts between different versions of the same dependent assembly

ASP.NET build manager is building the website by going through the folders alphabetically, and for each folder it figures out it dependencies and builds the dependencies first and then the selected folder.

In this case the problematic folder which is ~/Controls, is selected to be built at the beginning, from yet an unknown reason, it builds some of the controls there as a separate assembly instead of inside the same assembly as other controls (seems to be connected to the fact that some controls are dependent on other controls in the same folder).

Then the next folder which is built (~/File-Center/Control) is dependent on the root folder ~/ which is dependent on ~/Controls, so the folder ~/Controls is being built again only this time the controls which were separated to their own assembly are now joined to the same assembly as other controls with the separated assembly still being referenced.

So at this point 2 assembly (at least) have the same controls and the build fails.

Although we still don't know why this happened, we were able to work around it by changing the Controls folder name to ZControls, this way it is not built before ~/File-Center/Control, only after and this way it is built as it should.

Bootstrap 3 grid with no gap

I always add this style to my Bootstrap LESS / SASS:

.row-no-padding {
  [class*="col-"] {
    padding-left: 0 !important;
    padding-right: 0 !important;
  }
}

Then in the HTML you can write:

<div class="row row-no-padding">

Character Limit in HTML

use the "maxlength" attribute as others have said.

if you need to put a max character length on a text AREA, you need to turn to Javascript. Take a look here: How to impose maxlength on textArea in HTML using JavaScript

PHPMailer AddAddress()

Some great answers above, using that info here is what I did today to solve the same issue:

$to_array = explode(',', $to);
foreach($to_array as $address)
{
    $mail->addAddress($address, 'Web Enquiry');
}

This app won't run unless you update Google Play Services (via Bazaar)

According to a discussion with Android Developers on Google+, running the new Map API on the emulator is not possible at the moment.

(The comment is from Zhelyazko Atanasov yesterday at 23:18, I don't know how to link directly to it)

Also, you don't see the "(via Bazaar)" part when running from an actual device, and the update button open the Play Store. I am assuming Bazaar is meant to provide Google Play Services on the Android emulator, but it is not ready yet...

SQL: Two select statements in one query

select name, games, goals
from tblMadrid where name = 'ronaldo'
union
select name, games, goals
from tblBarcelona where name = 'messi'
ORDER  BY goals 

Check existence of directory and create if doesn't exist

As of April 16, 2015, with the release of R 3.2.0 there's a new function called dir.exists(). To use this function and create the directory if it doesn't exist, you can use:

ifelse(!dir.exists(file.path(mainDir, subDir)), dir.create(file.path(mainDir, subDir)), FALSE)

This will return FALSE if the directory already exists or is uncreatable, and TRUE if it didn't exist but was succesfully created.

Note that to simply check if the directory exists you can use

dir.exists(file.path(mainDir, subDir))

VB.NET: how to prevent user input in a ComboBox

Set the ReadOnly attribute to true.

Or if you want the combobox to appear and display the list of "available" values, you could handle the ValueChanged event and force it back to your immutable value.

Random number c++ in some range

You can use the random functionality included within the additions to the standard library (TR1). Or you can use the same old technique that works in plain C:

25 + ( std::rand() % ( 63 - 25 + 1 ) )

How can I remove Nan from list Python/NumPy

In your example 'nan' is a string so instead of using isnan() just check for the string

like this:

cleanedList = [x for x in countries if x != 'nan']

How to ignore ansible SSH authenticity checking?

forward to nikobelia

For those who using jenkins to run the play book, I just added to my jenkins job before running the ansible-playbook the he environment variable ANSIBLE_HOST_KEY_CHECKING = False For instance this:

export ANSIBLE_HOST_KEY_CHECKING=False
ansible-playbook 'playbook.yml' \
--extra-vars="some vars..." \
--tags="tags_name..." -vv

Javascript ES6/ES5 find in array and change

Whereas most of the existing answers are great, I would like to include an answer using a traditional for loop, which should also be considered here. The OP requests an answer which is ES5/ES6 compatible, and the traditional for loop applies :)

The problem with using array functions in this scenario, is that they don't mutate objects, but in this case, mutation is a requirement. The performance gain of using a traditional for loop is just a (huge) bonus.

const findThis = 2;
const items = [{id:1, ...}, {id:2, ...}, {id:3, ...}];

for (let i = 0, l = items.length; i < l; ++i) {
  if (items[i].id === findThis) {
    items[i].iAmChanged = true;
    break;
  }
}

Although I am a great fan of array functions, don't let them be the only tool in your toolbox. If the purpose is mutating the array, they are not the best fit.

How to create an empty array in Swift?

Here you go:

var yourArray = [String]()

The above also works for other types and not just strings. It's just an example.

Adding Values to It

I presume you'll eventually want to add a value to it!

yourArray.append("String Value")

Or

let someString = "You can also pass a string variable, like this!"
yourArray.append(someString)

Add by Inserting

Once you have a few values, you can insert new values instead of appending. For example, if you wanted to insert new objects at the beginning of the array (instead of appending them to the end):

yourArray.insert("Hey, I'm first!", atIndex: 0)

Or you can use variables to make your insert more flexible:

let lineCutter = "I'm going to be first soon."
let positionToInsertAt = 0
yourArray.insert(lineCutter, atIndex: positionToInsertAt)

You May Eventually Want to Remove Some Stuff

var yourOtherArray = ["MonkeysRule", "RemoveMe", "SwiftRules"]
yourOtherArray.remove(at: 1)

The above works great when you know where in the array the value is (that is, when you know its index value). As the index values begin at 0, the second entry will be at index 1.

Removing Values Without Knowing the Index

But what if you don't? What if yourOtherArray has hundreds of values and all you know is you want to remove the one equal to "RemoveMe"?

if let indexValue = yourOtherArray.index(of: "RemoveMe") {
    yourOtherArray.remove(at: indexValue)
}

This should get you started!

"git rm --cached x" vs "git reset head --? x"?

Perhaps an example will help:

git rm --cached asd
git commit -m "the file asd is gone from the repository"

versus

git reset HEAD -- asd
git commit -m "the file asd remains in the repository"

Note that if you haven't changed anything else, the second commit won't actually do anything.

Print array without brackets and commas

With Java 8 or newer, you can use String.join, which provides the same functionality:

Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter

String[] array = new String[] { "a", "n", "d", "r", "o", "i", "d" };
String joined = String.join("", array); //returns "android"

With an array of a different type, one should convert it to a String array or to a char sequence Iterable:

int[] numbers = { 1, 2, 3, 4, 5, 6, 7 };

//both of the following return "1234567"
String joinedNumbers = String.join("",
        Arrays.stream(numbers).mapToObj(String::valueOf).toArray(n -> new String[n]));
String joinedNumbers2 = String.join("",
        Arrays.stream(numbers).mapToObj(String::valueOf).collect(Collectors.toList()));

The first argument to String.join is the delimiter, and can be changed accordingly.

How to watch and reload ts-node when TypeScript files change

add this to your package.json file

scripts {
"dev": "nodemon --watch '**/*.ts' --exec 'ts-node' index.ts"
}

and to make this work you also need to install ts-node as dev-dependency

yarn add ts-node -D

run yarn dev to start the dev server

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

Refactored the code from balexandre a little so objects gets disposed and the new language features of C# 3.5+ are used (Linq, var, etc). Also renamed the variables to more meaningful names. I also merged some of the functions to be able to do more configuration with less WMI interaction. I removed the WINS code as I don't need to configure WINS anymore. Feel free to add the WINS code if you need it.

For the case anybody likes to use the refactored/modernized code I put it back into the community here.

/// <summary>
/// Helper class to set networking configuration like IP address, DNS servers, etc.
/// </summary>
public class NetworkConfigurator
{
    /// <summary>
    /// Set's a new IP Address and it's Submask of the local machine
    /// </summary>
    /// <param name="ipAddress">The IP Address</param>
    /// <param name="subnetMask">The Submask IP Address</param>
    /// <param name="gateway">The gateway.</param>
    /// <remarks>Requires a reference to the System.Management namespace</remarks>
    public void SetIP(string ipAddress, string subnetMask, string gateway)
    {
        using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
        {
            using (var networkConfigs = networkConfigMng.GetInstances())
            {
                foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(managementObject => (bool)managementObject["IPEnabled"]))
                {
                    using (var newIP = managementObject.GetMethodParameters("EnableStatic"))
                    {
                        // Set new IP address and subnet if needed
                        if ((!String.IsNullOrEmpty(ipAddress)) || (!String.IsNullOrEmpty(subnetMask)))
                        {
                            if (!String.IsNullOrEmpty(ipAddress))
                            {
                                newIP["IPAddress"] = new[] { ipAddress };
                            }

                            if (!String.IsNullOrEmpty(subnetMask))
                            {
                                newIP["SubnetMask"] = new[] { subnetMask };
                            }

                            managementObject.InvokeMethod("EnableStatic", newIP, null);
                        }

                        // Set mew gateway if needed
                        if (!String.IsNullOrEmpty(gateway))
                        {
                            using (var newGateway = managementObject.GetMethodParameters("SetGateways"))
                            {
                                newGateway["DefaultIPGateway"] = new[] { gateway };
                                newGateway["GatewayCostMetric"] = new[] { 1 };
                                managementObject.InvokeMethod("SetGateways", newGateway, null);
                            }
                        }
                    }
                }
            }
        }
    }

    /// <summary>
    /// Set's the DNS Server of the local machine
    /// </summary>
    /// <param name="nic">NIC address</param>
    /// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
    /// <remarks>Requires a reference to the System.Management namespace</remarks>
    public void SetNameservers(string nic, string dnsServers)
    {
        using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
        {
            using (var networkConfigs = networkConfigMng.GetInstances())
            {
                foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(objMO => (bool)objMO["IPEnabled"] && objMO["Caption"].Equals(nic)))
                {
                    using (var newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder"))
                    {
                        newDNS["DNSServerSearchOrder"] = dnsServers.Split(',');
                        managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
                    }
                }
            }
        }
    }
}

Spool Command: Do not output SQL statement to file

My shell script calls the sql file and executes it. The spool output had the SQL query at the beginning followed by the query result.

This did not resolve my problem:

set echo off

This resolved my problem:

set verify off

Presenting a UIAlertController properly on an iPad using iOS 8

Just add the following code before presenting your action sheet:

if let popoverController = optionMenu.popoverPresentationController {
    popoverController.sourceView = self.view
    popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
    popoverController.permittedArrowDirections = []
}

Integer.valueOf() vs. Integer.parseInt()

Actually, valueOf uses parseInt internally. The difference is parseInt returns an int primitive while valueOf returns an Integer object. Consider from the Integer.class source:

public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s, 10);
}

public static Integer valueOf(String s, int radix) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, radix));
}

public static Integer valueOf(String s) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, 10));
}

As for parsing with a comma, I'm not familiar with one. I would sanitize them.

int million = Integer.parseInt("1,000,000".replace(",", ""));

SHA-256 or MD5 for file integrity

  1. Yes, on most CPUs, SHA-256 is two to three times slower than MD5, though not primarily because of its longer hash. See other answers here and the answers to this Stack Overflow questions.
  2. Here's a backup scenario where MD5 would not be appropriate:
    • Your backup program hashes each file being backed up. It then stores each file's data by its hash, so if you're backing up the same file twice you only end up with one copy of it.
    • An attacker can cause the system to backup files they control.
    • The attacker knows the MD5 hash of a file they want to remove from the backup.
    • The attacker can then use the known weaknesses of MD5 to craft a new file that has the same hash as the file to remove. When that file is backed up, it will replace the file to remove, and that file's backed up data will be lost.
    • This backup system could be strengthened a bit (and made more efficient) by not replacing files whose hash it has previously encountered, but then an attacker could prevent a target file with a known hash from being backed up by preemptively backing up a specially constructed bogus file with the same hash.
    • Obviously most systems, backup and otherwise, do not satisfy the conditions necessary for this attack to be practical, but I just wanted to give an example of a situation where SHA-256 would be preferable to MD5. Whether this would be the case for the system you're creating depends on more than just the characteristics of MD5 and SHA-256.
  3. Yes, cryptographic hashes like the ones generated by MD5 and SHA-256 are a type of checksum.

Happy hashing!

What does `dword ptr` mean?

The dword ptr part is called a size directive. This page explains them, but it wasn't possible to direct-link to the correct section.

Basically, it means "the size of the target operand is 32 bits", so this will bitwise-AND the 32-bit value at the address computed by taking the contents of the ebp register and subtracting four with 0.

Disable button in jQuery

I want to disable button on some condition, i am using 1st solution but it won't work for me. But when I use 2nd one it worked.Below are outputs from browser console.

1. $('#psl2 .btn-continue').prop("disabled", true)

<a class=?"btn btn-yellow btn-continue" href=?"#">?Next?</a>?

2. $('#psl2 .btn-continue').attr("disabled","disabled")

<a class=?"btn btn-yellow btn-continue" href=?"#" disabled=?"disabled">?Next?</a>?

jQuery limit to 2 decimal places

Here is a working example in both Javascript and jQuery:

http://jsfiddle.net/GuLYN/312/

//In jQuery
$("#calculate").click(function() {
    var num = parseFloat($("#textbox").val());
    var new_num = $("#textbox").val(num.toFixed(2));
});


// In javascript
document.getElementById('calculate').onclick = function() {
    var num = parseFloat(document.getElementById('textbox').value);
    var new_num = num.toFixed(2);
    document.getElementById('textbox').value = new_num;
};
?

remove / reset inherited css from an element

you may use this below option.

<style>
  div:not(.no_common_style){
      background-color:red;
  }
</style>

now , if their any place where you do not want to apply default style you can use 'no_common_style' class as class. ex:

<div class="no_common_style">
  It will not display in red
</div>

How to install iPhone application in iPhone Simulator

Enter the following in the terminal:

$/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app/Contents/MacOS/iPhone\ Simulator -SimulateApplication path/to/your/file/projectname.app/projectname

Pointer to 2D arrays in C

Both your examples are equivalent. However, the first one is less obvious and more "hacky", while the second one clearly states your intention.

int (*pointer)[280];
pointer = tab1;

pointer points to an 1D array of 280 integers. In your assignment, you actually assign the first row of tab1. This works since you can implicitly cast arrays to pointers (to the first element).

When you are using pointer[5][12], C treats pointer as an array of arrays (pointer[5] is of type int[280]), so there is another implicit cast here (at least semantically).

In your second example, you explicitly create a pointer to a 2D array:

int (*pointer)[100][280];
pointer = &tab1;

The semantics are clearer here: *pointer is a 2D array, so you need to access it using (*pointer)[i][j].

Both solutions use the same amount of memory (1 pointer) and will most likely run equally fast. Under the hood, both pointers will even point to the same memory location (the first element of the tab1 array), and it is possible that your compiler will even generate the same code.

The first solution is "more advanced" since one needs quite a deep understanding on how arrays and pointers work in C to understand what is going on. The second one is more explicit.

What does "int 0x80" mean in assembly code?

Minimal runnable Linux system call example

Linux sets up the interrupt handler for 0x80 such that it implements system calls, a way for userland programs to communicate with the kernel.

.data
    s:
        .ascii "hello world\n"
        len = . - s
.text
    .global _start
    _start:

        movl $4, %eax   /* write system call number */
        movl $1, %ebx   /* stdout */
        movl $s, %ecx   /* the data to print */
        movl $len, %edx /* length of the buffer */
        int $0x80

        movl $1, %eax   /* exit system call number */
        movl $0, %ebx   /* exit status */
        int $0x80

Compile and run with:

as -o main.o main.S
ld -o main.out main.o
./main.out

Outcome: the program prints to stdout:

hello world

and exits cleanly.

You cannot set your own interrupt handlers directly from userland because you only have ring 3 and Linux prevents you from doing so.

GitHub upstream. Tested on Ubuntu 16.04.

Better alternatives

int 0x80 has been superseded by better alternatives for making system calls: first sysenter, then VDSO.

x86_64 has a new syscall instruction.

See also: What is better "int 0x80" or "syscall"?

Minimal 16-bit example

First learn how to create a minimal bootloader OS and run it on QEMU and real hardware as I've explained here: https://stackoverflow.com/a/32483545/895245

Now you can run in 16-bit real mode:

    movw $handler0, 0x00
    mov %cs, 0x02
    movw $handler1, 0x04
    mov %cs, 0x06
    int $0
    int $1
    hlt
handler0:
    /* Do 0. */
    iret
handler1:
    /* Do 1. */
    iret

This would do in order:

  • Do 0.
  • Do 1.
  • hlt: stop executing

Note how the processor looks for the first handler at address 0, and the second one at 4: that is a table of handlers called the IVT, and each entry has 4 bytes.

Minimal example that does some IO to make handlers visible.

Minimal protected mode example

Modern operating systems run in the so called protected mode.

The handling has more options in this mode, so it is more complex, but the spirit is the same.

The key step is using the LGDT and LIDT instructions, which point the address of an in-memory data structure (the Interrupt Descriptor Table) that describes the handlers.

Minimal example

Get the index of the object inside an array, matching a condition

I have seen many solutions in the above.

Here I am using map function to find the index of the search text in an array object.

I am going to explain my answer with using students data.

  • step 1: create array object for the students(optional you can create your own array object).
    var students = [{name:"Rambabu",htno:"1245"},{name:"Divya",htno:"1246"},{name:"poojitha",htno:"1247"},{name:"magitha",htno:"1248"}];

  • step 2: Create variable to search text
    var studentNameToSearch = "Divya";

  • step 3: Create variable to store matched index(here we use map function to iterate).
    var matchedIndex = students.map(function (obj) { return obj.name; }).indexOf(studentNameToSearch);

_x000D_
_x000D_
var students = [{name:"Rambabu",htno:"1245"},{name:"Divya",htno:"1246"},{name:"poojitha",htno:"1247"},{name:"magitha",htno:"1248"}];_x000D_
_x000D_
var studentNameToSearch = "Divya";_x000D_
_x000D_
var matchedIndex = students.map(function (obj) { return obj.name; }).indexOf(studentNameToSearch);_x000D_
_x000D_
console.log(matchedIndex);_x000D_
_x000D_
alert("Your search name index in array is:"+matchedIndex)
_x000D_
_x000D_
_x000D_

Selenium -- How to wait until page is completely loaded

3 answers, which you can combine:

  1. Set implicit wait immediately after creating the web driver instance:

    _ = driver.Manage().Timeouts().ImplicitWait;

    This will try to wait until the page is fully loaded on every page navigation or page reload.

  2. After page navigation, call JavaScript return document.readyState until "complete" is returned. The web driver instance can serve as JavaScript executor. Sample code:

    C#

    new WebDriverWait(driver, MyDefaultTimeout).Until(
    d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));
    

    Java

    new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
          webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
    
  3. Check if the URL matches the pattern you expect.

Can't load AMD 64-bit .dll on a IA 32-bit platform

If you are still getting that error after installing the 64 bit JRE, it means that the JVM running Gurobi package is still using the 32 bit JRE.

Check that you have updated the PATH and JAVA_HOME globally and in the command shell that you are using. (Maybe you just need to exit and restart it.)

Check that your command shell runs the right version of Java by running "java -version" and checking that it says it is a 64bit JRE.

If you are launching the example via a wrapper script / batch file, make sure that the script is using the right JRE. Modify as required ...

PHP - Redirect and send data via POST

You have to open a socket to the site with fsockopen and simulate a HTTP-Post-Request. Google will show you many snippets how to simulate the request.

How to set a default row for a query that returns no rows?

Insert your default values into a table variable, then update this tableVar's single row with a match from your actual table. If a row is found, tableVar will be updated; if not, the default value remains. Return the table variable.

    ---=== The table & its data
    CREATE TABLE dbo.Rates (
        PkId int,
        name varchar(10),
        rate decimal(10,2)
    )
    INSERT INTO dbo.Rates(PkId, name, rate) VALUES (1, 'Schedule 1', 0.1)
    INSERT INTO dbo.Rates(PkId, name, rate) VALUES (2, 'Schedule 2', 0.2)

Here's the solution:

---=== The solution 
CREATE PROCEDURE dbo.GetRate 
  @PkId int
AS
BEGIN
  DECLARE @tempTable TABLE (
    PkId int, 
    name varchar(10), 
    rate decimal(10,2)
 )

 --- [1] Insert default values into @tempTable. PkId=0 is dummy value  
 INSERT INTO @tempTable(PkId, name, rate) VALUES (0, 'DEFAULT', 0.00)

 --- [2] Update the single row in @tempTable with the actual value.
 ---     This only happens if a match is found
 UPDATE @tempTable
    SET t.PkId=x.PkId, t.name=x.name, t.rate = x.rate
    FROM @tempTable t INNER JOIN dbo.Rates x
    ON t.PkId = 0
    WHERE x.PkId = @PkId

 SELECT * FROM @tempTable
END

Test the code:

EXEC dbo.GetRate @PkId=1     --- returns values for PkId=1
EXEC dbo.GetRate @PkId=12314 --- returns default values

Where in memory are my variables stored in C?

Linux minimal runnable examples with disassembly analysis

Since this is an implementation detail not specified by standards, let's just have a look at what the compiler is doing on a particular implementation.

In this answer, I will either link to specific answers that do the analysis, or provide the analysis directly here, and summarize all results here.

All of those are in various Ubuntu / GCC versions, and the outcomes are likely pretty stable across versions, but if we find any variations let's specify more precise versions.

Local variable inside a function

Be it main or any other function:

void f(void) {
    int my_local_var;
}

As shown at: What does <value optimized out> mean in gdb?

  • -O0: stack
  • -O3: registers if they don't spill, stack otherwise

For motivation on why the stack exists see: What is the function of the push / pop instructions used on registers in x86 assembly?

Global variables and static function variables

/* BSS */
int my_global_implicit;
int my_global_implicit_explicit_0 = 0;

/* DATA */
int my_global_implicit_explicit_1 = 1;

void f(void) {
    /* BSS */
    static int my_static_local_var_implicit;
    static int my_static_local_var_explicit_0 = 0;

    /* DATA */
    static int my_static_local_var_explicit_1 = 1;
}
  • if initialized to 0 or not initialized (and therefore implicitly initialized to 0): .bss section, see also: Why is the .bss segment required?
  • otherwise: .data section

char * and char c[]

As shown at: Where are static variables stored in C and C++?

void f(void) {
    /* RODATA / TEXT */
    char *a = "abc";

    /* Stack. */
    char b[] = "abc";
    char c[] = {'a', 'b', 'c', '\0'};
}

TODO will very large string literals also be put on the stack? Or .data? Or does compilation fail?

Function arguments

void f(int i, int j);

Must go through the relevant calling convention, e.g.: https://en.wikipedia.org/wiki/X86_calling_conventions for X86, which specifies either specific registers or stack locations for each variable.

Then as shown at What does <value optimized out> mean in gdb?, -O0 then slurps everything into the stack, while -O3 tries to use registers as much as possible.

If the function gets inlined however, they are treated just like regular locals.

const

I believe that it makes no difference because you can typecast it away.

Conversely, if the compiler is able to determine that some data is never written to, it could in theory place it in .rodata even if not const.

TODO analysis.

Pointers

They are variables (that contain addresses, which are numbers), so same as all the rest :-)

malloc

The question does not make much sense for malloc, since malloc is a function, and in:

int *i = malloc(sizeof(int));

*i is a variable that contains an address, so it falls on the above case.

As for how malloc works internally, when you call it the Linux kernel marks certain addresses as writable on its internal data structures, and when they are touched by the program initially, a fault happens and the kernel enables the page tables, which lets the access happen without segfaul: How does x86 paging work?

Note however that this is basically exactly what the exec syscall does under the hood when you try to run an executable: it marks pages it wants to load to, and writes the program there, see also: How does kernel get an executable binary file running under linux? Except that exec has some extra limitations on where to load to (e.g. is the code is not relocatable).

The exact syscall used for malloc is mmap in modern 2020 implementations, and in the past brk was used: Does malloc() use brk() or mmap()?

Dynamic libraries

Basically get mmaped to memory: https://unix.stackexchange.com/questions/226524/what-system-call-is-used-to-load-libraries-in-linux/462710#462710

envinroment variables and main's argv

Above initial stack: https://unix.stackexchange.com/questions/75939/where-is-the-environment-string-actual-stored TODO why not in .data?

ng-change not working on a text input

Maybe you can try something like this:

Using a directive

directive('watchChange', function() {
    return {
        scope: {
            onchange: '&watchChange'
        },
        link: function(scope, element, attrs) {
            element.on('input', function() {
                scope.onchange();
            });
        }
    };
});

http://jsfiddle.net/H2EAB/

How to mock a final class with mockito

I had the same problem. Since the class I was trying to mock was a simple class, I simply created an instance of it and returned that.

How to send an HTTP request with a header parameter?

If it says the API key is listed as a header, more than likely you need to set it in the headers option of your http request. Normally something like this :

headers: {'Authorization': '[your API key]'}

Here is an example from another Question

$http({method: 'GET', url: '[the-target-url]', headers: {
  'Authorization': '[your-api-key]'}
});

Edit : Just saw you wanted to store the response in a variable. In this case I would probably just use AJAX. Something like this :

$.ajax({ 
   type : "GET", 
   url : "[the-target-url]", 
   beforeSend: function(xhr){xhr.setRequestHeader('Authorization', '[your-api-key]');},
   success : function(result) { 
       //set your variable to the result 
   }, 
   error : function(result) { 
     //handle the error 
   } 
 }); 

I got this from this question and I'm at work so I can't test it at the moment but looks solid

Edit 2: Pretty sure you should be able to use this line :

headers: {'Authorization': '[your API key]'},

instead of the beforeSend line in the first edit. This may be simpler for you

How to change color of SVG image using CSS (jQuery SVG image replacement)?

Since SVG is basically code, you need just contents. I used PHP to obtain content, but you can use whatever you want.

<?php
$content    = file_get_contents($pathToSVG);
?>

Then, I've printed content "as is" inside a div container

<div class="fill-class"><?php echo $content;?></div>

To finnaly set rule to container's SVG childs on CSS

.fill-class > svg { 
    fill: orange;
}

I got this results with a material icon SVG:

  1. Mozilla Firefox 59.0.2 (64-bit) Linux

enter image description here

  1. Google Chrome66.0.3359.181 (Build oficial) (64 bits) Linux

enter image description here

  1. Opera 53.0.2907.37 Linux

enter image description here

Get webpage contents with Python?

A solution with works with Python 2.X and Python 3.X:

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

url = 'http://hiscore.runescape.com/index_lite.ws?player=zezima'
response = urlopen(url)
data = str(response.read())

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.

Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload

Jenkins / Hudson environment variables

This is how I solved this annoying issue:

I changed the PATH variable as @sagar suggested in his 2nd option, but still I got different PATH value than I expected.

Eventually I found out that it was the EnvInject plugin that replaced my PATH variable!

So I could either uninstall EnvInject or just use it to inject the PATH variable.

As many of our Jenkins jobs use that plugin, I didn't want to uninstall it...

So I created a file: environment_variables.properties under my Jenkins home directory.

This file contained the path environment value that I needed: PATH=$PATH:/usr/local/git/bin/.

From the Jenkins web interface: Manage Jenkins -> Configure System. In that screen - I ticked the Prepare jobs environment option, and in the Properties File Path field I entered the path to my file: /var/lib/jenkins/environment_variables.properties.

This way every Jenkins job we have receive whatever variables I put in this environment_variables.properties file.

Converting an integer to a string in PHP

There's many ways to do this.

Two examples:

 $str = (string) $int;
 $str = "$int";     

See the PHP Manual on Types Juggling for more.

How to add a custom Ribbon tab using VBA?

Another approach to this would be to download Jan Karel Pieterse's free Open XML class module from this page: Editing elements in an OpenXML file using VBA

With this added to your VBA project, you can unzip the Excel file, use VBA to modify the XML, then use the class to rezip the files.

How to set an "Accept:" header on Spring RestTemplate request?

If, like me, you struggled to find an example that uses headers with basic authentication and the rest template exchange API, this is what I finally worked out...

private HttpHeaders createHttpHeaders(String user, String password)
{
    String notEncoded = user + ":" + password;
    String encodedAuth = Base64.getEncoder().encodeToString(notEncoded.getBytes());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "Basic " + encodedAuth);
    return headers;
}

private void doYourThing() 
{
    String theUrl = "http://blah.blah.com:8080/rest/api/blah";
    RestTemplate restTemplate = new RestTemplate();
    try {
        HttpHeaders headers = createHttpHeaders("fred","1234");
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
        ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);
        System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
    }
    catch (Exception eek) {
        System.out.println("** Exception: "+ eek.getMessage());
    }
}

How can I add a line to a file in a shell script?

To answer your original question, here's how you do it with sed:

sed -i '1icolumn1, column2, column3' testfile.csv

The "1i" command tells sed to go to line 1 and insert the text there.

The -i option causes the file to be edited "in place" and can also take an optional argument to create a backup file, for example

sed -i~ '1icolumn1, column2, column3' testfile.csv

would keep the original file in "testfile.csv~".

Regex - how to match everything except a particular pattern

pattern - re

str.split(/re/g) 

will return everything except the pattern.

Test here

Convert boolean to int in Java

If true -> 1 and false -> 0 mapping is what you want, you can do:

boolean b = true;
int i = b ? 1 : 0; // assigns 1 to i.

Making TextView scrollable on Android

Use it like this

<TextView  
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:maxLines = "AN_INTEGER"
    android:scrollbars = "vertical"
/>

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

In case anyone still has to support legacy fancybox with jQuery 3.0+ here are some other changes you'll have to make:

.unbind() deprecated

Replace all instances of .unbind with .off

.removeAttribute() is not a function

Change lines 580-581 to use jQuery's .removeAttr() instead:

Old code:

580: content[0].style.removeAttribute('filter');
581: wrap[0].style.removeAttribute('filter');

New code:

580: content.removeAttr('filter');
581: wrap.removeAttr('filter');

This combined with the other patch mentioned above solved my compatibility issues.

Pass an array of integers to ASP.NET Web API?

I have created a custom model binder which converts any comma separated values (only primitive, decimal, float, string) to their corresponding arrays.

public class CommaSeparatedToArrayBinder<T> : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            Type type = typeof(T);
            if (type.IsPrimitive || type == typeof(Decimal) || type == typeof(String) || type == typeof(float))
            {
                ValueProviderResult val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                if (val == null) return false;

                string key = val.RawValue as string;
                if (key == null) { bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Wrong value type"); return false; }

                string[] values = key.Split(',');
                IEnumerable<T> result = this.ConvertToDesiredList(values).ToArray();
                bindingContext.Model = result;
                return true;
            }

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Only primitive, decimal, string and float data types are allowed...");
            return false;
        }

        private IEnumerable<T> ConvertToDesiredArray(string[] values)
        {
            foreach (string value in values)
            {
                var val = (T)Convert.ChangeType(value, typeof(T));
                yield return val;
            }
        }
    }

And how to use in Controller:

 public IHttpActionResult Get([ModelBinder(BinderType = typeof(CommaSeparatedToArrayBinder<int>))] int[] ids)
        {
            return Ok(ids);
        }

Passing multiple parameters to pool.map() function in Python

You could use a map function that allows multiple arguments, as does the fork of multiprocessing found in pathos.

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> 
>>> def add_and_subtract(x,y):
...   return x+y, x-y
... 
>>> res = Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))
>>> res
[(-5, 5), (-2, 6), (1, 7), (4, 8), (7, 9), (10, 10), (13, 11), (16, 12), (19, 13), (22, 14)]
>>> Pool().map(add_and_subtract, *zip(*res))
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

pathos enables you to easily nest hierarchical parallel maps with multiple inputs, so we can extend our example to demonstrate that.

>>> from pathos.multiprocessing import ThreadingPool as TPool
>>> 
>>> res = TPool().amap(add_and_subtract, *zip(*Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))))
>>> res.get()
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

Even more fun, is to build a nested function that we can pass into the Pool. This is possible because pathos uses dill, which can serialize almost anything in python.

>>> def build_fun_things(f, g):
...   def do_fun_things(x, y):
...     return f(x,y), g(x,y)
...   return do_fun_things
... 
>>> def add(x,y):
...   return x+y
... 
>>> def sub(x,y):
...   return x-y
... 
>>> neato = build_fun_things(add, sub)
>>> 
>>> res = TPool().imap(neato, *zip(*Pool().map(neato, range(0,20,2), range(-5,5,1))))
>>> list(res)
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]

If you are not able to go outside of the standard library, however, you will have to do this another way. Your best bet in that case is to use multiprocessing.starmap as seen here: Python multiprocessing pool.map for multiple arguments (noted by @Roberto in the comments on the OP's post)

Get pathos here: https://github.com/uqfoundation

Meaning of = delete after function declaration

This excerpt from The C++ Programming Language [4th Edition] - Bjarne Stroustrup book talks about the real purpose behind using =delete:

3.3.4 Suppressing Operations

Using the default copy or move for a class in a hierarchy is typically a disaster: given only a pointer to a base, we simply don’t know what members the derived class has, so we can’t know how to copy them. So, the best thing to do is usually to delete the default copy and move operations, that is, to eliminate the default definitions of those two operations:

class Shape {
public:
  Shape(const Shape&) =delete; // no copy operations
  Shape& operator=(const Shape&) =delete;

  Shape(Shape&&) =delete; // no move operations
  Shape& operator=(Shape&&) =delete;
  ˜Shape();
    // ...
};

Now an attempt to copy a Shape will be caught by the compiler.

The =delete mechanism is general, that is, it can be used to suppress any operation

Python - use list as function parameters

Use an asterisk:

some_func(*params)

How to expand/collapse a diff sections in Vimdiff?

Actually if you do Ctrl+W W, you won't need to add that extra Ctrl. Does the same thing.

Append a tuple to a list - what's the difference between two ways?

There should be no difference, but your tuple method is wrong, try:

a_list.append(tuple([3, 4]))

Is it possible to open a Windows Explorer window from PowerShell?

I wanted to write this as a comment but I do not have 50 reputation.

All of the answers in this thread are essentially to use Invoke-Item or to use explorer.exe directly; however, this isn't completely synonymous with "open containing folder", so in terms of opening an Explorer window as the question states, if we wanted to apply the answer to a particular file the question still hasn't really been answered.

e.g.,

Invoke-Item C:\Users\Foo\bar.txt
explorer.exe C:\Users\Foo\bar.html

^ those two commands would result in Notepad.exe or Firefox.exe being invoked on the two files respectively, not an explorer.exe window on C:\Users\Foo\ (the containing directory).

Whereas if one was issuing this command from powershell, this would be no big deal (less typing anyway), if one is scripting and needs to "open containing folder" on a variable, it becomes a matter of string matching to extract the directory from the full path to the file.

Is there no simple command "Open-Containing-Folder" such that a variable could be substituted?

e.g.,

$foo = "C:\Users\Foo\foo.txt"    
[some code] $fooPath
# opens C:\Users\Foo\ and not the default program for .txt file extension

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

1.

Add the applicationId to the application's build.gradle:

android {
    ...
    defaultConfig {
        applicationId "com.example.my.app"
        ...
    }
}

And than Clean Project -> Build or Rebuild Project


2. If your minSdkVersion <= 20 (https://developer.android.com/studio/build/multidex)

Use Multidex correctly.

application's build.gradle

android {
...               
    defaultConfig {
    ....
        multiDexEnabled true
    }
    ...
}

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
    ...
}

manifest.xml

<application
    ...
    android:name="android.support.multidex.MultiDexApplication" >
    ...

3.

If you use a custom Application class

public class MyApplication extends MultiDexApplication {
    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
    }
}

manifest.xml

<application
    ...
    android:name="com.example.my.app.MyApplication" >
    ...

AngularJS - value attribute for select

If you use the track by option, the value attribute is correctly written, e.g.:

<div ng-init="a = [{label: 'one', value: 15}, {label: 'two', value: 20}]">
    <select ng-model="foo" ng-options="x for x in a track by x.value"/>
</div>

produces:

<select>
    <option value="" selected="selected"></option>
    <option value="15">one</option>
    <option value="20">two</option>
</select>

Restart container within pod

There was an issue in coredns pod, I deleted such pod by

kubectl delete pod -n=kube-system coredns-fb8b8dccf-8ggcf

Its pod will restart automatically.

X close button only using css

You can use svg.

_x000D_
_x000D_
<svg viewPort="0 0 12 12" version="1.1"_x000D_
     xmlns="http://www.w3.org/2000/svg">_x000D_
    <line x1="1" y1="11" _x000D_
          x2="11" y2="1" _x000D_
          stroke="black" _x000D_
          stroke-width="2"/>_x000D_
    <line x1="1" y1="1" _x000D_
          x2="11" y2="11" _x000D_
          stroke="black" _x000D_
          stroke-width="2"/>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Set position / size of UI element as percentage of screen size

I think what you want is to set the android:layout_weight,

http://developer.android.com/resources/tutorials/views/hello-linearlayout.html

something like this (I'm just putting text views above and below as placeholders):

  <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:weightSum="1">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="68"/>
    <Gallery 
        android:id="@+id/gallery"
        android:layout_width="fill_parent"
        android:layout_height="0dp"

        android:layout_weight="16"
    />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="16"/>

  </LinearLayout>

Codeigniter : calling a method of one controller from other

You can use the redirect() function. Like this

class ControllerA extends CI_Controller{
    public function MethodA(){
       redirect("ControllerB/MethodB");
    }
}

Difference between Eclipse Europa, Helios, Galileo

Those are just version designations (just like windows xp, vista or windows 7) which they are using to name their major releases, instead of using version numbers. so you'll want to use the newest eclipse version available, which is helios (or 3.6 which is the corresponding version number).

Simple way to find if two different lists contain exactly the same elements?

Sample code:

public static '<'T'>' boolean isListDifferent(List'<'T'>' previousList,
        List'<'T'>' newList) {

    int sizePrevoisList = -1;
    int sizeNewList = -1;

    if (previousList != null && !previousList.isEmpty()) {
        sizePrevoisList = previousList.size();
    }
    if (newList != null && !newList.isEmpty()) {
        sizeNewList = newList.size();
    }

    if ((sizePrevoisList == -1) && (sizeNewList == -1)) {
        return false;
    }

    if (sizeNewList != sizePrevoisList) {
        return true;
    }

    List n_prevois = new ArrayList(previousList);
    List n_new = new ArrayList(newList);

    try {
        Collections.sort(n_prevois);
        Collections.sort(n_new);
    } catch (ClassCastException exp) {
        return true;
    }

    for (int i = 0; i < sizeNewList; i++) {
        Object obj_prevois = n_prevois.get(i);
        Object obj_new = n_new.get(i);
        if (obj_new.equals(obj_prevois)) {
            // Object are same
        } else {
            return true;
        }
    }

    return false;
}

A completely free agile software process tool

One possibility would be to use a Google Drawing, part of Google Drive, if you want a more visual and easy-to-edit option. You can create the cards by grouping a color-filled rectangle and one or more text fields together. Being a sufficiently free-form online vector drawing program, it doesn't really limit your possibilities like if you use a more dedicated solution.

The only real downsides are that you have to first create the building blocks from the beginning, and don't get numerical statistics like with a more structured tool.

How does Python's super() work with multiple inheritance?

Consider calling super().Foo() called from a sub-class. The Method Resolution Order (MRO) method is the order in which method calls are resolved.

Case 1: Single Inheritance

In this, super().Foo() will be searched up in the hierarchy and will consider the closest implementation, if found, else raise an Exception. The "is a" relationship will always be True in between any visited sub-class and its super class up in the hierarchy. But this story isn't the same always in Multiple Inheritance.

Case 2: Multiple Inheritance

Here, while searching for super().Foo() implementation, every visited class in the hierarchy may or may not have is a relation. Consider following examples:

class A(object): pass
class B(object): pass
class C(A): pass
class D(A): pass
class E(C, D): pass
class F(B): pass
class G(B): pass
class H(F, G): pass
class I(E, H): pass

Here, I is the lowest class in the hierarchy. Hierarchy diagram and MRO for I will be

enter image description here

(Red numbers showing the MRO)

MRO is I E C D A H F G B object

Note that a class X will be visited only if all its sub-classes, which inherit from it, have been visited(i.e., you should never visit a class that has an arrow coming into it from a class below that you have not yet visited).

Here, note that after visiting class C , D is visited although C and D DO NOT have is a relationship between them(but both have with A). This is where super() differs from single inheritance.

Consider a slightly more complicated example:

enter image description here

(Red numbers showing the MRO)

MRO is I E C H D A F G B object

In this case we proceed from I to E to C. The next step up would be A, but we have yet to visit D, a subclass of A. We cannot visit D, however, because we have yet to visit H, a subclass of D. The leaves H as the next class to visit. Remember, we attempt to go up in hierarchy, if possible, so we visit its leftmost superclass, D. After D we visit A, but we cannot go up to object because we have yet to visit F, G, and B. These classes, in order, round out the MRO for I.

Note that no class can appear more than once in MRO.

This is how super() looks up in the hierarchy of inheritance.

Credits for resources: Richard L Halterman Fundamentals of Python Programming

How can I kill a process by name instead of PID?

I normally use the killall command.

Check this link for details of this command.

DateTime.Compare how to check if a date is less than 30 days old?

No, the Compare function will return either 1, 0, or -1. 0 when the two values are equal, -1 and 1 mean less than and greater than, I believe in that order, but I often mix them up.

How to unzip a file using the command line?

Firstly, write an unzip utility using vbscript to trigger the native unzip functionality in Windows. Then pipe out the script from within your batch file and then call it. Then it's as good as stand alone. I've done it in the past for numerous tasks. This way it does not require need of third party applications, just the one batch file that does everything.

I put an example on my blog on how to unzip a file using a batch file:

' j_unzip.vbs
'
' UnZip a file script
'
' By Justin Godden 2010
'
' It's a mess, I know!!!
'

' Dim ArgObj, var1, var2
Set ArgObj = WScript.Arguments

If (Wscript.Arguments.Count > 0) Then
 var1 = ArgObj(0)
Else
 var1 = ""
End if

If var1 = "" then
 strFileZIP = "example.zip"
Else
 strFileZIP = var1
End if

'The location of the zip file.
REM Set WshShell = CreateObject("Wscript.Shell")
REM CurDir = WshShell.ExpandEnvironmentStrings("%%cd%%")
Dim sCurPath
sCurPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")
strZipFile = sCurPath & "\" & strFileZIP
'The folder the contents should be extracted to.
outFolder = sCurPath & "\"

 WScript.Echo ( "Extracting file " & strFileZIP)

Set objShell = CreateObject( "Shell.Application" )
Set objSource = objShell.NameSpace(strZipFile).Items()
Set objTarget = objShell.NameSpace(outFolder)
intOptions = 256
objTarget.CopyHere objSource, intOptions

 WScript.Echo ( "Extracted." )

' This bit is for testing purposes
REM Dim MyVar
REM MyVar = MsgBox ( strZipFile, 65, "MsgBox Example"

Use it like this:

cscript //B j_unzip.vbs zip_file_name_goes_here.zip

How to use JavaScript source maps (.map files)?

Just wanted to focus on the last part of the question; How source map files are created? by listing the build tools I know that can create source maps.

  1. Grunt: using plugin grunt-contrib-uglify
  2. Gulp: using plugin gulp-uglify
  3. Google closure: using parameter --create_source_map

Add left/right horizontal padding to UILabel

One thing I did to overcome this issue was to use a UIButton instead of a UILabel. Then in the Attributes Inspector of the Interface Builder, I used the Edge for the Title as the padding.
If you do not attach the button to an action, when clicked it will not get selected but it will still show the highlight.

You can also do this programmatically with the following code:

UIButton *mButton = [[UIButton alloc] init];
[mButton setTitleEdgeInsets:UIEdgeInsetsMake(top, left, bottom, right)];
[mButton setTitle:@"Title" forState:UIControlStateNormal];
[self.view addSubView:mButton];

This approach gives the same result but sometimes it did not work for some reason that I did not investigate since if possible I use the Interface Builder.

This is still a workaround but it works quite nicely if the highlight doesn't bother you. Hope it is useful

How do I name the "row names" column in r

The tibble package now has a dedicated function that converts row names to an explicit variable.

library(tibble)
rownames_to_column(mtcars, var="das_Auto") %>% head

Gives:

           das_Auto  mpg cyl disp  hp drat    wt  qsec vs am gear carb
1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

How to convert list of numpy arrays into single numpy array?

In general you can concatenate a whole sequence of arrays along any axis:

numpy.concatenate( LIST, axis=0 )

but you do have to worry about the shape and dimensionality of each array in the list (for a 2-dimensional 3x5 output, you need to ensure that they are all 2-dimensional n-by-5 arrays already). If you want to concatenate 1-dimensional arrays as the rows of a 2-dimensional output, you need to expand their dimensionality.

As Jorge's answer points out, there is also the function stack, introduced in numpy 1.10:

numpy.stack( LIST, axis=0 )

This takes the complementary approach: it creates a new view of each input array and adds an extra dimension (in this case, on the left, so each n-element 1D array becomes a 1-by-n 2D array) before concatenating. It will only work if all the input arrays have the same shape—even along the axis of concatenation.

vstack (or equivalently row_stack) is often an easier-to-use solution because it will take a sequence of 1- and/or 2-dimensional arrays and expand the dimensionality automatically where necessary and only where necessary, before concatenating the whole list together. Where a new dimension is required, it is added on the left. Again, you can concatenate a whole list at once without needing to iterate:

numpy.vstack( LIST )

This flexible behavior is also exhibited by the syntactic shortcut numpy.r_[ array1, ...., arrayN ] (note the square brackets). This is good for concatenating a few explicitly-named arrays but is no good for your situation because this syntax will not accept a sequence of arrays, like your LIST.

There is also an analogous function column_stack and shortcut c_[...], for horizontal (column-wise) stacking, as well as an almost-analogous function hstack—although for some reason the latter is less flexible (it is stricter about input arrays' dimensionality, and tries to concatenate 1-D arrays end-to-end instead of treating them as columns).

Finally, in the specific case of vertical stacking of 1-D arrays, the following also works:

numpy.array( LIST )

...because arrays can be constructed out of a sequence of other arrays, adding a new dimension to the beginning.

reading a line from ifstream into a string variable

Use the std::getline() from <string>.

 istream & getline(istream & is,std::string& str)

So, for your case it would be:

std::getline(read,x);

PSEXEC, access denied errors

For anybody who may stumble upon this. There is a recent (Dec 2013) Security Update from Microsoft Windows on Windows 7 that is preventing remote execution. See http://support.microsoft.com/kb/2893294/en-us

I uninstalled the Security Update by going to Control Panel\Programs\Programs and Features\Installed Updates

It worked right after that.

How to launch jQuery Fancybox on page load?

why isn't this one of the answers yet?:

$("#manual2").click(function() {
    $.fancybox([
        'http://farm5.static.flickr.com/4044/4286199901_33844563eb.jpg',
        'http://farm3.static.flickr.com/2687/4220681515_cc4f42d6b9.jpg',
        {
            'href'  : 'http://farm5.static.flickr.com/4005/4213562882_851e92f326.jpg',
            'title' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'
        }
    ], {
        'padding'           : 0,
        'transitionIn'      : 'none',
        'transitionOut'     : 'none',
        'type'              : 'image',
        'changeFade'        : 0
    });
});

now just trigger your link!!

got this from the Fancybox homepage

Extract names of objects from list

Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want

x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)

WORD.C <- function(WORDS){
  require(wordcloud)

  L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))

  # Takes a dataframe and the text you want to display
  FUN <- function(X, text){
    windows() 
    wordcloud(X[, 1], X[, 2], min.freq=1)
    mtext(text, 3, padj=-4.5, col="red")  #what I'm trying that isn't working
  }

  # Now creates the sequence 1,...,length(L2)
  # Loops over that and then create an anonymous function
  # to send in the information you want to use.
  lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})

  # Since you asked about loops
  # you could use i in seq_along(L2) 
  # instead of 1:length(L2) if you wanted to
  #for(i in 1:length(L2)){
  #  FUN(L2[[i]], names(L2)[i])
  #}
}

WORD.C(list.xy)

Why doesn't TFS get latest get the latest?

I had the same issue with Visual Studio 2012. No matter what I did, it didn't get the code from TFS source control.

In my case, the cause was mappings a folder + subfolder from the source control separately but to the same tree in my local HD.

The solution was removing the subfolder mapping using the "manage workspaces" window.

How to change Bootstrap's global default font size?

There are several ways but since you are using just the CSS version and not the SASS or LESS versions, your best bet to use Bootstraps own customization tool:

http://getbootstrap.com/customize/

Customize whatever you want on this page and then you can download a custom build with your own font sizes and anything else you want to change.

Altering the CSS file directly (or simply adding new CSS styles that override the Bootstrap CSS) is not recommended because other Bootstrap styles' values are derived from the base font size. For example:

https://github.com/twbs/bootstrap-sass/blob/master/assets/stylesheets/bootstrap/_variables.scss#L52

You can see that the base font size is used to calculate the sizes of the h1, h2, h3 etc. If you just changed the font size in the CSS (or added your own overriding font-size) all the other values that used the font size in calculations would no longer be proportionally accurate according to Bootstrap's design.

As I said, your best bet is to just use their own Customize tool. That is exactly what it's for.

If you are using SASS or LESS, you would change the font size in the variables file before compiling.

How to set a JavaScript breakpoint from code in Chrome?

It is possible and there are many reasons you might want to do this. For example debugging a javascript infinite loop close to the start of the page loading, that stops the chrome developer toolset (or firebug) from loading correctly.

See section 2 of

http://www.laurencegellert.com/2012/05/the-three-ways-of-setting-breakpoints-in-javascript/

or just add a line containing the word debugger to your code at the required test point.

Byte array to image conversion

You are writing to your memory stream twice, also you are not disposing the stream after use. You are also asking the image decoder to apply embedded color correction.

Try this instead:

using (var ms = new MemoryStream(byteArrayIn))
{
    return Image.FromStream(ms);
}

How to set the font size in Emacs?

Press Shift and the first mouse button. You can change the font size in the following way: This website has more detail.

Merge PDF files

The pdfrw library can do this quite easily, assuming you don't need to preserve bookmarks and annotations, and your PDFs aren't encrypted. cat.py is an example concatenation script, and subset.py is an example page subsetting script.

The relevant part of the concatenation script -- assumes inputs is a list of input filenames, and outfn is an output file name:

from pdfrw import PdfReader, PdfWriter

writer = PdfWriter()
for inpfn in inputs:
    writer.addpages(PdfReader(inpfn).pages)
writer.write(outfn)

As you can see from this, it would be pretty easy to leave out the last page, e.g. something like:

    writer.addpages(PdfReader(inpfn).pages[:-1])

Disclaimer: I am the primary pdfrw author.

How to use MySQLdb with Python and Django in OSX 10.6?

For me the problem got solved by simply reinstalling mysql-python

pip uninstall mysql-python
pip install mysql-python

IF-THEN-ELSE statements in postgresql

As stated in PostgreSQL docs here:

The SQL CASE expression is a generic conditional expression, similar to if/else statements in other programming languages.

Code snippet specifically answering your question:

SELECT field1, field2,
  CASE
    WHEN field1>0 THEN field2/field1
    ELSE 0
  END 
  AS field3
FROM test

Reset all changes after last commit in git

First, reset any changes

This will undo any changes you've made to tracked files and restore deleted files:

git reset HEAD --hard

Second, remove new files

This will delete any new files that were added since the last commit:

git clean -fd

Files that are not tracked due to .gitignore are preserved; they will not be removed

Warning: using -x instead of -fd would delete ignored files. You probably don't want to do this.

In Swift how to call method with parameters on GCD main thread?

Reload collectionView on Main Thread

DispatchQueue.main.async {
    self.collectionView.reloadData()
}

Clear variable in python

Actually, that does not delete the variable/property. All it will do is set its value to None, therefore the variable will still take up space in memory. If you want to completely wipe all existence of the variable from memory, you can just type:

del self.left

What is Android's file system?

Android supports all filesystems supported by the Linux kernel, except for a few ported ones like NTFS.

The SD card is formatted as ext3, for example.

How to interpret "loss" and "accuracy" for a machine learning model

They are two different metrics to evaluate your model's performance usually being used in different phases.

Loss is often used in the training process to find the "best" parameter values for your model (e.g. weights in neural network). It is what you try to optimize in the training by updating weights.

Accuracy is more from an applied perspective. Once you find the optimized parameters above, you use this metrics to evaluate how accurate your model's prediction is compared to the true data.

Let us use a toy classification example. You want to predict gender from one's weight and height. You have 3 data, they are as follows:(0 stands for male, 1 stands for female)

y1 = 0, x1_w = 50kg, x2_h = 160cm;

y2 = 0, x2_w = 60kg, x2_h = 170cm;

y3 = 1, x3_w = 55kg, x3_h = 175cm;

You use a simple logistic regression model that is y = 1/(1+exp-(b1*x_w+b2*x_h))

How do you find b1 and b2? you define a loss first and use optimization method to minimize the loss in an iterative way by updating b1 and b2.

In our example, a typical loss for this binary classification problem can be: (a minus sign should be added in front of the summation sign)

We don't know what b1 and b2 should be. Let us make a random guess say b1 = 0.1 and b2 = -0.03. Then what is our loss now?

so the loss is

Then you learning algorithm (e.g. gradient descent) will find a way to update b1 and b2 to decrease the loss.

What if b1=0.1 and b2=-0.03 is the final b1 and b2 (output from gradient descent), what is the accuracy now?

Let's assume if y_hat >= 0.5, we decide our prediction is female(1). otherwise it would be 0. Therefore, our algorithm predict y1 = 1, y2 = 1 and y3 = 1. What is our accuracy? We make wrong prediction on y1 and y2 and make correct one on y3. So now our accuracy is 1/3 = 33.33%

PS: In Amir's answer, back-propagation is said to be an optimization method in NN. I think it would be treated as a way to find gradient for weights in NN. Common optimization method in NN are GradientDescent and Adam.

FtpWebRequest Download File

This paragraph from the FptWebRequest class reference might be of interest to you:

The URI may be relative or absolute. If the URI is of the form "ftp://contoso.com/%2fpath" (%2f is an escaped '/'), then the URI is absolute, and the current directory is /path. If, however, the URI is of the form "ftp://contoso.com/path", first the .NET Framework logs into the FTP server (using the user name and password set by the Credentials property), then the current directory is set to /path.

Local storage in Angular 2

To store in LocalStorage :

window.localStorage.setItem(key, data);

To remove an item from LocalStorage :

window.localStorage.removeItem(key);

To get an item from LocalStorage :

window.localStorage.getItem(key);

You can only store a string in LocalStorage; if you have an object, first you have to convert it to string like the following:

window.localStorage.setItem(key, JSON.stringify(obj));

And when you want to get an object from LocalStorage :

const result=JSON.parse(window.localStorage.getItem(key));

All Tips above are the same for SessionStorage.

You can use the following service to work on SessionStorage and LocalStorage. All methods in the service :

getSession(key: string): any
setSession(key: string, value: any): void
removeSession(key: string): void
removeAllSessions(): void
getLocal(key: string): any
setLocal(key: string, value: any): void
removeLocal(key: string): void 
removeAllLocals(): void

Inject this service in your components, services and ...; Do not forget to register the service in your core module.

import { Injectable } from '@angular/core';

@Injectable()
export class BrowserStorageService {

  getSession(key: string): any {
    const data = window.sessionStorage.getItem(key);
    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  setSession(key: string, value: any): void {
    const data = value === undefined ? '' : JSON.stringify(value);
    window.sessionStorage.setItem(key, data);
  }

  removeSession(key: string): void {
    window.sessionStorage.removeItem(key);
  }

  removeAllSessions(): void {
    for (const key in window.sessionStorage) {
      if (window.sessionStorage.hasOwnProperty(key)) {
        this.removeSession(key);
      }
    }
  }

  getLocal(key: string): any {
    const data = window.localStorage.getItem(key);
    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  setLocal(key: string, value: any): void {
    const data = value === undefined ? '' : JSON.stringify(value);
    window.localStorage.setItem(key, data);
  }

  removeLocal(key: string): void {
    window.localStorage.removeItem(key);
  }

  removeAllLocals(): void {
    for (const key in window.localStorage) {
      if (window.localStorage.hasOwnProperty(key)) {
        this.removeLocal(key);
      }
    }
  }
}

Dynamic SQL results into temp table in SQL Stored procedure

Be careful of a global temp table solution as this may fail if two users use the same routine at the same time as a global temp table can be seen by all users...

Set System.Drawing.Color values

You could do:

Color c = Color.FromArgb(red, green, blue); //red, green and blue are integer variables containing red, green and blue components

How to convert seconds to HH:mm:ss in moment.js

You can use moment-duration-format plugin:

_x000D_
_x000D_
var seconds = 3820;
var duration = moment.duration(seconds, 'seconds');
var formatted = duration.format("hh:mm:ss");
console.log(formatted); // 01:03:40
_x000D_
<!-- Moment.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

<!-- moment-duration-format plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
_x000D_
_x000D_
_x000D_

See also this Fiddle

Upd: To avoid trimming for values less than 60-sec use { trim: false }:

var formatted = duration.format("hh:mm:ss", { trim: false }); // "00:00:05"

How do a send an HTTPS request through a proxy in Java?

Try the Apache Commons HttpClient library instead of trying to roll your own: http://hc.apache.org/httpclient-3.x/index.html

From their sample code:

  HttpClient httpclient = new HttpClient();
  httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);

  /* Optional if authentication is required.
  httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
   new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
  */

  PostMethod post = new PostMethod("https://someurl");
  NameValuePair[] data = {
     new NameValuePair("user", "joe"),
     new NameValuePair("password", "bloggs")
  };
  post.setRequestBody(data);
  // execute method and handle any error responses.
  // ...
  InputStream in = post.getResponseBodyAsStream();
  // handle response.


  /* Example for a GET reqeust
  GetMethod httpget = new GetMethod("https://someurl");
  try { 
    httpclient.executeMethod(httpget);
    System.out.println(httpget.getStatusLine());
  } finally {
    httpget.releaseConnection();
  }
  */

Simulating Slow Internet Connection

On Linux machines u can use wondershaper

apt-get install wondershaper

$ sudo wondershaper {interface} {down} {up}

the {down} and {up} are bandwidth in kpbs

So for example if you want to limit the bandwidth of interface eth1 to 256kbps uplink and 128kbps downlink,

$ sudo wondershaper eth1 256 128

To clear the limit,

$ sudo wondershaper clear eth1 

Serving favicon.ico in ASP.NET MVC

It should also be possible to create a controller that returns the ico file and register the route /favicon.ico to point to that controller.

How can I insert vertical blank space into an html document?

Read up some on css, it's fun: http://www.w3.org/Style/Examples/007/units.en.html

<style>
  .bottom-three {
     margin-bottom: 3cm;
  }
</style>


<p class="bottom-three">
   This is the first question?
</p>
<p class="bottom-three">
   This is the second question?
</p>

jQuery Dialog Box

My solution: remove some init options (ex. show), because constructor doesnt yield if something is not working (ex slide effect). My function without dynamic html insertion:

function ySearch(){ console.log('ysearch');
    $( "#aaa" ).dialog({autoOpen: true,closeOnEscape: true, dialogClass: "ysearch-dialog",modal: false,height: 510, width:860
    });
    $('#aaa').dialog("open");

    console.log($('#aaa').dialog("isOpen"));
    return false;
}

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

Click on Deployment Assembly ( right above Java Build Path that you show as active ) and make sure that you see json-lib-2.4-jdk15.jar there.

Usually, you should add it to your build path and export it from your project. Once it's exported you will see the WTP warning that it's not a part of the deployment. Choose the Quick Fix option and add it to your deployment path.

"make clean" results in "No rule to make target `clean'"

Check that the file is called GNUMakefile, makefile or Makefile.

If it is called anything else (and you don't want to rename it) then try:

make -f othermakefilename clean

Generate a random number in the range 1 - 10

The correct version of hythlodayr's answer.

-- ERROR:  operator does not exist: double precision % integer
-- LINE 1: select (trunc(random() * 10) % 10) + 1

The output from trunc has to be converted to INTEGER. But it can be done without trunc. So it turns out to be simple.

select (random() * 9)::INTEGER + 1

Generates an INTEGER output in range [1, 10] i.e. both 1 & 10 inclusive.

For any number (floats), see user80168's answer. i.e just don't convert it to INTEGER.

TypeError: $ is not a function when calling jQuery function

What worked for me. The first library to import is the query library and right then call the jQuery.noConflict() method.

<head>
 <script type="text/javascript" src="jquery.min.js"/>
 <script>
  var jq = jQuery.noConflict();
  jq(document).ready(function(){
  //.... your code here
    });
 </script>

Is there a better way to do optional function parameters in JavaScript?

I am used to seeing a few basic variations on handling optional variables. Sometimes, the relaxed versions are useful.

function foo(a, b, c) {
  a = a || "default";   // Matches 0, "", null, undefined, NaN, false.
  a || (a = "default"); // Matches 0, "", null, undefined, NaN, false.

  if (b == null) { b = "default"; } // Matches null, undefined.

  if (typeof c === "undefined") { c = "default"; } // Matches undefined.
}

The falsy default used with variable a is, for example, used extensively in Backbone.js.