Programs & Examples On #Group policy

Executing a batch script on Windows shutdown

You can create a local computer policy on Windows. See the TechNet at http://technet.microsoft.com/en-us/magazine/dd630947

  1. Run gpedit.msc to open the Group Policy Editor,
  2. Navigate to Computer Configuration | Windows Settings | Scripts (Startup/Shutdown).

enter image description here

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

I find the answer. 1/First put in the presets, i have this example "Output format MPEG2 DVD HQ"

-vcodec mpeg2video -vstats_file MFRfile.txt -r 29.97 -s 352x480 -aspect 4:3 -b 4000k -mbd rd -trellis -mv0 -cmp 2 -subcmp 2 -acodec mp2 -ab 192k -ar 48000 -ac 2

If you want a report includes the commands -vstats_file MFRfile.txt into the presets like the example. this can make a report which it's ubicadet in the folder source of your file Source. you can put any name if you want , i solved my problem "i write many times in this forum" reading a complete .docx about mpeg properties. finally i can do my progress bar reading this txt file generated.

Regards.

How to globally replace a forward slash in a JavaScript string?

Hi a small correction in the above script.. above script skipping the first character when displaying the output.

function stripSlashes(x)
{
var y = "";
for(i = 0; i < x.length; i++)
{
    if(x.charAt(i) == "/")
    {
        y += "";
    }
    else
    {
        y+= x.charAt(i);
    }
}
return y;   
}

Create ArrayList from array

// Guava
import com.google.common.collect.ListsLists
...
List<String> list = Lists.newArrayList(aStringArray); 

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

In my case it was an old dependency that was using compile for the transitive dependencies : com.jakewharton.hugo

After removing it from my gradle it compiled.

Android 5.0 - Add header/footer to a RecyclerView

You can use the library SectionedRecyclerViewAdapter to group your items in sections and add a header to each section, like on the image below:

enter image description here

First you create your section class:

class MySection extends StatelessSection {

    String title;
    List<String> list;

    public MySection(String title, List<String> list) {
        // call constructor with layout resources for this Section header, footer and items 
        super(R.layout.section_header, R.layout.section_item);

        this.title = title;
        this.list = list;
    }

    @Override
    public int getContentItemsTotal() {
        return list.size(); // number of items of this section
    }

    @Override
    public RecyclerView.ViewHolder getItemViewHolder(View view) {
        // return a custom instance of ViewHolder for the items of this section
        return new MyItemViewHolder(view);
    }

    @Override
    public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
        MyItemViewHolder itemHolder = (MyItemViewHolder) holder;

        // bind your view here
        itemHolder.tvItem.setText(list.get(position));
    }

    @Override
    public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
        return new SimpleHeaderViewHolder(view);
    }

    @Override
    public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
        MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder;

        // bind your header view here
        headerHolder.tvItem.setText(title);
    }
}

Then you set up the RecyclerView with your sections and change the SpanSize of the headers with a GridLayoutManager:

// Create an instance of SectionedRecyclerViewAdapter 
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();

// Create your sections with the list of data
MySection section1 = new MySection("My Section 1 title", dataList1);
MySection section2 = new MySection("My Section 2 title", dataList2);

// Add your Sections to the adapter
sectionAdapter.addSection(section1);
sectionAdapter.addSection(section2);

// Set up a GridLayoutManager to change the SpanSize of the header
GridLayoutManager glm = new GridLayoutManager(getContext(), 2);
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
    @Override
    public int getSpanSize(int position) {
        switch(sectionAdapter.getSectionItemViewType(position)) {
            case SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER:
                return 2;
            default:
                return 1;
        }
    }
});

// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(glm);
recyclerView.setAdapter(sectionAdapter);

In SQL Server, what does "SET ANSI_NULLS ON" mean?

If ANSI_NULLS is set to "ON" and if we apply = , <> on NULL column value while writing select statement then it will not return any result.

Example

create table #tempTable (sn int, ename varchar(50))

insert into #tempTable
values (1, 'Manoj'), (2, 'Pankaj'), (3, NULL), (4, 'Lokesh'), (5, 'Gopal')

SET ANSI_NULLS ON

select * from #tempTable where ename is NULL -- (1 row(s) affected)
select * from #tempTable where ename = NULL -- (0 row(s) affected)
select * from #tempTable where ename is not NULL -- (4 row(s) affected)
select * from #tempTable where ename <> NULL -- (0 row(s) affected)

SET ANSI_NULLS OFF

select * from #tempTable where ename is NULL -- (1 row(s) affected)
select * from #tempTable where ename = NULL -- (1 row(s) affected)
select * from #tempTable where ename is not NULL -- (4 row(s) affected)
select * from #tempTable where ename <> NULL -- (4 row(s) affected)

A CSS selector to get last visible div

in other way, you can do it with javascript , in Jquery you can use something like:

$('div:visible').last()

*reedited

Scala list concatenation, ::: vs ++

Legacy. List was originally defined to be functional-languages-looking:

1 :: 2 :: Nil // a list
list1 ::: list2  // concatenation of two lists

list match {
  case head :: tail => "non-empty"
  case Nil          => "empty"
}

Of course, Scala evolved other collections, in an ad-hoc manner. When 2.8 came out, the collections were redesigned for maximum code reuse and consistent API, so that you can use ++ to concatenate any two collections -- and even iterators. List, however, got to keep its original operators, aside from one or two which got deprecated.

How do I find which program is using port 80 in Windows?

Type in the command:

netstat -aon | findstr :80

It will show you all processes that use port 80. Notice the pid (process id) in the right column.

If you would like to free the port, go to Task Manager, sort by pid and close those processes.

-a displays all connections and listening ports.

-o displays the owning process ID associated with each connection.

-n displays addresses and port numbers in numerical form.

What does $(function() {} ); do?

The following is a jQuery function call:

$(...);

Which is the "jQuery function." $ is a function, and $(...) is you calling that function.

The first parameter you've supplied is the following:

function() {}

The parameter is a function that you specified, and the $ function will call the supplied method when the DOM finishes loading.

How to send control+c from a bash script?

CTRL-C generally sends a SIGINT signal to the process so you can simply do:

kill -INT <processID>

from the command line (or a script), to affect the specific processID.

I say "generally" because, as with most of UNIX, this is near infinitely configurable. If you execute stty -a, you can see which key sequence is tied to the intr signal. This will probably be CTRL-C but that key sequence may be mapped to something else entirely.


The following script shows this in action (albeit with TERM rather than INT since sleep doesn't react to INT in my environment):

#!/usr/bin/env bash

sleep 3600 &
pid=$!
sleep 5

echo ===
echo PID is $pid, before kill:
ps -ef | grep -E "PPID|$pid" | sed 's/^/   /'
echo ===

( kill -TERM $pid ) 2>&1
sleep 5

echo ===
echo PID is $pid, after kill:
ps -ef | grep -E "PPID|$pid" | sed 's/^/   /'
echo ===

It basically starts an hour-log sleep process and grabs its process ID. It then outputs the relevant process details before killing the process.

After a small wait, it then checks the process table to see if the process has gone. As you can see from the output of the script, it is indeed gone:

===
PID is 28380, before kill:
   UID   PID     PPID    TTY     STIME      COMMAND
   pax   28380   24652   tty42   09:26:49   /bin/sleep
===
./qq.sh: line 12: 28380 Terminated              sleep 3600
===
PID is 28380, after kill:
   UID   PID     PPID    TTY     STIME      COMMAND
===

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

The answers presented before mine provide apt solutions to the problem, however, I feel that it is important to understand why this error results:

The Session property of the Page returns an instance of type HttpSessionState relative to that particular request. Page.Session is actually equivalent to calling Page.Context.Session.

MSDN explains how this is possible:

Because ASP.NET pages contain a default reference to the System.Web namespace (which contains the HttpContext class), you can reference the members of HttpContext on an .aspx page without the fully qualified class reference to HttpContext.

However, When you try to access this property within a class in App_Code, the property will not be available to you unless your class derives from the Page Class.

My solution to this oft-encountered scenario is that I never pass page objects to classes. I would rather extract the required objects from the page Session and pass them to the Class in the form of a name-value collection / Array / List, depending on the case.

Reliable way to convert a file to a byte[]

looks good enough as a generic version. You can modify it to meet your needs, if they're specific enough.

also test for exceptions and error conditions, such as file doesn't exist or can't be read, etc.

you can also do the following to save some space:

 byte[] bytes = System.IO.File.ReadAllBytes(filename);

Java Could not reserve enough space for object heap error

4gb RAM doesn't mean you can use it all for java process. Lots of RAM is needed for system processes. Dont go above 2GB or it will be trouble some.

Before starting jvm just check how much RAM is available and then set memory accordingly.

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

Yes, your secret key appears to be missing. Without it, you will not be able to decrypt the files.

Do you have the key backed up somewhere?

Re-creating the keys, whether you use the same passphrase or not, will not work. Each key pair is unique.

Double Iteration in List Comprehension

I hope this helps someone else since a,b,x,y don't have much meaning to me! Suppose you have a text full of sentences and you want an array of words.

# Without list comprehension
list_of_words = []
for sentence in text:
    for word in sentence:
       list_of_words.append(word)
return list_of_words

I like to think of list comprehension as stretching code horizontally.

Try breaking it up into:

# List Comprehension 
[word for sentence in text for word in sentence]

Example:

>>> text = (("Hi", "Steve!"), ("What's", "up?"))
>>> [word for sentence in text for word in sentence]
['Hi', 'Steve!', "What's", 'up?']

This also works for generators

>>> text = (("Hi", "Steve!"), ("What's", "up?"))
>>> gen = (word for sentence in text for word in sentence)
>>> for word in gen: print(word)
Hi
Steve!
What's
up?

Multi-dimensional arrays in Bash

After a lot of trial and error i actually find the best, clearest and easiest multidimensional array on bash is to use a regular var. Yep.

Advantages: You don't have to loop through a big array, you can just echo "$var" and use grep/awk/sed. It's easy and clear and you can have as many columns as you like.

Example:

$ var=$(echo -e 'kris hansen oslo\nthomas jonson peru\nbibi abu johnsonville\njohnny lipp peru')

$ echo "$var"
kris hansen oslo
thomas johnson peru
bibi abu johnsonville
johnny lipp peru

If you want to find everyone in peru

$ echo "$var" | grep peru
thomas johnson peru
johnny lipp peru

Only grep(sed) in the third field

$ echo "$var" | sed -n -E '/(.+) (.+) peru/p'
thomas johnson peru
johnny lipp peru

If you only want x field

$ echo "$var" | awk '{print $2}'
hansen
johnson
abu
johnny

Everyone in peru that's called thomas and just return his lastname

$ echo "$var" |grep peru|grep thomas|awk '{print $2}'
johnson

Any query you can think of... supereasy.

To change an item:

$ var=$(echo "$var"|sed "s/thomas/pete/")

To delete a row that contains "x"

$ var=$(echo "$var"|sed "/thomas/d")

To change another field in the same row based on a value from another item

$ var=$(echo "$var"|sed -E "s/(thomas) (.+) (.+)/\1 test \3/")
$ echo "$var"
kris hansen oslo                                                                                                                                             
thomas test peru                                                                                                                                          
bibi abu johnsonville
johnny lipp peru

Of course looping works too if you want to do that

$ for i in "$var"; do echo "$i"; done
kris hansen oslo
thomas jonson peru
bibi abu johnsonville
johnny lipp peru

The only gotcha iv'e found with this is that you must always quote the var(in the example; both var and i) or things will look like this

$ for i in "$var"; do echo $i; done
kris hansen oslo thomas jonson peru bibi abu johnsonville johnny lipp peru

and someone will undoubtedly say it won't work if you have spaces in your input, however that can be fixed by using another delimeter in your input, eg(using an utf8 char now to emphasize that you can choose something your input won't contain, but you can choose whatever ofc):

$ var=$(echo -e 'field one?field two hello?field three yes moin\nfield 1?field 2?field 3 dsdds aq')

$ for i in "$var"; do echo "$i"; done
field one?field two hello?field three yes moin
field 1?field 2?field 3 dsdds aq

$ echo "$var" | awk -F '?' '{print $3}'
field three yes moin
field 3 dsdds aq

$ var=$(echo "$var"|sed -E "s/(field one)?(.+)?(.+)/\1?test?\3/")
$ echo "$var"
field one?test?field three yes moin
field 1?field 2?field 3 dsdds aq

If you want to store newlines in your input, you could convert the newline to something else before input and convert it back again on output(or don't use bash...). Enjoy!

What does `dword ptr` mean?

It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:

[bits 32]
.
.
and  [ebp-4], 0

Simple way to calculate median with MySQL

A comment on this page in the MySQL documentation has the following suggestion:

-- (mostly) High Performance scaling MEDIAN function per group
-- Median defined in http://en.wikipedia.org/wiki/Median
--
-- by Peter Hlavac
-- 06.11.2008
--
-- Example Table:

DROP table if exists table_median;
CREATE TABLE table_median (id INTEGER(11),val INTEGER(11));
COMMIT;


INSERT INTO table_median (id, val) VALUES
(1, 7), (1, 4), (1, 5), (1, 1), (1, 8), (1, 3), (1, 6),
(2, 4),
(3, 5), (3, 2),
(4, 5), (4, 12), (4, 1), (4, 7);



-- Calculating the MEDIAN
SELECT @a := 0;
SELECT
id,
AVG(val) AS MEDIAN
FROM (
SELECT
id,
val
FROM (
SELECT
-- Create an index n for every id
@a := (@a + 1) mod o.c AS shifted_n,
IF(@a mod o.c=0, o.c, @a) AS n,
o.id,
o.val,
-- the number of elements for every id
o.c
FROM (
SELECT
t_o.id,
val,
c
FROM
table_median t_o INNER JOIN
(SELECT
id,
COUNT(1) AS c
FROM
table_median
GROUP BY
id
) t2
ON (t2.id = t_o.id)
ORDER BY
t_o.id,val
) o
) a
WHERE
IF(
-- if there is an even number of elements
-- take the lower and the upper median
-- and use AVG(lower,upper)
c MOD 2 = 0,
n = c DIV 2 OR n = (c DIV 2)+1,

-- if its an odd number of elements
-- take the first if its only one element
-- or take the one in the middle
IF(
c = 1,
n = 1,
n = c DIV 2 + 1
)
)
) a
GROUP BY
id;

-- Explanation:
-- The Statement creates a helper table like
--
-- n id val count
-- ----------------
-- 1, 1, 1, 7
-- 2, 1, 3, 7
-- 3, 1, 4, 7
-- 4, 1, 5, 7
-- 5, 1, 6, 7
-- 6, 1, 7, 7
-- 7, 1, 8, 7
--
-- 1, 2, 4, 1

-- 1, 3, 2, 2
-- 2, 3, 5, 2
--
-- 1, 4, 1, 4
-- 2, 4, 5, 4
-- 3, 4, 7, 4
-- 4, 4, 12, 4


-- from there we can select the n-th element on the position: count div 2 + 1 

Fastest way to get the first n elements of a List into an Array

Assumption:

list - List<String>

Using Java 8 Streams,

  • to get first N elements from a list into a list,

    List<String> firstNElementsList = list.stream().limit(n).collect(Collectors.toList());

  • to get first N elements from a list into an Array,

    String[] firstNElementsArray = list.stream().limit(n).collect(Collectors.toList()).toArray(new String[n]);

Python 2,3 Convert Integer to "bytes" Cleanly

You can use the struct's pack:

In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'

The ">" is the byte-order (big-endian) and the "I" is the format character. So you can be specific if you want to do something else:

In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'

In [13]: struct.pack("B", 1)
Out[13]: '\x01'

This works the same on both python 2 and python 3.

Note: the inverse operation (bytes to int) can be done with unpack.

keytool error bash: keytool: command not found

If you are not using openjdk, use the below commands to set your keytool.

sudo update-alternatives --install "/usr/bin/keytool" "keytool" "/usr/lib/jvm/java8/jdk1.8.0_251/bin/keytool" 1

AND

sudo update-alternatives --set keytool /usr/lib/jvm/java8/jdk1.8.0_251/bin/keytool

This worked for me!

How do you dismiss the keyboard when editing a UITextField

if you want all editing of in a UIViewController you can use.

[[self view]endEditing:YES];

and if you want dismiss a perticular UITextField keyboard hide then use.

1.add delegate in your viewcontroller.h

<UITextFieldDelegate>
  1. make delegation unable to your textfield .

    self.yourTextField.delegate = self;

  2. add this method in to your viewcontroller.

    -(BOOL)textFieldShouldEndEditing:(UITextField *)textField{ [textField resignFirstResponder]; return YES;}

SCRIPT5: Access is denied in IE9 on xmlhttprequest

I had faced similar issue on IE10. I had a workaround by using the jQuery ajax request to retrieve data:

$.ajax({
    url: YOUR_XML_FILE
    aync: false,
    success: function (data) {   
        // Store data into a variable
    },
    dataType: YOUR_DATA_TYPE,
    complete: ON_COMPLETE_FUNCTION_CALL
});

Search and replace in bash using regular expressions

I know this is an ancient thread, but it was my first hit on Google, and I wanted to share the following resub that I put together, which adds support for multiple $1, $2, etc. backreferences...

#!/usr/bin/env bash

############################################
###  resub - regex substitution in bash  ###
############################################

resub() {
    local match="$1" subst="$2" tmp

    if [[ -z $match ]]; then
        echo "Usage: echo \"some text\" | resub '(.*) (.*)' '\$2 me \${1}time'" >&2
        return 1
    fi

    ### First, convert "$1" to "$BASH_REMATCH[1]" and 'single-quote' for later eval-ing...

    ### Utility function to 'single-quote' a list of strings
    squot() { local a=(); for i in "$@"; do a+=( $(echo \'${i//\'/\'\"\'\"\'}\' )); done; echo "${a[@]}"; }

    tmp=""
    while [[ $subst =~ (.*)\${([0-9]+)}(.*) ]] || [[ $subst =~ (.*)\$([0-9]+)(.*) ]]; do
        tmp="\${BASH_REMATCH[${BASH_REMATCH[2]}]}$(squot "${BASH_REMATCH[3]}")${tmp}"
        subst="${BASH_REMATCH[1]}"
    done
    subst="$(squot "${subst}")${tmp}"

    ### Now start (globally) substituting

    tmp=""
    while read line; do
        counter=0
        while [[ $line =~ $match(.*) ]]; do
            eval tmp='"${tmp}${line%${BASH_REMATCH[0]}}"'"${subst}"
            line="${BASH_REMATCH[$(( ${#BASH_REMATCH[@]} - 1 ))]}"
        done
        echo "${tmp}${line}"
    done
}

resub "$@"

##################
###  EXAMPLES  ###
##################

###  % echo "The quick brown fox jumps quickly over the lazy dog" | resub quick slow
###    The slow brown fox jumps slowly over the lazy dog

###  % echo "The quick brown fox jumps quickly over the lazy dog" | resub 'quick ([^ ]+) fox' 'slow $1 sheep'
###    The slow brown sheep jumps quickly over the lazy dog

###  % animal="sheep"
###  % echo "The quick brown fox 'jumps' quickly over the \"lazy\" \$dog" | resub 'quick ([^ ]+) fox' "\"\$low\" \${1} '$animal'"
###    The "$low" brown 'sheep' 'jumps' quickly over the "lazy" $dog

###  % echo "one two three four five" | resub "one ([^ ]+) three ([^ ]+) five" 'one $2 three $1 five'
###    one four three two five

###  % echo "one two one four five" | resub "one ([^ ]+) " 'XXX $1 '
###    XXX two XXX four five

###  % echo "one two three four five one six three seven eight" | resub "one ([^ ]+) three ([^ ]+) " 'XXX $1 YYY $2 '
###    XXX two YYY four five XXX six YYY seven eight

H/T to @Charles Duffy re: (.*)$match(.*)

Get selected value from combo box in C# WPF

Write it like this:

String CmbTitle = (cmb.SelectedItem as ComboBoxItem).Content.ToString()

Replace line break characters with <br /> in ASP.NET MVC Razor view

Applying the DRY principle to Omar's solution, here's an HTML Helper extension:

using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace System.Web.Mvc.Html {
    public static class MyHtmlHelpers {
        public static MvcHtmlString EncodedReplace(this HtmlHelper helper, string input, string pattern, string replacement) {
            return new MvcHtmlString(Regex.Replace(helper.Encode(input), pattern, replacement));
        }
    }
}

Usage (with improved regex):

@Html.EncodedReplace(Model.CommentText, "[\n\r]+", "<br />")

This also has the added benefit of putting less onus on the Razor View developer to ensure security from XSS vulnerabilities.


My concern with Jacob's solution is that rendering the line breaks with CSS breaks the HTML semantics.

Sequence contains more than one element

The problem is that you are using SingleOrDefault. This method will only succeed when the collections contains exactly 0 or 1 element. I believe you are looking for FirstOrDefault which will succeed no matter how many elements are in the collection.

Java - Abstract class to contain variables?

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

How to recursively download a folder via FTP on Linux

toggle the prompt by PROMPT command.

Usage:

ftp>cd /to/directory    
ftp>prompt    
ftp>mget  *

Search text in stored procedure in SQL Server

Every so often I use this script to figure out which procs to modify, or to figure out what uses a column of a table, or that table at all to remove some old junk. It checks each database on the instance it is ran on by the wonderfully supplied sp_msforeachdb.

if object_id('tempdb..##nothing') is not null
    drop table ##nothing

CREATE TABLE ##nothing
(
    DatabaseName varchar(30),
    SchemaName varchar(30),
    ObjectName varchar(100),
    ObjectType varchar(50)
)

EXEC master.sys.sp_msforeachdb 
'USE ?
insert into ##nothing
SELECT 
db_name() AS [Database],
[Scehma]=schema_name(o.schema_id), 
o.Name, 
o.type 
FROM sys.sql_modules m
INNER JOIN sys.objects o
    ON o.object_id = m.object_id
WHERE 
    m.definition like ''%SOME_TEXT%'''  
--edit this text

SELECT * FROM ##nothing n
order by OBJECTname 

querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript

querySelector can be a complete CSS(3)-Selector with IDs and Classes and Pseudo-Classes together like this:

'#id.class:pseudo'

// or

'tag #id .class .class.class'

with getElementsByClassName you can just define a class

'class'

with getElementById you can just define an id

'id'

How to get the bluetooth devices as a list?

I tried the below code,

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<TextView 
    android:id="@+id/bluetoothstate" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
<Button
    android:id="@+id/listpaireddevices" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:text="List Paired Devices" 
    android:enabled="false"
    /> 
<TextView
    android:id="@+id/bluetoothstate" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />

ListPairedDevicesActivity.java

import java.util.Set;

import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListPairedDevicesActivity extends ListActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);

  ArrayAdapter<String> btArrayAdapter 
    = new ArrayAdapter<String>(this,
             android.R.layout.simple_list_item_1);

  BluetoothAdapter bluetoothAdapter 
   = BluetoothAdapter.getDefaultAdapter();
  Set<BluetoothDevice> pairedDevices 
   = bluetoothAdapter.getBondedDevices();

  if (pairedDevices.size() > 0) {
      for (BluetoothDevice device : pairedDevices) {
       String deviceBTName = device.getName();
       String deviceBTMajorClass 
        = getBTMajorDeviceClass(device
          .getBluetoothClass()
          .getMajorDeviceClass());
       btArrayAdapter.add(deviceBTName + "\n" 
         + deviceBTMajorClass);
      }
  }
  setListAdapter(btArrayAdapter);

 }

 private String getBTMajorDeviceClass(int major){
  switch(major){ 
  case BluetoothClass.Device.Major.AUDIO_VIDEO:
   return "AUDIO_VIDEO";
  case BluetoothClass.Device.Major.COMPUTER:
   return "COMPUTER";
  case BluetoothClass.Device.Major.HEALTH:
   return "HEALTH";
  case BluetoothClass.Device.Major.IMAGING:
   return "IMAGING"; 
  case BluetoothClass.Device.Major.MISC:
   return "MISC";
  case BluetoothClass.Device.Major.NETWORKING:
   return "NETWORKING"; 
  case BluetoothClass.Device.Major.PERIPHERAL:
   return "PERIPHERAL";
  case BluetoothClass.Device.Major.PHONE:
   return "PHONE";
  case BluetoothClass.Device.Major.TOY:
   return "TOY";
  case BluetoothClass.Device.Major.UNCATEGORIZED:
   return "UNCATEGORIZED";
  case BluetoothClass.Device.Major.WEARABLE:
   return "AUDIO_VIDEO";
  default: return "unknown!";
  }
 }

 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
  // TODO Auto-generated method stub
  super.onListItemClick(l, v, position, id);

     Intent intent = new Intent();
     setResult(RESULT_OK, intent);
     finish();
 }

}

AndroidBluetooth.java

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AndroidBluetooth extends Activity {

 private static final int REQUEST_ENABLE_BT = 1;
 private static final int REQUEST_PAIRED_DEVICE = 2;

    /** Called when the activity is first created. */
 Button btnListPairedDevices;
 TextView stateBluetooth;
 BluetoothAdapter bluetoothAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnListPairedDevices = (Button)findViewById(R.id.listpaireddevices);

        stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        CheckBlueToothState();

        btnListPairedDevices.setOnClickListener(btnListPairedDevicesOnClickListener);
    }

    private void CheckBlueToothState(){
     if (bluetoothAdapter == null){
         stateBluetooth.setText("Bluetooth NOT support");
        }else{
         if (bluetoothAdapter.isEnabled()){
          if(bluetoothAdapter.isDiscovering()){
           stateBluetooth.setText("Bluetooth is currently in device discovery process.");
          }else{
           stateBluetooth.setText("Bluetooth is Enabled.");
           btnListPairedDevices.setEnabled(true);
          }
         }else{
          stateBluetooth.setText("Bluetooth is NOT Enabled!");
          Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
             startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
         }
        }
    }

    private Button.OnClickListener btnListPairedDevicesOnClickListener
    = new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   Intent intent = new Intent();
   intent.setClass(AndroidBluetooth.this, ListPairedDevicesActivity.class);
   startActivityForResult(intent, REQUEST_PAIRED_DEVICE); 
  }};

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  if(requestCode == REQUEST_ENABLE_BT){
   CheckBlueToothState();
  }if (requestCode == REQUEST_PAIRED_DEVICE){
   if(resultCode == RESULT_OK){

   }
  } 
 }   
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test.AndroidBluetooth"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidBluetooth"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
  <activity android:name=".ListPairedDevicesActivity" 
      android:label="AndroidBluetooth: List of Paired Devices"/>
    </application>
</manifest>

Declare an array in TypeScript

this is how you can create an array of boolean in TS and initialize it with false:

var array: boolean[] = [false, false, false]

or another approach can be:

var array2: Array<boolean> =[false, false, false] 

you can specify the type after the colon which in this case is boolean array

"The file "MyApp.app" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4

I had the same issue with Xcode 10 & react-native. All the above solutions didn't help me.

My solution: Create a new project with the same name. And change project & workspace files with the ones from the duplicated project. And it works!!! (after some small build-issues with path etc)

How to check if an element exists in the xml using xpath?

The Saxon documentation, though a little unclear, seems to suggest that the JAXP XPath API will return false when evaluating an XPath expression if no matching nodes are found.

This IBM article mentions a return value of null when no nodes are matched.

You might need to play around with the return types a bit based on this API, but the basic idea is that you just run a normal XPath and check whether the result is a node / false / null / etc.

XPathFactory xpathFactory = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
XPath xpath = xpathFactory.newXPath();
XPathExpression expr = xpath.compile("/Consumers/Consumer/DataSources/Credit/CreditReport/AttachedXml");
Object result = expr.evaluate(doc, XPathConstants.NODE);

if ( result == null ) {
    // do something
}

Android get Current UTC time

see my answer here:

How can I get the current date and time in UTC or GMT in Java?

I've fully tested it by changing the timezones on the emulator

Change user-agent for Selenium web-driver

There is no way in Selenium to read the request or response headers. You could do it by instructing your browser to connect through a proxy that records this kind of information.

Setting the User Agent in Firefox

The usual way to change the user agent for Firefox is to set the variable "general.useragent.override" in your Firefox profile. Note that this is independent from Selenium.

You can direct Selenium to use a profile different from the default one, like this:

from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "whatever you want")
driver = webdriver.Firefox(profile)

Setting the User Agent in Chrome

With Chrome, what you want to do is use the user-agent command line option. Again, this is not a Selenium thing. You can invoke Chrome at the command line with chrome --user-agent=foo to set the agent to the value foo.

With Selenium you set it like this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
opts = Options()
opts.add_argument("user-agent=whatever you want")

driver = webdriver.Chrome(chrome_options=opts)

Both methods above were tested and found to work. I don't know about other browsers.

Getting the User Agent

Selenium does not have methods to query the user agent from an instance of WebDriver. Even in the case of Firefox, you cannot discover the default user agent by checking what general.useragent.override would be if not set to a custom value. (This setting does not exist before it is set to some value.)

Once the browser is started, however, you can get the user agent by executing:

agent = driver.execute_script("return navigator.userAgent")

The agent variable will contain the user agent.

Add click event on div tag using javascript

Pure Javascript

document.getElementsByClassName('drill_cursor')[0]
        .addEventListener('click', function (event) {
            // do something
        });

jQuery

$(".drill_cursor").click(function(){
//do something
});

Compiler error: "initializer element is not a compile-time constant"

When you define a variable outside the scope of a function, that variable's value is actually written into your executable file. This means you can only use a constant value. Since you don't know everything about the runtime environment at compile time (which classes are available, what is their structure, etc.), you cannot create objective c objects until runtime, with the exception of constant strings, which are given a specific structure and guaranteed to stay that way. What you should do is initialize the variable to nil and use +initialize to create your image. initialize is a class method which will be called before any other method is called on your class.

Example:

NSImage *imageSegment = nil;
+ (void)initialize {
    if(!imageSegment)
        imageSegment = [[NSImage alloc] initWithContentsOfFile:@"/User/asd.jpg"];
}
- (id)init {
    self = [super init];
    if (self) {
        // Initialization code here.
    }

    return self;
}

How to rename a table column in Oracle 10g

The syntax of the query is as follows:

Alter table <table name> rename column <column name> to <new column name>;

Example:

Alter table employee rename column eName to empName;

To rename a column name without space to a column name with space:

Alter table employee rename column empName to "Emp Name";

To rename a column with space to a column name without space:

Alter table employee rename column "emp name" to empName;

How to find the mime type of a file in python?

For byte Array type data you can use magic.from_buffer(_byte_array,mime=True)

How to create json by JavaScript for loop?

From what I understand of your request, this should work:

<script>
//  var status  = document.getElementsByID("uniqueID"); // this works too
var status  = document.getElementsByName("status")[0];
var jsonArr = [];

for (var i = 0; i < status.options.length; i++) {
    jsonArr.push({
        id: status.options[i].text,
        optionValue: status.options[i].value
    });
}
</script>

CSS Margin: 0 is not setting to 0

you should have either (or both):

  1. a paddding != 0 on body
  2. a margin !=0 on #header

try

html, #header {
    margin: 0 !important;
    padding: 0 !important;
}

The margin is the "space" outside the box, the padding is the "space" inside the box (between the border and the content). The !important prevent overriding of property by latter rules.

Map with Key as String and Value as List in Groovy

Joseph forgot to add the value in his example with withDefault. Here is the code I ended up using:

Map map = [:].withDefault { key -> return [] }
listOfObjects.each { map.get(it.myKey).add(it.myValue) }

WARNING: Can't verify CSRF token authenticity rails

I just thought I'd link this here as the article has most of the answer you're looking for and it's also very interesting

http://www.kalzumeus.com/2011/11/17/i-saw-an-extremely-subtle-bug-today-and-i-just-have-to-tell-someone/

SVG fill color transparency / alpha?

To change transparency on an svg code the simplest way is to open it on any text editor and look for the style attributes. It depends on the svg creator the way the styles are displayed. As i am an Inkscape user the usual way it set the style values is through a style tag just as if it were html but using svg native attributes like fill, stroke, stroke-width, opacity and so on. opacity affects the whole svg object, or path or group in which its stated and fill-opacity, stroke-opacity will affect just the fill and the stroke transparency. That said, I have also used and tasted to just use fill and instead of using#fff use instead the rgba standard like this rgba(255, 255, 255, 1) just as in css. This works fine for must modern browsers.

Keep in mind that if you intend to further reedit your svg the best practice, in my experience, is to always keep an untouched version at hand. Inkscape is more flexible with hand changed svgs but Illustrator and CorelDraw may have issues importing and edited svg.

Example

<path style="fill:#ff0000;fill-opacity:1;stroke:#1a1a1a;stroke-width:2px;stroke-opacity:1" d="m 144.44226,461.14425 q 16.3125,-15.05769 37.64423,-15.05769 21.33173,0 36.38942,15.05769 15.0577,15.05769 15.0577,36.38942 0,21.33173 -15.0577,36.38943 -15.05769,16.3125 -36.38942,16.3125 -21.33173,0 -37.64423,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z M 28.99995,35.764435 l 85.32692,0 23.84135,52.701923 386.48078,0 q 10.03846,0 17.5673,7.528847 8.78366,7.528845 8.78366,17.567305 0,7.52885 -2.50962,12.54808 l -94.11058,161.87019 q -13.80288,27.60577 -45.17307,27.60577 l -194.4952,0 -26.35096,40.15385 q -2.50962,6.27404 -2.50962,7.52885 0,6.27404 6.27404,6.27404 l 298.64424,0 0,50.1923 -304.91828,0 q -25.09615,0 -41.40865,-13.80288 -15.05769,-13.80289 -15.05769,-38.89904 0,-15.05769 6.27404,-25.09615 l 38.89903,-63.9952 -92.855766,-189.475962 -52.701924,0 0,-52.701923 z M 401.67784,461.14425 q 15.05769,-15.05769 36.38942,-15.05769 21.33174,0 36.38943,15.05769 16.3125,15.05769 16.3125,36.38942 0,21.33173 -16.3125,36.38943 -15.05769,16.3125 -36.38943,16.3125 -21.33173,0 -36.38942,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z"/>

Example 2

<path style="fill:#ff0000;fill-opacity:.5;stroke:#1a1a1a;stroke-width:2px;stroke-opacity:1" d="m 144.44226,461.14425 q 16.3125,-15.05769 37.64423,-15.05769 21.33173,0 36.38942,15.05769 15.0577,15.05769 15.0577,36.38942 0,21.33173 -15.0577,36.38943 -15.05769,16.3125 -36.38942,16.3125 -21.33173,0 -37.64423,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z M 28.99995,35.764435 l 85.32692,0 23.84135,52.701923 386.48078,0 q 10.03846,0 17.5673,7.528847 8.78366,7.528845 8.78366,17.567305 0,7.52885 -2.50962,12.54808 l -94.11058,161.87019 q -13.80288,27.60577 -45.17307,27.60577 l -194.4952,0 -26.35096,40.15385 q -2.50962,6.27404 -2.50962,7.52885 0,6.27404 6.27404,6.27404 l 298.64424,0 0,50.1923 -304.91828,0 q -25.09615,0 -41.40865,-13.80288 -15.05769,-13.80289 -15.05769,-38.89904 0,-15.05769 6.27404,-25.09615 l 38.89903,-63.9952 -92.855766,-189.475962 -52.701924,0 0,-52.701923 z M 401.67784,461.14425 q 15.05769,-15.05769 36.38942,-15.05769 21.33174,0 36.38943,15.05769 16.3125,15.05769 16.3125,36.38942 0,21.33173 -16.3125,36.38943 -15.05769,16.3125 -36.38943,16.3125 -21.33173,0 -36.38942,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z"/>

Example 3

<path style="fill:rgba(255, 0, 0, .5;stroke:#1a1a1a;stroke-width:2px;stroke-opacity:1" d="m 144.44226,461.14425 q 16.3125,-15.05769 37.64423,-15.05769 21.33173,0 36.38942,15.05769 15.0577,15.05769 15.0577,36.38942 0,21.33173 -15.0577,36.38943 -15.05769,16.3125 -36.38942,16.3125 -21.33173,0 -37.64423,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z M 28.99995,35.764435 l 85.32692,0 23.84135,52.701923 386.48078,0 q 10.03846,0 17.5673,7.528847 8.78366,7.528845 8.78366,17.567305 0,7.52885 -2.50962,12.54808 l -94.11058,161.87019 q -13.80288,27.60577 -45.17307,27.60577 l -194.4952,0 -26.35096,40.15385 q -2.50962,6.27404 -2.50962,7.52885 0,6.27404 6.27404,6.27404 l 298.64424,0 0,50.1923 -304.91828,0 q -25.09615,0 -41.40865,-13.80288 -15.05769,-13.80289 -15.05769,-38.89904 0,-15.05769 6.27404,-25.09615 l 38.89903,-63.9952 -92.855766,-189.475962 -52.701924,0 0,-52.701923 z M 401.67784,461.14425 q 15.05769,-15.05769 36.38942,-15.05769 21.33174,0 36.38943,15.05769 16.3125,15.05769 16.3125,36.38942 0,21.33173 -16.3125,36.38943 -15.05769,16.3125 -36.38943,16.3125 -21.33173,0 -36.38942,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z"/>

Notice that in the last example the fill-opacity has been removed as rgba standard covers both color and alpha channel.

How can I force a hard reload in Chrome for Android

You can use the Request Desktop Site option from the app menu (to the right of the address bar) which will force the page to reload.

Simply tap it, wait for the refresh, then deselect it.

How to trap the backspace key using jQuery?

try this one :

 $('html').keyup(function(e){if(e.keyCode == 8)alert('backspace trapped')})  

How to redirect to another page using AngularJS?

A good way to do this is using $state.go('statename', {params...}) is faster and more friendly for user experience in cases when you don't have to reload and bootsraping whole app config and stuff

(function() {
    'use strict';

    angular
        .module('app.appcode')
        .controller('YourController', YourController);

    YourController.$inject = ['rootURL', '$scope', '$state', '$http'];

    function YourController(rootURL, $scope, $state, $http) {

        $http({
                url: rootURL + 'app-code/common.service.php',
                method: "POST",
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                dataType: 'json',
                data:data + '&method=signin'

            }).success(function (response) {
                if (response['code'] == '420') {

                    $scope.message = response['message'];
                    $scope.loginPassword = '';
                } else if (response['code'] != '200') {

                    $scope.message = response['message'];
                    $scope.loginPassword = '';
                } else {
                    // $state.go('home'); // select here the route that you want to redirect
                    $state.go(response['state']); // response['state'] should be a route on your app.routes
                }
            })
    }

});

// routes

(function() {
    'use strict';

    angular
        .module('app')
        .config(routes);

    routes.$inject = [
        '$stateProvider',
        '$urlRouterProvider'
    ];

    function routes($stateProvider, $urlRouterProvider) {
        /**
         * Default path for any unmatched url
        */
        $urlRouterProvider.otherwise('/');

        $stateProvider
            .state('home', {
                url: '/',
                templateUrl: '/app/home/home.html',
                controller: 'Home'
            })
            .state('login', {
                url: '/login',
                templateUrl: '/app/login/login.html',
                controller: 'YourController'
            })
            // ... more routes .state
   }

})();

How can I compare two dates in PHP?

If all your dates are posterior to the 1st of January of 1970, you could use something like:

$today = date("Y-m-d");
$expire = $row->expireDate; //from database

$today_time = strtotime($today);
$expire_time = strtotime($expire);

if ($expire_time < $today_time) { /* do Something */ }

If you are using PHP 5 >= 5.2.0, you could use the DateTime class:

$today_dt = new DateTime($today);
$expire_dt = new DateTime($expire);

if ($expire_dt < $today_dt) { /* Do something */ }

Or something along these lines.

Can't update data-attribute value

Basically, there are two ways to set / update data attribute value, depends on your need. The difference is just, where the data saved,

If you use .data() it will be saved in local variable called data_user, and its not visible upon element inspection, If you use .attr() it will be publicly visible.

Much clearer explanation on this comment

System.Data.OracleClient requires Oracle client software version 8.1.7

When we first moved over to Vista with Oracle 10g, we experienced this issue when we installed the Oracle client on our Vista boxes, even when we were running with admin privileges during install.

Oracle brought out a new version of the 10g client (10.2.0.3) that was Vista compatible.

I do believe that this was after 11g was released, so it is possible that there is a 'Vista compatible' version for 11g also.

Programmatically set the initial view controller using Storyboards

I don't think it's possible. Instead you can have one initial controller which will have segues to different view controllers. On startup, you can decide which segue to perform programmatically.

Get current cursor position

GetCursorPos() will return to you the x/y if you pass in a pointer to a POINT structure.

Hiding the cursor can be done with ShowCursor().

Can Powershell Run Commands in Parallel?

You can execute parallel jobs in Powershell 2 using Background Jobs. Check out Start-Job and the other job cmdlets.

# Loop through the server list
Get-Content "ServerList.txt" | %{

  # Define what each job does
  $ScriptBlock = {
    param($pipelinePassIn) 
    Test-Path "\\$pipelinePassIn\c`$\Something"
    Start-Sleep 60
  }

  # Execute the jobs in parallel
  Start-Job $ScriptBlock -ArgumentList $_
}

Get-Job

# Wait for it all to complete
While (Get-Job -State "Running")
{
  Start-Sleep 10
}

# Getting the information back from the jobs
Get-Job | Receive-Job

Evaluate if list is empty JSTL

empty is an operator:

The empty operator is a prefix operation that can be used to determine whether a value is null or empty.

<c:if test="${empty myObject.featuresList}">

Imply bit with constant 1 or 0 in SQL Server

Enjoy this :) Without cast each value individually.

SELECT ...,
  IsCoursedBased = CAST(
      CASE WHEN fc.CourseId is not null THEN 1 ELSE 0 END
    AS BIT
  )
FROM fc

Convert.ToDateTime: how to set format

DateTime doesn't have a format. the format only applies when you're turning a DateTime into a string, which happens implicitly you show the value on a form, web page, etc.

Look at where you're displaying the DateTime and set the format there (or amend your question if you need additional guidance).

Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

plot(t) is in this case the same as

plot(t[[1]], t[[2]])

As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

> length(t)
[1] 4
> length(1)
[1] 1

In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.

Edit:

If you want to plot lines use

plot(t, type="l")

Text Editor which shows \r\n?

With Notepad++, you can show end-of-line characters. It shows CR and LF, instead of "\r" and "\n", but it gets the point across. However, it will still insert the line breaks. But you do get to see the line-ending characters.

To use Notepad++ for this, open the View menu, open the Show Symbols slide out, and select either "Show all characters" or "Show end-of-line characters".

enter image description here

PHP using Gettext inside <<<EOF string

As far as I can see, you just added heredoc by mistake
No need to use ugly heredoc syntax here.
Just remove it and everything will work:

<p>Hello</p>
<p><?= _("World"); ?></p>

How to set the height of table header in UITableView?

In case you still need it, have you tried to set the property

self.tableView.tableHeaderView 

If you calculate the heigh you need, and set a new view for tableHeaderView:

CGRect frame = self.tableView.tableHeaderView.frame;
frame.size.height = newHeight;

self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:frame];

It should work.

How to automatically update your docker containers, if base-images are updated

have you tried this: https://github.com/v2tec/watchtower. it's a simple tool running in docker container watching other containers, if their base image changed, it will pull and redeploy.

MVC4 input field placeholder

Try this:

@Html.TextbBoxFor(x=>x.Email,new { @[email protected]}

If this possible or else what could be the way

How can I exclude multiple folders using Get-ChildItem -exclude?

You can exclude like this, the regex 'or' symbol, assuming a file you want doesn't have the same name as a folder you're excluding.

$exclude = 'dir1|dir2|dir3'
ls -r | where { $_.fullname -notmatch $exclude }

ls -r -dir | where fullname -notmatch 'dir1|dir2|dir3'

Detect change to selected date with bootstrap-datepicker

Try this:

$("#dp3").on("dp.change", function(e) {
    alert('hey');
});

Position absolute but relative to parent

#father {
   position: relative;
}

#son1 {
   position: absolute;
   top: 0;
}

#son2 {
   position: absolute;
   bottom: 0;
}

This works because position: absolute means something like "use top, right, bottom, left to position yourself in relation to the nearest ancestor who has position: absolute or position: relative."

So we make #father have position: relative, and the children have position: absolute, then use top and bottom to position the children.

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available

For centos 7:

Install openssl:

sudo yum install openssl-devel

now goto python directory were we extracted the python tar,

run below commands

sudo ./configure
sudo make
sudo make install

This will fix the problem in centos...

Remote branch is not showing up in "git branch -r"

I had the same issue. It seems the easiest solution is to just remove the remote, readd it, and fetch.

Mongoose and multiple database in single node.js project

A bit optimized(for me atleast) solution. write this to a file db.js and require this to wherever required and call it with a function call and you are good to go.

   const MongoClient = require('mongodb').MongoClient;
    async function getConnections(url,db){
        return new Promise((resolve,reject)=>{
            MongoClient.connect(url, { useUnifiedTopology: true },function(err, client) {
                if(err) { console.error(err) 
                    resolve(false);
                }
                else{
                    resolve(client.db(db));
                }
            })
        });
    }

    module.exports = async function(){
        let dbs      = [];
        dbs['db1']     = await getConnections('mongodb://localhost:27017/','db1');
        dbs['db2']     = await getConnections('mongodb://localhost:27017/','db2');
        return dbs;
    };

Add a dependency in Maven

I'll assume that you're asking how to push a dependency out to a "well-known repository," and not simply asking how to update your POM.

If yes, then this is what you want to read.

And for anyone looking to set up an internal repository server, look here (half of the problem with using Maven 2 is finding the docs)

C++ printing boolean, what is displayed?

0 will get printed.

As in C++ true refers to 1 and false refers to 0.

In case, you want to print false instead of 0,then you have to sets the boolalpha format flag for the str stream.

When the boolalpha format flag is set, bool values are inserted/extracted by their textual representation: either true or false, instead of integral values.

#include <iostream>
int main()
{
  std::cout << std::boolalpha << false << std::endl;
}

output:

false

IDEONE

Pandas: Subtracting two date columns and the result being an integer

How about:

df_test['Difference'] = (df_test['First_Date'] - df_test['Second Date']).dt.days

This will return difference as int if there are no missing values(NaT) and float if there is.

session handling in jquery

In my opinion you should not load and use plugins you don't have to. This particular jQuery plugin doesn't give you anything since directly using the JavaScript sessionStorage object is exactly the same level of complexity. Nor, does the plugin provide some easier way to interact with other jQuery functionality. In addition the practice of using a plugin discourages a deep understanding of how something works. sessionStorage should be used only if its understood. If its understood, then using the jQuery plugin is actually MORE effort.

Consider using sessionStorage directly: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage

Render HTML to PDF in Django site

I get the code to generate the PDF from html template :

    import os

    from weasyprint import HTML

    from django.template import Template, Context
    from django.http import HttpResponse 


    def generate_pdf(self, report_id):

            # Render HTML into memory and get the template firstly
            template_file_loc = os.path.join(os.path.dirname(__file__), os.pardir, 'templates', 'the_template_pdf_generator.html')
            template_contents = read_all_as_str(template_file_loc)
            render_template = Template(template_contents)

            #rendering_map is the dict for params in the template 
            render_definition = Context(rendering_map)
            render_output = render_template.render(render_definition)

            # Using Rendered HTML to generate PDF
            response = HttpResponse(content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename=%s-%s-%s.pdf' % \
                                              ('topic-test','topic-test', '2018-05-04')
            # Generate PDF
            pdf_doc = HTML(string=render_output).render()
            pdf_doc.pages[0].height = pdf_doc.pages[0]._page_box.children[0].children[
                0].height  # Make PDF file as single page file 
            pdf_doc.write_pdf(response)
            return response

    def read_all_as_str(self, file_loc, read_method='r'):
        if file_exists(file_loc):
            handler = open(file_loc, read_method)
            contents = handler.read()
            handler.close()
            return contents
        else:
            return 'file not exist'  

How do I set the request timeout for one controller action in an asp.net mvc application

You can set this programmatically in the controller:-

HttpContext.Current.Server.ScriptTimeout = 300;

Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

Check you routes, the update on 9/28/2014 impacted us. We had to adjust our older servers and add new routes. Here is the article http://www.rackspace.com/knowledge_center/article/updating-servicenet-routes-on-cloud-servers-created-before-june-3-2013

How to check all versions of python installed on osx and centos

Here is a cleaner way to show them (technically without symbolic links):

ls -1 /usr/bin/python* | grep '[2-3].[0-9]$'

Where grep filters the output of ls that that has that numeric pattern at the end ($).

Or using find:

find /usr/bin/python* ! -type l

Which shows all the different (!) of symbolic link type (-type l).

Converting HTML element to string in JavaScript / JQuery

(document.body.outerHTML).constructor will return String. (take off .constructor and that's your string)

That aughta do it :)

github: server certificate verification failed

Another possible cause is that the clock of your machine is not synced (e.g. on Raspberry Pi). Check the current date/time using:

$ date

If the date and/or time is incorrect, try to update using:

$ sudo ntpdate -u time.nist.gov

Format of the initialization string does not conform to specification starting at index 0

Referencing the full sp path resolved this issue for me:

var command = new SqlCommand("DatabaseName.dbo.StoredProcedureName", conn)

Create JPA EntityManager without persistence.xml configuration file

Yes you can without using any xml file using spring like this inside a @Configuration class (or its equivalent spring config xml):

@Bean
public LocalContainerEntityManagerFactoryBean emf(){
    properties.put("javax.persistence.jdbc.driver", dbDriverClassName);
    properties.put("javax.persistence.jdbc.url", dbConnectionURL);
    properties.put("javax.persistence.jdbc.user", dbUser); //if needed

    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setPersistenceProviderClass(org.eclipse.persistence.jpa.PersistenceProvider.class); //If your using eclipse or change it to whatever you're using
    emf.setPackagesToScan("com.yourpkg"); //The packages to search for Entities, line required to avoid looking into the persistence.xml
    emf.setPersistenceUnitName(SysConstants.SysConfigPU);
    emf.setJpaPropertyMap(properties);
    emf.setLoadTimeWeaver(new ReflectiveLoadTimeWeaver()); //required unless you know what your doing
    return emf;
}

Check if input is number or letter javascript

Try this:

if(parseInt("0"+x, 10) > 0){/* x is integer */}

Best way to implement multi-language/globalization in large .NET project

I´ve been searching and I´ve found this:

If your using WPF or Silverlight your aproach could be use WPF LocalizationExtension for many reasons.

IT´s Open Source It´s FREE (and will stay free) is in a real stabel state

In a Windows Application you could do someting like this:

public partial class App : Application  
{  
     public App()  
     {             
     }  
 
     protected override void OnStartup(StartupEventArgs e)  
     {  
         Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE"); ;  
         Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("de-DE"); ;  
 
          FrameworkElement.LanguageProperty.OverrideMetadata(  
              typeof(FrameworkElement),  
              new FrameworkPropertyMetadata(  
                  XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));  
          base.OnStartup(e);  
    }  
} 

And I think on a Wep Page the aproach could be the same.

Good Luck!

Unique on a dataframe with only selected columns

Using unique():

dat <- data.frame(id=c(1,1,3),id2=c(1,1,4),somevalue=c("x","y","z"))    
dat[row.names(unique(dat[,c("id", "id2")])),]

"Warning: iPhone apps should include an armv6 architecture" even with build config set

Try changing your deployment target to something higher than an armv6 processor. The settings for xCode are referencing the operating system level, for instance: iOS version#{3.1, 3.2, 4.0, 4.1, 4.2, 4.3, 5.0, 5.1}

(i)You can set this in the build settings tab or the summary tab. Start at the top left of the window in the Project Navigator, with all the files listed in it. Click the top-most one which has a blue icon.

(ii)If you are planning on using the programmable shader line circuitry, which is accessed and controlled through openGL ES 2.0 API, then you should set your "Deployment Version" to about 4.3, which I believe is only available on devices such as the 3GS or newer. xCode is reporting that iOS 4.2.5 or higher is needed run armv7 code. And once again, this processor, I believe, started with the 3GS.* iOS 4.3 seems to be the choice for me, for now.

http://theiphonewiki.com/wiki/index.php?title=Armv7

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

Regex date format validation on Java

Below added code is working for me if you are using pattern dd-MM-yyyy.

public boolean isValidDate(String date) {
        boolean check;
        String date1 = "^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-([12][0-9]{3})$";
        check = date.matches(date1);

        return check;
    }

How to insert a value that contains an apostrophe (single quote)?

You just have to double up on the single quotes...

insert into Person (First, Last)
values ('Joe', 'O''Brien')

Break out of a While...Wend loop

Another option would be to set a flag variable as a Boolean and then change that value based on your criteria.

Dim count as Integer 
Dim flag as Boolean

flag = True

While flag
    count = count + 1 

    If count = 10 Then
        'Set the flag to false         '
        flag = false
    End If 
Wend

updating Google play services in Emulator

Use emulator that has Play Store installed. Updating play services would be as easy as in real device.

Since Google introduced Google Play Store images in Android SDK Tools 26.0.0 now emulators comes with installed Google Play Store.

enter image description here

From 26.0.3

  • Adds a new tab in the extended window for Google Play Store images that displays the Play Services version and a button to check for updates to Play Services.

emulator settings

@Nullable annotation usage

This annotation is commonly used to eliminate NullPointerExceptions. @Nullable says that this parameter might be null. A good example of such behaviour can be found in Google Guice. In this lightweight dependency injection framework you can tell that this dependency might be null. If you would try to pass null without an annotation the framework would refuse to do it's job.

What is more @Nullable might be used with @NotNull annotation. Here you can find some tips on how to use them properly. Code inspection in IntelliJ checks the annotations and helps to debug the code.

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

C# "as" cast vs classic cast

You use the "as" statement to avoid the possibility of an exception, e.g. you can handle the cast failure gracefully via logic. Only use the cast when you are sure that the object is of the desired type. I almost always use the "as" and then check for null.

Easy way to convert a unicode list to a list containing python strings?

There are several ways to do this. I converted like this

def clean(s):
    s = s.replace("u'","")
    return re.sub("[\[\]\'\s]", '', s)

EmployeeList = [clean(i) for i in str(EmployeeList).split(',')]

After that you can check

if '1001' in EmployeeList:
    #do something

Hope it will help you.

ImportError: No module named MySQLdb

While @Edward van Kuik's answer is correct, it doesn't take into account an issue with virtualenv v1.7 and above.

In particular installing python-mysqldb via apt on Ubuntu put it under /usr/lib/pythonX.Y/dist-packages, but this path isn't included by default in the virtualenv's sys.path.

So to resolve this, you should create your virtualenv with system packages by running something like:

virtualenv --system-site-packages .venv

Reactjs setState() with a dynamic key name?

Your state with dictionary update some key without losing other value

state = 
{   
    name:"mjpatel"  
    parsedFilter:
    {
      page:2,
      perPage:4,
      totalPages: 50,
    }
}

Solution is below

 let { parsedFilter } = this.state
 this.setState({
      parsedFilter: {
        ...this.state.parsedFilter,
        page: 5
      }
  });

here update value for key "page" with value 5

MongoDB: How to find out if an array field contains an element?

I am trying to explain by putting problem statement and solution to it. I hope it will help

Problem Statement:

Find all the published products, whose name like ABC Product or PQR Product, and price should be less than 15/-

Solution:

Below are the conditions that need to be taken care of

  1. Product price should be less than 15
  2. Product name should be either ABC Product or PQR Product
  3. Product should be in published state.

Below is the statement that applies above criterion to create query and fetch data.

$elements = $collection->find(
             Array(
                [price] => Array( [$lt] => 15 ),
                [$or] => Array(
                            [0]=>Array(
                                    [product_name]=>Array(
                                       [$in]=>Array(
                                            [0] => ABC Product,
                                            [1]=> PQR Product
                                            )
                                        )
                                    )
                                ),
                [state]=>Published
                )
            );

If Else in LINQ

I assume from db that this is LINQ-to-SQL / Entity Framework / similar (not LINQ-to-Objects);

Generally, you do better with the conditional syntax ( a ? b : c) - however, I don't know if it will work with your different queries like that (after all, how would your write the TSQL?).

For a trivial example of the type of thing you can do:

select new {p.PriceID, Type = p.Price > 0 ? "debit" : "credit" };

You can do much richer things, but I really doubt you can pick the table in the conditional. You're welcome to try, of course...

How to open maximized window with Javascript?

var params = [
    'height='+screen.height,
    'width='+screen.width,
    'fullscreen=yes' // only works in IE, but here for completeness
].join(',');
     // and any other options from
     // https://developer.mozilla.org/en/DOM/window.open

var popup = window.open('http://www.google.com', 'popup_window', params); 
popup.moveTo(0,0);

Please refrain from opening the popup unless the user really wants it, otherwise they will curse you and blacklist your site. ;-)

edit: Oops, as Joren Van Severen points out in a comment, this may not take into account taskbars and window decorations (in a possibly browser-dependent way). Be aware. It seems that ignoring height and width (only param is fullscreen=yes) seems to work on Chrome and perhaps Firefox too; the original 'fullscreen' functionality has been disabled in Firefox for being obnoxious, but has been replaced with maximization. This directly contradicts information on the same page of https://developer.mozilla.org/en/DOM/window.open which says that window-maximizing is impossible. This 'feature' may or may not be supported depending on the browser.

What does 'git blame' do?

The command explains itself quite well. It's to figure out which co-worker wrote the specific line or ruined the project, so you can blame them :)

How do I activate a specific workbook and a specific sheet?

You do not need to activate the sheet (you'll take a huge performance hit for doing so, actually). Since you are declaring an object for the sheet, when you call the method starting with "wb." you are selecting that object. For example, you can jump in between workbooks without activating anything like here:

Sub Test()

Dim wb1 As Excel.Workbook
Set wb1 = Workbooks.Open("C:\Documents and Settings\xxxx\Desktop\test1.xls")
Dim wb2 As Excel.Workbook
Set wb2 = Workbooks.Open("C:\Documents and Settings\xxxx\Desktop\test2.xls")

wb1.Sheets("Sheet1").Cells(1, 1).Value = 24
wb2.Sheets("Sheet1").Cells(1, 1).Value = 24
wb1.Sheets("Sheet1").Cells(2, 1).Value = 54

End Sub

Formula to convert date to number

If you change the format of the cells to General then this will show the date value of a cell as behind the scenes Excel saves a date as the number of days since 01/01/1900

Screenprint 1

Screenprint 2

If your date is text and you need to convert it then DATEVALUE will do this:

Datevalue function

String replacement in batch file

This works fine

@echo off    
set word=table    
set str=jump over the chair    
set rpl=%str:chair=%%word%    
echo %rpl%

$(this).val() not working to get text from span using jquery

To retrieve text of an auto generated span value just do this :

var al = $("#id-span-name").text();    
alert(al);

How can I stop a running MySQL query?

If you have mysqladmin available, you may get the list of queries with:

> mysqladmin -uUSERNAME -pPASSWORD pr

+-----+------+-----------------+--------+---------+------+--------------+------------------+
| Id  | User | Host            | db     | Command | Time | State        | Info             |
+-----+------+-----------------+--------+---------+------+--------------+------------------+
| 137 | beet | localhost:53535 | people | Query   | 292  | Sending data | DELETE FROM      |
| 145 | root | localhost:55745 |        | Query   | 0    |              | show processlist |
+-----+------+-----------------+--------+---------+------+--------------+------------------+

Then you may stop the mysql process that is hosting the long running query:

> mysqladmin -uUSERNAME -pPASSWORD kill 137

Git add all subdirectories

Also struggled, but got it right typing

git add -f ./JS/*

where JS was my folder name which contain sub folders and files

Count(*) vs Count(1) - SQL Server

As this question comes up again and again, here is one more answer. I hope to add something for beginners wondering about "best practice" here.

SELECT COUNT(*) FROM something counts records which is an easy task.

SELECT COUNT(1) FROM something retrieves a 1 per record and than counts the 1s that are not null, which is essentially counting records, only more complicated.

Having said this: Good dbms notice that the second statement will result in the same count as the first statement and re-interprete it accordingly, as not to do unnecessary work. So usually both statements will result in the same execution plan and take the same amount of time.

However from the point of readability you should use the first statement. You want to count records, so count records, not expressions. Use COUNT(expression) only when you want to count non-null occurences of something.

Correct way to write loops for promise.

Use async and await (es6):

function taskAsync(paramets){
 return new Promise((reslove,reject)=>{
 //your logic after reslove(respoce) or reject(error)
})
}

async function fName(){
let arry=['list of items'];
  for(var i=0;i<arry.length;i++){
   let result=await(taskAsync('parameters'));
}

}

What is a handle in C++?

A handle is whatever you want it to be.

A handle can be a unsigned integer used in some lookup table.

A handle can be a pointer to, or into, a larger set of data.

It depends on how the code that uses the handle behaves. That determines the handle type.

The reason the term 'handle' is used is what is important. That indicates them as an identification or access type of object. Meaning, to the programmer, they represent a 'key' or access to something.

Catch multiple exceptions in one line (except block)

From Python Documentation:

An except clause may name multiple exceptions as a parenthesized tuple, for example

except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

Or, for Python 2 only:

except (IDontLikeYouException, YouAreBeingMeanException), e:
    pass

Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using as.

In a javascript array, how do I get the last 5 elements, excluding the first element?

Here is one I haven't seen that's even shorter

arr.slice(1).slice(-5)

Run the code snippet below for proof of it doing what you want

_x000D_
_x000D_
var arr1 = [0, 1, 2, 3, 4, 5, 6, 7],_x000D_
  arr2 = [0, 1, 2, 3];_x000D_
_x000D_
document.body.innerHTML = 'ARRAY 1: ' + arr1.slice(1).slice(-5) + '<br/>ARRAY 2: ' + arr2.slice(1).slice(-5);
_x000D_
_x000D_
_x000D_

Another way to do it would be using lodash https://lodash.com/docs#rest - that is of course if you don't mind having to load a huge javascript minified file if your trying to do it from your browser.

_.slice(_.rest(arr), -5)

How to make a simple collection view with Swift

For swift 4.2 --

//MARK: UICollectionViewDataSource

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1     //return number of sections in collection view
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 10    //return number of rows in section
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)
    configureCell(cell: cell, forItemAtIndexPath: indexPath)
    return cell      //return your cell
}

func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
    cell.backgroundColor = UIColor.black


    //Customise your cell

}

func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    let view =  collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", for: indexPath as IndexPath) as UICollectionReusableView
    return view
}

//MARK: UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    // When user selects the cell
}

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    // When user deselects the cell
}

What does Java option -Xmx stand for?

Max heap Usage for the application is is 1024 MB

TypeScript getting error TS2304: cannot find name ' require'

You can

declare var require: any

Or, for more comprehensive support, use DefinitelyTyped's require.d.ts

Also, instead of var mongoose = require('mongoose'), you could try the following

import mongoose from 'mongoose' // or
import mongoose = require('mongoose')

How do I compare strings in Java?

String a = new String("foo");
String b = new String("foo");
System.out.println(a == b); // prints false
System.out.println(a.equals(b)); // prints true

Make sure you understand why. It's because the == comparison only compares references; the equals() method does a character-by-character comparison of the contents.

When you call new for a and b, each one gets a new reference that points to the "foo" in the string table. The references are different, but the content is the same.

PHPMyAdmin Default login password

I just installed Fedora 16 (yea, I know it's old and not supported but, I had the CD burnt :) )

Anyway, coming to the solution, this is what I was required to do:

su -
gedit /etc/phpMyAdmin/config.inc.php

if not found... try phpmyadmin - all small caps.

gedit /etc/phpmyadmin/config.inc.php

Locate

$cfg['Servers'][$i]['AllowNoPassword']

and set it to:

$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

Save it.

How to Insert Double or Single Quotes

Or Select range and Format cells > Custom \"@\"

How to show "Done" button on iPhone number pad

All those implementation about finding the keyboard view and adding the done button at the 3rd row (that is why button.y = 163 b/c keyboard's height is 216) are fragile because iOS keeps change the view hierarchy. For example none of above codes work for iOS9.

I think it is more safe to just find the topmost view, by [[[UIApplication sharedApplication] windows] lastObject], and just add the button at bottom left corner of it, doneButton.frame = CGRectMake(0, SCREEN_HEIGHT-53, 106, 53);// portrait mode

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

How can I get the Google cache age of any URL or web page?

Use the URL

https://webcache.googleusercontent.com/search?q=cache:<your url without "http://">

Example:

https://webcache.googleusercontent.com/search?q=cache:stackoverflow.com

It contains a header like this:

This is Google's cache of https://stackoverflow.com/. It is a snapshot of the page as it appeared on 21 Aug 2012 11:33:38 GMT. The current page could have changed in the meantime. Learn more
Tip: To quickly find your search term on this page, press Ctrl+F or ?+F (Mac) and use the find bar.

combining two data frames of different lengths

i had similar problem, i matched the entries in a particular column of two data sets and cbind only if it matched. For two data sets, data1 & data2, i am adding a column in data1 from data2 after comparing first column of both.

for(i in 1:nrow(data1){
  for( j in 1:nrow(data2){
    if (data1[i,1]==data2[j,1]) data1[i,3]<- data2[j,2]
  }
}

Converting File to MultiPartFile

File file = new File("src/test/resources/validation.txt");
DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length() , file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

You need the

fileItem.getOutputStream();

because it will throw NPE otherwise.

Using the AND and NOT Operator in Python

Use the keyword and, not & because & is a bit operator.

Be careful with this... just so you know, in Java and C++, the & operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is &&. Similarly | is a bit operator, and || is a boolean operator. In Python and and or are used for boolean comparisons.

Turning a Comma Separated string into individual rows

When using this approach you have to make sure that none of your values contains something that would be illegal XML – user1151923

I always use the XML method. Make sure you use VALID XML. I have two functions to convert between valid XML and Text. (I tend to strip out the carriage returns as I don't usually need them.

CREATE FUNCTION dbo.udf_ConvertTextToXML (@Text varchar(MAX)) 
    RETURNS varchar(MAX)
AS
    BEGIN
        SET @Text = REPLACE(@Text,CHAR(10),'')
        SET @Text = REPLACE(@Text,CHAR(13),'')
        SET @Text = REPLACE(@Text,'<','&lt;')
        SET @Text = REPLACE(@Text,'&','&amp;')
        SET @Text = REPLACE(@Text,'>','&gt;')
        SET @Text = REPLACE(@Text,'''','&apos;')
        SET @Text = REPLACE(@Text,'"','&quot;')
    RETURN @Text
END


CREATE FUNCTION dbo.udf_ConvertTextFromXML (@Text VARCHAR(MAX)) 
    RETURNS VARCHAR(max)
AS
    BEGIN
        SET @Text = REPLACE(@Text,'&lt;','<')
        SET @Text = REPLACE(@Text,'&amp;','&')
        SET @Text = REPLACE(@Text,'&gt;','>')
        SET @Text = REPLACE(@Text,'&apos;','''')
        SET @Text = REPLACE(@Text,'&quot;','"')
    RETURN @Text
END

When does a cookie with expiration time 'At end of session' expire?

When you use setcookie, you can either set the expiration time to 0 or simply omit the parametre - the cookie will then expire at the end of session (ie, when you close the browser).

How to replace substrings in windows batch file

To avoid problems with the batch parser (e.g. exclamation point), look at Problem with search and replace batch file.

Following modification of aflat's script will include special characters like exclamation points.

@echo off
setlocal DisableDelayedExpansion
set INTEXTFILE=test.txt
set OUTTEXTFILE=test_out.txt
set SEARCHTEXT=bath
set REPLACETEXT=hello
set OUTPUTLINE=

for /f "tokens=1,* delims=¶" %%A in ( '"type %INTEXTFILE%"') do (
    SET string=%%A
    setlocal EnableDelayedExpansion
    SET modified=!string:%SEARCHTEXT%=%REPLACETEXT%!

    >> %OUTTEXTFILE% echo(!modified!
    endlocal
)
del %INTEXTFILE%
rename %OUTTEXTFILE% %INTEXTFILE%

iOS detect if user is on an iPad

Many Answers are good but I use like this in swift 4

  1. Create Constant

    struct App {
        static let isRunningOnIpad = UIDevice.current.userInterfaceIdiom == .pad ? true : false
    }
    
  2. Use like this

    if App.isRunningOnIpad {
        return load(from: .main, identifier: identifier)
    } else {
        return load(from: .ipad, identifier: identifier)
    }
    

Edit: As Suggested Cœur simply create an extension on UIDevice

extension UIDevice {
    static let isRunningOnIpad = UIDevice.current.userInterfaceIdiom == .pad ? true : false
}

How to play video with AVPlayerViewController (AVKit) in Swift

Swift 5+

First of all you have to define 2 variables globally inside your view controller.

var player: AVPlayer!
var playerViewController: AVPlayerViewController!

Here I'm adding player to a desired view.

@IBOutlet weak var playerView: UIView!

Then add following code to the viewDidLoad method.

let videoURL = URL(string: "videoUrl")
self.player = AVPlayer(url: videoURL!)
self.playerViewController = AVPlayerViewController()
playerViewController.player = self.player
playerViewController.view.frame = self.playerView.frame
playerViewController.player?.pause()
self.playerView.addSubview(playerViewController.view)

If you are not defining player and playerViewController globally, you won't be able to embed player.

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

You can use .attr() as a part of however you plan to toggle it:

$("button").attr("aria-expanded","true");

lexers vs parsers

When is lexing enough, when do you need EBNF?

EBNF really doesn't add much to the power of grammars. It's just a convenience / shortcut notation / "syntactic sugar" over the standard Chomsky's Normal Form (CNF) grammar rules. For example, the EBNF alternative:

S --> A | B

you can achieve in CNF by just listing each alternative production separately:

S --> A      // `S` can be `A`,
S --> B      // or it can be `B`.

The optional element from EBNF:

S --> X?

you can achieve in CNF by using a nullable production, that is, the one which can be replaced by an empty string (denoted by just empty production here; others use epsilon or lambda or crossed circle):

S --> B       // `S` can be `B`,
B --> X       // and `B` can be just `X`,
B -->         // or it can be empty.

A production in a form like the last one B above is called "erasure", because it can erase whatever it stands for in other productions (product an empty string instead of something else).

Zero-or-more repetiton from EBNF:

S --> A*

you can obtan by using recursive production, that is, one which embeds itself somewhere in it. It can be done in two ways. First one is left recursion (which usually should be avoided, because Top-Down Recursive Descent parsers cannot parse it):

S --> S A    // `S` is just itself ended with `A` (which can be done many times),
S -->        // or it can begin with empty-string, which stops the recursion.

Knowing that it generates just an empty string (ultimately) followed by zero or more As, the same string (but not the same language!) can be expressed using right-recursion:

S --> A S    // `S` can be `A` followed by itself (which can be done many times),
S -->        // or it can be just empty-string end, which stops the recursion.

And when it comes to + for one-or-more repetition from EBNF:

S --> A+

it can be done by factoring out one A and using * as before:

S --> A A*

which you can express in CNF as such (I use right recursion here; try to figure out the other one yourself as an exercise):

S --> A S   // `S` can be one `A` followed by `S` (which stands for more `A`s),
S --> A     // or it could be just one single `A`.

Knowing that, you can now probably recognize a grammar for a regular expression (that is, regular grammar) as one which can be expressed in a single EBNF production consisting only from terminal symbols. More generally, you can recognize regular grammars when you see productions similar to these:

A -->        // Empty (nullable) production (AKA erasure).
B --> x      // Single terminal symbol.
C --> y D    // Simple state change from `C` to `D` when seeing input `y`.
E --> F z    // Simple state change from `E` to `F` when seeing input `z`.
G --> G u    // Left recursion.
H --> v H    // Right recursion.

That is, using only empty strings, terminal symbols, simple non-terminals for substitutions and state changes, and using recursion only to achieve repetition (iteration, which is just linear recursion - the one which doesn't branch tree-like). Nothing more advanced above these, then you're sure it's a regular syntax and you can go with just lexer for that.

But when your syntax uses recursion in a non-trivial way, to produce tree-like, self-similar, nested structures, like the following one:

S --> a S b    // `S` can be itself "parenthesized" by `a` and `b` on both sides.
S -->          // or it could be (ultimately) empty, which ends recursion.

then you can easily see that this cannot be done with regular expression, because you cannot resolve it into one single EBNF production in any way; you'll end up with substituting for S indefinitely, which will always add another as and bs on both sides. Lexers (more specifically: Finite State Automata used by lexers) cannot count to arbitrary number (they are finite, remember?), so they don't know how many as were there to match them evenly with so many bs. Grammars like this are called context-free grammars (at the very least), and they require a parser.

Context-free grammars are well-known to parse, so they are widely used for describing programming languages' syntax. But there's more. Sometimes a more general grammar is needed -- when you have more things to count at the same time, independently. For example, when you want to describe a language where one can use round parentheses and square braces interleaved, but they have to be paired up correctly with each other (braces with braces, round with round). This kind of grammar is called context-sensitive. You can recognize it by that it has more than one symbol on the left (before the arrow). For example:

A R B --> A S B

You can think of these additional symbols on the left as a "context" for applying the rule. There could be some preconditions, postconditions etc. For example, the above rule will substitute R into S, but only when it's in between A and B, leaving those A and B themselves unchanged. This kind of syntax is really hard to parse, because it needs a full-blown Turing machine. It's a whole another story, so I'll end here.

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Check The data you are writing to Server. May be data has delimiter which is not used.

like

045|2272575|0.000|0.000|2013-10-07
045|2272585|0.000|0.000;2013-10-07

your delimiter is '|' but data has a delimiter ';'. So for this you are getting the error.

How to downgrade from Internet Explorer 11 to Internet Explorer 10?

  1. Go to Control Panel -> Programs -> Programs and features

    Step 1 - Programs and features

  2. Go to Windows Features and disable Internet Explorer 11

    Step 2 - Windows Features

    Step 3 - Uncheck Internet Explorer 11

  3. Then click on Display installed updates

    Step 4 - Display installed updates

  4. Search for Internet explorer

  5. Right-click on Internet Explorer 11 -> Uninstall

    Step 5 - Uninstall Internet Explorer 11

  6. Do the same with Internet Explorer 10

  7. Restart your computer
  8. Install Internet Explorer 10 here (old broken link)

I think it will be okay.

Increment variable value by 1 ( shell programming)

There are more than one way to increment a variable in bash, but what you tried is not correct.

You can use for example arithmetic expansion:

i=$((i+1))

or only:

((i=i+1))

or:

((i+=1))

or even:

((i++))

Or you can use let:

let "i=i+1"

or only:

let "i+=1"

or even:

let "i++"

See also: http://tldp.org/LDP/abs/html/dblparens.html.

Best way to handle multiple constructors in Java

You need to specify what are the class invariants, i.e. properties which will always be true for an instance of the class (for example, the title of a book will never be null, or the size of a dog will always be > 0).

These invariants should be established during construction, and be preserved along the lifetime of the object, which means that methods shall not break the invariants. The constructors can set these invariants either by having compulsory arguments, or by setting default values:

class Book {
    private String title; // not nullable
    private String isbn;  // nullable

    // Here we provide a default value, but we could also skip the 
    // parameterless constructor entirely, to force users of the class to
    // provide a title
    public Book()
    {
        this("Untitled"); 
    }

    public Book(String title) throws IllegalArgumentException
    {
        if (title == null) 
            throw new IllegalArgumentException("Book title can't be null");
        this.title = title;
        // leave isbn without value
    }
    // Constructor with title and isbn
}

However, the choice of these invariants highly depends on the class you're writing, how you'll use it, etc., so there's no definitive answer to your question.

How can I format DateTime to web UTC format?

string foo = yourDateTime.ToUniversalTime()
                         .ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");

How to check if smtp is working from commandline (Linux)

Not sure if this help or not but this is a command line tool which let you simply send test mails from a SMTP server priodically. http://code.google.com/p/woodpecker-tester/

start MySQL server from command line on Mac OS Lion

Simply:

mysql.server start

mysql.server stop

mysql.server restart

SQL Server: Query fast, but slow from procedure

I had the same problem as the original poster but the quoted answer did not solve the problem for me. The query still ran really slow from a stored procedure.

I found another answer here "Parameter Sniffing", Thanks Omnibuzz. Boils down to using "local Variables" in your stored procedure queries, but read the original for more understanding, it's a great write up. e.g.

Slow way:

CREATE PROCEDURE GetOrderForCustomers(@CustID varchar(20))
AS
BEGIN
    SELECT * 
    FROM orders
    WHERE customerid = @CustID
END

Fast way:

CREATE PROCEDURE GetOrderForCustomersWithoutPS(@CustID varchar(20))
AS
BEGIN
    DECLARE @LocCustID varchar(20)
    SET @LocCustID = @CustID

    SELECT * 
    FROM orders
    WHERE customerid = @LocCustID
END

Hope this helps somebody else, doing this reduced my execution time from 5+ minutes to about 6-7 seconds.

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

It happened for me as well while running a game using and-engine. It was fixed after i added the below code to my manifest.xml. This code should be added to your mainactivity.

android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|mcc|mnc"

How to give the background-image path in CSS?

Use the below.

background-image: url("././images/image.png");

This shall work.

How to use php serialize() and unserialize()

Most storage mediums can store string types. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.

Instead, serialize() allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().

If you are familiar with json_encode() and json_decode() (and JSON in general), the concept is similar.

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

There is an issue in php version less than 5.2.6. You may need to upgrade the version of php.

Checking if an object is a number in C#

If your requirement is really

.ToString() would result in a string containing digits and +,-,.

and you want to use double.TryParse then you need to use the overload that takes a NumberStyles parameter, and make sure you are using the invariant culture.

For example for a number which may have a leading sign, no leading or trailing whitespace, no thousands separator and a period decimal separator, use:

NumberStyles style = 
   NumberStyles.AllowLeadingSign | 
   NumberStyles.AllowDecimalPoint | 
double.TryParse(input, style, CultureInfo.InvariantCulture, out result);

How to convert Blob to String and String to Blob in java

And here is my solution, that always works for me

StringBuffer buf = new StringBuffer();
String temp;
BufferedReader bufReader = new BufferedReader(new InputStreamReader(myBlob.getBinaryStream()));
    while ((temp=bufReader.readLine())!=null) {
        bufappend(temp);
    }

Convert tabs to spaces in Notepad++

Follow this procedure to convert spaces to tabs or vice-versa:

Space - Tab

A method to count occurrences in a list

You can do something like this to count from a list of things.

IList<String> names = new List<string>() { "ToString", "Format" };
IEnumerable<String> methodNames = typeof(String).GetMethods().Select(x => x.Name);

int count = methodNames.Where(x => names.Contains(x)).Count();

To count a single element

string occur = "Test1";
IList<String> words = new List<string>() {"Test1","Test2","Test3","Test1"};

int count = words.Where(x => x.Equals(occur)).Count();

C# - What does the Assert() method do? Is it still useful?

First of all Assert() method is available for Trace and Debug classes.
Debug.Assert() is executing only in Debug mode.
Trace.Assert() is executing in Debug and Release mode.

Here is an example:

        int i = 1 + 3;
        // Debug.Assert method in Debug mode fails, since i == 4
        Debug.Assert(i == 3);
        Debug.WriteLine(i == 3, "i is equal to 3");

        // Trace.Assert method in Release mode is not failing.
        Trace.Assert(i == 4);
        Trace.WriteLine(i == 4, "i is equla to 4");

        Console.WriteLine("Press a key to continue...");
        Console.ReadLine();

Run this code in Debug mode and then in Release mode.

enter image description here

You will notice that during Debug mode your code Debug.Assert statement fails, you get a message box showing the current stack trace of the application. This is not happening in Release mode since Trace.Assert() condition is true (i == 4).

WriteLine() method simply gives you an option of logging the information to Visual Studio output. enter image description here

When should you NOT use a Rules Engine?

In my experience, rules engines work best when the following are true:

  1. Well-defined doctrine for your problem domain
  2. High quality (preferably automated) data to help drive most of your inputs
  3. Access to subject matter experts
  4. Software developers with experience creating expert systems

If any of these four traits are missing, you still might find a rules engine works for you, but every time I've tried it with even 1 missing, I've run into trouble.

How to check version of python modules?

you can first install some package like this and then check its version

pip install package
import package
print(package.__version__)

it should give you package version

Error while installing json gem 'mkmf.rb can't find header files for ruby'

I also encountered this problem because I install Ruby on Ubuntu via brightbox, and I thought ruby-dev is the trunk of ruby. So I did not install. Install ruby2.3-dev fixes it:

sudo apt-get install ruby2.3-dev

Call to a member function fetch_assoc() on boolean in <path>

You have to update the php.ini config file with in your host provider's server, trust me on this, more than likely there is nothing wrong with your code. It took me almost a month and a half to realize that most hosting servers are not up to date on php.ini files, eg. php 5.5 or later, I believe.

Disable button in angular with two conditions?

It sounds like you need an OR instead:

<button type="submit" [disabled]="!validate || !SAForm.valid">Add</button>

This will disable the button if not validate or if not SAForm.valid.

What are naming conventions for MongoDB?

I think it's all personal preference. My preferences come from using NHibernate, in .NET, with SQL Server, so they probably differ from what others use.

  • Databases: The application that's being used.. ex: Stackoverflow
  • Collections: Singular in name, what it's going to be a collection of, ex: Question
  • Document fields, ex: MemberFirstName

Honestly, it doesn't matter too much, as long as it's consistent for the project. Just get to work and don't sweat the details :P

Storing JSON in database vs. having a new column for each key

short answer you have to mix between them , use json for data that you are not going to make relations with them like contact data , address , products variabls

Import Certificate to Trusted Root but not to Personal [Command Line]

There is a fairly simple answer with powershell.

Import-PfxCertificate -Password $secure_pw  -CertStoreLocation Cert:\LocalMachine\Root -FilePath certs.pfx

The trick is making a "secure" password...

$plaintext_pw = 'PASSWORD';
$secure_pw = ConvertTo-SecureString $plaintext_pw -AsPlainText -Force; 
Import-PfxCertificate -Password $secure_pw  -CertStoreLocation Cert:\LocalMachine\Root -FilePath certs.pfx;

HttpClient - A task was cancelled?

I was using a simple call instead of async. As soon I added await and made method async it started working fine.

public async Task<T> ExecuteScalarAsync<T>(string query, object parameter = null, CommandType commandType = CommandType.Text) where T : IConvertible
        {
            using (IDbConnection db = new SqlConnection(_con))
            {
                return await db.ExecuteScalarAsync<T>(query, parameter, null, null, commandType);
            }
        }

Swing/Java: How to use the getText and setText string properly

the getText method returns a String, while the setText receives a String, so you can write it like label1.setText(nameField.getText()); in your listener.

What does "\r" do in the following script?

'\r' means 'carriage return' and it is similar to '\n' which means 'line break' or more commonly 'new line'

in the old days of typewriters, you would have to move the carriage that writes back to the start of the line, and move the line down in order to write onto the next line.

in the modern computer era we still have this functionality for multiple reasons. but mostly we use only '\n' and automatically assume that we want to start writing from the start of the line, since it would not make much sense otherwise.

however, there are some times when we want to use JUST the '\r' and that would be if i want to write something to an output, and the instead of going down to a new line and writing something else, i want to write something over what i already wrote, this is how many programs in linux or in windows command line are able to have 'progress' information that changes on the same line.

nowadays most systems use only the '\n' to denote a newline. but some systems use both together.

you can see examples of this given in some of the other answers, but the most common are:

  • windows ends lines with '\r\n'
  • mac ends lines with '\r'
  • unix/linux use '\n'

and some other programs also have specific uses for them.

for more information about the history of these characters

What is the best way to paginate results in SQL Server

create PROCEDURE SP_Company_List (@pagesize int = -1 ,@pageindex int= 0   ) > AS BEGIN  SET NOCOUNT ON;


    select  Id , NameEn     from Company  ORDER by Id ASC  
OFFSET (@pageindex-1 )* @pagesize   ROWS FETCH NEXt @pagesize ROWS ONLY END  GO

DECLARE   @return_value int

EXEC  @return_value = [dbo].[SP_Company_List]         @pagesize = 1 ,         > @pageindex = 2

SELECT    'Return Value' = @return_value

GO

What is the purpose of Looper and how to use it?

What is Looper?

Looper is a class which is used to execute the Messages(Runnables) in a queue. Normal threads have no such queue, e.g. simple thread does not have any queue. It executes once and after method execution finishes, the thread will not run another Message(Runnable).

Where we can use Looper class?

If someone wants to execute multiple messages(Runnables) then he should use the Looper class which is responsible for creating a queue in the thread. For example, while writing an application that downloads files from the internet, we can use Looper class to put files to be downloaded in the queue.

How it works?

There is prepare() method to prepare the Looper. Then you can use loop() method to create a message loop in the current thread and now your Looper is ready to execute the requests in the queue until you quit the loop.

Here is the code by which you can prepare the Looper.

class LooperThread extends Thread {
      public Handler mHandler;

      @Override
      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              @Override
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }

npm install gives error "can't find a package.json file"

I was facing the same issue as below.

npm ERR! errno -4058 npm ERR! syscall open npm ERR! enoent ENOENT: no such file or directory, open 'D:\SVenu\FullStackDevelopment\Angular\Angular2_Splitter_CodeSkeleton\CodeSke leton\run\package.json' npm ERR! enoent This is related to npm not being able to find a file. npm ERR! enoent

The problem I made was, I was running the command npm build run instead of running npm run build.

Just sharing to help someone who does small mistakes like me.

How can I apply a function to every row/column of a matrix in MATLAB?

For completeness/interest I'd like to add that matlab does have a function that allows you to operate on data per-row rather than per-element. It is called rowfun (http://www.mathworks.se/help/matlab/ref/rowfun.html), but the only "problem" is that it operates on tables (http://www.mathworks.se/help/matlab/ref/table.html) rather than matrices.

How do I display the current value of an Android Preference in the Preference summary?

For EditTextPreference:

public class MyEditTextPreference extends EditTextPreference {
    public MyEditTextPreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MyEditTextPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void setText(String text) {
        super.setText(text);
        setSummary(text);
    }
}

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

How do I get LaTeX to hyphenate a word that contains a dash?

To avoid hyphenation in already hyphenated word I used non-breaking space ~ in combination with backward space \!. For example, command

3~\!\!\!\!-~\!\!\!D

used in the text, suppress hyphenation in word 3-D. Probably not the best solution, but it worked for me!

Changing background color of selected cell?

I was able to solve this problem by creating a subclass of UITableViewCell and implementing the setSelected:animated: method

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
    if(selected) {
        [self setSelectionStyle:UITableViewCellSelectionStyleNone];
        [self setBackgroundColor:[UIColor greenColor]];
    } else {
        [self setBackgroundColor:[UIColor whiteColor]];
    }
}

The trick was setting the

cell.selectionStyle = UITableViewCellSelectionStyleDefault;

in the implementing view controller and then in the tableViewCell setting it as

[self setSelectionStyle:UITableViewCellSelectionStyleNone];

Hope this helps. :)

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

You need to prevent the default action for the click event (i.e. navigating to the link target) from occurring.

There are two ways to do this.

Option 1: event.preventDefault()

Call the .preventDefault() method of the event object passed to your handler. If you're using jQuery to bind your handlers, that event will be an instance of jQuery.Event and it will be the jQuery version of .preventDefault(). If you're using addEventListener to bind your handlers, it will be an Event and the raw DOM version of .preventDefault(). Either way will do what you need.

Examples:

$('#ma_link').click(function($e) {
    $e.preventDefault();
    doSomething();
});

document.getElementById('#ma_link').addEventListener('click', function (e) {
    e.preventDefault();
    doSomething();
})

Option 2: return false;

In jQuery:

Returning false from an event handler will automatically call event.stopPropagation() and event.preventDefault()

So, with jQuery, you can alternatively use this approach to prevent the default link behaviour:

$('#ma_link').click(function(e) {
     doSomething();
     return false;
});

If you're using raw DOM events, this will also work on modern browsers, since the HTML 5 spec dictates this behaviour. However, older versions of the spec did not, so if you need maximum compatibility with older browsers, you should call .preventDefault() explicitly. See event.preventDefault() vs. return false (no jQuery) for the spec detail.

Sublime Text 3, convert spaces to tabs

Here is how you to do it automatically on save: https://coderwall.com/p/zvyg7a/convert-tabs-to-spaces-on-file-save

Unfortunately the package is not working when you install it from the Package Manager.

How to configure robots.txt to allow everything?

I understand that this is fairly old question and has some pretty good answers. But, here is my two cents for the sake of completeness.

As per the official documentation, there are four ways, you can allow complete access for robots to access your site.

Clean:

Specify a global matcher with a disallow segment as mentioned by @unor. So your /robots.txt looks like this.

User-agent: *
Disallow:

The hack:

Create a /robots.txt file with no content in it. Which will default to allow all for all type of Bots.

I don't care way:

Do not create a /robots.txt altogether. Which should yield the exact same results as the above two.

The ugly:

From the robots documentation for meta tags, You can use the following meta tag on all your pages on your site to let the Bots know that these pages are not supposed to be indexed.

<META NAME="ROBOTS" CONTENT="NOINDEX">

In order for this to be applied to your entire site, You will have to add this meta tag for all of your pages. And this tag should strictly be placed under your HEAD tag of the page. More about this meta tag here.

ORA-12560: TNS:protocol adaptor error

In my case (for OracleExpress) the service was running, but I got this issue when trying to access the database via sqlplus without connection identifier:

sqlplus sys/mypassword as sysdba  

To make it work I needed to add the connection identifier (XE for Oracle Express), so following command worked ok:

sqlplus sys/mypassword@XE as sysdba

If you still get ORA-12560, make sure you can ping the XE service. Use:

tnsping XE

And you should get OK message along with full connection string (tnsping command is located in oracle's installation dir: [oracle express installation dir]\app\oracle\product\11.2.0\server\bin). If you can not ping make sure your tnsnames.ora file is reachable for sqlplus. You might need to set TNS_ADMIN environment variable pointing to your ADMIN directory, where the file is located, for example:

TNS_ADMIN=[oracle express installation dir]\app\oracle\product\11.2.0\server\network\ADMIN

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

I liked galloglas's code, and I changed the main function so that it shows a sorted list of total size by application:

verbose = True
if __name__ == '__main__':
    mbdb = process_mbdb_file("Manifest.mbdb")
    mbdx = process_mbdx_file("Manifest.mbdx")
    sizes = {}
    for offset, fileinfo in mbdb.items():
        if offset in mbdx:
            fileinfo['fileID'] = mbdx[offset]
        else:
            fileinfo['fileID'] = "<nofileID>"
            print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
        print fileinfo_str(fileinfo, verbose)
        if (fileinfo['mode'] & 0xE000) == 0x8000:
        sizes[fileinfo['domain']]= sizes.get(fileinfo['domain'],0) + fileinfo['filelen']
    for domain in sorted(sizes, key=sizes.get):
        print "%-60s %11d (%dMB)" % (domain, sizes[domain], int(sizes[domain]/1024/1024))

That way you can figure out what application is eating all that space.

update one table with data from another

Use the following block of query to update Table1 with Table2 based on ID:

UPDATE Table1, Table2 
SET Table1.DataColumn= Table2.DataColumn
where Table1.ID= Table2.ID;

This is the easiest and fastest way to tackle this problem.

Storing data into list with class

And if you want to create the list with some elements to start with:

var emailList = new List<EmailData>
{
   new EmailData { FirstName = "John", LastName = "Doe", Location = "Moscow" },
   new EmailData {.......}
};

How do I make a file:// hyperlink that works in both IE and Firefox?

At least with Chrome, (I don't know about Firefox) You can drag the icon to the left of the URL in the browser to a folder location on your desktop and it will create a file that behaves as an internet shortcut.

I don't know if the file format is universal yet, however Chrome seems to know what to do with it.

The file produced is a .url file and contains the following:

[InternetShortcut] URL=http://www.accordingtothescriptures.org/prophecy/353prophecies.html

You can replace the URL with anything you'd like.

Why is Visual Studio 2010 not able to find/open PDB files?

First change the following parameters:

Tools -> Options -> Debugging -> Symbols -> Server -> Yes

Then press Ctrl+F5 and you will see amazing things.

CSS selector for disabled input type="submit"

I used @jensgram solution to hide a div that contains a disabled input. So I hide the entire parent of the input.

Here is the code :

div:has(>input[disabled=disabled]) {
    display: none;
}

Maybe it could help some of you.

How can I select the row with the highest ID in MySQL?

SELECT *
FROM permlog
WHERE id = ( SELECT MAX(id) FROM permlog ) ;

This would return all rows with highest id, in case id column is not constrained to be unique.

Difference between map and collect in Ruby?

I've been told they are the same.

Actually they are documented in the same place under ruby-doc.org:

http://www.ruby-doc.org/core/classes/Array.html#M000249

  • ary.collect {|item| block } ? new_ary
  • ary.map {|item| block } ? new_ary
  • ary.collect ? an_enumerator
  • ary.map ? an_enumerator

Invokes block once for each element of self. Creates a new array containing the values returned by the block. See also Enumerable#collect.
If no block is given, an enumerator is returned instead.

a = [ "a", "b", "c", "d" ]
a.collect {|x| x + "!" }   #=> ["a!", "b!", "c!", "d!"]
a                          #=> ["a", "b", "c", "d"]

Bootstrap datetimepicker is not a function

I changed the import sequence without fixing the problem, until finally I installed moments and tempus dominius (Core and bootrap), using npm and include them in boostrap.js

try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('moment'); /*added*/
require('bootstrap');
require('tempusdominus-bootstrap-4');/*added*/} catch (e) {}

How to initialize a list with constructor?

Are you looking for this?

ContactNumbers = new List<ContactNumber>(){ new ContactNumber("555-5555"),
                                            new ContactNumber("555-1234"),
                                            new ContactNumber("555-5678") };

How to empty a file using Python

Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:

open(filename, 'w').close()

Update ViewPager dynamically?

When using FragmentPagerAdapter or FragmentStatePagerAdapter, it is best to deal solely with getItem() and not touch instantiateItem() at all. The instantiateItem()-destroyItem()-isViewFromObject() interface on PagerAdapter is a lower-level interface that FragmentPagerAdapter uses to implement the much simpler getItem() interface.

Before getting into this, I should clarify that

if you want to switch out the actual fragments that are being displayed, you need to avoid FragmentPagerAdapter and use FragmentStatePagerAdapter.

An earlier version of this answer made the mistake of using FragmentPagerAdapter for its example - that won't work because FragmentPagerAdapter never destroys a fragment after it's been displayed the first time.

I don't recommend the setTag() and findViewWithTag() workaround provided in the post you linked. As you've discovered, using setTag() and findViewWithTag() doesn't work with fragments, so it's not a good match.

The right solution is to override getItemPosition(). When notifyDataSetChanged() is called, ViewPager calls getItemPosition() on all the items in its adapter to see whether they need to be moved to a different position or removed.

By default, getItemPosition() returns POSITION_UNCHANGED, which means, "This object is fine where it is, don't destroy or remove it." Returning POSITION_NONE fixes the problem by instead saying, "This object is no longer an item I'm displaying, remove it." So it has the effect of removing and recreating every single item in your adapter.

This is a completely legitimate fix! This fix makes notifyDataSetChanged behave like a regular Adapter without view recycling. If you implement this fix and performance is satisfactory, you're off to the races. Job done.

If you need better performance, you can use a fancier getItemPosition() implementation. Here's an example for a pager creating fragments off of a list of strings:

ViewPager pager = /* get my ViewPager */;
// assume this actually has stuff in it
final ArrayList<String> titles = new ArrayList<String>();

FragmentManager fm = getSupportFragmentManager();
pager.setAdapter(new FragmentStatePagerAdapter(fm) {
    public int getCount() {
        return titles.size();
    }

    public Fragment getItem(int position) {
        MyFragment fragment = new MyFragment();
        fragment.setTitle(titles.get(position));
        return fragment;
    }

    public int getItemPosition(Object item) {
        MyFragment fragment = (MyFragment)item;
        String title = fragment.getTitle();
        int position = titles.indexOf(title);

        if (position >= 0) {
            return position;
        } else {
            return POSITION_NONE;
        }
    }
});

With this implementation, only fragments displaying new titles will get displayed. Any fragments displaying titles that are still in the list will instead be moved around to their new position in the list, and fragments with titles that are no longer in the list at all will be destroyed.

What if the fragment has not been recreated, but needs to be updated anyway? Updates to a living fragment are best handled by the fragment itself. That's the advantage of having a fragment, after all - it is its own controller. A fragment can add a listener or an observer to another object in onCreate(), and then remove it in onDestroy(), thus managing the updates itself. You don't have to put all the update code inside getItem() like you do in an adapter for a ListView or other AdapterView types.

One last thing - just because FragmentPagerAdapter doesn't destroy a fragment doesn't mean that getItemPosition is completely useless in a FragmentPagerAdapter. You can still use this callback to reorder your fragments in the ViewPager. It will never remove them completely from the FragmentManager, though.

Ternary operation in CoffeeScript

Coffeescript doesn't support javascript ternary operator. Here is the reason from the coffeescript author:

I love ternary operators just as much as the next guy (probably a bit more, actually), but the syntax isn't what makes them good -- they're great because they can fit an if/else on a single line as an expression.

Their syntax is just another bit of mystifying magic to memorize, with no analogue to anything else in the language. The result being equal, I'd much rather have if/elses always look the same (and always be compiled into an expression).

So, in CoffeeScript, even multi-line ifs will compile into ternaries when appropriate, as will if statements without an else clause:

if sunny   
  go_outside() 
else   
  read_a_book().

if sunny then go_outside() else read_a_book()

Both become ternaries, both can be used as expressions. It's consistent, and there's no new syntax to learn. So, thanks for the suggestion, but I'm closing this ticket as "wontfix".

Please refer to the github issue: https://github.com/jashkenas/coffeescript/issues/11#issuecomment-97802

Xcode: Could not locate device support files

Having the same exact issue with iOS 10.3 and Xcode 8.2.1. I'm not going to download the new Xcode beta just to fix this. Come on Apple!

To anyone reading this, you have to go to https://developer.apple.com/download/ and get the latest version, which might even be the beta, if the stable release doesn't work.

In the future, I would be aware if you update iOS on your devices you may break Xcode/iOS version so update wisely if you want to keep testing on it without jumping through hoops that Apple makes.

Does "display:none" prevent an image from loading?

** 2019 Answer **

In a normal situation display:none doesn't prevent the image to be downloaded

/*will be downloaded*/

#element1 {
    display: none;
    background-image: url('https://picsum.photos/id/237/100');
}

But if an ancestor element has display:none then the descendant's images will not be downloaded


/* Markup */

<div id="father">
    <div id="son"></div>
</div>


/* Styles */

#father {
    display: none;
}

/* #son will not be downloaded because the #father div has display:none; */

#son {
    background-image: url('https://picsum.photos/id/234/500');
}

Other situations that prevent the image to be downloaded:

1- The target element doesn't exist

/* never will be downloaded because the target element doesn't exist */

#element-dont-exist {
    background-image: url('https://picsum.photos/id/240/400');
}

2- Two equal classes loading different images

/* The first image of #element2 will never be downloaded because the other #element2 class */

#element2 {
    background-image: url('https://picsum.photos/id/238/200');
}

/* The second image of #element2 will be downloaded */

#element2 {
    background-image: url('https://picsum.photos/id/239/300');
}

You can watch for yourself here: https://codepen.io/juanmamenendez15/pen/dLQPmX

Why is NULL undeclared?

Don't use NULL, C++ allows you to use the unadorned 0 instead:

previous = 0;
next = 0;

And, as at C++11, you generally shouldn't be using either NULL or 0 since it provides you with nullptr of type std::nullptr_t, which is better suited to the task.

Gradle, Android and the ANDROID_HOME SDK location

I have faced with the same issue on Ubuntu(both local.properties and ANDROID_HOME was added), but build fail persisted. So workaround is to add following lines

export ANDROID_HOME=/home/<user>/Android/Sdk export PATH=$PATH:/home/<user>/Android/Sdk/tools

directly to the studio.sh script (inside /usr/local/android-studio/bin)

Maybe it will be helpful.

How to list all methods for an object in Ruby?

Or just User.methods(false) to return only the methods defined within that class.

Github: Can I see the number of downloads for a repo?

I have written a small web application in javascript for showing count of the number of downloads of all the assets in the available releases of any project on Github. You can try out the application over here: http://somsubhra.github.io/github-release-stats/

Programmatically generate video or animated GIF in Python?

I just tried the following and was very useful:

First Download the libraries Figtodat and images2gif to your local directory.

Secondly Collect the figures in an array and convert them to an animated gif:

import sys
sys.path.insert(0,"/path/to/your/local/directory")
import Figtodat
from images2gif import writeGif
import matplotlib.pyplot as plt
import numpy

figure = plt.figure()
plot   = figure.add_subplot (111)

plot.hold(False)
    # draw a cardinal sine plot
images=[]
y = numpy.random.randn(100,5)
for i in range(y.shape[1]):
    plot.plot (numpy.sin(y[:,i]))  
    plot.set_ylim(-3.0,3)
    plot.text(90,-2.5,str(i))
    im = Figtodat.fig2img(figure)
    images.append(im)

writeGif("images.gif",images,duration=0.3,dither=0)

How to set image to fit width of the page using jsPDF?

My answer deals with a more specific case of what you are asking but I think one could draw some ideas from this to apply more generally. Also, I would post this as a comment to Purushoth's answer (on which mine is based), if only I could.

Ok, so my problem was how to fit a web page into the pdf document, without losing the aspect ratio. I used jsPDF in conjuction with html2canvas and I calculated the ratio from my div's width and height. I applied that same ratio to the pdf document and the page fit perfectly onto the page without any distortion.

var divHeight = $('#div_id').height();
var divWidth = $('#div_id').width();
var ratio = divHeight / divWidth;
html2canvas(document.getElementById("div_id"), {
     height: divHeight,
     width: divWidth,
     onrendered: function(canvas) {
          var image = canvas.toDataURL("image/jpeg");
          var doc = new jsPDF(); // using defaults: orientation=portrait, unit=mm, size=A4
          var width = doc.internal.pageSize.getWidth();    
          var height = doc.internal.pageSize.getHeight();
          height = ratio * width;
          doc.addImage(image, 'JPEG', 0, 0, width-20, height-10);
          doc.save('myPage.pdf'); //Download the rendered PDF.
     }
});

How to get TimeZone from android mobile?

Simplest Solution With Simple Date Format: SimpleDateFormat("ZZZZZ"):

 Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
                Locale.getDefault());
        Date currentLocalTime = calendar.getTime();

        DateFormat date = new SimpleDateFormat("ZZZZZ",Locale.getDefault());
        String localTime = date.format(currentLocalTime);
        System.out.println(localTime+ "  TimeZone   " );

==> Output is : +05:30

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

This happened to me when using java sdk. The problem was for me was i wasnt using the session token from assumed role.

Working code example ( in kotlin )

        val identityUserPoolProviderClient = AWSCognitoIdentityProviderClientBuilder
            .standard()
            .withCredentials(AWSStaticCredentialsProvider(BasicSessionCredentials("accessKeyId", ""secretAccessKey, "sessionToken")))
            .build()

How can I use JSON data to populate the options of a select box?

Why not just make the server return the names?

["Woodland Hills", "none", "Los Angeles", "Laguna Hills"]

Then create the <option> elements using JavaScript.

$.ajax({
    url:'suggest.html',
    type:'POST',
    data: 'q=' + str,
    dataType: 'json',
    success: function( json ) {
        $.each(json, function(i, value) {
            $('#myselect').append($('<option>').text(value).attr('value', value));
        });
    }
});