Programs & Examples On #Rows

A row is a single data item in a database, spreadsheet, table, grid or list. When using this tag, please also add additional tags to clarify your specific environment/language/use case.

How to append rows to an R data frame

Lets take a vector 'point' which has numbers from 1 to 5

point = c(1,2,3,4,5)

if we want to append a number 6 anywhere inside the vector then below command may come handy

i) Vectors

new_var = append(point, 6 ,after = length(point))

ii) columns of a table

new_var = append(point, 6 ,after = length(mtcars$mpg))

The command append takes three arguments:

  1. the vector/column to be modified.
  2. value to be included in the modified vector.
  3. a subscript, after which the values are to be appended.

simple...!! Apologies in case of any...!

Removing specific rows from a dataframe

DF[ ! ( ( DF$sub ==1 & DF$day==2) | ( DF$sub ==3 & DF$day==4) ) , ]   # note the ! (negation)

Or if sub is a factor as suggested by your use of quotes:

DF[ ! paste(sub,day,sep="_") %in% c("1_2", "3_4"), ]

Could also use subset:

subset(DF,  ! paste(sub,day,sep="_") %in% c("1_2", "3_4") )

(And I endorse the use of which in Dirk's answer when using "[" even though some claim it is not needed.)

More than 1 row in <Input type="textarea" />

As said by Sparky in comments on many answers to this question, there is NOT any textarea value for the type attribute of the input tag.

On other terms, the following markup is not valid :

<input type="textarea" />

And the browser replaces it by the default :

<input type="text" />

To define a multi-lines text input, use :

<textarea></textarea>

See the textarea element documentation for more details.

Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

In dplyr:

setdiff(a1,a2)

Basically, setdiff(bigFrame, smallFrame) gets you the extra records in the first table.

In the SQLverse this is called a

Left Excluding Join Venn Diagram

For good descriptions of all join options and set subjects, this is one of the best summaries I've seen put together to date: http://www.vertabelo.com/blog/technical-articles/sql-joins

But back to this question - here are the results for the setdiff() code when using the OP's data:

> a1
  a b
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e

> a2
  a b
1 1 a
2 2 b
3 3 c

> setdiff(a1,a2)
  a b
1 4 d
2 5 e

Or even anti_join(a1,a2) will get you the same results.
For more info: https://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf

Excel Create Collapsible Indented Row Hierarchies

Create a Pivot Table. It has these features and many more.

If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.

Select multiple rows with the same value(s)

Assuming that you want all rows for which there is another row with the exact same Chromosome and Locus:

You can achieve this by joining the table to itself, but only returning the columns from one "side" of the join.

The trick is to set the join condition to "the same locus and chromosome":

select left.*
from Genes left
inner join Genes right
on left.Locus = right.Locus and 
  left.Chromosome = right.Chromosome and left.ID != right.ID

You can also easily extend this by adding a filter in a where-clause.

Find which rows have different values for a given column in Teradata SQL

You can do this using a group by:

select id, addressCode
from t
group by id, addressCode
having min(address) <> max(address)

Another way of writing this may seem clearer, but does not perform as well:

select id, addressCode
from t
group by id, addressCode
having count(distinct address) > 1

Delete rows containing specific strings in R

You can use this function if it's multiple string df[!grepl("REVERSE|GENJJS", df$Name),]

Add some word to all or some rows in Excel?

Save a copy of your spreadsheet first (just in case).

  1. Insert two new columns to the left of the numbered column.

  2. Put a k in the first row of the first (new) column.

  3. Copy it (the k).

  4. Go to the original first column (now the third column) and leave your cursor on the first row that has data.

  5. Hit ctrl and down arrow (at the same time) to jump to the bottom of the populated data range for your original first column.

  6. Left arrow twice to get to the new first column, the one with a k at the very top.

  7. Hit Ctrl-shift-up arrow to go to the first cell with data populated (the original k you put in), highlighting all the cells in-between your starting and ending point.

  8. Use paste (ctrl-v, right-click or whatever your preferred method), and it'll fill all those cells with a k.

  9. Then use the "Concatenate" formula in the second column. Its two arguments will be the column of Ks (column A, first column) and the column with the numbers in it.

  10. This will get you a column with the results of the K column and your numbers.

Hope this helps! The ctrl-shift-arrow and ctrl-arrow shortcuts are amazing for working with large datasets in Excel.

How to remove rows with any zero value

Using tidyverse/dplyr, you can also remove rows with any zero value in a subset of variables:

# variables starting with Mac must be non-zero
filter_at(df, vars(starts_with("Mac")), all_vars((.) != 0))

# variables x, y, and z must be non-zero
filter_at(df, vars(x, y, z), all_vars((.) != 0))

# all numeric variables must be non-zero
filter_if(df, is.numeric, all_vars((.) != 0))

SQL count rows in a table

Use This Query :

Select
    S.name + '.' + T.name As TableName ,
    SUM( P.rows ) As RowCont 

From sys.tables As T
    Inner Join sys.partitions As P On ( P.OBJECT_ID = T.OBJECT_ID )
    Inner Join sys.schemas As S On ( T.schema_id = S.schema_id )
Where
    ( T.is_ms_shipped = 0 )
    AND 
    ( P.index_id IN (1,0) )
    And
    ( T.type = 'U' )

Group By S.name , T.name 

Order By SUM( P.rows ) Desc

Convert multiple rows into one with comma as separator

In SQLite this is simpler. I think there are similar implementations for MySQL, MSSql and Orable

CREATE TABLE Beatles (id integer, name string );
INSERT INTO Beatles VALUES (1, "Paul");
INSERT INTO Beatles VALUES (2, "John");
INSERT INTO Beatles VALUES (3, "Ringo");
INSERT INTO Beatles VALUES (4, "George");
SELECT GROUP_CONCAT(name, ',') FROM Beatles;

Numpy - add row to array

You can use numpy.append() to append a row to numpty array and reshape to a matrix later on.

import numpy as np
a = np.array([1,2])
a = np.append(a, [3,4])
print a
# [1,2,3,4]
# in your example
A = [1,2]
for row in X:
    A = np.append(A, row)

Converting Columns into rows with their respective data in sql server

select 'ScriptName', scriptName from table
union all
select 'ScriptCode', scriptCode from table
union all
select 'Price', price from table

Converting rows into columns and columns into rows using R

Simply use the base transpose function t, wrapped with as.data.frame:

final_df <- as.data.frame(t(starting_df))
final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Above updated. As docendo discimus pointed out, t returns a matrix. As Mark suggested wrapping it with as.data.frame gets back a data frame instead of a matrix. Thanks!

Update multiple rows with different values in a single SQL query

Try with "update tablet set (row='value' where id=0001'), (row='value2' where id=0002'), ...

Python: Number of rows affected by cursor.execute("SELECT ...)

The number of rows effected is returned from execute:

rows_affected=cursor.execute("SELECT ... ")

of course, as AndiDog already mentioned, you can get the row count by accessing the rowcount property of the cursor at any time to get the count for the last execute:

cursor.execute("SELECT ... ")
rows_affected=cursor.rowcount

From the inline documentation of python MySQLdb:

 def execute(self, query, args=None):

    """Execute a query.

    query -- string, query to execute on server
    args -- optional sequence or mapping, parameters to use with query.

    Note: If args is a sequence, then %s must be used as the
    parameter placeholder in the query. If a mapping is used,
    %(key)s must be used as the placeholder.

    Returns long integer rows affected, if any

    """

Repeat rows of a data.frame

The rep.row function seems to sometimes make lists for columns, which leads to bad memory hijinks. I have written the following which seems to work well:

library(plyr)
rep.row <- function(r, n){
  colwise(function(x) rep(x, n))(r)
}

Excel CSV. file with more than 1,048,576 rows of data

Split the CSV into two files in Notepad. It's a pain, but you can just edit each of them individually in Excel after that.

For each row in an R dataframe

I was curious about the time performance of the non-vectorised options. For this purpose, I have used the function f defined by knguyen

f <- function(x, output) {
  wellName <- x[1]
  plateName <- x[2]
  wellID <- 1
  print(paste(wellID, x[3], x[4], sep=","))
  cat(paste(wellID, x[3], x[4], sep=","), file= output, append = T, fill = T)
}

and a dataframe like the one in his example:

n = 100; #number of rows for the data frame
d <- data.frame( name = LETTERS[ sample.int( 25, n, replace=T ) ],
                  plate = paste0( "P", 1:n ),
                  value1 = 1:n,
                  value2 = (1:n)*10 )

I included two vectorised functions (for sure quicker than the others) in order to compare the cat() approach with a write.table() one...

library("ggplot2")
library( "microbenchmark" )
library( foreach )
library( iterators )

tm <- microbenchmark(S1 =
                       apply(d, 1, f, output = 'outputfile1'),
                     S2 = 
                       for(i in 1:nrow(d)) {
                         row <- d[i,]
                         # do stuff with row
                         f(row, 'outputfile2')
                       },
                     S3 = 
                       foreach(d1=iter(d, by='row'), .combine=rbind) %dopar% f(d1,"outputfile3"),
                     S4= {
                       print( paste(wellID=rep(1,n), d[,3], d[,4], sep=",") )
                       cat( paste(wellID=rep(1,n), d[,3], d[,4], sep=","), file= 'outputfile4', sep='\n',append=T, fill = F)                           
                     },
                     S5 = {
                       print( (paste(wellID=rep(1,n), d[,3], d[,4], sep=",")) )
                       write.table(data.frame(rep(1,n), d[,3], d[,4]), file='outputfile5', row.names=F, col.names=F, sep=",", append=T )
                     },
                     times=100L)
autoplot(tm)

The resulting image shows that apply gives the best performance for a non-vectorised version, whereas write.table() seems to outperform cat(). ForEachRunningTime

Adding rows to tbody of a table using jQuery

As @wirey said appendTo should work, if not then you can try this:

$("#tblEntAttributes tbody").append(newRowContent);

Node.js: Python not found exception due to node-sass and node-gyp

so this happened to me on windows recently. I fix it by following the following steps using a PowerShell with admin privileges:

  1. delete node_modulesfolder
  2. running npm install --global windows-build-tools
  3. reinstalling node modules or node-sass with npm install

WebDriver - wait for element using Java

Above wait statement is a nice example of Explicit wait.

As Explicit waits are intelligent waits that are confined to a particular web element(as mentioned in above x-path).

By Using explicit waits you are basically telling WebDriver at the max it is to wait for X units(whatever you have given as timeoutInSeconds) of time before it gives up.

android - how to convert int to string and place it in a EditText?

Use +, the string concatenation operator:

ed = (EditText) findViewById (R.id.box);
int x = 10;
ed.setText(""+x);

or use String.valueOf(int):

ed.setText(String.valueOf(x));

or use Integer.toString(int):

ed.setText(Integer.toString(x));

Angles between two n-dimensional vectors in Python

Using numpy (highly recommended), you would do:

from numpy import (array, dot, arccos, clip)
from numpy.linalg import norm

u = array([1.,2,3,4])
v = ...
c = dot(u,v)/norm(u)/norm(v) # -> cosine of the angle
angle = arccos(clip(c, -1, 1)) # if you really want the angle

How to start activity in another application?

If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:

Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);

Hope it helps.

Sum function in VBA

Function is not a property/method from range.

If you want to sum values then use the following:

Range("A1").Value = Application.Sum(Range(Cells(2, 1), Cells(3, 2)))

EDIT:

if you want the formula then use as follows:

Range("A1").Formula = "=SUM(" & Range(Cells(2, 1), Cells(3, 2)).Address(False, False) & ")"

'The two false after Adress is to define the address as relative (A2:B3).
'If you omit the parenthesis clause or write True instead, you can set the address
'as absolute ($A$2:$B$3).

In case you are allways going to use the same range address then you can use as Rory sugested:

Range("A1").Formula ="=Sum(A2:B3)"

Make the console wait for a user input to close

I'd like to add that usually you'll want the program to wait only if it's connected to a console. Otherwise (like if it's a part of a pipeline) there is no point printing a message or waiting. For that you could use Java's Console like this:

import java.io.Console;
// ...
public static void waitForEnter(String message, Object... args) {
    Console c = System.console();
    if (c != null) {
        // printf-like arguments
        if (message != null)
            c.format(message, args);
        c.format("\nPress ENTER to proceed.\n");
        c.readLine();
    }
}

Algorithm to return all combinations of k elements from n

Art of Computer Programming Volume 4: Fascicle 3 has a ton of these that might fit your particular situation better than how I describe.

Gray Codes

An issue that you will come across is of course memory and pretty quickly, you'll have problems by 20 elements in your set -- 20C3 = 1140. And if you want to iterate over the set it's best to use a modified gray code algorithm so you aren't holding all of them in memory. These generate the next combination from the previous and avoid repetitions. There are many of these for different uses. Do we want to maximize the differences between successive combinations? minimize? et cetera.

Some of the original papers describing gray codes:

  1. Some Hamilton Paths and a Minimal Change Algorithm
  2. Adjacent Interchange Combination Generation Algorithm

Here are some other papers covering the topic:

  1. An Efficient Implementation of the Eades, Hickey, Read Adjacent Interchange Combination Generation Algorithm (PDF, with code in Pascal)
  2. Combination Generators
  3. Survey of Combinatorial Gray Codes (PostScript)
  4. An Algorithm for Gray Codes

Chase's Twiddle (algorithm)

Phillip J Chase, `Algorithm 382: Combinations of M out of N Objects' (1970)

The algorithm in C...

Index of Combinations in Lexicographical Order (Buckles Algorithm 515)

You can also reference a combination by its index (in lexicographical order). Realizing that the index should be some amount of change from right to left based on the index we can construct something that should recover a combination.

So, we have a set {1,2,3,4,5,6}... and we want three elements. Let's say {1,2,3} we can say that the difference between the elements is one and in order and minimal. {1,2,4} has one change and is lexicographically number 2. So the number of 'changes' in the last place accounts for one change in the lexicographical ordering. The second place, with one change {1,3,4} has one change but accounts for more change since it's in the second place (proportional to the number of elements in the original set).

The method I've described is a deconstruction, as it seems, from set to the index, we need to do the reverse – which is much trickier. This is how Buckles solves the problem. I wrote some C to compute them, with minor changes – I used the index of the sets rather than a number range to represent the set, so we are always working from 0...n. Note:

  1. Since combinations are unordered, {1,3,2} = {1,2,3} --we order them to be lexicographical.
  2. This method has an implicit 0 to start the set for the first difference.

Index of Combinations in Lexicographical Order (McCaffrey)

There is another way:, its concept is easier to grasp and program but it's without the optimizations of Buckles. Fortunately, it also does not produce duplicate combinations:

The set x_k...x_1 in N that maximizes i = C(x_1,k) + C(x_2,k-1) + ... + C(x_k,1), where C(n,r) = {n choose r}.

For an example: 27 = C(6,4) + C(5,3) + C(2,2) + C(1,1). So, the 27th lexicographical combination of four things is: {1,2,5,6}, those are the indexes of whatever set you want to look at. Example below (OCaml), requires choose function, left to reader:

(* this will find the [x] combination of a [set] list when taking [k] elements *)
let combination_maccaffery set k x =
    (* maximize function -- maximize a that is aCb              *)
    (* return largest c where c < i and choose(c,i) <= z        *)
    let rec maximize a b x =
        if (choose a b ) <= x then a else maximize (a-1) b x
    in
    let rec iterate n x i = match i with
        | 0 -> []
        | i ->
            let max = maximize n i x in
            max :: iterate n (x - (choose max i)) (i-1)
    in
    if x < 0 then failwith "errors" else
    let idxs =  iterate (List.length set) x k in
    List.map (List.nth set) (List.sort (-) idxs)

A small and simple combinations iterator

The following two algorithms are provided for didactic purposes. They implement an iterator and (a more general) folder overall combinations. They are as fast as possible, having the complexity O(nCk). The memory consumption is bound by k.

We will start with the iterator, which will call a user provided function for each combination

let iter_combs n k f =
  let rec iter v s j =
    if j = k then f v
    else for i = s to n - 1 do iter (i::v) (i+1) (j+1) done in
  iter [] 0 0

A more general version will call the user provided function along with the state variable, starting from the initial state. Since we need to pass the state between different states we won't use the for-loop, but instead, use recursion,

let fold_combs n k f x =
  let rec loop i s c x =
    if i < n then
      loop (i+1) s c @@
      let c = i::c and s = s + 1 and i = i + 1 in
      if s < k then loop i s c x else f c x
    else x in
  loop 0 0 [] x

How to edit binary file on Unix systems

In vim You can type :%!xxd to turn it into a hexeditor. :%!xxd -r to go back to normal mode. xxd is shipped in a vim installation.

See here for some remarks about editing binary files with vim (boils down to :set binary to avoid trouble, use only the "R" or "r" command to change text, don't delete characters).

If You are an Emacs fan, see here for a guide on how to edit a binary file with Emacs.

Jquery sortable 'change' event element position

If anyone is interested in a sortable list with a changing index per listitem (1st, 2nd, 3th etc...:

http://jsfiddle.net/aph0c1rL/1/

$(".sortable").sortable(
{
  handle:         '.handle'
, placeholder:    'sort-placeholder'
, forcePlaceholderSize: true
, start: function( e, ui )
{
    ui.item.data( 'start-pos', ui.item.index()+1 );
}
, change: function( e, ui )
  {
      var seq
      , startPos = ui.item.data( 'start-pos' )
      , $index
      , correction
      ;

      // if startPos < placeholder pos, we go from top to bottom
      // else startPos > placeholder pos, we go from bottom to top and we need to correct the index with +1
      //
      correction = startPos <= ui.placeholder.index() ? 0 : 1;

      ui.item.parent().find( 'li.prize').each( function( idx, el )
      {
        var $this = $( el )
        , $index = $this.index()
        ;

        // correction 0 means moving top to bottom, correction 1 means bottom to top
        //
        if ( ( $index+1 >= startPos && correction === 0) || ($index+1 <= startPos && correction === 1 ) )
        {
          $index = $index + correction;
          $this.find( '.ordinal-position').text( $index + ordinalSuffix( $index ) );
        }

      });

      // handle dragged item separatelly
      seq = ui.item.parent().find( 'li.sort-placeholder').index() + correction;
      ui.item.find( '.ordinal-position' ).text( seq + ordinalSuffix( seq ) );
} );

// this function adds the correct ordinal suffix to the provide number
function ordinalSuffix( number )
{
  var suffix = '';

  if ( number / 10 % 10 === 1 )
  {
    suffix = "th";
  }
  else if ( number > 0 )
  {

    switch( number % 10 )
    {
      case 1:
        suffix = "st";
        break;
      case 2:
        suffix = "nd";
        break;
      case 3:
        suffix = "rd";
        break;
      default:
        suffix = "th";
        break;
    }
  }
  return suffix;
}

Your markup can look like this:

<ul class="sortable ">
<li >        
    <div>
        <span class="ordinal-position">1st</span>
         A header
    </div>
    <div>
        <span class="icon-button handle"><i class="fa fa-arrows"></i></span>
    </div>
    <div class="bpdy" >
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    </div>
</li>
 <li >        
    <div>
        <span class="ordinal-position">2nd</span>
         A header
    </div>
    <div>
        <span class="icon-button handle"><i class="fa fa-arrows"></i></span>
    </div>
    <div class="bpdy" >
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    </div>
</li>
etc....
</ul>

Using 'sudo apt-get install build-essentials'

The package is called build-essential without the plural "s". So

sudo apt-get install build-essential

should do what you want.

state machines tutorials

Unfortunately, most of the articles on state machines are written for C++ or other languages that have direct support for polymorphism as it's nice to model the states in an FSM implementation as classes that derive from an abstract state class.

However, it's pretty easy to implement state machines in C using either switch statements to dispatch events to states (for simple FSMs, they pretty much code right up) or using tables to map events to state transitions.

There are a couple of simple, but decent articles on a basic framework for state machines in C here:

Edit: Site "under maintenance", web archive links:

switch statement-based state machines often use a set of macros to 'hide' the mechanics of the switch statement (or use a set of if/then/else statements instead of a switch) and make what amounts to a "FSM language" for describing the state machine in C source. I personally prefer the table-based approach, but these certainly have merit, are widely used, and can be effective especially for simpler FSMs.

One such framework is outlined by Steve Rabin in "Game Programming Gems" Chapter 3.0 (Designing a General Robust AI Engine).

A similar set of macros is discussed here:

If you're also interested in C++ state machine implementations there's a lot more that can be found. I'll post pointers if you're interested.

Produce a random number in a range using C#

Something like:

var rnd = new Random(DateTime.Now.Millisecond);
int ticks = rnd.Next(0, 3000);

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

If you need it prefix than you might like this

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

that will yield

07
08
09
10
11
12

How to set socket timeout in C when making multiple connections?

Can't you implement your own timeout system?

Keep a sorted list, or better yet a priority heap as Heath suggests, of timeout events. In your select or poll calls use the timeout value from the top of the timeout list. When that timeout arrives, do that action attached to that timeout.

That action could be closing a socket that hasn't connected yet.

SELECT max(x) is returning null; how can I make it return 0?

For OLEDB you can use this query:

select IIF(MAX(faculty_id) IS NULL,0,MAX(faculty_id)) AS max_faculty_id from faculties;

As IFNULL is not working there

How to use both onclick and target="_blank"

onclick="window.open('your_html', '_blank')"

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

change it to Console (/SUBSYSTEM:CONSOLE) it will work

How can I change the image of an ImageView?

If you created imageview using xml file then follow the steps.

Solution 1:

Step 1: Create an XML file

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="#cc8181"
  >

  <ImageView
      android:id="@+id/image"
      android:layout_width="50dip"
      android:layout_height="fill_parent" 
      android:src="@drawable/icon"
      android:layout_marginLeft="3dip"
      android:scaleType="center"/>

</LinearLayout>

Step 2: create an Activity

ImageView img= (ImageView) findViewById(R.id.image);
img.setImageResource(R.drawable.my_image);

Solution 2:

If you created imageview from Java Class

ImageView img = new ImageView(this);
img.setImageResource(R.drawable.my_image);

Get RETURN value from stored procedure in SQL

The accepted answer is invalid with the double EXEC (only need the first EXEC):

DECLARE @returnvalue int;
EXEC @returnvalue = SP_SomeProc
PRINT @returnvalue

And you still need to call PRINT (at least in Visual Studio).

How do I POST urlencoded form data with $http without jQuery?

you need to post plain javascript object, nothing else

           var request = $http({
                method: "post",
                url: "process.cfm",
                transformRequest: transformRequestAsFormPost,
                data: { id: 4, name: "Kim" }
            });

            request.success(
                function( data ) {
                    $scope.localData = data;
                }
            );

if you have php as back-end then you will need to do some more modification.. checkout this link for fixing php server side

Gson: How to exclude specific fields from Serialization without annotations

I used this strategy: i excluded every field which is not marked with @SerializedName annotation, i.e.:

public class Dummy {

    @SerializedName("VisibleValue")
    final String visibleValue;
    final String hiddenValue;

    public Dummy(String visibleValue, String hiddenValue) {
        this.visibleValue = visibleValue;
        this.hiddenValue = hiddenValue;
    }
}


public class SerializedNameOnlyStrategy implements ExclusionStrategy {

    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        return f.getAnnotation(SerializedName.class) == null;
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
        return false;
    }
}


Gson gson = new GsonBuilder()
                .setExclusionStrategies(new SerializedNameOnlyStrategy())
                .create();

Dummy dummy = new Dummy("I will see this","I will not see this");
String json = gson.toJson(dummy);

It returns

{"VisibleValue":"I will see this"}

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:

url:   'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',

to this line:

url: '/path/to/phpscript.php',

and then in the php script (if you have permission to use the file_get_contents() function):

<?php

header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

?>

Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.

Edit: If you want to cache the result in php, here's the php file you would use:

<?php

$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
  $contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
  file_put_contents($cacheName, $contents);
}

$xml = simplexml_load_file($cacheName);

header('Content-type: application/xml');
echo $xml;

?>

Caching code take from here.

How to get a string after a specific substring?

You want to use str.partition():

>>> my_string.partition("world")[2]
" , i'm a beginner "

because this option is faster than the alternatives.

Note that this produces an empty string if the delimiter is missing:

>>> my_string.partition("Monty")[2]  # delimiter missing
''

If you want to have the original string, then test if the second value returned from str.partition() is non-empty:

prefix, success, result = my_string.partition(delimiter)
if not success: result = prefix

You could also use str.split() with a limit of 1:

>>> my_string.split("world", 1)[-1]
" , i'm a beginner "
>>> my_string.split("Monty", 1)[-1]  # delimiter missing
"hello python world , i'm a beginner "

However, this option is slower. For a best-case scenario, str.partition() is easily about 15% faster compared to str.split():

                                missing        first         lower         upper          last
      str.partition(...)[2]:  [3.745 usec]  [0.434 usec]  [1.533 usec]  <3.543 usec>  [4.075 usec]
str.partition(...) and test:   3.793 usec    0.445 usec    1.597 usec    3.208 usec    4.170 usec
      str.split(..., 1)[-1]:  <3.817 usec>  <0.518 usec>  <1.632 usec>  [3.191 usec]  <4.173 usec>
            % best vs worst:         1.9%         16.2%          6.1%          9.9%          2.3%

This shows timings per execution with inputs here the delimiter is either missing (worst-case scenario), placed first (best case scenario), or in the lower half, upper half or last position. The fastest time is marked with [...] and <...> marks the worst.

The above table is produced by a comprehensive time trial for all three options, produced below. I ran the tests on Python 3.7.4 on a 2017 model 15" Macbook Pro with 2.9 GHz Intel Core i7 and 16 GB ram.

This script generates random sentences with and without the randomly selected delimiter present, and if present, at different positions in the generated sentence, runs the tests in random order with repeats (producing the fairest results accounting for random OS events taking place during testing), and then prints a table of the results:

import random
from itertools import product
from operator import itemgetter
from pathlib import Path
from timeit import Timer

setup = "from __main__ import sentence as s, delimiter as d"
tests = {
    "str.partition(...)[2]": "r = s.partition(d)[2]",
    "str.partition(...) and test": (
        "prefix, success, result = s.partition(d)\n"
        "if not success: result = prefix"
    ),
    "str.split(..., 1)[-1]": "r = s.split(d, 1)[-1]",
}

placement = "missing first lower upper last".split()
delimiter_count = 3

wordfile = Path("/usr/dict/words")  # Linux
if not wordfile.exists():
    # macos
    wordfile = Path("/usr/share/dict/words")
words = [w.strip() for w in wordfile.open()]

def gen_sentence(delimiter, where="missing", l=1000):
    """Generate a random sentence of length l

    The delimiter is incorporated according to the value of where:

    "missing": no delimiter
    "first":   delimiter is the first word
    "lower":   delimiter is present in the first half
    "upper":   delimiter is present in the second half
    "last":    delimiter is the last word

    """
    possible = [w for w in words if delimiter not in w]
    sentence = random.choices(possible, k=l)
    half = l // 2
    if where == "first":
        # best case, at the start
        sentence[0] = delimiter
    elif where == "lower":
        # lower half
        sentence[random.randrange(1, half)] = delimiter
    elif where == "upper":
        sentence[random.randrange(half, l)] = delimiter
    elif where == "last":
        sentence[-1] = delimiter
    # else: worst case, no delimiter

    return " ".join(sentence)

delimiters = random.choices(words, k=delimiter_count)
timings = {}
sentences = [
    # where, delimiter, sentence
    (w, d, gen_sentence(d, w)) for d, w in product(delimiters, placement)
]
test_mix = [
    # label, test, where, delimiter sentence
    (*t, *s) for t, s in product(tests.items(), sentences)
]
random.shuffle(test_mix)

for i, (label, test, where, delimiter, sentence) in enumerate(test_mix, 1):
    print(f"\rRunning timed tests, {i:2d}/{len(test_mix)}", end="")
    t = Timer(test, setup)
    number, _ = t.autorange()
    results = t.repeat(5, number)
    # best time for this specific random sentence and placement
    timings.setdefault(
        label, {}
    ).setdefault(
        where, []
    ).append(min(dt / number for dt in results))

print()

scales = [(1.0, 'sec'), (0.001, 'msec'), (1e-06, 'usec'), (1e-09, 'nsec')]
width = max(map(len, timings))
rows = []
bestrow = dict.fromkeys(placement, (float("inf"), None))
worstrow = dict.fromkeys(placement, (float("-inf"), None))

for row, label in enumerate(tests):
    columns = []
    worst = float("-inf")
    for p in placement:
        timing = min(timings[label][p])
        if timing < bestrow[p][0]:
            bestrow[p] = (timing, row)
        if timing > worstrow[p][0]:
            worstrow[p] = (timing, row)
        worst = max(timing, worst)
        columns.append(timing)

    scale, unit = next((s, u) for s, u in scales if worst >= s)
    rows.append(
        [f"{label:>{width}}:", *(f" {c / scale:.3f} {unit} " for c in columns)]
    )

colwidth = max(len(c) for r in rows for c in r[1:])
print(' ' * (width + 1), *(p.center(colwidth) for p in placement), sep="  ")
for r, row in enumerate(rows):
    for c, p in enumerate(placement, 1):
        if bestrow[p][1] == r:
            row[c] = f"[{row[c][1:-1]}]"
        elif worstrow[p][1] == r:
            row[c] = f"<{row[c][1:-1]}>"
    print(*row, sep="  ")

percentages = []
for p in placement:
    best, worst = bestrow[p][0], worstrow[p][0]
    ratio = ((worst - best) / worst)
    percentages.append(f"{ratio:{colwidth - 1}.1%} ")

print("% best vs worst:".rjust(width + 1), *percentages, sep="  ")

What is the difference between children and childNodes in JavaScript?

Good answers so far, I want to only add that you could check the type of a node using nodeType:

yourElement.nodeType

This will give you an integer: (taken from here)

| Value |             Constant             |                          Description                          |  |
|-------|----------------------------------|---------------------------------------------------------------|--|
|    1  | Node.ELEMENT_NODE                | An Element node such as <p> or <div>.                         |  |
|    2  | Node.ATTRIBUTE_NODE              | An Attribute of an Element. The element attributes            |  |
|       |                                  | are no longer implementing the Node interface in              |  |
|       |                                  | DOM4 specification.                                           |  |
|    3  | Node.TEXT_NODE                   | The actual Text of Element or Attr.                           |  |
|    4  | Node.CDATA_SECTION_NODE          | A CDATASection.                                               |  |
|    5  | Node.ENTITY_REFERENCE_NODE       | An XML Entity Reference node. Removed in DOM4 specification.  |  |
|    6  | Node.ENTITY_NODE                 | An XML <!ENTITY ...> node. Removed in DOM4 specification.     |  |
|    7  | Node.PROCESSING_INSTRUCTION_NODE | A ProcessingInstruction of an XML document                    |  |
|       |                                  | such as <?xml-stylesheet ... ?> declaration.                  |  |
|    8  | Node.COMMENT_NODE                | A Comment node.                                               |  |
|    9  | Node.DOCUMENT_NODE               | A Document node.                                              |  |
|   10  | Node.DOCUMENT_TYPE_NODE          | A DocumentType node e.g. <!DOCTYPE html> for HTML5 documents. |  |
|   11  | Node.DOCUMENT_FRAGMENT_NODE      | A DocumentFragment node.                                      |  |
|   12  | Node.NOTATION_NODE               | An XML <!NOTATION ...> node. Removed in DOM4 specification.   |  |

Note that according to Mozilla:

The following constants have been deprecated and should not be used anymore: Node.ATTRIBUTE_NODE, Node.ENTITY_REFERENCE_NODE, Node.ENTITY_NODE, Node.NOTATION_NODE

Difference between malloc and calloc?

There's no difference in the size of the memory block allocated. calloc just fills the memory block with physical all-zero-bits pattern. In practice it is often assumed that the objects located in the memory block allocated with calloc have initilial value as if they were initialized with literal 0, i.e. integers should have value of 0, floating-point variables - value of 0.0, pointers - the appropriate null-pointer value, and so on.

From the pedantic point of view though, calloc (as well as memset(..., 0, ...)) is only guaranteed to properly initialize (with zeroes) objects of type unsigned char. Everything else is not guaranteed to be properly initialized and may contain so called trap representation, which causes undefined behavior. In other words, for any type other than unsigned char the aforementioned all-zero-bits patterm might represent an illegal value, trap representation.

Later, in one of the Technical Corrigenda to C99 standard, the behavior was defined for all integer types (which makes sense). I.e. formally, in the current C language you can initialize only integer types with calloc (and memset(..., 0, ...)). Using it to initialize anything else in general case leads to undefined behavior, from the point of view of C language.

In practice, calloc works, as we all know :), but whether you'd want to use it (considering the above) is up to you. I personally prefer to avoid it completely, use malloc instead and perform my own initialization.

Finally, another important detail is that calloc is required to calculate the final block size internally, by multiplying element size by number of elements. While doing that, calloc must watch for possible arithmetic overflow. It will result in unsuccessful allocation (null pointer) if the requested block size cannot be correctly calculated. Meanwhile, your malloc version makes no attempt to watch for overflow. It will allocate some "unpredictable" amount of memory in case overflow happens.

destination path already exists and is not an empty directory

This just means that the git clone copied the files down from github and placed them into a folder. If you try to do it again it will not let you because it can't clone into a folder that has files into it. So if you think the git clone did not complete properly, just delete the folder and do the git clone again. The clone creates a folder the same name as the git repo.

C# DLL config file

Since the assembly resides in a temporary cache, you should combine the path to get the dll's config:

var appConfig = ConfigurationManager.OpenExeConfiguration(
    Path.Combine(Environment.CurrentDirectory, Assembly.GetExecutingAssembly().ManifestModule.Name));

Could not extract response: no suitable HttpMessageConverter found for response type

public class Application {

    private static List<HttpMessageConverter<?>> getMessageConverters() {
        List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
        converters.add(new MappingJacksonHttpMessageConverter());
        return converters;
    }   

    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();

        restTemplate.setMessageConverters(getMessageConverters());
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        //Page page = restTemplate.getForObject("http://graph.facebook.com/pivotalsoftware", Page.class);

        ResponseEntity<Page> response = 
                  restTemplate.exchange("http://graph.facebook.com/skbh86", HttpMethod.GET, entity, Page.class, "1");
        Page page = response.getBody();
        System.out.println("Name:    " + page.getId());
        System.out.println("About:   " + page.getFirst_name());
        System.out.println("Phone:   " + page.getLast_name());
        System.out.println("Website: " + page.getMiddle_name());
        System.out.println("Website: " + page.getName());
    }
}

VMWare Player vs VMWare Workstation

from http://www.vmware.com/products/player/faqs.html:

How does VMware Player compare to VMware Workstation? VMware Player enables you to quickly and easily create and run virtual machines. However, VMware Player lacks many powerful features, remote connections to vSphere, drag and drop upload to vSphere, multiple Snapshots and Clones, and much more.

Not being able to revert snapshots it's a big no for me.

Enable remote MySQL connection: ERROR 1045 (28000): Access denied for user

if you are using dynamic ip just grant access to 192.168.2.% so now you dont have to worry about granting access to your ip address every time.

What is Teredo Tunneling Pseudo-Interface?

Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.

If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)

PHP String to Float

Well, if user write 1,00,000 then floatvar will show error. So -

floatval(preg_replace("/[^-0-9\.]/","",$input));

This is much more reliable.

Usage :

$input = '1,03,24,23,434,500.6798633 this';
echo floatval(preg_replace("/[^-0-9\.]/","",$input));

How do I alter the position of a column in a PostgreSQL database table?

There are some workarounds to make it possible:

  1. Recreating the whole table

  2. Create new columns within the current table

  3. Create a view

https://tableplus.com/blog/2018/09/postgresql-is-it-possible-to-alter-column-order-position-in-a-table.html

Test method is inconclusive: Test wasn't run. Error?

Another one method of solving this problem:

Run tests in another environment (TeamCity for example) and see your REAL problem. My problem was incorrect binding redirect to System.Web.Mvc 5.2.6.0 (not installed on my machine).

<DIV> inside link (<a href="">) tag

As of HTML5 it is OK to wrap <a> elements around a <div> (or any other block elements):

The a element may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links).

Just have to make sure you don't put an <a> within your <a> ( or a <button>).

PHP check whether property exists in object or class

property_exists( mixed $class , string $property )

if (property_exists($ob, 'a')) 

isset( mixed $var [, mixed $... ] )

if (isset($ob->a))

isset() will return false if property is null

Example 1:

$ob->a = null
var_dump(isset($ob->a)); // false

Example 2:

class Foo
{
   public $bar = null;
}

$foo = new Foo();

var_dump(property_exists($foo, 'bar')); // true
var_dump(isset($foo->bar)); // false

Get single row result with Doctrine NativeQuery

Both getSingleResult() and getOneOrNullResult() will throw an exception if there is more than one result. To fix this problem you could add setMaxResults(1) to your query builder.

 $firstSubscriber = $entity->createQueryBuilder()->select('sub')
        ->from("\Application\Entity\Subscriber", 'sub')
        ->where('sub.subscribe=:isSubscribe')
        ->setParameter('isSubscribe', 1)  
        ->setMaxResults(1)
        ->getQuery()
        ->getOneOrNullResult();

How do I Alter Table Column datatype on more than 1 column?

Use the following syntax:

  ALTER TABLE your_table
  MODIFY COLUMN column1 datatype,
  MODIFY COLUMN column2 datatype,
  ... ... ... ... ... 
  ... ... ... ... ...

Based on that, your ALTER command should be:

  ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100)

Note that:

  1. There are no second brackets around the MODIFY statements.
  2. I used two separate MODIFY statements for two separate columns.

This is the standard format of the MODIFY statement for an ALTER command on multiple columns in a MySQL table.

Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement

New line in JavaScript alert box

I saw some people had trouble with this in MVC, so... a simple way to pass '\n' using the Model, and in my case even using a translated text, is to use HTML.Raw to insert the text. That fixed it for me. In the code below, Model.Alert can contains newlines, like "Hello\nWorld"...

alert("@Html.Raw(Model.Alert)");

Read a file one line at a time in node.js?

This is my favorite way of going through a file, a simple native solution for a progressive (as in not a "slurp" or all-in-memory way) file read with modern async/await. It's a solution that I find "natural" when processing large text files without having to resort to the readline package or any non-core dependency.

let buf = '';
for await ( const chunk of fs.createReadStream('myfile') ) {
    const lines = buf.concat(chunk).split(/\r?\n/);
    buf = lines.pop();
    for( const line of lines ) {
        console.log(line);
    }
}
if(buf.length) console.log(buf);  // last line, if file does not end with newline

You can adjust encoding in the fs.createReadStream or use chunk.toString(<arg>). Also this let's you better fine-tune the line splitting to your taste, ie. use .split(/\n+/) to skip empty lines and control the chunk size with { highWaterMark: <chunkSize> }.

Don't forget to create a function like processLine(line) to avoid repeating the line processing code twice due to the ending buf leftover. Unfortunately, the ReadStream instance does not update its end-of-file flags in this setup, so there's no way, afaik, to detect within the loop that we're in the last iteration without some more verbose tricks like comparing the file size from a fs.Stats() with .bytesRead. Hence the final buf processing solution, unless you're absolutely sure your file ends with a newline \n, in which case the for await loop should suffice.

? If you prefer the evented asynchronous version, this would be it:

let buf = '';
fs.createReadStream('myfile')
.on('data', chunk => {
    const lines = buf.concat(chunk).split(/\r?\n/);
    buf = lines.pop();
    for( const line of lines ) {
        console.log(line);
    }
})
.on('end', () => buf.length && console.log(buf) );

? Now if you don't mind importing the stream core package, then this is the equivalent piped stream version, which allows for chaining transforms like gzip decompression:

const { Writable } = require('stream');
let buf = '';
fs.createReadStream('myfile').pipe(
    new Writable({
        write: (chunk, enc, next) => {
            const lines = buf.concat(chunk).split(/\r?\n/);
            buf = lines.pop();
            for (const line of lines) {
                console.log(line);
            }
            next();
        }
    })
).on('finish', () => buf.length && console.log(buf) );

Is there a simple way that I can sort characters in a string in alphabetical order

You can use LINQ:

String.Concat(str.OrderBy(c => c))

If you want to remove duplicates, add .Distinct().

Access HTTP response as string in Go

string(byteslice) will convert byte slice to string, just know that it's not only simply type conversion, but also memory copy.

java.lang.ClassNotFoundException on working app

Make sure that android:hasCode is not set to false in your manifest file. This is what solved the problem for me!

Undoing a 'git push'

you can use the command reset

git reset --soft HEAD^1

then:

git reset <files>
git commit --amend

and

git push -f

Jersey Exception : SEVERE: A message body reader for Java class

for Python and Swagger example:

import requests
base_url = 'https://petstore.swagger.io/v2'
def store_order(uid):
    api_url = f"{base_url}/store/order"
    api_data = {
        'id':uid,
        "petId": 0,
        "quantity": 0,
        "shipDate": "2020-04-08T07:56:05.832Z",
        "status": "placed",
        "complete": "true"
        }
    # is a kind of magic..
    r = requests.post(api_url, json=api_data)
    return r
print(store_order(0).content)    

Most important string with MIME type: r = requests.post(api_url, json=api_data)

How to encode the filename parameter of Content-Disposition header in HTTP?

I normally URL-encode (with %xx) the filenames, and it seems to work in all browsers. You might want to do some tests anyway.

Explain the "setUp" and "tearDown" Python methods used in test cases

Suppose you have a suite with 10 tests. 8 of the tests share the same setup/teardown code. The other 2 don't.

setup and teardown give you a nice way to refactor those 8 tests. Now what do you do with the other 2 tests? You'd move them to another testcase/suite. So using setup and teardown also helps give a natural way to break the tests into cases/suites

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

In PyCharm, I'd leave it out. It turns off the UTF-8 indicator at the bottom with a warning that the encoding is hard-coded. Don't think you need the PyCharm comment mentioned above.

Alternative to file_get_contents?

If you're trying to read XML generated from a URL without file_get_contents() then you'll probably want to have a look at cURL

Run C++ in command prompt - Windows

It depends on what compiler you're using.

For example, if you are using Visual C++ .NET 2010 Express, run Visual C++ 2010 Express Command Prompt from the start menu, and you can simply compile and run the code.

> cl /EHsc mycode.cpp
> mycode.exe

or from the regular command line, you can run vcvars32.bat first to set up the environment. Alternatively search for setvcvars.cmd (part of a FLOSS project) and use that to even locate the installed VS and have it call vcvars32.bat for you.

Please check your compiler's manual for command lines.

What's the difference between console.dir and console.log?

From the firebug site http://getfirebug.com/logging/

Calling console.dir(object) will log an interactive listing of an object's properties, like > a miniature version of the DOM tab.

How to set java.net.preferIPv4Stack=true at runtime?

System.setProperty is not working for applets. Because JVM already running before applet start. In this case we use applet parameters like this:

    deployJava.runApplet({
        id: 'MyApplet',
        code: 'com.mkysoft.myapplet.SomeClass',
        archive: 'com.mkysoft.myapplet.jar'
    }, {
        java_version: "1.6*", // Target version
        cache_option: "no",
        cache_archive: "",
        codebase_lookup: true,
        java_arguments: "-Djava.net.preferIPv4Stack=true"
    },
       "1.6" // Minimum version
    );

You can find deployJava.js at https://www.java.com/js/deployJava.js

Way to create multiline comments in Bash?

After reading the other answers here I came up with the below, which IMHO makes it really clear it's a comment. Especially suitable for in-script usage info:

<< ////

Usage:
This script launches a spaceship to the moon. It's doing so by 
leveraging the power of the Fifth Element, AKA Leeloo.
Will only work if you're Bruce Willis or a relative of Milla Jovovich.

////

As a programmer, the sequence of slashes immediately registers in my brain as a comment (even though slashes are normally used for line comments).

Of course, "////" is just a string; the number of slashes in the prefix and the suffix must be equal.

How to replace space with comma using sed?

Inside vim, you want to type when in normal (command) mode:

:%s/ /,/g

On the terminal prompt, you can use sed to perform this on a file:

sed -i 's/\ /,/g' input_file

Note: the -i option to sed means "in-place edit", as in that it will modify the input file.

How to determine one year from now in Javascript

This will create a Date exactly one year in the future with just one line. First we get the fullYear from a new Date, increment it, set that as the year of a new Date. You might think we'd be done there, but if we stopped it would return a timestamp, not a Date object so we wrap the whole thing in a Date constructor.

new Date(new Date().setFullYear(new Date().getFullYear() + 1))

How to exclude a directory in find . command

how-to-use-prune-option-of-find-in-sh is an excellent answer by Laurence Gonsalves on how -prune works.

And here is the generic solution:

find /path/to/search                    \
  -type d                               \
    \( -path /path/to/search/exclude_me \
       -o                               \
       -name exclude_me_too_anywhere    \
     \)                                 \
    -prune                              \
  -o                                    \
  -type f -name '*\.js' -print

To avoid typing /path/to/seach/ multiple times, wrap the find in a pushd .. popd pair.

pushd /path/to/search;                  \
find .                                  \
  -type d                               \
    \( -path ./exclude_me               \
       -o                               \
       -name exclude_me_too_anywhere    \
     \)                                 \
    -prune                              \
  -o                                    \
  -type f -name '*\.js' -print;         \
 popd

I need a Nodejs scheduler that allows for tasks at different intervals

I think the best ranking is

1.node-schedule

2.later

3.crontab

and the sample of node-schedule is below:

var schedule = require("node-schedule");
var rule = new schedule.RecurrenceRule();
//rule.minute = 40;
rule.second = 10;
var jj = schedule.scheduleJob(rule, function(){
    console.log("execute jj");
});

Maybe you can find the answer from node modules.

Accessing certain pixel RGB value in openCV

The current version allows the cv::Mat::at function to handle 3 dimensions. So for a Mat object m, m.at<uchar>(0,0,0) should work.

event.preventDefault() function not working in IE

I know this is quite an old post but I just spent some time trying to make this work in IE8.

It appears that there are some differences in IE8 versions because solutions posted here and in other threads didn't work for me.

Let's say that we have this code:

$('a').on('click', function(event) {
    event.preventDefault ? event.preventDefault() : event.returnValue = false;
});

In my IE8 preventDefault() method exists because of jQuery, but is not working (probably because of the point below), so this will fail.

Even if I set returnValue property directly to false:

$('a').on('click', function(event) {
    event.returnValue = false;
    event.preventDefault();
});

This also won't work, because I just set some property of jQuery custom event object.

Only solution that works for me is to set property returnValue of global variable event like this:

$('a').on('click', function(event) {
    if (window.event) {
        window.event.returnValue = false;
    }
    event.preventDefault();
});

Just to make it easier for someone who will try to convince IE8 to work. I hope that IE8 will die horribly in painful death soon.

UPDATE:

As sv_in points out, you could use event.originalEvent to get original event object and set returnValue property in the original one. But I haven't tested it in my IE8 yet.

How can I retrieve Id of inserted entity using Entity framework?

It is pretty easy. If you are using DB generated Ids (like IDENTITY in MS SQL) you just need to add entity to ObjectSet and SaveChanges on related ObjectContext. Id will be automatically filled for you:

using (var context = new MyContext())
{
  context.MyEntities.Add(myNewObject);
  context.SaveChanges();

  int id = myNewObject.Id; // Yes it's here
}

Entity framework by default follows each INSERT with SELECT SCOPE_IDENTITY() when auto-generated Ids are used.

Return HTML from ASP.NET Web API

ASP.NET Core. Approach 1

If your Controller extends ControllerBase or Controller you can use Content(...) method:

[HttpGet]
public ContentResult Index() 
{
    return base.Content("<div>Hello</div>", "text/html");
}

ASP.NET Core. Approach 2

If you choose not to extend from Controller classes, you can create new ContentResult:

[HttpGet]
public ContentResult Index() 
{
    return new ContentResult 
    {
        ContentType = "text/html",
        Content = "<div>Hello World</div>"
    };
}

Legacy ASP.NET MVC Web API

Return string content with media type text/html:

public HttpResponseMessage Get()
{
    var response = new HttpResponseMessage();
    response.Content = new StringContent("<div>Hello World</div>");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

Deprecated: mysql_connect()

You can remove the warning by adding a '@' before the mysql_connect.

@mysql_connect('localhost','root','');

but as the warning is telling you, use mysqli or PDO since the mysql extension will be removed in the future.

Difference between final and effectively final

If you could add the final modifier to a local variable, it was effectively final.

Lambda expressions can access

  • static variables,

  • instance variables,

  • effectively final method parameters, and

  • effectively final local variables.

Source: OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide, Jeanne Boyarsky, Scott Selikoff

Additionally,

An effectively final variable is a variable whose value is never changed, but it isn’t declared with the final keyword.

Source: Starting Out with Java: From Control Structures through Objects (6th Edition), Tony Gaddis

Furthermore, don't forget the meaning of final that it is initialized exactly once before it is used for the first time.

calling Jquery function from javascript

jQuery functions are called just like JavaScript functions.

For example, to dynamically add the class "red" to the document element with the id "orderedlist" using the jQuery addClass function:

$("#orderedlist").addClass("red");

As opposed to a regular line of JavaScript calling a regular function:

var x = document.getElementById("orderedlist");

addClass() is a jQuery function, getElementById() is a JavaScript function.

The dollar sign function makes the jQuery addClass function available.

The only difference is the jQuery example is calling the addclass function of the jQuery object $("#orderedlist") and the regular example is calling a function of the document object.

In your code

$(function() {
// code to execute when the DOM is ready
});

Is used to specify code to run when the DOM is ready.

It does not differentiate (as you may think) what is "jQuery code" from regular JavaScript code.

So, to answer your question, just call functions you defined as you normally would.

//create a function
function my_fun(){
  // call a jQuery function:
  $("#orderedlist").addClass("red");
}

//call the function you defined:
myfun();

Entity Framework - Linq query with order by and group by

You can try to cast the result of GroupBy and Take into an Enumerable first then process the rest (building on the solution provided by NinjaNye

var groupByReference = (from m in context.Measurements
                              .GroupBy(m => m.Reference)
                              .Take(numOfEntries).AsEnumerable()
                               .Select(g => new {Creation = g.FirstOrDefault().CreationTime, 
                                             Avg = g.Average(m => m.CreationTime.Ticks),
                                                Items = g })
                              .OrderBy(x => x.Creation)
                              .ThenBy(x => x.Avg)
                              .ToList() select m);

Your sql query would look similar (depending on your input) this

SELECT TOP (3) [t1].[Reference] AS [Key]
FROM (
    SELECT [t0].[Reference]
    FROM [Measurements] AS [t0]
    GROUP BY [t0].[Reference]
    ) AS [t1]
GO

-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref1'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]
GO

-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref2'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]

How to change app default theme to a different app theme?

Actually you should define your styles in res/values/styles.xml. I guess now you've got the following configuration:

<style name="AppBaseTheme" parent="android:Theme.Holo.Light"/>
<style name="AppTheme" parent="AppBaseTheme"/>

so if you want to use Theme.Black then change AppBaseTheme parent to android:Theme.Black or you could change app style directly in manifest file like this - android:theme="@android:style/Theme.Black". You must be lacking android namespace before style tag.

You can read more about styles and themes here.

LaTeX beamer: way to change the bullet indentation?

Setting \itemindent for a new itemize environment solves the problem:

\newenvironment{beameritemize}
{ \begin{itemize}
  \setlength{\itemsep}{1.5ex}
  \setlength{\parskip}{0pt}
  \setlength{\parsep}{0pt}   
  \addtolength{\itemindent}{-2em}  }
{ \end{itemize} } 

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

Reducing the gap between a bullet and text in a list item

Here You Go with Fiddle:

FIDDLE

HTML:

<ol>
        <li>List 1          
            <ol>
                <li>Sub-Chapter</li>
                <li>Sub-Chapter</li>
            </ol>
        </li>
        <li>List 2
            <ol>
                <li>Sub-Chapter</li>
                <li>Sub-Chapter</li>
            </ol>
        </li>
        <li>List 3</li>
</ol>

CSS:

ol {counter-reset:item;}
ol li {display:block;}
li:before {content:counters(item, ".");counter-increment:item;left:-7px;position:relative;font-weight:bold;}

assignment operator overloading in c++

it's right way to use operator overloading now you get your object by reference avoiding value copying.

When should we use Observer and Observable?

"I tried to figure out, why exactly we need Observer and Observable"

As previous answers already stated, they provide means of subscribing an observer to receive automatic notifications of an observable.

One example application where this may be useful is in data binding, let's say you have some UI that edits some data, and you want the UI to react when the data is updated, you can make your data observable, and subscribe your UI components to the data

Knockout.js is a MVVM javascript framework that has a great getting started tutorial, to see more observables in action I really recommend going through the tutorial. http://learn.knockoutjs.com/

I also found this article in Visual Studio 2008 start page (The Observer Pattern is the foundation of Model View Controller (MVC) development) http://visualstudiomagazine.com/articles/2013/08/14/the-observer-pattern-in-net.aspx

How to configure postgresql for the first time?

You probably need to update your pg_hba.conf file. This file controls what users can log in from what IP addresses. I think that the postgres user is pretty locked-down by default.

How to set time to a date object in java

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,17);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);

Date d = cal.getTime();

Also See

How to resolve ORA 00936 Missing Expression Error?

This happens every time you insert/ update and you don't use single quotes. When the variable is empty it will result in that error. Fix it by using ''

Assuming the first parameter is an empty variable here is a simple example:

Wrong

nvl( ,0)

Fix

nvl('' ,0)

Put your query into your database software and check it for that error. Generally this is an easy fix

Matplotlib different size subplots

You can use gridspec and figure:

import numpy as np
import matplotlib.pyplot as plt 
from matplotlib import gridspec

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
fig = plt.figure(figsize=(8, 6)) 
gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1]) 
ax0 = plt.subplot(gs[0])
ax0.plot(x, y)
ax1 = plt.subplot(gs[1])
ax1.plot(y, x)

plt.tight_layout()
plt.savefig('grid_figure.pdf')

resulting plot

jquery: get id from class selector

Use "attr" method in jquery.

$('.test').click(function(){
    var id = $(this).attr('id');
});

How to get the background color of an HTML element?

This worked for me:

var backgroundColor = window.getComputedStyle ? window.getComputedStyle(myDiv, null).getPropertyValue("background-color") : myDiv.style.backgroundColor;

And, even better:

var getStyle = function(element, property) {
    return window.getComputedStyle ? window.getComputedStyle(element, null).getPropertyValue(property) : element.style[property.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); })];
};
var backgroundColor = getStyle(myDiv, "background-color");

iPhone App Development on Ubuntu

Probably not. While I can't log into the Apple Development site, according to this post you need an intel mac platform.

http://tinleyharrier.blogspot.com/2008/03/iphone-sdk-requirements.html

How to connect to a secure website using SSL in Java with a pkcs12 file?

This is an example to use ONLY p12 file it's not optimazed but it work. The pkcs12 file where generated by OpenSSL by me. Example how to load p12 file and build Trust zone from it... It outputs certificates from p12 file and add good certs to TrustStore

KeyStore ks=KeyStore.getInstance("pkcs12");
ks.load(new FileInputStream("client_t_c1.p12"),"c1".toCharArray());

KeyStore jks=KeyStore.getInstance("JKS");
jks.load(null);

for (Enumeration<String>t=ks.aliases();t.hasMoreElements();)
{
    String alias = t.nextElement();
    System.out.println("@:" + alias);
    if (ks.isKeyEntry(alias)){
        Certificate[] a = ks.getCertificateChain(alias);
        for (int i=0;i<a.length;i++)
        {
            X509Certificate x509 = (X509Certificate)a[i];
            System.out.println(x509.getSubjectDN().toString());
            if (i>0)
                jks.setCertificateEntry(x509.getSubjectDN().toString(), x509);
            System.out.println(ks.getCertificateAlias(x509));
            System.out.println("ok");
        }
    }
}

System.out.println("init Stores...");

KeyManagerFactory kmf=KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, "c1".toCharArray());

TrustManagerFactory tmf=TrustManagerFactory.getInstance("SunX509");
tmf.init(jks);

SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

How to use LINQ to select object with minimum or maximum property value

Perfectly simple use of aggregate (equivalent to fold in other languages):

var firstBorn = People.Aggregate((min, x) => x.DateOfBirth < min.DateOfBirth ? x : min);

The only downside is that the property is accessed twice per sequence element, which might be expensive. That's hard to fix.

document.getelementbyId will return null if element is not defined?

Yes it will return null if it's not present you can try this below in the demo. Both will return true. The first elements exists the second doesn't.

Demo

Html

<div id="xx"></div>

Javascript:

   if (document.getElementById('xx') !=null) 
     console.log('it exists!');

   if (document.getElementById('xxThisisNotAnElementOnThePage') ==null) 
     console.log('does not exist!');

Get value of div content using jquery

your div looks like this:

<div class="readonly_label" id="field-function_purpose">Other</div>

With jquery you can easily get inner content:

Use .html() : HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.

var text = $('#field-function_purpose').html(); 

Read more about jquery .html()

or

Use .text() : Get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

var text = $('#field-function_purpose').text();

Read more about jquery .text()

SQL to generate a list of numbers from 1 to 100

Peter's answer is my favourite, too.

If you are looking for more details there is a quite good overview, IMO, here.
Especially interesting is to read the benchmarks.

Common sources of unterminated string literal

Whitespace is another issue I find, causes this error. Using a function to trim the whitespace may help.

Java Package Does Not Exist Error

Are they in the right subdirectories?

If you put /usr/share/stuff on the class path, files defined with package org.name should be in /usr/share/stuff/org/name.

EDIT: If you don't already know this, you should probably read this: http://download.oracle.com/javase/1.5.0/docs/tooldocs/windows/classpath.html#Understanding

EDIT 2: Sorry, I hadn't realised you were talking of Java source files in /usr/share/stuff. Not only they need to be in the appropriate sub-directory, but you need to compile them. The .java files don't need to be on the classpath, but on the source path. (The generated .class files need to be on the classpath.)

You might get away with compiling them if they're not under the right directory structure, but they should be, or it will generate warnings at least. The generated class files will be in the right subdirectories (wherever you've specified -d if you have).

You should use something like javac -sourcepath .:/usr/share/stuff test.java, assuming you've put the .java files that were under /usr/share/stuff under /usr/share/stuff/org/name (or whatever is appropriate according to their package names).

What does enumerate() mean?

I am reading a book (Effective Python) by Brett Slatkin and he shows another way to iterate over a list and also know the index of the current item in the list but he suggests that it is better not to use it and to use enumerate instead. I know you asked what enumerate means, but when I understood the following, I also understood how enumerate makes iterating over a list while knowing the index of the current item easier (and more readable).

list_of_letters = ['a', 'b', 'c']
for i in range(len(list_of_letters)):
    letter = list_of_letters[i]
    print (i, letter)

The output is:

0 a
1 b
2 c

I also used to do something, even sillier before I read about the enumerate function.

i = 0
for n in list_of_letters:
    print (i, n)
    i += 1

It produces the same output.

But with enumerate I just have to write:

list_of_letters = ['a', 'b', 'c']
for i, letter in enumerate(list_of_letters):
    print (i, letter)

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

Using only CSS, show div on hover over <a>

You can do something like this:

_x000D_
_x000D_
div {_x000D_
    display: none;_x000D_
}_x000D_
    _x000D_
a:hover + div {_x000D_
    display: block;_x000D_
}
_x000D_
<a>Hover over me!</a>_x000D_
<div>Stuff shown on hover</div>
_x000D_
_x000D_
_x000D_

This uses the adjacent sibling selector, and is the basis of the suckerfish dropdown menu.

HTML5 allows anchor elements to wrap almost anything, so in that case the div element can be made a child of the anchor. Otherwise the principle is the same - use the :hover pseudo-class to change the display property of another element.

Sending HTML email using Python

You might try using my mailer module.

from mailer import Mailer
from mailer import Message

message = Message(From="[email protected]",
                  To="[email protected]")
message.Subject = "An HTML Email"
message.Html = """<p>Hi!<br>
   How are you?<br>
   Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""

sender = Mailer('smtp.example.com')
sender.send(message)

Android Saving created bitmap to directory on sd card

Pass bitmap to the saveImage Method, It will save your bitmap in the name of a saveBitmap, inside created test folder.

private void saveImage(Bitmap data) {
                    File createFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"test");
                    if(!createFolder.exists())
                    createFolder.mkdir();
                    File saveImage = new File(createFolder,"saveBitmap.jpg");
                    try {
                        OutputStream outputStream = new FileOutputStream(saveImage);
                        data.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
                        outputStream.flush();
                        outputStream.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

and use this:

  saveImage(bitmap);

Output PowerShell variables to a text file

I usually construct custom objects in these loops, and then add these objects to an array that I can easily manipulate, sort, export to CSV, etc.:

# Construct an out-array to use for data export
$OutArray = @()

# The computer loop you already have
foreach ($server in $serverlist)
    {
        # Construct an object
        $myobj = "" | Select "computer", "Speed", "Regcheck"

        # Fill the object
        $myobj.computer = $computer
        $myobj.speed = $speed
        $myobj.regcheck = $regcheck

        # Add the object to the out-array
        $outarray += $myobj

        # Wipe the object just to be sure
        $myobj = $null
    }

# After the loop, export the array to CSV
$outarray | export-csv "somefile.csv"

The connection to adb is down, and a severe error has occurred

I had a similar problem with adb.exe and Eclipse last time I updated ADT plugin. The solution was to run Eclipse as administrator and reinstall ADT.

How to install Laravel's Artisan?

Explanation: When you install a new laravel project on your folder(for example myfolder) using the composer, it installs the complete laravel project inside your folder(myfolder/laravel) than artisan is inside laravel.that's, why you see an error,

Could not open input file: artisan

Solution: You have to go inside by command prompt to that location or move laravel files inside your folder.

AFNetworking Post Request

NSURL *URL = [NSURL URLWithString:@"url"];


AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"prefix":@"param",@"prefix":@"param",@"prefix":@"param"};
[manager POST:URL.absoluteString parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    self.arrayFromPost = [responseObject objectForKey:@"data"];
    // values in foreach loop


    NSLog(@"POst send: %@",_arrayFromPost);
} failure:^(NSURLSessionTask *operation, NSError *error) {


    NSLog(@"Error: %@", error);
}];

How to check for palindrome using Python logic

You are asking palindrome in python. palindrome can be performed on strings, numbers and lists. However, I just posted a simple code to check palindrome of a string.

# Palindrome of string
str=raw_input("Enter the string\n")
ln=len(str)
for i in range(ln/2) :
    if(str[ln-i-1]!=str[i]):
        break
if(i==(ln/2)-1):
    print "Palindrome"
else:
    print "Not Palindrome"

Hibernate Group by Criteria Object

GroupBy using in Hibernate

This is the resulting code

public Map getStateCounts(final Collection ids) {
    HibernateSession hibernateSession = new HibernateSession();
    Session session = hibernateSession.getSession();
    Criteria criteria = session.createCriteria(DownloadRequestEntity.class)
            .add(Restrictions.in("id", ids));
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.groupProperty("state"));
    projectionList.add(Projections.rowCount());
    criteria.setProjection(projectionList);
    List results = criteria.list();
    Map stateMap = new HashMap();
    for (Object[] obj : results) {
        DownloadState downloadState = (DownloadState) obj[0];
        stateMap.put(downloadState.getDescription().toLowerCase() (Integer) obj[1]);
    }
    hibernateSession.closeSession();
    return stateMap;
}

How to determine the number of days in a month in SQL Server?

here's another one...

Select Day(DateAdd(day, -Day(DateAdd(month, 1, getdate())), 
                         DateAdd(month, 1, getdate())))

Alter column, add default constraint

Actually you have to Do Like below Example, which will help to Solve the Issue...

drop table ABC_table

create table ABC_table
(
    names varchar(20),
    age int
)

ALTER TABLE ABC_table
ADD CONSTRAINT MyConstraintName
DEFAULT 'This is not NULL' FOR names

insert into ABC(age) values(10)

select * from ABC

Why am I getting the error "connection refused" in Python? (Sockets)

in your server.py file make : host ='192.168.1.94' instead of host = socket.gethostname()

How to switch to another domain and get-aduser

I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.

$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite

Get-ADUser -Server $dc.HostName[0] `
    -Filter { EmailAddress -Like "*Smith_Karla*" } `
    -Properties EmailAddress

How to determine CPU and memory consumption from inside a process?

I used this following code in my C++ project and it worked fine:

static HANDLE self;
static int numProcessors;
SYSTEM_INFO sysInfo;

double percent;

numProcessors = sysInfo.dwNumberOfProcessors;

//Getting system times information
FILETIME SysidleTime;
FILETIME SyskernelTime; 
FILETIME SysuserTime; 
ULARGE_INTEGER SyskernelTimeInt, SysuserTimeInt;
GetSystemTimes(&SysidleTime, &SyskernelTime, &SysuserTime);
memcpy(&SyskernelTimeInt, &SyskernelTime, sizeof(FILETIME));
memcpy(&SysuserTimeInt, &SysuserTime, sizeof(FILETIME));
__int64 denomenator = SysuserTimeInt.QuadPart + SyskernelTimeInt.QuadPart;  

//Getting process times information
FILETIME ProccreationTime, ProcexitTime, ProcKernelTime, ProcUserTime;
ULARGE_INTEGER ProccreationTimeInt, ProcexitTimeInt, ProcKernelTimeInt, ProcUserTimeInt;
GetProcessTimes(self, &ProccreationTime, &ProcexitTime, &ProcKernelTime, &ProcUserTime);
memcpy(&ProcKernelTimeInt, &ProcKernelTime, sizeof(FILETIME));
memcpy(&ProcUserTimeInt, &ProcUserTime, sizeof(FILETIME));
__int64 numerator = ProcUserTimeInt.QuadPart + ProcKernelTimeInt.QuadPart;
//QuadPart represents a 64-bit signed integer (ULARGE_INTEGER)

percent = 100*(numerator/denomenator);

case-insensitive matching in xpath?

This does not work in Chrome Developer tools to locate a element, i am looking to locate the 'Submit' button in the screen

//input[matches(@value,'submit','i')]

However, using 'translate' to replace all caps to small works as below

//input[translate(@value,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz') = 'submit']

Update: I just found the reason why 'matches' doesnt work. I am using Chrome with xpath 1.0 which wont understand the syntax 'matches'. It should be xpath 2.0

Checkbox Check Event Listener

Short answer: Use the change event. Here's a couple of practical examples. Since I misread the question, I'll include jQuery examples along with plain JavaScript. You're not gaining much, if anything, by using jQuery though.

Single checkbox

Using querySelector.

_x000D_
_x000D_
var checkbox = document.querySelector("input[name=checkbox]");

checkbox.addEventListener('change', function() {
  if (this.checked) {
    console.log("Checkbox is checked..");
  } else {
    console.log("Checkbox is not checked..");
  }
});
_x000D_
<input type="checkbox" name="checkbox" />
_x000D_
_x000D_
_x000D_

Single checkbox with jQuery

_x000D_
_x000D_
$('input[name=checkbox]').change(function() {
  if ($(this).is(':checked')) {
    console.log("Checkbox is checked..")
  } else {
    console.log("Checkbox is not checked..")
  }
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" name="checkbox" />
_x000D_
_x000D_
_x000D_

Multiple checkboxes

Here's an example of a list of checkboxes. To select multiple elements we use querySelectorAll instead of querySelector. Then use Array.filter and Array.map to extract checked values.

_x000D_
_x000D_
// Select all checkboxes with the name 'settings' using querySelectorAll.
var checkboxes = document.querySelectorAll("input[type=checkbox][name=settings]");
let enabledSettings = []

/*
For IE11 support, replace arrow functions with normal functions and
use a polyfill for Array.forEach:
https://vanillajstoolkit.com/polyfills/arrayforeach/
*/

// Use Array.forEach to add an event listener to each checkbox.
checkboxes.forEach(function(checkbox) {
  checkbox.addEventListener('change', function() {
    enabledSettings = 
      Array.from(checkboxes) // Convert checkboxes to an array to use filter and map.
      .filter(i => i.checked) // Use Array.filter to remove unchecked checkboxes.
      .map(i => i.value) // Use Array.map to extract only the checkbox values from the array of objects.
      
    console.log(enabledSettings)
  })
});
_x000D_
<label>
   <input type="checkbox" name="settings" value="forcefield">
   Enable forcefield
</label>
<label>
  <input type="checkbox" name="settings" value="invisibilitycloak">
  Enable invisibility cloak
</label>
<label>
  <input type="checkbox" name="settings" value="warpspeed">
  Enable warp speed
</label>
_x000D_
_x000D_
_x000D_

Multiple checkboxes with jQuery

_x000D_
_x000D_
let checkboxes = $("input[type=checkbox][name=settings]")
let enabledSettings = [];

// Attach a change event handler to the checkboxes.
checkboxes.change(function() {
  enabledSettings = checkboxes
    .filter(":checked") // Filter out unchecked boxes.
    .map(function() { // Extract values using jQuery map.
      return this.value;
    }) 
    .get() // Get array.
    
  console.log(enabledSettings);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
   <input type="checkbox" name="settings" value="forcefield">
   Enable forcefield
</label>
<label>
  <input type="checkbox" name="settings" value="invisibilitycloak">
  Enable invisibility cloak
</label>
<label>
  <input type="checkbox" name="settings" value="warpspeed">
  Enable warp speed
</label>
_x000D_
_x000D_
_x000D_

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

Could not load NIB in bundle

Swift4 example if your MyCustomView.swift and MyCustomView.xib in a framework. Place this in the MyCustomView's init:

let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "MyCustomView", bundle: bundle)
if let nibView = nib.instantiate(withOwner: self, options: nil).first as? UIView {
    self.aViewInMyCustomView = nibView
    self.aViewInMyCustomView.frame = self.frame
    self.addSubview(self.aViewInMyCustomView)
    // set constraints
    self.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint(item: self.aViewInMyCustomView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
    NSLayoutConstraint(item: self.aViewInMyCustomView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
    NSLayoutConstraint(item: self.aViewInMyCustomView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
    NSLayoutConstraint(item: self.aViewInMyCustomView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
} 

Your project path contains non-ASCII characters android studio

I created a symbol link like described by Clézio before. However, I had to specify a suitable encoding (e.g chcp 65001) in command line before.

chcp 65001
mklink /D "C:\android-sdk" "C:\Users\René\AppData\Local\Android\sdk"

If you have your SDK installed under Path C:\Users[USER]\AppData... you may have to run command line with administrativ priviledges.

Sending and Parsing JSON Objects in Android

if your are looking for fast json parsing in android than i suggest you a tool which is freely available.

JSON Class Creator tool

It's free to use and it's create your all json parsing class within a one-two seconds.. :D

How to get a list of images on docker registry v2

Here is a nice little one liner (uses JQ) to print out a list of Repos and associated tags.

If you dont have jq installed you can use: brew install jq

# This is my URL but you can use any
REPO_URL=10.230.47.94:443

curl -k -s -X GET https://$REPO_URL/v2/_catalog \
 | jq '.repositories[]' \
 | sort \
 | xargs -I _ curl -s -k -X GET https://$REPO_URL/v2/_/tags/list

How do I concatenate a boolean to a string in Python?

The recommended way is to let str.format handle the casting (docs). Methods with %s substitution may be deprecated eventually (see PEP3101).

>>> answer = True
>>> myvar = "the answer is {}".format(answer)
>>> print(myvar)
the answer is True

In Python 3.6+ you may use literal string interpolation:

 >>> print(f"the answer is {answer}")
the answer is True

Is there a way to use shell_exec without waiting for the command to complete?

You can also give your output back to the client instantly and continue processing your PHP code afterwards.

This is the method I am using for long-waiting Ajax calls which would not have any effect on client side:

ob_end_clean();
ignore_user_abort();
ob_start();
header("Connection: close");
echo json_encode($out);
header("Content-Length: " . ob_get_length());
ob_end_flush();
flush();
// execute your command here. client will not wait for response, it already has one above.

You can find the detailed explanation here: http://oytun.co/response-now-process-later

Convert Long into Integer

The best simple way of doing so is:

public static int safeLongToInt( long longNumber ) 
    {
        if ( longNumber < Integer.MIN_VALUE || longNumber > Integer.MAX_VALUE ) 
        {
            throw new IllegalArgumentException( longNumber + " cannot be cast to int without changing its value." );
        }
        return (int) longNumber;
    }

Cursor inside cursor

This smells of something that should be done with a JOIN instead. Can you share the larger problem with us?


Hey, I should be able to get this down to a single statement, but I haven't had time to play with it further yet today and may not get to. In the mean-time, know that you should be able to edit the query for your inner cursor to create the row numbers as part of the query using the ROW_NUMBER() function. From there, you can fold the inner cursor into the outer by doing an INNER JOIN on it (you can join on a sub query). Finally, any SELECT statement can be converted to an UPDATE using this method:

UPDATE [YourTable/Alias]
   SET [Column] = q.Value
FROM
(
   ... complicate select query here ...
) q

Where [YourTable/Alias] is a table or alias used in the select query.

Python: Random numbers into a list

Fix the indentation of the print statement

import random

my_randoms=[]
for i in range (10):
    my_randoms.append(random.randrange(1,101,1))

print (my_randoms)

Reading from a text file and storing in a String

How can we read data from a text file and store in a String Variable?

Err, read data from the file and store it in a String variable. It's just code. Not a real question so far.

Is it possible to pass the filename in a method and it would return the String which is the text from the file.

Yes it's possible. It's also a very bad idea. You should deal with the file a part at a time, for example a line at a time. Reading the entire file into memory before you process any of it adds latency; wastes memory; and assumes that the entire file will fit into memory. One day it won't. You don't want to do it this way.

how to check if the input is a number or not in C?

Using fairly simple code:

int i;
int value;
int n;
char ch;

/* Skip i==0 because that will be the program name */
for (i=1; i<argc; i++) {
    n = sscanf(argv[i], "%d%c", &value, &ch);

    if (n != 1) {
        /* sscanf didn't find a number to convert, so it wasn't a number */
    }
    else {
        /* It was */
    }
}

How does the Python's range function work?

When I'm teaching someone programming (just about any language) I introduce for loops with terminology similar to this code example:

for eachItem in someList:
    doSomething(eachItem)

... which, conveniently enough, is syntactically valid Python code.

The Python range() function simply returns or generates a list of integers from some lower bound (zero, by default) up to (but not including) some upper bound, possibly in increments (steps) of some other number (one, by default).

So range(5) returns (or possibly generates) a sequence: 0, 1, 2, 3, 4 (up to but not including the upper bound).

A call to range(2,10) would return: 2, 3, 4, 5, 6, 7, 8, 9

A call to range(2,12,3) would return: 2, 5, 8, 11

Notice that I said, a couple times, that Python's range() function returns or generates a sequence. This is a relatively advanced distinction which usually won't be an issue for a novice. In older versions of Python range() built a list (allocated memory for it and populated with with values) and returned a reference to that list. This could be inefficient for large ranges which might consume quite a bit of memory and for some situations where you might want to iterate over some potentially large range of numbers but were likely to "break" out of the loop early (after finding some particular item in which you were interested, for example).

Python supports more efficient ways of implementing the same semantics (of doing the same thing) through a programming construct called a generator. Instead of allocating and populating the entire list and return it as a static data structure, Python can instantiate an object with the requisite information (upper and lower bounds and step/increment value) ... and return a reference to that.

The (code) object then keeps track of which number it returned most recently and computes the new values until it hits the upper bound (and which point it signals the end of the sequence to the caller using an exception called "StopIteration"). This technique (computing values dynamically rather than all at once, up-front) is referred to as "lazy evaluation."

Other constructs in the language (such as those underlying the for loop) can then work with that object (iterate through it) as though it were a list.

For most cases you don't have to know whether your version of Python is using the old implementation of range() or the newer one based on generators. You can just use it and be happy.

If you're working with ranges of millions of items, or creating thousands of different ranges of thousands each, then you might notice a performance penalty for using range() on an old version of Python. In such cases you could re-think your design and use while loops, or create objects which implement the "lazy evaluation" semantics of a generator, or use the xrange() version of range() if your version of Python includes it, or the range() function from a version of Python that uses the generators implicitly.

Concepts such as generators, and more general forms of lazy evaluation, permeate Python programming as you go beyond the basics. They are usually things you don't have to know for simple programming tasks but which become significant as you try to work with larger data sets or within tighter constraints (time/performance or memory bounds, for example).

[Update: for Python3 (the currently maintained versions of Python) the range() function always returns the dynamic, "lazy evaluation" iterator; the older versions of Python (2.x) which returned a statically allocated list of integers are now officially obsolete (after years of having been deprecated)].

Parse String date in (yyyy-MM-dd) format

You may need to format the out put as follows.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date convertedCurrentDate = sdf.parse("2013-09-18");
String date=sdf.format(convertedCurrentDate );
System.out.println(date);

Use

String convertedCurrentDate =sdf.format(sdf.parse("2013-09-18"));

Output:

2013-09-18

change image opacity using javascript

Supposing you're using plain JS (see other answers for jQuery), to change an element's opacity, write:

var element = document.getElementById('id');
element.style.opacity = "0.9";
element.style.filter  = 'alpha(opacity=90)'; // IE fallback

Constructor of an abstract class in C#

It's there to enforce some initialization logic required by all implementations of your abstract class, or any methods you have implemented on your abstract class (not all the methods on your abstract class have to be abstract, some can be implemented).

Any class which inherits from your abstract base class will be obliged to call the base constructor.

Statically rotate font-awesome icons

Before FontAwesome 5:

The standard declarations just contain .fa-rotate-90, .fa-rotate-180 and .fa-rotate-270. However you can easily create your own:

.fa-rotate-45 {
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    transform: rotate(45deg);
}

With FontAwesome 5:

You can use what’s so called “Power Transforms”. Example:

<i class="fas fa-snowman" data-fa-transform="rotate-90"></i>
<i class="fas fa-snowman" data-fa-transform="rotate-180"></i>
<i class="fas fa-snowman" data-fa-transform="rotate-270"></i>
<i class="fas fa-snowman" data-fa-transform="rotate-30"></i>
<i class="fas fa-snowman" data-fa-transform="rotate--30"></i>

You need to add the data-fa-transform attribute with the value of rotate- and your desired rotation in degrees.

Source: https://fontawesome.com/how-to-use/on-the-web/styling/power-transforms

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

Declare globally delayed listener:

var resize_timeout;

$(window).on('resize orientationchange', function(){
    clearTimeout(resize_timeout);

    resize_timeout = setTimeout(function(){
        $(window).trigger('resized');
    }, 250);
});

And below use listeners to resized event as you want:

$(window).on('resized', function(){
    console.log('resized');
});

AngularJS: How to run additional code after AngularJS has rendered a template?

i've had to do this quite often. i have a directive and need to do some jquery stuff after model stuff is fully loaded into the DOM. so i put my logic in the link: function of the directive and wrap the code in a setTimeout(function() { ..... }, 1); the setTimout will fire after the DOM is loaded and 1 milisecond is the shortest amount of time after DOM is loaded before code would execute. this seems to work for me but i do wish angular raised an event once a template was done loading so that directives used by that template could do jquery stuff and access DOM elements. hope this helps.

c++ string array initialization

In C++11 you can. A note beforehand: Don't new the array, there's no need for that.

First, string[] strArray is a syntax error, that should either be string* strArray or string strArray[]. And I assume that it's just for the sake of the example that you don't pass any size parameter.

#include <string>

void foo(std::string* strArray, unsigned size){
  // do stuff...
}

template<class T>
using alias = T;

int main(){
  foo(alias<std::string[]>{"hi", "there"}, 2);
}

Note that it would be better if you didn't need to pass the array size as an extra parameter, and thankfully there is a way: Templates!

template<unsigned N>
void foo(int const (&arr)[N]){
  // ...
}

Note that this will only match stack arrays, like int x[5] = .... Or temporary ones, created by the use of alias above.

int main(){
  foo(alias<int[]>{1, 2, 3});
}

Table overflowing outside of div

At first I used James Lawruk's method. This however changed all the widths of the td's.

The solution for me was to use white-space: normal on the columns (which was set to white-space: nowrap). This way the text will always break. Using word-wrap: break-word will ensure that everything will break when needed, even halfway through a word.

The CSS will look like this then:

td, th {
    white-space: normal; /* Only needed when it's set differntly somewhere else */
    word-wrap: break-word;
}

This might not always be the desirable solution, as word-wrap: break-word might make your words in the table illegible. It will however keep your table the right width.

How do I uniquely identify computers visiting my web site?

The suggestions to use cookies aside, the only comprehensive set of identifying attributes available to interrogate are contained in the HTTP request header. So it is possible to use some subset of these to create a pseudo-unique identifier for a user agent (i.e., browser). Further, most of this information is possibly already being logged in the so-called "access log" of your web server software by default and, if not, can be easily configured to do so. Then, a utlity could be developed that simply scans the content of this log, creating fingerprints of each request comprised of, say, the IP address and User Agent string, etc. The more data available, even including the contents of specific cookies, adds to the quality of the uniqueness of this fingerprint. Though, as many others have stated already, the HTTP protocol doesn't make this 100% foolproof - at best it can only be a fairly good indicator.

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

The algorithm you are using, "AES", is a shorthand for "AES/ECB/NoPadding". What this means is that you are using the AES algorithm with 128-bit key size and block size, with the ECB mode of operation and no padding.

In other words: you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException exception.

If you want to encrypt data in sizes that are not multiple of 16 bytes, you are either going to have to use some kind of padding, or a cipher-stream. For instance, you could use CBC mode (a mode of operation that effectively transforms a block cipher into a stream cipher) by specifying "AES/CBC/NoPadding" as the algorithm, or PKCS5 padding by specifying "AES/ECB/PKCS5", which will automatically add some bytes at the end of your data in a very specific format to make the size of the ciphertext multiple of 16 bytes, and in a way that the decryption algorithm will understand that it has to ignore some data.

In any case, I strongly suggest that you stop right now what you are doing and go study some very introductory material on cryptography. For instance, check Crypto I on Coursera. You should understand very well the implications of choosing one mode or another, what are their strengths and, most importantly, their weaknesses. Without this knowledge, it is very easy to build systems which are very easy to break.


Update: based on your comments on the question, don't ever encrypt passwords when storing them at a database!!!!! You should never, ever do this. You must HASH the passwords, properly salted, which is completely different from encrypting. Really, please, don't do what you are trying to do... By encrypting the passwords, they can be decrypted. What this means is that you, as the database manager and who knows the secret key, you will be able to read every password stored in your database. Either you knew this and are doing something very, very bad, or you didn't know this, and should get shocked and stop it.

Fast way to get the min/max values among properties of object

You could try:

const obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
const max = Math.max.apply(null, Object.values(obj));
console.log(max) // 5

What is causing the error `string.split is not a function`?

maybe

string = document.location.href;
arrayOfStrings = string.toString().split('/');

assuming you want the current url

Find the most frequent number in a NumPy array

I'm recently doing a project and using collections.Counter.(Which tortured me).

The Counter in collections have a very very bad performance in my opinion. It's just a class wrapping dict().

What's worse, If you use cProfile to profile its method, you should see a lot of '__missing__' and '__instancecheck__' stuff wasting the whole time.

Be careful using its most_common(), because everytime it would invoke a sort which makes it extremely slow. and if you use most_common(x), it will invoke a heap sort, which is also slow.

Btw, numpy's bincount also have a problem: if you use np.bincount([1,2,4000000]), you will get an array with 4000000 elements.

Check if file is already open

Using the Apache Commons IO library...

boolean isFileUnlocked = false;
try {
    org.apache.commons.io.FileUtils.touch(yourFile);
    isFileUnlocked = true;
} catch (IOException e) {
    isFileUnlocked = false;
}

if(isFileUnlocked){
    // Do stuff you need to do with a file that is NOT locked.
} else {
    // Do stuff you need to do with a file that IS locked
}

Find row number of matching value

For your first method change ws.Range("A") to ws.Range("A:A") which will search the entirety of column a, like so:

Sub Find_Bingo()

        Dim wb As Workbook
        Dim ws As Worksheet
        Dim FoundCell As Range
        Set wb = ActiveWorkbook
        Set ws = ActiveSheet

            Const WHAT_TO_FIND As String = "Bingo"

            Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
            If Not FoundCell Is Nothing Then
                MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
            Else
                MsgBox (WHAT_TO_FIND & " not found")
            End If
End Sub

For your second method, you are using Bingo as a variable instead of a string literal. This is a good example of why I add Option Explicit to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.

Additionally, when you are using With...End With you need a period . before you reference Cells, so Cells should be .Cells. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)

Change Bingo to "Bingo" and change Cells to .Cells

With Sheet1
        Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
        LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    End With

If Not FoundCell Is Nothing Then
        MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
        MsgBox ("Bingo not found")
End If

Update

In my

With Sheet1
    .....
End With

The Sheet1 refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1. I can refer to that in code either with the code name of Sheet1 or I can refer to it with the index of Sheets("Sheet1"). The advantage to using a codename is that it does not change if you change the name of the worksheet.

Continuing this example, let's say I renamed Sheet1 to Data. Using Sheet1 would continue to work, as the code name doesn't change, but now using Sheets("Sheet1") would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data").

In the VB Editor you would see something like this:

code object explorer example

Notice how, even though I changed the name to Data, there is still a Sheet1 to the left. That is what I mean by codename.

The Data worksheet can be referenced in two ways:

Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name

Both should return Data

More discussion on worksheet code names can be found here.

How to update (append to) an href in jquery?

var _href = $("a.directions-link").attr("href");
$("a.directions-link").attr("href", _href + '&saddr=50.1234567,-50.03452');

To loop with each()

$("a.directions-link").each(function() {
   var $this = $(this);       
   var _href = $this.attr("href"); 
   $this.attr("href", _href + '&saddr=50.1234567,-50.03452');
});

What should I do if the current ASP.NET session is null?

Yes, the Session object might be null, but only in certain circumstances, which you will only rarely run into:

If you only have code in pages, you won't run into this. Most of my ASP .NET code uses Session without checking for null repeatedly. It is, however, something to think about if you are developing an IHttpModule or otherwise is down in the grittier details of ASP .NET.

Edit

In answer to the comment: Whether or not session state is available depends on whether the AcquireRequestState event has run for the request. This is where the session state module does it's work by reading the session cookie and finding the appropiate set of session variables for you.

AcquireRequestState runs before control is handed to your Page. So if you are calling other functionality, including static classes, from your page, you should be fine.

If you have some classes doing initialization logic during startup, for example on the Application_Start event or by using a static constructor, Session state might not be available. It all boils down to whether there is a current request and AcquireRequestState has been run.

Also, should the client have disabled cookies, the Session object will still be available - but on the next request, the user will return with a new empty Session. This is because the client is given a Session statebag if he does not have one already. If the client does not transport the session cookie, we have no way of identifying the client as the same, so he will be handed a new session again and again.

Set a path variable with spaces in the path in a Windows .cmd file or batch file

also just try adding double slashes like this works for me only

set dir="C:\\1. Some Folder\\Some Other Folder\\Just Because"

@echo on MKDIR %dir%

OMG after posting they removed the second \ in my post so if you open my comment and it shows three you should read them as two......

Local variable referenced before assignment?

You have to specify that test1 is global:

test1 = 0
def testFunc():
    global test1
    test1 += 1
testFunc()

Recommended way to embed PDF in HTML?

<object width="400" height="400" data="helloworld.pdf"></object>

Using isKindOfClass with Swift

Another approach using the new Swift 2 syntax is to use guard and nest it all in one conditional.

guard let touch = object.AnyObject() as? UITouch, let picker = touch.view as? UIPickerView else {
    return //Do Nothing
}
//Do something with picker

YAML: Do I need quotes for strings in YAML?

After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:

  • In general, you don't need quotes.
  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).
  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
  • Double quotes parse escape codes. "\n" would be returned as a line feed character.
  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.

Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.

Update

"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:

en:
  yesno:
    'yes': 'Yes'
    'no': 'No'

How do I programmatically set device orientation in iOS 7?

This worked me perfectly....

NSNumber *value = [NSNumber numberWithInt:UIDeviceOrientationPortrait];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];

How do I pass data to Angular routed components?

Solution with ActiveRoute (if you want pass object by route - use JSON.stringfy/JSON.parse):

Prepare object before sending:

export class AdminUserListComponent {

  users : User[];

  constructor( private router : Router) { }

  modifyUser(i) {

    let navigationExtras: NavigationExtras = {
      queryParams: {
          "user": JSON.stringify(this.users[i])
      }
    };

    this.router.navigate(["admin/user/edit"],  navigationExtras);
  }

}

Receive your object in destination component:

export class AdminUserEditComponent  {

  userWithRole: UserWithRole;      

  constructor( private route: ActivatedRoute) {}

  ngOnInit(): void {
    super.ngOnInit();

      this.route.queryParams.subscribe(params => {
        this.userWithRole.user = JSON.parse(params["user"]);
      });
  }

}

PHP's array_map including keys

YaLinqo library* is well suited for this sort of task. It's a port of LINQ from .NET which fully supports values and keys in all callbacks and resembles SQL. For example:

$mapped_array = from($test_array)
    ->select(function ($v, $k) { return "$k loves $v"; })
    ->toArray();

or just:

$mapped_iterator = from($test_array)->select('"$k loves $v"');

Here, '"$k loves $v"' is a shortcut for full closure syntax which this library supports. toArray() in the end is optional. The method chain returns an iterator, so if the result just needs to be iterated over using foreach, toArray call can be removed.

* developed by me

Use a.any() or a.all()

This should also work and is a closer answer to what is asked in the question:

for i in range(len(x)):
    if valeur.item(i) <= 0.6:
        print ("this works")
    else:   
        print ("valeur is too high")

How can I remove an entry in global configuration with git config?

Open config file to edit :

git config --global --edit

Press Insert and remove the setting

and finally type :wq and Enter to save.

How do I check if a string contains another string in Objective-C?

If certain position of the string is needed, this code comes to place in Swift 3.0:

let string = "This is my string"
let substring = "my"

let position = string.range(of: substring)?.lowerBound

MongoError: connect ECONNREFUSED 127.0.0.1:27017

You probably need to continue running your DB process (by running mongod) while running your node server.

How to nicely format floating numbers to string without unnecessary decimal 0's

Naw, never mind. The performance loss due to string manipulation is zero.

And here's the code to trim the end after %f:

private static String trimTrailingZeros(String number) {
    if(!number.contains(".")) {
        return number;
    }

    return number.replaceAll("\\.?0*$", "");
}

Adding double quote delimiters into csv file

Double quotes can be achieved using VBA in one of two ways

First one is often the best

"...text..." & Chr(34) & "...text..."

Or the second one, which is more literal

"...text..." & """" & "...text..."

Equivalent of shell 'cd' command to change the working directory?

If you use spyder and love GUI, you can simply click on the folder button on the upper right corner of your screen and navigate through folders/directories you want as current directory. After doing so you can go to the file explorer tab of the window in spyder IDE and you can see all the files/folders present there. to check your current working directory go to the console of spyder IDE and simply type

pwd

it will print the same path as you have selected before.

Converting a column within pandas dataframe from int to string

In [16]: df = DataFrame(np.arange(10).reshape(5,2),columns=list('AB'))

In [17]: df
Out[17]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

In [18]: df.dtypes
Out[18]: 
A    int64
B    int64
dtype: object

Convert a series

In [19]: df['A'].apply(str)
Out[19]: 
0    0
1    2
2    4
3    6
4    8
Name: A, dtype: object

In [20]: df['A'].apply(str)[0]
Out[20]: '0'

Don't forget to assign the result back:

df['A'] = df['A'].apply(str)

Convert the whole frame

In [21]: df.applymap(str)
Out[21]: 
   A  B
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

In [22]: df.applymap(str).iloc[0,0]
Out[22]: '0'

df = df.applymap(str)

How to write to error log file in PHP

If you don't want to change anything in your php.ini file, according to PHP documentation, you can do this.

error_log("Error message\n", 3, "/mypath/php.log");

The first parameter is the string to be sent to the log. The second parameter 3 means expect a file destination. The third parameter is the log file path.

Rotate an image in image source in html

This CSS seems to work in Safari and Chrome:

div#div2
{
-webkit-transform:rotate(90deg); /* Chrome, Safari, Opera */
transform:rotate(90deg); /* Standard syntax */
}

and in the body:

<div id="div2"><img src="image.jpg"  ></div>

But this (and the .rotate90 example above) pushes the rotated image higher up on the page than if it were un-rotated. Not sure how to control placement of the image relative to text or other rotated images.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

I can also confirm this error.

Workaround: is to use external maven inside m2eclipse, instead of it's embedded maven.

That is done in three steps:

1 Install maven on local machine (the test-machine was Ubuntu 10.10)

mvn --version

Apache Maven 2.2.1 (rdebian-4) Java version: 1.6.0_20 Java home: /usr/lib/jvm/java-6-openjdk/jre Default locale: de_DE, platform encoding: UTF-8 OS name: "linux" version: "2.6.35-32-generic" arch: "amd64" Family: "unix"

2 Run maven externally link how to run maven from console

> cd path-to-pom.xml
> mvn test
    [INFO] Scanning for projects...
    [INFO] ------------------------------------------------------------------------
    [INFO] Building Simple
    [INFO]    task-segment: [test]
    [INFO] ------------------------------------------------------------------------
    [...]
    [INFO] Surefire report directory: [...]/workspace/Simple/target/surefire-reports
    
    -------------------------------------------------------
     T E S T S
    -------------------------------------------------------
    Running net.tverrbjelke.experiment.MainAppTest
    Hello World
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.042 sec
    
    Results :
    
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
    
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESSFUL
    [INFO] ------------------------------------------------------------------------
    [...]

3 inside m2eclipse: switch from embedded maven to local maven

  • find out where local maven home installation dir is (mvn --version, or google for your MAVEN_HOME, for me this helped me that is /usr/share/maven2 )
  • in eclipse Menu->Window->Preferences->Maven->Installation-> enter that string. Then you should have switched to your new external maven.
  • then run your Project as e.g. "maven test".

The error-message should be gone.

Best way to get user GPS location in background in Android

You have to create service.That service should implement LocationListener. Then You have to use AlarmManager for calling service repeatedly with certain time limit.

I hope this one will help to you :)

How to use ESLint with Jest

You can also set the test env in your test file as follows:

/* eslint-env jest */

describe(() => {
  /* ... */
})

Get URL query string parameters

Also if you are looking for current file name along with the query string, you will just need following

basename($_SERVER['REQUEST_URI'])

It would provide you info like following example

file.php?arg1=val&arg2=val

And if you also want full path of file as well starting from root, e.g. /folder/folder2/file.php?arg1=val&arg2=val then just remove basename() function and just use fillowing

$_SERVER['REQUEST_URI']

Hamcrest compare collections

For list of objects you may need something like this:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
import static org.hamcrest.Matchers.is;

@Test
@SuppressWarnings("unchecked")
public void test_returnsList(){

    arrange();
  
    List<MyBean> myList = act();
    
    assertThat(myList , contains(allOf(hasProperty("id",          is(7L)), 
                                       hasProperty("name",        is("testName1")),
                                       hasProperty("description", is("testDesc1"))),
                                 allOf(hasProperty("id",          is(11L)), 
                                       hasProperty("name",        is("testName2")),
                                       hasProperty("description", is("testDesc2")))));
}

Use containsInAnyOrder if you do not want to check the order of the objects.

P.S. Any help to avoid the warning that is suppresed will be really appreciated.

How to filter array when object key value is in array

You can use Array#filter function and additional array for storing sorted values;

var recordsSorted = []

ids.forEach(function(e) {
    recordsSorted.push(records.filter(function(o) {
        return o.empid === e;
    }));
});

console.log(recordsSorted);

Result:

[ [ { empid: 1, fname: 'X', lname: 'Y' } ],
  [ { empid: 4, fname: 'C', lname: 'Y' } ],
  [ { empid: 5, fname: 'C', lname: 'Y' } ] ]

How to add a 'or' condition in #ifdef

#if defined(CONDITION1) || defined(CONDITION2)

should work. :)

#ifdef is a bit less typing, but doesn't work well with more complex conditions

Using "If cell contains #N/A" as a formula condition.

You can also use IFNA(expression, value)

Get an element by index in jQuery

You could skip the jquery and just use CSS style tagging:

 <ul>
 <li>India</li>
 <li>Indonesia</li>
 <li style="background-color:#343434;">China</li>
 <li>United States</li>
 <li>United Kingdom</li>
 </ul>

"Sub or Function not defined" when trying to run a VBA script in Outlook

This probably does not answer your question, but I had the same question and it answered mine.

I changed Private Function to Public Function and it worked.

How do I return the SQL data types from my query?

For SQL Server 2012 and above: If you place the query into a string then you can get the result set data types like so:

DECLARE @query nvarchar(max) = 'select 12.1 / 10.1 AS [Column1]';
EXEC sp_describe_first_result_set @query, null, 0;  

Is there a limit on number of tcp/ip connections between machines on linux?

There is a limit, yes. See ulimit.

Also you need to consider the TIMED_WAIT state. Once a TCP socket is closed (by default) the port remains occupied in TIMED_WAIT status for 2 minutes. This value is tunable. This will also "run you out of sockets" even though they are closed.

Run netstat to see the TIMED_WAIT stuff in action.

P.S. The reason for TIMED_WAIT is to handle the case of packets arriving after the socket is closed. This can happen because packets are delayed or the other side just doesn't know that the socket has been closed yet. This allows the OS to silently drop those packets without a chance of "infecting" a different, unrelated socket connection.

React.js: onChange event for contentEditable

This is the is simplest solution that worked for me.

<div
  contentEditable='true'
  onInput={e => console.log('Text inside div', e.currentTarget.textContent)}
>
Text inside div
</div>

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

You could compile and link in one command:

gcc file1.c file2.c -o myprogram

And run with:

./myprogram

But to answer the question as asked, simply pass the object files to gcc:

gcc file1.o file2.o -o myprogram

Get line number while using grep

grep -nr "search string" directory

This gives you the line with the line number.

How do I get the serial key for Visual Studio Express?

I have an improvement on the answer @DewiMorgan gave for VS 2008 express. I have since confirmed it also works on VS 2005 express.
It lets you run the software without it EVER requiring registration, and also makes it so you don't have to manually delete the key every 30 days. It does this by preventing the key from ever being written.

(Deleting the correct key can also let you avoid registering VS 2015 "Community Edition," but using permissions to prevent the key being written will make the IDE crash, so I haven't found a great solution for it yet.)

The directions assume Visual C# Express 2008, but this works on all the other visual studio express apps I can find.

  1. Open regedit, head to HKEY_CURRENT_USER\Software\Microsoft\VCSExpress\9.0\Registration.
  2. Delete the value Params. picture of me deleting the value 'Params' in the registry.
  3. Right click on the key 'Registration' in the tree, and click permissions.
  4. Click Advanced...
  5. Go to the permissions tab, and uncheck the box labeled Inherit from parent the permission entries that apply to child objects. Include these with entries explicitly defined here. me unchecking the box
  6. In the dialog that opens, click copy.
    the security dialog that pops up
    Note that in Windows 7 (and 8/8.1, I think), it appears the copy button was renamed to add, as in add inherited permissions as explicit permissions.

    In Windows 10, it appears things changed again. @ravuya says that you might have to manually re-create some of the permissions, as the registry editor no longer offers this exact functionality directly. I don't use Windows very much anymore, so I'll defer to them:

    On Win10, there is a button called "Disable Inheritance" that does the same thing as the checkbox mentioned in step 5. It is necessary to create new permissions just for Registration, instead of inheriting those permissions from an upstream registry key.

  7. Hit OK in the 'Advanced' window.
  8. Back in the first permissions window, click your user, and uncheck Full Control. Me unchecking 'full control'

  9. Do the same thing for the Administrators group. Me unchecking 'full control' for the Administrators group

  10. Hit OK or Apply. Congratulations, you will never again be plagued by the registration nag, and just like WinRAR, your trial will never expire.

You may have to do the same thing for other (non-Visual C#) programs, like Visual Basic express or Visual C++ express.

It has been reported by @IronManMark20 in the comments that simply deleting the registry key works and that Visual Studio does not attempt to re-create the key. I am not sure if I believe this because when I installed VS on a clean windows installation, the key was not created until I ran VS at least once. But for what it's worth, that may be an option as well.

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

SELECT st1.*
FROM some_table st1
inner join 
(
    SELECT relevant_field
    FROM some_table
    GROUP BY relevant_field
    HAVING COUNT(*) > 1
)st2 on st2.relevant_field = st1.relevant_field;

I've tried your query on one of my databases, and also tried it rewritten as a join to a sub-query.

This worked a lot faster, try it!

Java: How can I compile an entire directory structure of code ?

There is a way to do this without using a pipe character, which is convenient if you are forking a process from another programming language to do this:

find $JAVA_SRC_DIR -name '*.java' -exec javac -d $OUTPUT_DIR {} +

Though if you are in Bash and/or don't mind using a pipe, then you can do:

find $JAVA_SRC_DIR -name '*.java' | xargs javac -d $OUTPUT_DIR

How to set array length in c# dynamically

InputProperty[] ip = new InputProperty[nvPairs.Length]; 

Or, you can use a list like so:

List<InputProperty> list = new List<InputProperty>();
InputProperty ip = new (..);
list.Add(ip);
update.items = list.ToArray();

Another thing I'd like to point out, in C# you can delcare your int variable use in a for loop right inside the loop:

for(int i = 0; i<nvPairs.Length;i++
{
.
.
}

And just because I'm in the mood, here's a cleaner way to do this method IMO:

private Update BuildMetaData(MetaData[] nvPairs)
{
        Update update = new Update();
        var ip = new List<InputProperty>();

        foreach(var nvPair in nvPairs)
        {
            if (nvPair == null) break;
            var inputProp = new InputProperty
            {
               Name = "udf:" + nvPair.Name,
               Val = nvPair.Value
            };
            ip.Add(inputProp);
        }
        update.Items = ip.ToArray();
        return update;
}

pip install - locale.Error: unsupported locale setting

For Dockerfile, this works for me:

RUN locale-gen en_US.UTF-8  
ENV LANG en_US.UTF-8  
ENV LANGUAGE en_US:en  
ENV LC_ALL en_US.UTF-8  

How to install locale-gen?

docker ubuntu /bin/sh: 1: locale-gen: not found

Angularjs: Get element in controller

$element is one of four locals that $compileProvider gives to $controllerProvider which then gets given to $injector. The injector injects locals in your controller function only if asked.

The four locals are:

  • $scope
  • $element
  • $attrs
  • $transclude

The official documentation: AngularJS $compile Service API Reference - controller

The source code from Github angular.js/compile.js:

 function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
    var elementControllers = createMap();
    for (var controllerKey in controllerDirectives) {
      var directive = controllerDirectives[controllerKey];
      var locals = {
        $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
        $element: $element,
        $attrs: attrs,
        $transclude: transcludeFn
      };

      var controller = directive.controller;
      if (controller == '@') {
        controller = attrs[directive.name];
      }

      var controllerInstance = $controller(controller, locals, true, directive.controllerAs);

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

Summary

As mentioned by Ignacio, it updates your .config for you after you update the kernel source, e.g. with git pull.

It tries to keep your existing options.

Having a script for that is helpful because:

  • new options may have been added, or old ones removed

  • the kernel's Kconfig configuration format has options that:

    • imply one another via select
    • depend on another via depends

    Those option relationships make manual config resolution even harder.

Let's modify .config manually to understand how it resolves configurations

First generate a default configuration with:

make defconfig

Now edit the generated .config file manually to emulate a kernel update and run:

make oldconfig

to see what happens. Some conclusions:

  1. Lines of type:

    # CONFIG_XXX is not set
    

    are not mere comments, but actually indicate that the parameter is not set.

    For example, if we remove the line:

    # CONFIG_DEBUG_INFO is not set
    

    and run make oldconfig, it will ask us:

    Compile the kernel with debug info (DEBUG_INFO) [N/y/?] (NEW)
    

    When it is over, the .config file will be updated.

    If you change any character of the line, e.g. to # CONFIG_DEBUG_INFO, it does not count.

  2. Lines of type:

    # CONFIG_XXX is not set
    

    are always used for the negation of a property, although:

    CONFIG_XXX=n
    

    is also understood as the negation.

    For example, if you remove # CONFIG_DEBUG_INFO is not set and answer:

    Compile the kernel with debug info (DEBUG_INFO) [N/y/?] (NEW)
    

    with N, then the output file contains:

    # CONFIG_DEBUG_INFO is not set
    

    and not:

    CONFIG_DEBUG_INFO=n
    

    Also, if we manually modify the line to:

    CONFIG_DEBUG_INFO=n
    

    and run make oldconfig, then the line gets modified to:

    # CONFIG_DEBUG_INFO is not set
    

    without oldconfig asking us.

  3. Configs whose dependencies are not met, do not appear on the .config. All others do.

    For example, set:

    CONFIG_DEBUG_INFO=y
    

    and run make oldconfig. It will now ask us for: DEBUG_INFO_REDUCED, DEBUG_INFO_SPLIT, etc. configs.

    Those properties did not appear on the defconfig before.

    If we look under lib/Kconfig.debug where they are defined, we see that they depend on DEBUG_INFO:

    config DEBUG_INFO_REDUCED
        bool "Reduce debugging information"
        depends on DEBUG_INFO
    

    So when DEBUG_INFO was off, they did not show up at all.

  4. Configs which are selected by turned on configs are automatically set without asking the user.

    For example, if CONFIG_X86=y and we remove the line:

    CONFIG_ARCH_MIGHT_HAVE_PC_PARPORT=y
    

    and run make oldconfig, the line gets recreated without asking us, unlike DEBUG_INFO.

    This happens because arch/x86/Kconfig contains:

    config X86
        def_bool y
        [...]
        select ARCH_MIGHT_HAVE_PC_PARPORT
    

    and select forces that option to be true. See also: https://unix.stackexchange.com/questions/117521/select-vs-depends-in-kernel-kconfig

  5. Configs whose constraints are not met are asked for.

    For example, defconfig had set:

    CONFIG_64BIT=y
    CONFIG_RCU_FANOUT=64
    

    If we edit:

    CONFIG_64BIT=n
    

    and run make oldconfig, it will ask us:

    Tree-based hierarchical RCU fanout value (RCU_FANOUT) [32] (NEW)
    

    This is because RCU_FANOUT is defined at init/Kconfig as:

    config RCU_FANOUT
        int "Tree-based hierarchical RCU fanout value"
        range 2 64 if 64BIT
        range 2 32 if !64BIT
    

    Therefore, without 64BIT, the maximum value is 32, but we had 64 set on the .config, which would make it inconsistent.

Bonuses

make olddefconfig sets every option to their default value without asking interactively. It gets run automatically on make to ensure that the .config is consistent in case you've modified it manually like we did. See also: https://serverfault.com/questions/116299/automatically-answer-defaults-when-doing-make-oldconfig-on-a-kernel-tree

make alldefconfig is like make olddefconfig, but it also accepts a config fragment to merge. This target is used by the merge_config.sh script: https://stackoverflow.com/a/39440863/895245

And if you want to automate the .config modification, that is not too simple: How do you non-interactively turn on features in a Linux kernel .config file?

Hide separator line on one UITableViewCell

In iOS 7, the UITableView grouped style cell separator looks a bit different. It looks a bit like this:

enter image description here

I tried Kemenaran's answer of doing this:

cell.separatorInset = UIEdgeInsetsMake(0, 10000, 0, 0);

However that doesn't seem to work for me. I'm not sure why. So I decided to use Hiren's answer, but using UIView instead of UIImageView, and draws the line in the iOS 7 style:

UIColor iOS7LineColor = [UIColor colorWithRed:0.82f green:0.82f blue:0.82f alpha:1.0f];

//First cell in a section
if (indexPath.row == 0) {

    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 1)];
    line.backgroundColor = iOS7LineColor;
    [cell addSubview:line];
    [cell bringSubviewToFront:line];

} else if (indexPath.row == [self.tableViewCellSubtitles count] - 1) {

    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(21, 0, self.view.frame.size.width, 1)];
    line.backgroundColor = iOS7LineColor;
    [cell addSubview:line];
    [cell bringSubviewToFront:line];

    UIView *lineBottom = [[UIView alloc] initWithFrame:CGRectMake(0, 43, self.view.frame.size.width, 1)];
    lineBottom.backgroundColor = iOS7LineColor;
    [cell addSubview:lineBottom];
    [cell bringSubviewToFront:lineBottom];

} else {

    //Last cell in the table view
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(21, 0, self.view.frame.size.width, 1)];
    line.backgroundColor = iOS7LineColor;
    [cell addSubview:line];
    [cell bringSubviewToFront:line];
}

If you use this, make sure you plug in the correct table view height in the second if statement. I hope this is useful for someone.

Git Pull is Not Possible, Unmerged Files

There is a solution even if you don't want to remove your local changes. Just fix the unmerged files (by git add or git remove). Then do git pull.

how I can show the sum of in a datagridview column?

Add the total row to your data collection that will be bound to the grid.

What is the time complexity of indexing, inserting and removing from common data structures?

Information on this topic is now available on Wikipedia at: Search data structure

+----------------------+----------+------------+----------+--------------+
|                      |  Insert  |   Delete   |  Search  | Space Usage  |
+----------------------+----------+------------+----------+--------------+
| Unsorted array       | O(1)     | O(1)       | O(n)     | O(n)         |
| Value-indexed array  | O(1)     | O(1)       | O(1)     | O(n)         |
| Sorted array         | O(n)     | O(n)       | O(log n) | O(n)         |
| Unsorted linked list | O(1)*    | O(1)*      | O(n)     | O(n)         |
| Sorted linked list   | O(n)*    | O(1)*      | O(n)     | O(n)         |
| Balanced binary tree | O(log n) | O(log n)   | O(log n) | O(n)         |
| Heap                 | O(log n) | O(log n)** | O(n)     | O(n)         |
| Hash table           | O(1)     | O(1)       | O(1)     | O(n)         |
+----------------------+----------+------------+----------+--------------+

 * The cost to add or delete an element into a known location in the list 
   (i.e. if you have an iterator to the location) is O(1). If you don't 
   know the location, then you need to traverse the list to the location
   of deletion/insertion, which takes O(n) time. 

** The deletion cost is O(log n) for the minimum or maximum, O(n) for an
   arbitrary element.

Split output of command by columns using Bash?

Getting the correct line (example for line no. 6) is done with head and tail and the correct word (word no. 4) can be captured with awk:

command|head -n 6|tail -n 1|awk '{print $4}'

Laravel - Eloquent or Fluent random row

Laravel has a built-in method to shuffle the order of the results.

Here is a quote from the documentation:

shuffle()

The shuffle method randomly shuffles the items in the collection:

$collection = collect([1, 2, 3, 4, 5]);

$shuffled = $collection->shuffle();

$shuffled->all();

// [3, 2, 5, 1, 4] - (generated randomly)

You can see the documentation here.

Change private static final field using Java reflection

The whole point of a final field is that it cannot be reassigned once set. The JVM uses this guarentee to maintain consistency in various places (eg inner classes referencing outer variables). So no. Being able to do so would break the JVM!

The solution is not to declare it final in the first place.

Update my gradle dependencies in eclipse

You have to make sure that "Dependency Management" is enabled. To do so, right click on the project name, go to the "Gradle" sub-menu and click on "Enable Dependency Management". Once you do that, Gradle should load all the dependencies for you.

How to simulate target="_blank" in JavaScript

I know this is a done and sorted out deal, but here's what I'm using to solve the problem in my app.

if (!e.target.hasAttribute("target")) {
    e.preventDefault();     
    e.target.setAttribute("target", "_blank");
    e.target.click();
    return;
}

Basically what is going on here is I run a check for if the link has target=_blank attribute. If it doesn't, it stops the link from triggering, sets it up to open in a new window then programmatically clicks on it.

You can go one step further and skip the stopping of the original click (and make your code a whole lot more compact) by trying this:

if (!e.target.hasAttribute("target")) {
    e.target.setAttribute("target", "_blank");
}

If you were using jQuery to abstract away the implementation of adding an attribute cross-browser, you should use this instead of e.target.setAttribute("target", "_blank"):

    jQuery(event.target).attr("target", "_blank")

You may need to rework it to fit your exact use-case, but here's how I scratched my own itch.

Here's a demo of it in action for you to mess with.

(The link in jsfiddle comes back to this discussion .. no need a new tab :))

Private properties in JavaScript ES6 classes

Reading the previous answer i thought that this example can summarise the above solutions

const friend = Symbol('friend');

const ClassName = ((hidden, hiddenShared = 0) => {

    class ClassName {
        constructor(hiddenPropertyValue, prop){
            this[hidden] = hiddenPropertyValue * ++hiddenShared;
            this.prop = prop
        }

        get hidden(){
            console.log('getting hidden');
            return this[hidden];
        }

        set [friend](v){
            console.log('setting hiddenShared');
            hiddenShared = v;
        }

        get counter(){
            console.log('getting hiddenShared');
            return hiddenShared;
        }

        get privileged(){
            console.log('calling privileged method');
            return privileged.bind(this);
        }
    }

    function privileged(value){
        return this[hidden] + value;
    }

    return ClassName;
})(Symbol('hidden'), 0);

const OtherClass = (() => class OtherClass extends ClassName {
    constructor(v){
        super(v, 100);
        this[friend] = this.counter - 1;
    }
})();

UPDATE

now is it possible to make true private properties and methods (at least on chrome based browsers for now).

The syntax is pretty neat

class MyClass {
    #privateProperty = 1
    #privateMethod() { return 2 }
    static #privateStatic = 3
    static #privateStaticMethod(){return 4}
    static get #privateStaticGetter(){return 5}

    // also using is quite straightforward
    method(){
        return (
            this.#privateMethod() +
            this.#privateProperty +
            MyClass.#privateStatic +
            MyClass.#privateStaticMethod() +
            MyClass.#privateStaticGetter
        )
    }
}

new MyClass().method()
// returns 15

Note that for retrieving static references you wouldn't use this.constructor.#private, because it would brake its subclasses. You must use a reference to the proper class in order to retrieve its static private references (that are available only inside the methods of that class), ie MyClass.#private.

javascript date + 7 days

You can add or increase the day of week for the following example and hope this will helpful for you.Lets see....

        //Current date
        var currentDate = new Date();
        //to set Bangladeshi date need to add hour 6           

        currentDate.setUTCHours(6);            
        //here 2 is day increament for the date and you can use -2 for decreament day
        currentDate.setDate(currentDate.getDate() +parseInt(2));

        //formatting date by mm/dd/yyyy
        var dateInmmddyyyy = currentDate.getMonth() + 1 + '/' + currentDate.getDate() + '/' + currentDate.getFullYear();           

Declare variable in SQLite and use it

SQLite doesn't support native variable syntax, but you can achieve virtually the same using an in-memory temp table.

I've used the below approach for large projects and works like a charm.

/* Create in-memory temp table for variables */
BEGIN;

PRAGMA temp_store = 2;
CREATE TEMP TABLE _Variables(Name TEXT PRIMARY KEY, RealValue REAL, IntegerValue INTEGER, BlobValue BLOB, TextValue TEXT);

/* Declaring a variable */
INSERT INTO _Variables (Name) VALUES ('VariableName');

/* Assigning a variable (pick the right storage class) */
UPDATE _Variables SET IntegerValue = ... WHERE Name = 'VariableName';

/* Getting variable value (use within expression) */
... (SELECT coalesce(RealValue, IntegerValue, BlobValue, TextValue) FROM _Variables WHERE Name = 'VariableName' LIMIT 1) ...

DROP TABLE _Variables;
END;

How to add more than one machine to the trusted hosts list using winrm

I prefer to work with the PSDrive WSMan:\.

Get TrustedHosts

Get-Item WSMan:\localhost\Client\TrustedHosts

Set TrustedHosts

provide a single, comma-separated, string of computer names

Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineA,machineB'

or (dangerous) a wild-card

Set-Item WSMan:\localhost\Client\TrustedHosts -Value '*'

to append to the list, the -Concatenate parameter can be used

Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineC' -Concatenate

Android: install .apk programmatically

I solved the problem. I made mistake in setData(Uri) and setType(String).

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

That is correct now, my auto-update is working. Thanks for help. =)

Edit 20.7.2016:

After a long time, I had to use this way of updating again in another project. I encountered a number of problems with old solution. A lot of things have changed in that time, so I had to do this with a different approach. Here is the code:

    //get destination to update file and set Uri
    //TODO: First I wanted to store my update .apk file on internal storage for my app but apparently android does not allow you to open and install
    //aplication with existing package from there. So for me, alternative solution is Download directory in external storage. If there is better
    //solution, please inform us in comment
    String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
    String fileName = "AppName.apk";
    destination += fileName;
    final Uri uri = Uri.parse("file://" + destination);

    //Delete update file if exists
    File file = new File(destination);
    if (file.exists())
    //file.delete() - test this, I think sometimes it doesnt work
        file.delete();

    //get url of app on server
    String url = Main.this.getString(R.string.update_app_url);

    //set downloadmanager
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request.setDescription(Main.this.getString(R.string.notification_description));
    request.setTitle(Main.this.getString(R.string.app_name));

    //set destination
    request.setDestinationUri(uri);

    // get download service and enqueue file
    final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    final long downloadId = manager.enqueue(request);

    //set BroadcastReceiver to install app when .apk is downloaded
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            install.setDataAndType(uri,
                    manager.getMimeTypeForDownloadedFile(downloadId));
            startActivity(install);

            unregisterReceiver(this);
            finish();
        }
    };
    //register receiver for when .apk download is compete
    registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

Does MySQL ignore null values on unique constraints?

I am unsure if the author originally was just asking whether or not this allows duplicate values or if there was an implied question here asking, "How to allow duplicate NULL values while using UNIQUE?" Or "How to only allow one UNIQUE NULL value?"

The question has already been answered, yes you can have duplicate NULL values while using the UNIQUE index.

Since I stumbled upon this answer while searching for "how to allow one UNIQUE NULL value." For anyone else who may stumble upon this question while doing the same, the rest of my answer is for you...

In MySQL you can not have one UNIQUE NULL value, however you can have one UNIQUE empty value by inserting with the value of an empty string.

Warning: Numeric and types other than string may default to 0 or another default value.

Concatenate multiple node values in xpath

<xsl:template match="element3">
        <xsl:value-of select="element4,element5" separator="."/>
    </xsl:template>

How to compare binary files to check if they are the same?

There is a relatively simple way to check if two binary files are the same.

If you use file input/output in a programming language; you can store each bit of both the binary files into their own arrays.

At this point the check is as simple as :

if(file1 != file2){
    //do this
}else{
    /do that
}

How to set -source 1.7 in Android Studio and Gradle

Java 7 support was added at build tools 19. You can now use features like the diamond operator, multi-catch, try-with-resources, strings in switches, etc. Add the following to your build.gradle.

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 19
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

Gradle 1.7+, Android gradle plugin 0.6.+ are required.

Note, that only try with resources require minSdkVersion 19. Other features works on previous platforms.

Link to android gradle plugin user guide

Link to see how source vs target are different

Why does my Spring Boot App always shutdown immediately after starting?

I think the right answer was at Why does Spring Boot web app close immediately after starting? about the starter-tomcat not being set and if set and running through the IDE, the provided scope should be commented off. Scope doesn't create an issue while running through command. I wonder why.

Anyways just added my additional thoughts.

How to match a substring in a string, ignoring case

import re
if re.search('(?i)Mandy Pande:', line):
    ...

How to display request headers with command line curl

The verbose option is handy, but if you want to see everything that curl does (including the HTTP body that is transmitted, and not just the headers), I suggest using one of the below options:

  • --trace-ascii - # stdout
  • --trace-ascii output_file.txt # file

Is an HTTPS query string secure?

Yes. The entire text of an HTTPS session is secured by SSL. That includes the query and the headers. In that respect, a POST and a GET would be exactly the same.

As to the security of your method, there's no real way to say without proper inspection.

PHP json_encode json_decode UTF-8

Work for me :)

function jsonEncodeArray( $array ){
    array_walk_recursive( $array, function(&$item) { 
       $item = utf8_encode( $item ); 
    });
    return json_encode( $array );
}

How to paste text to end of every line? Sublime 2

You can use the Search & Replace feature with this regex ^([\w\d\_\.\s\-]*)$ to find text and the replaced text is "$1".

NodeJS/express: Cache and 304 status code

  • Operating system: Windows
  • Browser: Chrome

I used Ctrl + F5 keyboard combination. By doing so, instead of reading from cache, I wanted to get a new response. The solution is to do hard refresh the page.

On MDN Web Docs:

"The HTTP 304 Not Modified client redirection response code indicates that there is no need to retransmit the requested resources. It is an implicit redirection to a cached resource."