Programs & Examples On #Jqgrid asp.net

jqGrid-ASP.NET is a commercial grid component for ASP.NET & PHP based on the world's most popular and flexible jQuery grid plugin jqGrid.

How to get a jqGrid selected row cells value

You can use in this manner also

var rowId =$("#list").jqGrid('getGridParam','selrow');  
var rowData = jQuery("#list").getRowData(rowId);
var colData = rowData['UserId'];   // perticuler Column name of jqgrid that you want to access

Head and tail in one line

Under Python 3.x, you can do this nicely:

>>> head, *tail = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]

A new feature in 3.x is to use the * operator in unpacking, to mean any extra values. It is described in PEP 3132 - Extended Iterable Unpacking. This also has the advantage of working on any iterable, not just sequences.

It's also really readable.

As described in the PEP, if you want to do the equivalent under 2.x (without potentially making a temporary list), you have to do this:

it = iter(iterable)
head, tail = next(it), list(it)

As noted in the comments, this also provides an opportunity to get a default value for head rather than throwing an exception. If you want this behaviour, next() takes an optional second argument with a default value, so next(it, None) would give you None if there was no head element.

Naturally, if you are working on a list, the easiest way without the 3.x syntax is:

head, tail = seq[0], seq[1:]

python pandas: apply a function with arguments to a series

You can pass any number of arguments to the function that apply is calling through either unnamed arguments, passed as a tuple to the args parameter, or through other keyword arguments internally captured as a dictionary by the kwds parameter.

For instance, let's build a function that returns True for values between 3 and 6, and False otherwise.

s = pd.Series(np.random.randint(0,10, 10))
s

0    5
1    3
2    1
3    1
4    6
5    0
6    3
7    4
8    9
9    6
dtype: int64

s.apply(lambda x: x >= 3 and x <= 6)

0     True
1     True
2    False
3    False
4     True
5    False
6     True
7     True
8    False
9     True
dtype: bool

This anonymous function isn't very flexible. Let's create a normal function with two arguments to control the min and max values we want in our Series.

def between(x, low, high):
    return x >= low and x =< high

We can replicate the output of the first function by passing unnamed arguments to args:

s.apply(between, args=(3,6))

Or we can use the named arguments

s.apply(between, low=3, high=6)

Or even a combination of both

s.apply(between, args=(3,), high=6)

XML Schema (XSD) validation tool?

http://www.xmlvalidation.com/

(Be sure to check the " Validate against external XML schema" Box)

How to detect input type=file "change" for the same file?

I got this to work by clearing the file input value onClick and then posting the file onChange. This allows the user to select the same file twice in a row and still have the change event fire to post to the server. My example uses the the jQuery form plugin.

$('input[type=file]').click(function(){
    $(this).attr("value", "");
})  
$('input[type=file]').change(function(){
    $('#my-form').ajaxSubmit(options);      
})

How to accept Date params in a GET request to Spring MVC Controller?

This is what I did to get formatted date from front end

  @RequestMapping(value = "/{dateString}", method = RequestMethod.GET)
  @ResponseBody
  public HttpStatus getSomething(@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String dateString) {
   return OK;
  }

You can use it to get what you want.

Better way to sum a property value in an array

Use reduce with destructuring to sum Amount:

const traveler = [
  { description: 'Senior', Amount: 50 },
  { description: 'Senior', Amount: 50 },
  { description: 'Adult', Amount: 75 },
  { description: 'Child', Amount: 35 },
  { description: 'Infant', Amount: 25 },
];

console.log(traveler.reduce((n, {Amount}) => n + Amount, 0))

Go to Matching Brace in Visual Studio?

I use Visual Studio 2008, and you can customize what you want this shortcut to be.

Click menu Tools -> Options -> Environment -> Keyboard. Then look for Edit.GotoBrace.

This will tell you what key combination is currently assigned for this. I think you can change this if you want, but it's useful if the Ctrl + ] doesn't work.

Setting a divs background image to fit its size?

Set your css to this

img {
    max-width:100%,
    max-height100%
}

Round integers to the nearest 10

if you want the algebric form and still use round for it it's hard to get simpler than:

interval = 5
n = 4
print(round(n/interval))*interval

TypeError: $ is not a function WordPress

Function errors are a common thing in almost all content management systems and there is a few ways you can approach this.

  1. Wrap your code using:

    <script> 
    jQuery(function($) {
    
    YOUR CODE GOES HERE
    
    });
    </script>
    
  2. You can also use jQuery's API using noConflict();

    <script>
    $.noConflict();
    jQuery( document ).ready(function( $ ) {
    // Code that uses jQuery's $ can follow here.
    });
    // Code that uses other library's $ can follow here.
    </script>
    
  3. Another example of using noConflict without using document ready:

    <script>
    jQuery.noConflict();
        (function( $ ) {
            $(function() { 
                // YOUR CODE HERE
            });
         });
    </script>
    
  4. You could even choose to create your very alias to avoid conflicts like so:

    var jExample = jQuery.noConflict();
    // Do something with jQuery
    jExample( "div p" ).hide();
    
  5. Yet another longer solution is to rename all referances of $ to jQuery:

    $( "div p" ).hide(); to jQuery( "div p" ).hide();

Sorting arrays in NumPy by column

You can sort on multiple columns as per Steve Tjoa's method by using a stable sort like mergesort and sorting the indices from the least significant to the most significant columns:

a = a[a[:,2].argsort()] # First sort doesn't need to be stable.
a = a[a[:,1].argsort(kind='mergesort')]
a = a[a[:,0].argsort(kind='mergesort')]

This sorts by column 0, then 1, then 2.

Laravel - display a PDF file in storage without forcing download?

Ben Swinburne answer was so helpful.

The code below is for those who have their PDF file in database like me.

$pdf = DB::table('exportfiles')->select('pdf')->where('user_id', $user_id)->first();

return Response::make(base64_decode( $pdf->pdf), 200, [
    'Content-Type' => 'application/pdf',
    'Content-Disposition' => 'inline; filename="'.$filename.'"',
]);

Where $pdf->pdf is the file column in database.

How can I make a multipart/form-data POST request using Java?

We have a pure java implementation of multipart-form submit without using any external dependencies or libraries outside jdk. Refer https://github.com/atulsm/https-multipart-purejava/blob/master/src/main/java/com/atul/MultipartPure.java

private static String body = "{\"key1\":\"val1\", \"key2\":\"val2\"}";
private static String subdata1 = "@@ -2,3 +2,4 @@\r\n";
private static String subdata2 = "<data>subdata2</data>";

public static void main(String[] args) throws Exception{        
    String url = "https://" + ip + ":" + port + "/dataupload";
    String token = "Basic "+ Base64.getEncoder().encodeToString((userName+":"+password).getBytes());

    MultipartBuilder multipart = new MultipartBuilder(url,token);       
    multipart.addFormField("entity", "main", "application/json",body);
    multipart.addFormField("attachment", "subdata1", "application/octet-stream",subdata1);
    multipart.addFormField("attachment", "subdata2", "application/octet-stream",subdata2);        
    List<String> response = multipart.finish();         
    for (String line : response) {
        System.out.println(line);
    }
}

How to rename a table column in Oracle 10g

alter table table_name 
rename column old_column_name/field_name to new_column_name/field_name;

example: alter table student column name to username;

Sass Variable in CSS calc() function

Try this:

@mixin heightBox($body_padding){
   height: calc(100% - $body_padding);
}

body{
   @include heightBox(100% - 25%);
   box-sizing: border-box
   padding:10px;
}

Links in <select> dropdown options

Add an onchange event handler and set the pages location to the value

<select id="foo">
    <option value="">Pick a site</option>
    <option value="http://www.google.com">x</option>
    <option value="http://www.yahoo.com">y</option>
</select>

<script>
    document.getElementById("foo").onchange = function() {
        if (this.selectedIndex!==0) {
            window.location.href = this.value;
        }        
    };
</script>

Calculating percentile of dataset column

The quantile() function will do much of what you probably want, but since the question was ambiguous, I will provide an alternate answer that does something slightly different from quantile().

ecdf(infert$age)(infert$age)

will generate a vector of the same length as infert$age giving the proportion of infert$age that is below each observation. You can read the ecdf documentation, but the basic idea is that ecdf() will give you a function that returns the empirical cumulative distribution. Thus ecdf(X)(Y) is the value of the cumulative distribution of X at the points in Y. If you wanted to know just the probability of being below 30 (thus what percentile 30 is in the sample), you could say

ecdf(infert$age)(30)

The main difference between this approach and using the quantile() function is that quantile() requires that you put in the probabilities to get out the levels, and this requires that you put in the levels to get out the probabilities.

How do I update pip itself from inside my virtual environment?

I had installed Python in C:\Python\Python36 so I went to the Windows command prompt and typed "cd C:\Python\Python36 to get to the right directory. Then entered the "python -m install --upgrade pip" all good!

Calling filter returns <filter object at ... >

It's an iterator returned by the filter function.

If you want a list, just do

list(filter(f, range(2, 25)))

Nonetheless, you can just iterate over this object with a for loop.

for e in filter(f, range(2, 25)):
    do_stuff(e)

How to initialize a nested struct?

Well, any specific reason to not make Proxy its own struct?

Anyway you have 2 options:

The proper way, simply move proxy to its own struct, for example:

type Configuration struct {
    Val string
    Proxy Proxy
}

type Proxy struct {
    Address string
    Port    string
}

func main() {

    c := &Configuration{
        Val: "test",
        Proxy: Proxy{
            Address: "addr",
            Port:    "port",
        },
    }
    fmt.Println(c)
    fmt.Println(c.Proxy.Address)
}

The less proper and ugly way but still works:

c := &Configuration{
    Val: "test",
    Proxy: struct {
        Address string
        Port    string
    }{
        Address: "addr",
        Port:    "80",
    },
}

Get the _id of inserted document in Mongo database in NodeJS

You could use async functions to get _id field automatically without manipulating data object:

async function save() {
  const data = {
    name: "John"
  }

  await db.collection('users').insertOne(data)

  return data
}

Returns data:

{
  _id: '5dbff150b407cc129ab571ca',
  name: 'John'
}

When to use MongoDB or other document oriented database systems?

In NoSQL: If Only It Was That Easy, the author writes about MongoDB:

MongoDB is not a key/value store, it’s quite a bit more. It’s definitely not a RDBMS either. I haven’t used MongoDB in production, but I have used it a little building a test app and it is a very cool piece of kit. It seems to be very performant and either has, or will have soon, fault tolerance and auto-sharding (aka it will scale). I think Mongo might be the closest thing to a RDBMS replacement that I’ve seen so far. It won’t work for all data sets and access patterns, but it’s built for your typical CRUD stuff. Storing what is essentially a huge hash, and being able to select on any of those keys, is what most people use a relational database for. If your DB is 3NF and you don’t do any joins (you’re just selecting a bunch of tables and putting all the objects together, AKA what most people do in a web app), MongoDB would probably kick ass for you.

Then, in the conclusion:

The real thing to point out is that if you are being held back from making something super awesome because you can’t choose a database, you are doing it wrong. If you know mysql, just use it. Optimize when you actually need to. Use it like a k/v store, use it like a rdbms, but for god sake, build your killer app! None of this will matter to most apps. Facebook still uses MySQL, a lot. Wikipedia uses MySQL, a lot. FriendFeed uses MySQL, a lot. NoSQL is a great tool, but it’s certainly not going to be your competitive edge, it’s not going to make your app hot, and most of all, your users won’t care about any of this.

What am I going to build my next app on? Probably Postgres. Will I use NoSQL? Maybe. I might also use Hadoop and Hive. I might keep everything in flat files. Maybe I’ll start hacking on Maglev. I’ll use whatever is best for the job. If I need reporting, I won’t be using any NoSQL. If I need caching, I’ll probably use Tokyo Tyrant. If I need ACIDity, I won’t use NoSQL. If I need a ton of counters, I’ll use Redis. If I need transactions, I’ll use Postgres. If I have a ton of a single type of documents, I’ll probably use Mongo. If I need to write 1 billion objects a day, I’d probably use Voldemort. If I need full text search, I’d probably use Solr. If I need full text search of volatile data, I’d probably use Sphinx.

I like this article, I find it very informative, it gives a good overview of the NoSQL landscape and hype. But, and that's the most important part, it really helps to ask yourself the right questions when it comes to choose between RDBMS and NoSQL. Worth the read IMHO.

Alternate link to article

How do I get the information from a meta tag with JavaScript?

One liner here

document.querySelector("meta[property='og:image']").getAttribute("content");

Working with Enums in android

There has been some debate around this point of contention, but even in the most recent documents android suggests that it's not such a good idea to use enums in an android application. The reason why is because they use up more memory than a static constants variable. Here is a document from a page of 2014 that advises against the use of enums in an android application. http://developer.android.com/training/articles/memory.html#Overhead

I quote:

Be aware of memory overhead

Be knowledgeable about the cost and overhead of the language and libraries you are using, and keep this information in mind when you design your app, from start to finish. Often, things on the surface that look innocuous may in fact have a large amount of overhead. Examples include:

  • Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.

  • Every class in Java (including anonymous inner classes) uses about 500 bytes of code.

  • Every class instance has 12-16 bytes of RAM overhead.

  • Putting a single entry into a HashMap requires the allocation of an additional entry object that takes 32 bytes (see the previous section about optimized data containers).

A few bytes here and there quickly add up—app designs that are class- or object-heavy will suffer from this overhead. That can leave you in the difficult position of looking at a heap analysis and realizing your problem is a lot of small objects using up your RAM.

There has been some places where they say that these tips are outdated and no longer valuable, but the reason they keep repeating it, must be there is some truth to it. Writing an android application is something you should keep as lightweight as possible for a smooth user experience. And every little inch of performance counts!

How to count instances of character in SQL Column

Below solution help to find out no of character present from a string with a limitation:

1) using SELECT LEN(REPLACE(myColumn, 'N', '')), but limitation and wrong output in below condition:

SELECT LEN(REPLACE('YYNYNYYNNNYYNY', 'N', ''));
--8 --Correct

SELECT LEN(REPLACE('123a123a12', 'a', ''));
--8 --Wrong

SELECT LEN(REPLACE('123a123a12', '1', ''));
--7 --Wrong

2) Try with below solution for correct output:

  • Create a function and also modify as per requirement.
  • And call function as per below

select dbo.vj_count_char_from_string('123a123a12','2');
--2 --Correct

select dbo.vj_count_char_from_string('123a123a12','a');
--2 --Correct

-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      VIKRAM JAIN
-- Create date: 20 MARCH 2019
-- Description: Count char from string
-- =============================================
create FUNCTION vj_count_char_from_string
(
    @string nvarchar(500),
    @find_char char(1)  
)
RETURNS integer
AS
BEGIN
    -- Declare the return variable here
    DECLARE @total_char int; DECLARE @position INT;
    SET @total_char=0; set @position = 1;

    -- Add the T-SQL statements to compute the return value here
    if LEN(@string)>0
    BEGIN
        WHILE @position <= LEN(@string) -1
        BEGIN
            if SUBSTRING(@string, @position, 1) = @find_char
            BEGIN
                SET @total_char+= 1;
            END
            SET @position+= 1;
        END
    END;

    -- Return the result of the function
    RETURN @total_char;

END
GO

Delaying AngularJS route change until model loaded to prevent flicker

I like darkporter's idea because it will be easy for a dev team new to AngularJS to understand and worked straight away.

I created this adaptation which uses 2 divs, one for loader bar and another for actual content displayed after data is loaded. Error handling would be done elsewhere.

Add a 'ready' flag to $scope:

$http({method: 'GET', url: '...'}).
    success(function(data, status, headers, config) {
        $scope.dataForView = data;      
        $scope.ready = true;  // <-- set true after loaded
    })
});

In html view:

<div ng-show="!ready">

    <!-- Show loading graphic, e.g. Twitter Boostrap progress bar -->
    <div class="progress progress-striped active">
        <div class="bar" style="width: 100%;"></div>
    </div>

</div>

<div ng-show="ready">

    <!-- Real content goes here and will appear after loading -->

</div>

See also: Boostrap progress bar docs

How to fix itunes could not connect to the iphone because an invalid response was received from the device?

Try resetting your network settings

Settings -> General -> Reset -> Reset Network Settings

And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".

http://support.apple.com/kb/ts2529

This one worked for me.

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

A solution would be to declare your key as nvarchar(20).

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

Disable Access Protection in Antivirus,

I faced same issue at last found the below logs from antivirus.

Blocked by Access Protection rule NT AUTHORITY\SYSTEM C:\WINDOWS\SYSTEM32\SVCHOST.EXE C:\PROGRAM FILES (X86)\MCAFEE\VIRUSSCAN ENTERPRISE\MCCONSOL.EXE Common Standard Protection:Prevent termination of McAfee processes Action blocked : Terminate Blocked by port blocking rule C:\USERS\username\APPDATA\LOCAL\PROGRAMS\PYTHON\PYTHON37-32\PYTHON.EXE Anti-virus Standard Protection:Prevent mass mailing worms from sending mail

How to clear Tkinter Canvas?

Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.

To clear a canvas, use the delete method. Give it the special parameter "all" to delete all items on the canvas (the string "all"" is a special tag that represents all items on the canvas):

canvas.delete("all")

If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all", you could supply the name of a tag.

If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.

unix sort descending order

To list files based on size in asending order.

find ./ -size +1000M -exec ls -tlrh {} \; |awk -F" " '{print $5,$9}'  | sort -n\

Postgresql GROUP_CONCAT equivalent?

This is probably a good starting point (version 8.4+ only):

SELECT id_field, array_agg(value_field1), array_agg(value_field2)
FROM data_table
GROUP BY id_field

array_agg returns an array, but you can CAST that to text and edit as needed (see clarifications, below).

Prior to version 8.4, you have to define it yourself prior to use:

CREATE AGGREGATE array_agg (anyelement)
(
    sfunc = array_append,
    stype = anyarray,
    initcond = '{}'
);

(paraphrased from the PostgreSQL documentation)

Clarifications:

  • The result of casting an array to text is that the resulting string starts and ends with curly braces. Those braces need to be removed by some method, if they are not desired.
  • Casting ANYARRAY to TEXT best simulates CSV output as elements that contain embedded commas are double-quoted in the output in standard CSV style. Neither array_to_string() or string_agg() (the "group_concat" function added in 9.1) quote strings with embedded commas, resulting in an incorrect number of elements in the resulting list.
  • The new 9.1 string_agg() function does NOT cast the inner results to TEXT first. So "string_agg(value_field)" would generate an error if value_field is an integer. "string_agg(value_field::text)" would be required. The array_agg() method requires only one cast after the aggregation (rather than a cast per value).

How to change Rails 3 server default port in develoment?

First - do not edit anything in your gem path! It will influence all projects, and you will have a lot problems later...

In your project edit script/rails this way:

#!/usr/bin/env ruby
# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.

APP_PATH = File.expand_path('../../config/application',  __FILE__)
require File.expand_path('../../config/boot',  __FILE__)

# THIS IS NEW:
require "rails/commands/server"
module Rails
  class Server
    def default_options
      super.merge({
        :Port        => 10524,
        :environment => (ENV['RAILS_ENV'] || "development").dup,
        :daemonize   => false,
        :debugger    => false,
        :pid         => File.expand_path("tmp/pids/server.pid"),
        :config      => File.expand_path("config.ru")
      })
    end
  end
end
# END OF CHANGE
require 'rails/commands'

The principle is simple - you are monkey-patching the server runner - so it will influence just one project.

UPDATE: Yes, I know that the there is simpler solution with bash script containing:

#!/bin/bash
rails server -p 10524

but this solution has a serious drawback - it is boring as hell.

Could not insert new outlet connection: Could not find any information for the class named

I had the same problem. I realised than in X-Code Manual item was selected when I tried to create an outlet by control-drag

enter image description here

After I set it to automatic it worked

enter image description here

PHP: trying to create a new line with "\n"

If you want a new line character to be inserted into a plain text stream then you could use the OS independent global PHP_EOL

echo "foo";
echo PHP_EOL ;
echo "bar";

In HTML terms you would see a newline between foo and bar if you looked at the source code of the page.

ergo, it is useful if you are outputting say, a loop of values for a select box and you value having html source code which is "prettier" or easier to read for yourself later. e.g.

foreach( $dogs as $dog )
echo "<option>$dog</option>" . PHP_EOL ;

C++ Array of pointers: delete or delete []?

delete[] monsters;

Is incorrect because monsters isn't a pointer to a dynamically allocated array, it is an array of pointers. As a class member it will be destroyed automatically when the class instance is destroyed.

Your other implementation is the correct one as the pointers in the array do point to dynamically allocated Monster objects.

Note that with your current memory allocation strategy you probably want to declare your own copy constructor and copy-assignment operator so that unintentional copying doesn't cause double deletes. (If you you want to prevent copying you could declare them as private and not actually implement them.)

Leader Not Available Kafka in Console Producer

What solved it for me is to set listeners like so:

advertised.listeners = PLAINTEXT://my.public.ip:9092
listeners = PLAINTEXT://0.0.0.0:9092

This makes KAFKA broker listen to all interfaces.

Cannot push to Git repository on Bitbucket

I got this very same error for one repository - suddenly, all other ones were and still work fine when I'm trying to push commits. The problem appeared to be with the SSH key (as you already know from the previous comments) - on bitbucket go to View Profile then click Manage Account.

On the left hand side click on the SSH Keys then add the one that you have on your system under ~/.ssh/ directory.

If you don't have one generated yet - use the instructions from one of the posts, but make sure that you either use the default id_dsa.pub file or custom named one, with later requiring the -i option with the path to the key when you connect i.e.

ssh -i ~/.ssh/customkeyname username@ip_address

Once you've added your local key to your account at bitbucket, you'll be able to start interacting with your repository.

When do I need to do "git pull", before or after "git add, git commit"?

I'd suggest pulling from the remote branch as often as possible in order to minimise large merges and possible conflicts.

Having said that, I would go with the first option:

git add foo.js
git commit foo.js -m "commit"
git pull
git push

Commit your changes before pulling so that your commits are merged with the remote changes during the pull. This may result in conflicts which you can begin to deal with knowing that your code is already committed should anything go wrong and you have to abort the merge for whatever reason.

I'm sure someone will disagree with me though, I don't think there's any correct way to do this merge flow, only what works best for people.

Ignore .classpath and .project from Git

Add the below lines in .gitignore and place the file inside ur project folder

/target/
/.classpath
/*.project
/.settings
/*.springBeans

Difference between the System.Array.CopyTo() and System.Array.Clone()

As stated in many other answers both methods perform shallow copies of the array. However there are differences and recommendations that have not been addressed yet and that are highlighted in the following lists.

Characteristics of System.Array.Clone:

  • Tests, using .NET 4.0, show that it is slower than CopyTo probably because it uses Object.MemberwiseClone;
  • Requires casting the result to the appropriate type;
  • The resulting array has the same length as the source.

Characteristics of System.Array.CopyTo:

  • Is faster than Clone when copying to array of same type;
  • It calls into Array.Copy inheriting is capabilities, being the most useful ones:
    • Can box value type elements into reference type elements, for example, copying an int[] array into an object[];
    • Can unbox reference type elements into value type elements, for example, copying a object[] array of boxed int into an int[];
    • Can perform widening conversions on value types, for example, copying a int[] into a long[].
    • Can downcast elements, for example, copying a Stream[] array into a MemoryStream[] (if any element in source array is not convertible to MemoryStream an exception is thrown).
  • Allows to copy the source to a target array that has a length greater than the source.

Also note, these methods are made available to support ICloneable and ICollection, so if you are dealing with variables of array types you should not use Clone or CopyTo and instead use Array.Copy or Array.ConstrainedCopy. The constrained copy assures that if the copy operation cannot complete successful then the target array state is not corrupted.

How to make an app's background image repeat

Here is a pure-java implementation of background image repeating:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.bg_image);
    BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
    bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
    LinearLayout layout = new LinearLayout(this);
    layout.setBackgroundDrawable(bitmapDrawable);
}

In this case, our background image would have to be stored in res/drawable/bg_image.png.

Creating an empty list in Python

I do not really know about it, but it seems to me, by experience, that jpcgt is actually right. Following example: If I use following code

t = [] # implicit instantiation
t = t.append(1)

in the interpreter, then calling t gives me just "t" without any list, and if I append something else, e.g.

t = t.append(2)

I get the error "'NoneType' object has no attribute 'append'". If, however, I create the list by

t = list() # explicit instantiation

then it works fine.

/bin/sh: pushd: not found

here is a method to point

sh -> bash

run this command on terminal

sudo dpkg-reconfigure dash

After this you should see

ls -l /bin/sh

point to /bin/bash (and not to /bin/dash)

Reference

How can I convert an image into Base64 string using JavaScript?

Try this code:

For a file upload change event, call this function:

$("#fileproof").on('change', function () {
    readImage($(this)).done(function (base64Data) { $('#<%=hfimgbs64.ClientID%>').val(base64Data); });
});

function readImage(inputElement) {
    var deferred = $.Deferred();

    var files = inputElement.get(0).files;

    if (files && files[0]) {
        var fr = new FileReader();
        fr.onload = function (e) {
            deferred.resolve(e.target.result);
        };
        fr.readAsDataURL(files[0]);
    } else {
        deferred.resolve(undefined);
    }

    return deferred.promise();
}

Store Base64 data in hidden filed to use.

DataGridView - Focus a specific cell

I had a similar problem. I've hidden some columns and afterwards I tried to select the first row. This didn't really work:

datagridview1.Rows[0].Selected = true;

So I tried selecting cell[0,0], but it also didn't work, because this cell was not displayed. Now my final solution is working very well:

datagridview1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;    
datagridview1.CurrentCell = datagridview1.FirstDisplayedCell;

So this selects the complete first row.

Why does range(start, end) not include end?

Basically in python range(n) iterates n times, which is of exclusive nature that is why it does not give last value when it is being printed, we can create a function which gives inclusive value it means it will also print last value mentioned in range.

def main():
    for i in inclusive_range(25):
        print(i, sep=" ")


def inclusive_range(*args):
    numargs = len(args)
    if numargs == 0:
        raise TypeError("you need to write at least a value")
    elif numargs == 1:
        stop = args[0]
        start = 0
        step = 1
    elif numargs == 2:
        (start, stop) = args
        step = 1
    elif numargs == 3:
        (start, stop, step) = args
    else:
        raise TypeError("Inclusive range was expected at most 3 arguments,got {}".format(numargs))
    i = start
    while i <= stop:
        yield i
        i += step


if __name__ == "__main__":
    main()

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

Python way to clone a git repository

Here's a way to print progress while cloning a repo with GitPython

import time
import git
from git import RemoteProgress

class CloneProgress(RemoteProgress):
    def update(self, op_code, cur_count, max_count=None, message=''):
        if message:
            print(message)

print('Cloning into %s' % git_root)
git.Repo.clone_from('https://github.com/your-repo', '/your/repo/dir', 
        branch='master', progress=CloneProgress())

String.format() to format double in java

String.format("%4.3f" , x) ;

It means that we need total 4 digits in ans , of which 3 should be after decimal . And f is the format specifier of double . x means the variable for which we want to find it . Worked for me . . .

Node.js Hostname/IP doesn't match certificate's altnames

If you are going to trust a sub-domain, for example, aaa.localhost, Please don't do it like mkcert localhost *.localhost 127.0.0.1, this will not work since some browser doesn't accept wildcard subdomain.

Maybe try mkcert localhost aaa.localhost 127.0.0.1.

Python Pandas Error tokenizing data

In my case the separator was not the default "," but Tab.

pd.read_csv(file_name.csv, sep='\\t',lineterminator='\\r', engine='python', header='infer')

Note: "\t" did not work as suggested by some sources. "\\t" was required.

async for loop in node.js

I've reduced your code sample to the following lines to make it easier to understand the explanation of the concept.

var results = [];
var config = JSON.parse(queries);
for (var key in config) {
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
    });
}
res.writeHead( ... );
res.end(results);

The problem with the previous code is that the search function is asynchronous, so when the loop has ended, none of the callback functions have been called. Consequently, the list of results is empty.

To fix the problem, you have to put the code after the loop in the callback function.

    search(query, function(result) {
        results.push(result);
        // Put res.writeHead( ... ) and res.end(results) here
    });

However, since the callback function is called multiple times (once for every iteration), you need to somehow know that all callbacks have been called. To do that, you need to count the number of callbacks, and check whether the number is equal to the number of asynchronous function calls.

To get a list of all keys, use Object.keys. Then, to iterate through this list, I use .forEach (you can also use for (var i = 0, key = keys[i]; i < keys.length; ++i) { .. }, but that could give problems, see JavaScript closure inside loops – simple practical example).

Here's a complete example:

var results = [];
var config = JSON.parse(queries);
var onComplete = function() {
    res.writeHead( ... );
    res.end(results);
};
var keys = Object.keys(config);
var tasksToGo = keys.length;
if (tasksToGo === 0) {
   onComplete();
} else {
    // There is at least one element, so the callback will be called.
    keys.forEach(function(key) {
        var query = config[key].query;
        search(query, function(result) {
            results.push(result);
            if (--tasksToGo === 0) {
                // No tasks left, good to go
                onComplete();
            }
        });
    });
}

Note: The asynchronous code in the previous example are executed in parallel. If the functions need to be called in a specific order, then you can use recursion to get the desired effect:

var results = [];
var config = JSON.parse(queries);
var keys = Object.keys(config);
(function next(index) {
    if (index === keys.length) { // No items left
        res.writeHead( ... );
        res.end(results);
        return;
    }
    var key = keys[index];
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
        next(index + 1);
    });
})(0);

What I've shown are the concepts, you could use one of the many (third-party) NodeJS modules in your implementation, such as async.

Can attributes be added dynamically in C#?

Why do you need to? Attributes give extra information for reflection, but if you externally know which properties you want you don't need them.

You could store meta data externally relatively easily in a database or resource file.

presenting ViewController with NavigationViewController swift

The accepted answer is great. This is not answer, but just an illustration of the issue.

I present a viewController like this:

inside vc1:

func showVC2() {
    if let navController = self.navigationController{
        navController.present(vc2, animated: true)
    }
}

inside vc2:

func returnFromVC2() {
    if let navController = self.navigationController {
        navController.popViewController(animated: true)
    }else{
        print("navigationController is nil") <-- I was reaching here!
    }
}

As 'stefandouganhyde' has said: "it is not contained by your UINavigationController or any other"

new solution:

func returnFromVC2() {
    dismiss(animated: true, completion: nil)
}

Interfaces with static fields in java for sharing 'constants'

I do not pretend the right to be right, but lets see this small example:

public interface CarConstants {

      static final String ENGINE = "mechanical";
      static final String WHEEL  = "round";
      // ...

}

public interface ToyotaCar extends CarConstants //, ICar, ... {
      void produce();
}

public interface FordCar extends CarConstants //, ICar, ... {
      void produce();
}

// and this is implementation #1
public class CamryCar implements ToyotaCar {

      public void produce() {
           System.out.println("the engine is " + ENGINE );
           System.out.println("the wheel is " + WHEEL);
      }
}

// and this is implementation #2
public class MustangCar implements FordCar {

      public void produce() {
           System.out.println("the engine is " + ENGINE );
           System.out.println("the wheel is " + WHEEL);
      }
}

ToyotaCar doesnt know anything about FordCar, and FordCar doesnt know about ToyotaCar. principle CarConstants should be changed, but...

Constants should not be changed, because the wheel is round and egine is mechanical, but... In the future Toyota's research engineers invented electronic engine and flat wheels! Lets see our new interface

public interface InnovativeCarConstants {

          static final String ENGINE = "electronic";
          static final String WHEEL  = "flat";
          // ...
}

and now we can change our abstraction:

public interface ToyotaCar extends CarConstants

to

public interface ToyotaCar extends InnovativeCarConstants 

And now if we ever need to change the core value if the ENGINE or WHEEL we can change the ToyotaCar Interface on abstraction level, dont touching implementations

Its NOT SAFE, I know, but I still want to know that do you think about this

Java Serializable Object to Byte Array

The best way to do it is to use SerializationUtils from Apache Commons Lang.

To serialize:

byte[] data = SerializationUtils.serialize(yourObject);

To deserialize:

YourObject yourObject = SerializationUtils.deserialize(data)

As mentioned, this requires Commons Lang library. It can be imported using Gradle:

compile 'org.apache.commons:commons-lang3:3.5'

Maven:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.5</version>
</dependency>

Jar file

And more ways mentioned here

Alternatively, the whole collection can be imported. Refer this link

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

onActivityCreated() - Deprecated

onActivityCreated() is now deprecated as Fragments Version 1.3.0-alpha02

The onActivityCreated() method is now deprecated. Code touching the fragment's view should be done in onViewCreated() (which is called immediately before onActivityCreated()) and other initialization code should be in onCreate(). To receive a callback specifically when the activity's onCreate() is complete, a LifeCycleObserver should be registered on the activity's Lifecycle in onAttach(), and removed once the onCreate() callback is received.

Detailed information can be found here

Is there a way to pass javascript variables in url?

Do you mean include javascript variable values in the query string of the URL?

Yes:

 window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+var1+"&lon="+var2+"&setLatLon="+varEtc;

Handling back button in Android Navigation Component

A little late to the party, but with the latest release of Navigation Component 1.0.0-alpha09, now we have an AppBarConfiguration.OnNavigateUpListener.

Refer to these links for more information: https://developer.android.com/reference/androidx/navigation/ui/AppBarConfiguration.OnNavigateUpListener https://developer.android.com/jetpack/docs/release-notes

Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?

You need to re-add that certificate to your machine or chose another certificate.

To choose another certificate or to recreate one, head over to the Project's properties page, click on Signing tab and either

  • Click on Select from store
  • Click on Select from file
  • Click on Create test certificate

Once either of these is done, you should be able to build it again.

React.js create loop through Array

As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data with participants.

The alternative to the solution they provided would be to prevent render until participants exist, something like this:

    render: function() {
        if (!this.props.data.participants) {
            return null;
        }
        return (
            <ul className="PlayerList">
            // I'm the Player List {this.props.data}
            // <Player author="The Mini John" />
            {
                this.props.data.participants.map(function(player) {
                    return <li key={player}>{player}</li>
                })
            }
            </ul>
        );
    }

Add carriage return to a string

string s2 = s1.Replace(",", ",\n");

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

Inside the simple_html_dom.php change the value of the $offset variable from -1 to 0. this error usually happens when you migrate to PHP 7.

HtmlDomParser::file_get_html uses a default offset of -1, passing in 0 should fix your problem.

How can you create pop up messages in a batch script?

msg * message goes here

That method is very simple and easy and should work in any batch file i believe. The only "downside" to this method is that it can only show 1 message at once, if there is more than one message it will show each one after the other depending on the order you put them inside the code. Also make sure there is a different looping or continuous operator in your batch file or it will close automatically and only this message will appear. If you need a "quiet" background looping opperator, heres one:

pause >nul

That should keep it running but then it will close after a button is pressed.

Also to keep all the commands "quiet" when running, so they just run and dont display that they were typed into the file, just put the following line at the beginning of the batch file:

@echo off

I hope all these tips helped!

How to convert DateTime to VarChar

For SQL Server 2008+ You can use CONVERT and FORMAT together.

For example, for European style (e.g. Germany) timestamp:

CONVERT(VARCHAR, FORMAT(GETDATE(), 'dd.MM.yyyy HH:mm:ss', 'de-DE'))

Listview Scroll to the end of the list after updating the list

You need to use these parameters in your list view:

  • Scroll lv.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);

  • Set the head of the list to it bottom lv.setStackFromBottom(true);

You can also set these parameters in XML, eg. like this:

<ListView
   ...
   android:transcriptMode="alwaysScroll"
   android:stackFromBottom="true" />

Can I access a form in the controller?

This answer is a little late, but I stumbled upon a solution that makes everything a LOT easier.

You can actually assign the form name directly to your controller if you're using the controllerAs syntax and then reference it from your "this" variable. Here's how I did it in my code:

I configured the controller via ui-router (but you can do it however you want, even in the HTML directly with something like <div ng-controller="someController as myCtrl">) This is what it might look like in a ui-router configuration:

views: {
            "": {
                templateUrl: "someTemplate.html",
                controller: "someController",
                controllerAs: "myCtrl"
            }
       }

and then in the HTML, you just set the form name as the "controllerAs"."name" like so:

<ng-form name="myCtrl.someForm">
    <!-- example form code here -->
    <input name="firstName" ng-model="myCtrl.user.firstName" required>
</ng-form>

now inside your controller you can very simply do this:

angular
.module("something")
.controller("someController",
    [
       "$scope",
        function ($scope) {
            var vm = this;
            if(vm.someForm.$valid){
              // do something
            }
    }]);

How to get param from url in angular 4?

You can try this:

this.activatedRoute.paramMap.subscribe(x => {
    let id = x.get('id');
    console.log(id);  
});

What's the most efficient way to erase duplicates and sort a vector?

std::set<int> s;
std::for_each(v.cbegin(), v.cend(), [&s](int val){s.insert(val);});
v.clear();
std::copy(s.cbegin(), s.cend(), v.cbegin());

How to reference a file for variables using Bash?

The short answer

Use the source command.


An example using source

For example:

config.sh

#!/usr/bin/env bash
production="liveschool_joe"
playschool="playschool_joe"
echo $playschool

script.sh

#!/usr/bin/env bash
source config.sh
echo $production

Note that the output from sh ./script.sh in this example is:

~$ sh ./script.sh 
playschool_joe
liveschool_joe

This is because the source command actually runs the program. Everything in config.sh is executed.


Another way

You could use the built-in export command and getting and setting "environment variables" can also accomplish this.

Running export and echo $ENV should be all you need to know about accessing variables. Accessing environment variables is done the same way as a local variable.

To set them, say:

export variable=value

at the command line. All scripts will be able to access this value.

Undefined reference to vtable

If all else fails, look for duplication. I was misdirected by the explicit initial reference to constructors and destructors until I read a reference in another post. It's any unresolved method. In my case, I thought I had replaced the declaration that used char *xml as the parameter with one using the unnecessarily troublesome const char *xml, but instead, I had created a new one and left the other one in place.

How do I remove/delete a folder that is not empty?

Base on kkubasik's answer, check if folder exists before remove, more robust

import shutil
def remove_folder(path):
    # check if folder exists
    if os.path.exists(path):
         # remove if exists
         shutil.rmtree(path)
    else:
         # throw your exception to handle this special scenario
         raise XXError("your exception") 
remove_folder("/folder_name")

Collections.sort with multiple fields

I suggest to use Java 8 Lambda approach:

List<Report> reportList = new ArrayList<Report>();
reportList.sort(Comparator.comparing(Report::getRecord1).thenComparing(Report::getRecord2));

Can I get image from canvas element and use it in img src tag?

I´ve found two problems with your Fiddle, one of the problems is first in Zeta´s answer.

the method is not toDataUrl(); is toDataURL(); and you forgot to store the canvas in your variable.

So the Fiddle now works fine http://jsfiddle.net/gfyWK/12/

I hope this helps!

$(document).ready not Working

This will happen if the host page is HTTPS and the included javascript source path is HTTP. The two protocols must be the same, HTTPS. The tell tail sign would be to check under Firebug and notice that the JS is "denied access".

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

I would like to suggest another framework: Apache Pivot http://pivot.apache.org/.

I tried it briefly and was impressed by what it can offer as an RIA (Rich Internet Application) framework ala Flash.

It renders UI using Java2D, thus minimizing the impact of (IMO, bloated) legacies of Swing and AWT.

Skip first entry in for loop in python?

Well, your syntax isn't really Python to begin with.

Iterations in Python are over he contents of containers (well, technically it's over iterators), with a syntax for item in container. In this case, the container is the cars list, but you want to skip the first and last elements, so that means cars[1:-1] (python lists are zero-based, negative numbers count from the end, and : is slicing syntax.

So you want

for c in cars[1:-1]:
    do something with c

Bootstrap 3: How do you align column content to bottom of row

When working with bootsrap usually face three main problems:

  1. How to place the content of the column to the bottom?
  2. How to create a multi-row gallery of columns of equal height in one .row?
  3. How to center columns horizontally if their total width is less than 12 and the remaining width is odd?

To solve first two problems download this small plugin https://github.com/codekipple/conformity

The third problem is solved here http://www.minimit.com/articles/solutions-tutorials/bootstrap-3-responsive-centered-columns

Common code

<style>
    [class*=col-] {position: relative}
    .row-conformity .to-bottom {position:absolute; bottom:0; left:0; right:0}
    .row-centered {text-align:center}   
    .row-centered [class*=col-] {display:inline-block; float:none; text-align:left; margin-right:-4px; vertical-align:top} 
</style>

<script src="assets/conformity/conformity.js"></script>
<script>
    $(document).ready(function () {
        $('.row-conformity > [class*=col-]').conformity();
        $(window).on('resize', function() {
            $('.row-conformity > [class*=col-]').conformity();
        });
    });
</script>

1. Aligning content of the column to the bottom

<div class="row row-conformity">
    <div class="col-sm-3">
        I<br>create<br>highest<br>column
    </div>
    <div class="col-sm-3">
        <div class="to-bottom">
            I am on the bottom
        </div>
    </div>
</div>

2. Gallery of columns of equal height

<div class="row row-conformity">
    <div class="col-sm-4">We all have equal height</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
</div>

3. Horizontal alignment of columns to the center (less than 12 col units)

<div class="row row-centered">
    <div class="col-sm-3">...</div>
    <div class="col-sm-4">...</div>
</div>

All classes can work together

<div class="row row-conformity row-centered">
    ...
</div>

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

Reason for me is 2 of following code in one xml

<?xml version="1.0" encoding="utf-8"?>

LogCat message: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included

I also had the same issue. I also tried to look for solutions, but after I didn't find any of the solutions working, I tried to restart my mobile (Android device), and it resolved the issue.

Please give it a try! Restart your mobile device and Eclipse to be on safe side and check if it works.

How to change the Text color of Menu item in Android?

One simple line in your theme :)

<item name="android:actionMenuTextColor">@color/your_color</item>

Why use String.Format?

I can see a number of reasons:

Readability

string s = string.Format("Hey, {0} it is the {1}st day of {2}.  I feel {3}!", _name, _day, _month, _feeling);

vs:

string s = "Hey," + _name + " it is the " + _day + "st day of " + _month + ".  I feel " + feeling + "!";

Format Specifiers (and this includes the fact you can write custom formatters)

string s = string.Format("Invoice number: {0:0000}", _invoiceNum);

vs:

string s = "Invoice Number = " + ("0000" + _invoiceNum).Substr(..... /*can't even be bothered to type it*/)

String Template Persistence

What if I want to store string templates in the database? With string formatting:

_id         _translation
  1         Welcome {0} to {1}.  Today is {2}.
  2         You have {0} products in your basket.
  3         Thank-you for your order.  Your {0} will arrive in {1} working days.

vs:

_id         _translation
  1         Welcome
  2         to
  3         .  Today is
  4         . 
  5         You have
  6         products in your basket.
  7         Someone
  8         just shoot
  9         the developer.

Git: "please tell me who you are" error

git config user.email "insert github email here"
git config user.name "insert github real name here"

This worked great for me.

Filtering a list based on a list of booleans

filtered_list = [list_a[i] for i in range(len(list_a)) if filter[i]]

How to match "any character" in regular expression?

[^] should match any character, including newline. [^CHARS] matches all characters except for those in CHARS. If CHARS is empty, it matches all characters.

JavaScript example:

/a[^]*Z/.test("abcxyz \0\r\n\t012789ABCXYZ") // Returns ‘true’.

How do I use a third-party DLL file in Visual Studio C++?

I'f you're suppsed to be able to use it, then 3rd-party library should have a *.lib file as well as a *.dll file. You simply need to add the *.lib to the list of input file in your project's 'Linker' options.

This *.lib file isn't necessarily a 'static' library (which contains code): instead a *.lib can be just a file that links your executable to the DLL.

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

As kmcamara discovered, this is exactly the kind of problem that VLOOKUP is intended to solve, and using vlookup is arguably the simplest of the alternative ways to get the job done.

In addition to the three parameters for lookup_value, table_range to be searched, and the column_index for return values, VLOOKUP takes an optional fourth argument that the Excel documentation calls the "range_lookup".

Expanding on deathApril's explanation, if this argument is set to TRUE (or 1) or omitted, the table range must be sorted in ascending order of the values in the first column of the range for the function to return what would typically be understood to be the "correct" value. Under this default behavior, the function will return a value based upon an exact match, if one is found, or an approximate match if an exact match is not found.

If the match is approximate, the value that is returned by the function will be based on the next largest value that is less than the lookup_value. For example, if "12AT8003" were missing from the table in Sheet 1, the lookup formulas for that value in Sheet 2 would return '2', since "12AT8002" is the largest value in the lookup column of the table range that is less than "12AT8003". (VLOOKUP's default behavior makes perfect sense if, for example, the goal is to look up rates in a tax table.)

However, if the fourth argument is set to FALSE (or 0), VLOOKUP returns a looked-up value only if there is an exact match, and an error value of #N/A if there is not. It is now the usual practice to wrap an exact VLOOKUP in an IFERROR function in order to catch the no-match gracefully. Prior to the introduction of IFERROR, no matches were checked with an IF function using the VLOOKUP formula once to check whether there was a match, and once to return the actual match value.

Though initially harder to master, deusxmach1na's proposed solution is a variation on a powerful set of alternatives to VLOOKUP that can be used to return values for a column or list to the left of the lookup column, expanded to handle cases where an exact match on more than one criterion is needed, or modified to incorporate OR as well as AND match conditions among multiple criteria.

Repeating kcamara's chosen solution, the VLOOKUP formula for this problem would be:

   =VLOOKUP(A1,Sheet1!A$1:B$600,2,FALSE)

How do you convert a DataTable into a generic list?

DataTable.Select() doesnt give the Rows in the order they were present in the datatable.

If order is important I feel iterating over the datarow collection and forming a List is the right way to go or you could also use overload of DataTable.Select(string filterexpression, string sort).

But this overload may not handle all the ordering (like order by case ...) that SQL provides.

How to get mouse position in jQuery without mouse-events?

Moreover, mousemove events are not triggered if you perform drag'n'drop over a browser window. To track mouse coordinates during drag'n'drop you should attach handler for document.ondragover event and use it's originalEvent property.

Example:

var globalDragOver = function (e)
{
    var original = e.originalEvent;
    if (original)
    {
        window.x = original.pageX;
        window.y = original.pageY;
    }
}

Change keystore password from no password to a non blank password

Add -storepass to keytool arguments.

keytool -storepasswd -storepass '' -keystore mykeystore.jks

But also notice that -list command does not always require a password. I could execute follow command in both cases: without password or with valid password

$JAVA_HOME/bin/keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts

Concatenate columns in Apache Spark DataFrame

We can simple use SelectExpr as well.

df1.selectExpr("*","upper(_2||_3) as new")

How to send parameters with jquery $.get()

This is what worked for me:

$.get({
    method: 'GET',
    url: 'api.php',
    headers: {
        'Content-Type': 'application/json',
    },
    // query parameters go under "data" as an Object
    data: {
        client: 'mikescafe'
    }
});

will make a REST/AJAX call - > GET http://localhost:3000/api.php?client=mikescafe

Good Luck.

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

How to prevent SIGPIPEs (or handle them properly)

I'm super late to the party, but SO_NOSIGPIPE isn't portable, and might not work on your system (it seems to be a BSD thing).

A nice alternative if you're on, say, a Linux system without SO_NOSIGPIPE would be to set the MSG_NOSIGNAL flag on your send(2) call.

Example replacing write(...) by send(...,MSG_NOSIGNAL) (see nobar's comment)

char buf[888];
//write( sockfd, buf, sizeof(buf) );
send(    sockfd, buf, sizeof(buf), MSG_NOSIGNAL );

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

I make it simple, if the layout is same i just put the intent it.

My code like this:

public class RegistrationMenuActivity extends AppCompatActivity implements View.OnClickListener {


    private Button btnCertificate, btnSeminarKit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration_menu);

        initClick();
    }

    private void initClick() {
        btnCertificate = (Button) findViewById(R.id.btn_Certificate);
        btnCertificate.setOnClickListener(this);

        btnSeminarKit = (Button) findViewById(R.id.btn_SeminarKit);
        btnSeminarKit.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_Certificate:
                break;
            case R.id.btn_SeminarKit:
                break;
        }
        Intent intent = new Intent(RegistrationMenuActivity.this, ScanQRCodeActivity.class);
        startActivity(intent);
    }
}

What's the best strategy for unit-testing database-driven applications?

I use the first (running the code against a test database). The only substantive issue I see you raising with this approach is the possibilty of schemas getting out of sync, which I deal with by keeping a version number in my database and making all schema changes via a script which applies the changes for each version increment.

I also make all changes (including to the database schema) against my test environment first, so it ends up being the other way around: After all tests pass, apply the schema updates to the production host. I also keep a separate pair of testing vs. application databases on my development system so that I can verify there that the db upgrade works properly before touching the real production box(es).

PHP Warning: Invalid argument supplied for foreach()

Try this.

if(is_array($value) || is_object($value)){
    foreach($value as $item){
     //somecode
    }
}

Create a simple HTTP server with Java?

I have implemented one link

N.B. for processing json, i used jackson. You can remove that also, if you need

grid controls for ASP.NET MVC?

If it's just for viewing data, I use simple foreach or even aspRepeater. For editing I build specialized views and actions. Didn't like webforms GridView inline edit capabilities anyway, this is kinda much clearer and better - one view for viewing and another for edit/new.

How to format a number as percentage in R?

You can use the scales package just for this operation (without loading it with require or library)

scales::percent(m)

How do you remove an array element in a foreach loop?

If you also get the key, you can delete that item like this:

foreach ($display_related_tags as $key => $tag_name) {
    if($tag_name == $found_tag['name']) {
        unset($display_related_tags[$key]);
    }
}

How to "Open" and "Save" using java

You may also want to consider the possibility of using SWT (another Java GUI library). Pros and cons of each are listed at:

Java Desktop application: SWT vs. Swing

How do I clear inner HTML

Take a look at this. a clean and simple solution using jQuery.

http://jsfiddle.net/ma2Yd/

    <h1 onmouseover="go('The dog is in its shed')" onmouseout="clear()">lalala</h1>
    <div id="goy"></div>


    <script type="text/javascript">

    $(function() {
       $("h1").on('mouseover', function() {
          $("#goy").text('The dog is in its shed');
       }).on('mouseout', function() {
          $("#goy").text("");
       });
   });

Check if input is integer type in C

I developed this logic using gets and away from scanf hassle:

void readValidateInput() {

    char str[10] = { '\0' };

    readStdin: fgets(str, 10, stdin);
    //printf("fgets is returning %s\n", str);

    int numerical = 1;
    int i = 0;

    for (i = 0; i < 10; i++) {
        //printf("Digit at str[%d] is %c\n", i, str[i]);
        //printf("numerical = %d\n", numerical);
        if (isdigit(str[i]) == 0) {
            if (str[i] == '\n')break;
            numerical = 0;
            //printf("numerical changed= %d\n", numerical);
            break;
        }
    }
    if (!numerical) {
        printf("This is not a valid number of tasks, you need to enter at least 1 task\n");
        goto readStdin;
    }
    else if (str[i] == '\n') {
        str[i] = '\0';
        numOfTasks = atoi(str);
        //printf("Captured Number of tasks from stdin is %d\n", numOfTasks);
    }
}

How get data from material-ui TextField, DropDownMenu components?

Add an onChange handler to each of your TextField and DropDownMenu elements. When it is called, save the new value of these inputs in the state of your Content component. In render, retrieve these values from state and pass them as the value prop. See Controlled Components.

var Content = React.createClass({

    getInitialState: function() {
        return {
            textFieldValue: ''
        };
    },

    _handleTextFieldChange: function(e) {
        this.setState({
            textFieldValue: e.target.value
        });
    },

    render: function() {
        return (
            <div>
                <TextField value={this.state.textFieldValue} onChange={this._handleTextFieldChange} />
            </div>
        )
    }

});

Now all you have to do in your _handleClick method is retrieve the values of all your inputs from this.state and send them to the server.

You can also use the React.addons.LinkedStateMixin to make this process easier. See Two-Way Binding Helpers. The previous code becomes:

var Content = React.createClass({

    mixins: [React.addons.LinkedStateMixin],

    getInitialState: function() {
        return {
            textFieldValue: ''
        };
    },

    render: function() {
        return (
            <div>
                <TextField valueLink={this.linkState('textFieldValue')} />
            </div>
        )
    }

});

Install a Windows service using a Windows command prompt?

Follow these steps when deploying the Windows Service, don't lose time:

  1. Run command prompt by the Admin right

  2. Insure about release mode when compilling in your IDE

  3. Give a type to your project installer on design view

  4. Select authentication type in accordance the case

  5. Insure about software dependencies: If you are using a certificate install it correctly

  6. Go your console write this:

    C:\Windows\Microsoft.NET\Framework\yourRecentVersion\installutil.exe c:\yourservice.exe

there is a hidden -i argument before the exe path -i c:\ you can use -u for uninstallling

  1. Look your .exe path to seem log file. You can use event viewer to observing in the feature

How to "properly" create a custom object in JavaScript?

You can also do it this way, using structures :

function createCounter () {
    var count = 0;

    return {
        increaseBy: function(nb) {
            count += nb;
        },
        reset: function {
            count = 0;
        }
    }
}

Then :

var counter1 = createCounter();
counter1.increaseBy(4);

Best way to remove duplicate entries from a data table

There is a simple way using Linq GroupBy Method.

var duplicateValues = dt.AsEnumerable() 

        .GroupBy(row => row[0]) 

        .Where(group => (group.Count() == 1 || group.Count() > 1)) 

        .Select(g => g.Key); 



foreach (var d in duplicateValues)

        Console.WriteLine(d);

Embedding SVG into ReactJS

Update 2016-05-27

As of React v15, support for SVG in React is (close to?) 100% parity with current browser support for SVG (source). You just need to apply some syntax transformations to make it JSX compatible, like you already have to do for HTML (class ? className, style="color: purple" ? style={{color: 'purple'}}). For any namespaced (colon-separated) attribute, e.g. xlink:href, remove the : and capitalize the second part of the attribute, e.g. xlinkHref. Here’s an example of an svg with <defs>, <use>, and inline styles:

function SvgWithXlink (props) {
    return (
        <svg
            width="100%"
            height="100%"
            xmlns="http://www.w3.org/2000/svg"
            xmlnsXlink="http://www.w3.org/1999/xlink"
        >
            <style>
                { `.classA { fill:${props.fill} }` }
            </style>
            <defs>
                <g id="Port">
                    <circle style={{fill:'inherit'}} r="10"/>
                </g>
            </defs>

            <text y="15">black</text>
            <use x="70" y="10" xlinkHref="#Port" />
            <text y="35">{ props.fill }</text>
            <use x="70" y="30" xlinkHref="#Port" className="classA"/>
            <text y="55">blue</text>
            <use x="0" y="50" xlinkHref="#Port" style={{fill:'blue'}}/>
        </svg>
    );
}

Working codepen demo

For more details on specific support, check the docs’ list of supported SVG attributes. And here’s the (now closed) GitHub issue that tracked support for namespaced SVG attributes.


Previous answer

You can do a simple SVG embed without having to use dangerouslySetInnerHTML by just stripping the namespace attributes. For example, this works:

        render: function() {
            return (
                <svg viewBox="0 0 120 120">
                    <circle cx="60" cy="60" r="50"/>
                </svg>
            );
        }

At which point you can think about adding props like fill, or whatever else might be useful to configure.

dynamic_cast and static_cast in C++

More than code in C, I think that an english definition could be enough:

Given a class Base of which there is a derived class Derived, dynamic_cast will convert a Base pointer to a Derived pointer if and only if the actual object pointed at is in fact a Derived object.

class Base { virtual ~Base() {} };
class Derived : public Base {};
class Derived2 : public Base {};
class ReDerived : public Derived {};

void test( Base & base )
{
   dynamic_cast<Derived&>(base);
}

int main() {
   Base b;
   Derived d;
   Derived2 d2;
   ReDerived rd;

   test( b );   // throw: b is not a Derived object
   test( d );   // ok
   test( d2 );  // throw: d2 is not a Derived object
   test( rd );  // ok: rd is a ReDerived, and thus a derived object
}

In the example, the call to test binds different objects to a reference to Base. Internally the reference is downcasted to a reference to Derived in a typesafe way: the downcast will succeed only for those cases where the referenced object is indeed an instance of Derived.

How do I read the file content from the Internal storage - Android App

For others looking for an answer to why a file is not readable especially on a sdcard, write the file like this first.. Notice the MODE_WORLD_READABLE

try {
            FileOutputStream fos = Main.this.openFileOutput("exported_data.csv", MODE_WORLD_READABLE);
            fos.write(csv.getBytes());
            fos.close();
            File file = Main.this.getFileStreamPath("exported_data.csv");
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

Does Go have "if x in" construct similar to Python?

Another option is using a map as a set. You use just the keys and having the value be something like a boolean that's always true. Then you can easily check if the map contains the key or not. This is useful if you need the behavior of a set, where if you add a value multiple times it's only in the set once.

Here's a simple example where I add random numbers as keys to a map. If the same number is generated more than once it doesn't matter, it will only appear in the final map once. Then I use a simple if check to see if a key is in the map or not.

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    var MAX int = 10

    m := make(map[int]bool)

    for i := 0; i <= MAX; i++ {
        m[rand.Intn(MAX)] = true
    }

    for i := 0; i <= MAX; i++ {
        if _, ok := m[i]; ok {
            fmt.Printf("%v is in map\n", i)
        } else {
            fmt.Printf("%v is not in map\n", i)
        }
    }
}

Here it is on the go playground

PHP: Call to undefined function: simplexml_load_string()

I think it can be something like in this Post: Class 'SimpleXMLElement' not found on puphpet PHP 5.6 So maybe you could install/activate

php-xml or php-simplexml

Do not forget to activate the libraries in the php.ini file. (like the top comment)

How to refresh the data in a jqGrid?

Try this to reload jqGrid with new data

jQuery("#grid").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid');

How to add an existing folder with files to SVN?

In Windows 7 I did this:

  1. Have you installed SVN and Tortoise SVN? If not, Google them and do so now.
  2. Go to your SVN folder where you may have other repos (short for repository) (or if you're creating one from scratch, choose a location C drive, D drive, etc or network path).
  3. Create a new folder to store your new repository. Call it the same name as your project title
  4. Right click the folder and choose Tortoise SVN -> Create Repository here
  5. Say yes to Create Folder Structure
  6. Click OK. You should see a new icon looking like a "wave" next to your new folder/repo
  7. Right Click the new repo and choose SVN Repo Browser
  8. Right click 'trunk'
  9. Choose ADD Folder... and point to your folder structure of your project in development.
  10. Click OK and SVN will ADD your folder structure in. Be patient! It looks like SVN has crashed/frozen. Don't worry. It's doing its work.

Done!

jQuery: Can I call delay() between addClass() and such?

I know this this is a very old post but I've combined a few of the answers into a jQuery wrapper function that supports chaining. Hope it benefits someone:

$.fn.queueAddClass = function(className) {
    this.queue('fx', function(next) {
        $(this).addClass(className);
        next();
    });
    return this;
};

And here's a removeClass wrapper:

$.fn.queueRemoveClass = function(className) {
    this.queue('fx', function(next) {
        $(this).removeClass(className);
        next();
    });
    return this;
};

Now you can do stuff like this - wait 1sec, add .error, wait 3secs, remove .error:

$('#div').delay(1000).queueAddClass('error').delay(2000).queueRemoveClass('error');

Bind class toggle to window scroll event

Why do you all suggest heavy scope operations? I don't see why this is not an "angular" solution:

.directive('changeClassOnScroll', function ($window) {
  return {
    restrict: 'A',
    scope: {
        offset: "@",
        scrollClass: "@"
    },
    link: function(scope, element) {
        angular.element($window).bind("scroll", function() {
            if (this.pageYOffset >= parseInt(scope.offset)) {
                element.addClass(scope.scrollClass);
            } else {
                element.removeClass(scope.scrollClass);
            }
        });
    }
  };
})

So you can use it like this:

<navbar change-class-on-scroll offset="500" scroll-class="you-have-scrolled-down"></navbar>

or

<div change-class-on-scroll offset="500" scroll-class="you-have-scrolled-down"></div>

Creating a border like this using :before And :after Pseudo-Elements In CSS?

See the following snippet, is this what you want?

_x000D_
_x000D_
body {
    background: silver;
    padding: 0 10px;
}

#content:after {
    height: 10px;
    display: block;
    width: 100px;
    background: #808080;
    border-right: 1px white;
    content: '';
}

#footer:before {
    display: block;
    content: '';
    background: silver;
    height: 10px;
    margin-top: -20px;
    margin-left: 101px;
}

#content {
    background: white;
}


#footer {
    padding-top: 10px;
    background: #404040;
}

p {
    padding: 100px;
    text-align: center;
}

#footer p {
    color: white;
}
_x000D_
<body>
    <div id="content"><p>#content</p></div>
    <div id="footer"><p>#footer</p></div>
</body>
_x000D_
_x000D_
_x000D_

JSFiddle

Get Image Height and Width as integer values?

Try like this:

list($width, $height) = getimagesize('path_to_image');

Make sure that:

  1. You specify the correct image path there
  2. The image has read access
  3. Chmod image dir to 755

Also try to prefix path with $_SERVER["DOCUMENT_ROOT"], this helps sometimes when you are not able to read files.

How can I find the length of a number?

You should go for the simplest one (stringLength), readability always beats speed. But if you care about speed here are some below.

Three different methods all with varying speed.

// 34ms
let weissteinLength = function(n) { 
    return (Math.log(Math.abs(n)+1) * 0.43429448190325176 | 0) + 1;
}

// 350ms
let stringLength = function(n) {
    return n.toString().length;
}

// 58ms
let mathLength = function(n) {
    return Math.ceil(Math.log(n + 1) / Math.LN10);
}

// Simple tests below if you care about performance.

let iterations = 1000000;
let maxSize = 10000;

// ------ Weisstein length.

console.log("Starting weissteinLength length.");
let startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    weissteinLength(Math.random() * maxSize);
}

console.log("Ended weissteinLength length. Took : " + (Date.now() - startTime ) + "ms");


// ------- String length slowest.

console.log("Starting string length.");
startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    stringLength(Math.random() * maxSize);
}

console.log("Ended string length. Took : " + (Date.now() - startTime ) + "ms");


// ------- Math length.

console.log("Starting math length.");
startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    mathLength(Math.random() * maxSize);
}

How to temporarily exit Vim and go back

You can switch to shell mode temporarily by:

:! <command>

such as

:! ls

Convert integer to string Jinja

The OP needed to cast as string outside the {% set ... %}. But if that not your case you can do:

{% set curYear = 2013 | string() %}

Note that you need the parenthesis on that jinja filter.

If you're concatenating 2 variables, you can also use the ~ custom operator.

Python list subtraction operation

The other solutions have one of a few problems:

  1. They don't preserve order, or
  2. They don't remove a precise count of elements, e.g. for x = [1, 2, 2, 2] and y = [2, 2] they convert y to a set, and either remove all matching elements (leaving [1] only) or remove one of each unique element (leaving [1, 2, 2]), when the proper behavior would be to remove 2 twice, leaving [1, 2], or
  3. They do O(m * n) work, where an optimal solution can do O(m + n) work

Alain was on the right track with Counter to solve #2 and #3, but that solution will lose ordering. The solution that preserves order (removing the first n copies of each value for n repetitions in the list of values to remove) is:

from collections import Counter

x = [1,2,3,4,3,2,1]  
y = [1,2,2]  
remaining = Counter(y)

out = []
for val in x:
    if remaining[val]:
        remaining[val] -= 1
    else:
        out.append(val)
# out is now [3, 4, 3, 1], having removed the first 1 and both 2s.

Try it online!

To make it remove the last copies of each element, just change the for loop to for val in reversed(x): and add out.reverse() immediately after exiting the for loop.

Constructing the Counter is O(n) in terms of y's length, iterating x is O(n) in terms of x's length, and Counter membership testing and mutation are O(1), while list.append is amortized O(1) (a given append can be O(n), but for many appends, the overall big-O averages O(1) since fewer and fewer of them require a reallocation), so the overall work done is O(m + n).

You can also test for to determine if there were any elements in y that were not removed from x by testing:

remaining = +remaining  # Removes all keys with zero counts from Counter
if remaining:
    # remaining contained elements with non-zero counts

UL or DIV vertical scrollbar

Sometimes it is not eligible to set height to pixel values. However, it is possible to show vertical scrollbar through setting height of div to 100% and overflow to auto.

Let me show an example:

<div id="content" style="height: 100%; overflow: auto">
  <p>some text</p>
  <ul>
    <li>text</li>
    .....
    <li>text</li>
</div>

IE 8: background-size fix

As posted by 'Dan' in a similar thread, there is a possible fix if you're not using a sprite:

How do I make background-size work in IE?

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale');

-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale')";

However, this scales the entire image to fit in the allocated area. So if your using a sprite, this may cause issues.

Caution
The filter has a flaw, any links inside the allocated area are no longer clickable.

How can I convert a Word document to PDF?

unoconv, it's a python tool worked in UNIX. While I use Java to invoke the shell in UNIX, it works perfect for me. My source code : UnoconvTool.java. Both JODConverter and unoconv are said to use open office/libre office.

docx4j/docxreport, POI, PDFBox are good but they are missing some formats in conversion.

Convert a list to a dictionary in Python

Simple answer

Another option (courtesy of Alex Martelli - source):

dict(x[i:i+2] for i in range(0, len(x), 2))

Related note

If you have this:

a = ['bi','double','duo','two']

and you want this (each element of the list keying a given value (2 in this case)):

{'bi':2,'double':2,'duo':2,'two':2}

you can use:

>>> dict((k,2) for k in a)
{'double': 2, 'bi': 2, 'two': 2, 'duo': 2}

Android ListView Text Color

  1. Create a styles file, for example: my_styles.xml and save it in res/values.
  2. Add the following code:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
    <style name="ListFont" parent="@android:style/Widget.ListView">
        <item name="android:textColor">#FF0000</item>
        <item name="android:typeface">sans</item>
    </style>
    
    </resources>
    
  3. Add your style to your Activity definition in your AndroidManifest.xml as an android:theme attribute, and assign as value the name of the style you created. For example:

    <activity android:name="your.activityClass" android:theme="@style/ListFont">
    

NOTE: the Widget.ListView comes from here. Also check this.

converting json to string in python

There are other differences. For instance, {'time': datetime.now()} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).

What does value & 0xff do in Java?

It sets result to the (unsigned) value resulting from putting the 8 bits of value in the lowest 8 bits of result.

The reason something like this is necessary is that byte is a signed type in Java. If you just wrote:

int result = value;

then result would end up with the value ff ff ff fe instead of 00 00 00 fe. A further subtlety is that the & is defined to operate only on int values1, so what happens is:

  1. value is promoted to an int (ff ff ff fe).
  2. 0xff is an int literal (00 00 00 ff).
  3. The & is applied to yield the desired value for result.

(The point is that conversion to int happens before the & operator is applied.)

1Well, not quite. The & operator works on long values as well, if either operand is a long. But not on byte. See the Java Language Specification, sections 15.22.1 and 5.6.2.

How to properly URL encode a string in PHP?

For the URI query use urlencode/urldecode; for anything else use rawurlencode/rawurldecode.

The difference between urlencode and rawurlencode is that

How can I check whether a radio button is selected with JavaScript?

This would be valid for radio buttons sharing the same name, no JQuery needed.

var x = Array.prototype.filter.call(document.getElementsByName('checkThing'), function(x) { return x.checked })[0];

If we are talking about checkboxes and we want a list with the checkboxes checked sharing a name:

var x = Array.prototype.filter.call(document.getElementsByName('checkThing'), function(x) { return x.checked });

PHP - Get key name of array value

If you have a value and want to find the key, use array_search() like this:

$arr = array ('first' => 'a', 'second' => 'b', );
$key = array_search ('a', $arr);

$key will now contain the key for value 'a' (that is, 'first').

Convert Java object to XML string

Using ByteArrayOutputStream

public static String printObjectToXML(final Object object) throws TransformerFactoryConfigurationError,
        TransformerConfigurationException, SOAPException, TransformerException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEncoder xmlEncoder = new XMLEncoder(baos);
    xmlEncoder.writeObject(object);
    xmlEncoder.close();

    String xml = baos.toString();
    System.out.println(xml);

    return xml.toString();
}

Get file version in PowerShell

I find this useful:

function Get-Version($filePath)
{
   $name = @{Name="Name";Expression= {split-path -leaf $_.FileName}}
   $path = @{Name="Path";Expression= {split-path $_.FileName}}
   dir -recurse -path $filePath | % { if ($_.Name -match "(.*dll|.*exe)$") {$_.VersionInfo}} | select FileVersion, $name, $path
}

Div 100% height works on Firefox but not in IE

I don't think IE supports the use of auto for setting height / width, so you could try giving this a numeric value (like Jarett suggests).

Also, it doesn't look like you are clearing your floats properly. Try adding this to your CSS for #container:

#container {
    height:100%;
    width:100%;
    overflow:hidden;
    /* for IE */
    zoom:1;
}

How to insert date values into table

I simply wrote an embedded SQL program to write a new record with date fields. It was by far best and shortest without any errors I was able to reach my requirement.

_x000D_
_x000D_
w_dob = %char(%date(*date));      
exec sql insert into Tablename (ID_Number     , 
                             AmendmentNo   , 
                             OverrideDate  , 
                             Operator      , 
                             Text_ID       , 
                             Policy_Company, 
                             Policy_Number , 
                             Override      , 
                             CREATE_USER   ) 
                values ( '801010',    
                            1,            
                           :w_dob,      
                           'MYUSER',     
                            ' ',         
                            '01',        
                            '6535435023150', 
                            '1',         
                            'myuser');    
_x000D_
_x000D_
_x000D_

ALTER TABLE DROP COLUMN failed because one or more objects access this column

The @SqlZim's answer is correct but just to explain why this possibly have happened. I've had similar issue and this was caused by very innocent thing: adding default value to a column

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int DEFAULT NULL;

But in the realm of MS SQL Server a default value on a colum is a CONSTRAINT. And like every constraint it has an identifier. And you cannot drop a column if it is used in a CONSTRAINT.

So what you can actually do avoid this kind of problems is always give your default constraints a explicit name, for example:

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int NULL,
  CONSTRAINT DF_MyTable_MyColumn DEFAULT NULL FOR MyColumn;

You'll still have to drop the constraint before dropping the column, but you will at least know its name up front.

How to Install Windows Phone 8 SDK on Windows 7

Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator

And another link here

AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).

Convert UIImage to NSData and convert back to UIImage in Swift?

Use imageWithData: method, which gets translated to Swift as UIImage(data:)

let image : UIImage = UIImage(data: imageData)

$apply already in progress error

We can use setTimeout function in such cases.

console.log('primary task');

setTimeout(function() {
  
  console.log('secondary task');

}, 0);

This will make sure that secondary task will be executed when execution of primary task is finished.

git checkout master error: the following untracked working tree files would be overwritten by checkout

With Git 2.23 (August 2019), that would be, using git switch -f:

git switch -f master

That avoids the confusion with git checkout (which deals with files or branches).

And that will proceeds, even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
If --recurse-submodules is specified, submodule content is also restored to match the switching target.
This is used to throw away local changes.

Where do I put my php files to have Xampp parse them?

The default location to put all the web projects in ubuntu with LAMPP is :

 /var/www/

You may make symbolic link to public_html directory from this directory.Refered. Hope this is helpful.

What is Node.js' Connect, Express and "middleware"?

Node.js itself offers an HTTP module, whose createServer method returns an object that you can use to respond to HTTP requests. That object inherits the http.Server prototype.

Get user location by IP address

Use http://ipinfo.io , You need to pay them if you make more than 1000 requests per day.

The code below requires the Json.NET package.

public static string GetUserCountryByIp(string ip)
{
    IpInfo ipInfo = new IpInfo();
    try
    {
        string info = new WebClient().DownloadString("http://ipinfo.io/" + ip);
        ipInfo = JsonConvert.DeserializeObject<IpInfo>(info);
        RegionInfo myRI1 = new RegionInfo(ipInfo.Country);
        ipInfo.Country = myRI1.EnglishName;
    }
    catch (Exception)
    {
        ipInfo.Country = null;
    }
    
    return ipInfo.Country;
}

And the IpInfo Class I used:

public class IpInfo
{
    [JsonProperty("ip")]
    public string Ip { get; set; }

    [JsonProperty("hostname")]
    public string Hostname { get; set; }

    [JsonProperty("city")]
    public string City { get; set; }

    [JsonProperty("region")]
    public string Region { get; set; }

    [JsonProperty("country")]
    public string Country { get; set; }

    [JsonProperty("loc")]
    public string Loc { get; set; }

    [JsonProperty("org")]
    public string Org { get; set; }

    [JsonProperty("postal")]
    public string Postal { get; set; }
}

JavaScript for detecting browser language preference

I came across this piece of code to detect browser's language in Angular Translate module, which you can find the source here. I slightly modified the code by replacing angular.isArray with Array.isArray to make it independent of Angular library.

_x000D_
_x000D_
var getFirstBrowserLanguage = function () {_x000D_
    var nav = window.navigator,_x000D_
    browserLanguagePropertyKeys = ['language', 'browserLanguage', 'systemLanguage', 'userLanguage'],_x000D_
    i,_x000D_
    language;_x000D_
_x000D_
    // support for HTML 5.1 "navigator.languages"_x000D_
    if (Array.isArray(nav.languages)) {_x000D_
      for (i = 0; i < nav.languages.length; i++) {_x000D_
        language = nav.languages[i];_x000D_
        if (language && language.length) {_x000D_
          return language;_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
_x000D_
    // support for other well known properties in browsers_x000D_
    for (i = 0; i < browserLanguagePropertyKeys.length; i++) {_x000D_
      language = nav[browserLanguagePropertyKeys[i]];_x000D_
      if (language && language.length) {_x000D_
        return language;_x000D_
      }_x000D_
    }_x000D_
_x000D_
    return null;_x000D_
  };_x000D_
_x000D_
console.log(getFirstBrowserLanguage());
_x000D_
_x000D_
_x000D_

Trimming text strings in SQL Server 2008

You can use the RTrim function to trim all whitespace from the right. Use LTrim to trim all whitespace from the left. For example

UPDATE Table SET Name = RTrim(Name)

Or for both left and right trim

UPDATE Table SET Name = LTrim(RTrim(Name))

ab load testing

Load testing your API by using just ab is not enough. However, I think it's a great tool to give you a basic idea how your site is performant.

If you want to use the ab command in to test multiple API endpoints, with different data, all at the same time in background, you need to use "nohup" command. It runs any command even when you close the terminal.

I wrote a simple script that automates the whole process, feel free to use it: http://blog.ikvasnica.com/entry/load-test-multiple-api-endpoints-concurrently-use-this-simple-shell-script

Javascript communication between browser tabs/windows

I don't think you need cookies. Each document's js code can access the other document elements. So you can use them directly to share data. Your first window w1 opens w2 and save the reference

var w2 = window.open(...) 

In w2 you can access w1 using the opener property of window.

Swift Beta performance: sorting arrays

Swift 4.1 introduces new -Osize optimization mode.

In Swift 4.1 the compiler now supports a new optimization mode which enables dedicated optimizations to reduce code size.

The Swift compiler comes with powerful optimizations. When compiling with -O the compiler tries to transform the code so that it executes with maximum performance. However, this improvement in runtime performance can sometimes come with a tradeoff of increased code size. With the new -Osize optimization mode the user has the choice to compile for minimal code size rather than for maximum speed.

To enable the size optimization mode on the command line, use -Osize instead of -O.

Further reading : https://swift.org/blog/osize/

Nesting await in Parallel.ForEach

After introducing a bunch of helper methods, you will be able run parallel queries with this simple syntax:

const int DegreeOfParallelism = 10;
IEnumerable<double> result = await Enumerable.Range(0, 1000000)
    .Split(DegreeOfParallelism)
    .SelectManyAsync(async i => await CalculateAsync(i).ConfigureAwait(false))
    .ConfigureAwait(false);

What happens here is: we split source collection into 10 chunks (.Split(DegreeOfParallelism)), then run 10 tasks each processing its items one by one (.SelectManyAsync(...)) and merge those back into a single list.

Worth mentioning there is a simpler approach:

double[] result2 = await Enumerable.Range(0, 1000000)
    .Select(async i => await CalculateAsync(i).ConfigureAwait(false))
    .WhenAll()
    .ConfigureAwait(false);

But it needs a precaution: if you have a source collection that is too big, it will schedule a Task for every item right away, which may cause significant performance hits.

Extension methods used in examples above look as follows:

public static class CollectionExtensions
{
    /// <summary>
    /// Splits collection into number of collections of nearly equal size.
    /// </summary>
    public static IEnumerable<List<T>> Split<T>(this IEnumerable<T> src, int slicesCount)
    {
        if (slicesCount <= 0) throw new ArgumentOutOfRangeException(nameof(slicesCount));

        List<T> source = src.ToList();
        var sourceIndex = 0;
        for (var targetIndex = 0; targetIndex < slicesCount; targetIndex++)
        {
            var list = new List<T>();
            int itemsLeft = source.Count - targetIndex;
            while (slicesCount * list.Count < itemsLeft)
            {
                list.Add(source[sourceIndex++]);
            }

            yield return list;
        }
    }

    /// <summary>
    /// Takes collection of collections, projects those in parallel and merges results.
    /// </summary>
    public static async Task<IEnumerable<TResult>> SelectManyAsync<T, TResult>(
        this IEnumerable<IEnumerable<T>> source,
        Func<T, Task<TResult>> func)
    {
        List<TResult>[] slices = await source
            .Select(async slice => await slice.SelectListAsync(func).ConfigureAwait(false))
            .WhenAll()
            .ConfigureAwait(false);
        return slices.SelectMany(s => s);
    }

    /// <summary>Runs selector and awaits results.</summary>
    public static async Task<List<TResult>> SelectListAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> selector)
    {
        List<TResult> result = new List<TResult>();
        foreach (TSource source1 in source)
        {
            TResult result1 = await selector(source1).ConfigureAwait(false);
            result.Add(result1);
        }
        return result;
    }

    /// <summary>Wraps tasks with Task.WhenAll.</summary>
    public static Task<TResult[]> WhenAll<TResult>(this IEnumerable<Task<TResult>> source)
    {
        return Task.WhenAll<TResult>(source);
    }
}

Why do I need an IoC container as opposed to straightforward DI code?

Presumably no one is forcing you to use a DI container framework. You're already using DI to decouple your classes and improve testability, so you're getting many of the benefits. In short, you're favoring simplicity, which is generally a good thing.

If your system reaches a level of complexity where manual DI becomes a chore (that is, increases maintenance), weigh that against the team learning curve of a DI container framework.

If you need more control over dependency lifetime management (that is, if you feel the need to implement the Singleton pattern), look at DI containers.

If you use a DI container, use only the features you need. Skip the XML configuration file and configure it in code if that is sufficient. Stick to constructor injection. The basics of Unity or StructureMap can be condensed down to a couple of pages.

There's a great blog post by Mark Seemann on this: When to use a DI Container

Updating Python on Mac

I wanted to achieve the same today. The Mac with Snow Leopard comes with Python 2.6.1 version.

Since multiple Python versions can coexist, I downloaded Python 3.2.3 from: http://www.python.org/getit/

After installation the newer Python will be available under the Application folder and the IDE there uses 3.2.3 version of Python.

From the shell, python3 works with the newer version. That serves the purpose :)

Effectively use async/await with ASP.NET Web API

You are not leveraging async / await effectively because the request thread will be blocked while executing the synchronous method ReturnAllCountries()

The thread that is assigned to handle a request will be idly waiting while ReturnAllCountries() does it's work.

If you can implement ReturnAllCountries() to be asynchronous, then you would see scalability benefits. This is because the thread could be released back to the .NET thread pool to handle another request, while ReturnAllCountries() is executing. This would allow your service to have higher throughput, by utilizing threads more efficiently.

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

I researched on the internet and some answers includes enabling the "access for lesser app" and "unlocking gmail captcha" which sadly didn't work for me until I found the 2-step verification.

What I did the following was:

  1. enable the 2-step verification to google HERE

  2. Create App Password to be use by your system HERE

  3. I selected Others (custom name) and clicked generate

  4. Went to my env file in laravel and edited this

    [email protected]

    MAIL_PASSWORD=thepasswordgenerated

  5. Restarted my apache server and boom! It works again.

This was my solution. I created this to atleast make other people not go wasting their time researching for a possible answer.

Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

In iOS 10 beta 4.The right code in HTML5 is

<video src="file.mp4" webkit-playsinline="true" playsinline="true">

webkit-playsinline is for iOS < 10, and playsinline is for iOS >= 10

See details via https://webkit.org/blog/6784/new-video-policies-for-ios/

How to create a global variable?

if you want to use it in all of your classes you can use:

public var yourVariable = "something"

if you want to use just in one class you can use :

var yourVariable = "something"

How to add an Access-Control-Allow-Origin header

According to the official docs, browsers do not like it when you use the

Access-Control-Allow-Origin: "*"

header if you're also using the

Access-Control-Allow-Credentials: "true"

header. Instead, they want you to allow their origin specifically. If you still want to allow all origins, you can do some simple Apache magic to get it to work (make sure you have mod_headers enabled):

Header set Access-Control-Allow-Origin "%{HTTP_ORIGIN}e" env=HTTP_ORIGIN

Browsers are required to send the Origin header on all cross-domain requests. The docs specifically state that you need to echo this header back in the Access-Control-Allow-Origin header if you are accepting/planning on accepting the request. That's what this Header directive is doing.

Remove Backslashes from Json Data in JavaScript

Your string is invalid, but assuming it was valid, you'd have to do:

var finalData = str.replace(/\\/g, "");

When you want to replace all the occurences with .replace, the first parameter must be a regex, if you supply a string, only the first occurrence will be replaced, that's why your replace wouldn't work.

Cheers

Run certain code every n seconds

Here's a version that doesn't create a new thread every n seconds:

from threading import Event, Thread

def call_repeatedly(interval, func, *args):
    stopped = Event()
    def loop():
        while not stopped.wait(interval): # the first call is in `interval` secs
            func(*args)
    Thread(target=loop).start()    
    return stopped.set

The event is used to stop the repetitions:

cancel_future_calls = call_repeatedly(5, print, "Hello, World")
# do something else here...
cancel_future_calls() # stop future calls

See Improve current implementation of a setInterval python

Tomcat 7: How to set initial heap size correctly?

It works even without using 'export' keyword. This is what i have in my setenv.sh (/usr/share/tomcat7/bin/setenv.sh) and it works.

OS : 14.04.1-Ubuntu Server version: Apache Tomcat/7.0.52 (Ubuntu) Server built: Jun 30 2016 01:59:37 Server number: 7.0.52.0

JAVA_OPTS="-Dorg.apache.catalina.security.SecurityListener.UMASK=`umask` -server -Xms6G -Xmx6G -Xmn1400m -XX:HeapDumpPath=/Some/logs/ -XX:+HeapDumpOnOutOfMemoryError -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:SurvivorRatio=8 -XX:+UseCompressedOops -Dcom.sun.management.jmxremote.port=8181 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"
JAVA_OPTS="$JAVA_OPTS -Dserver.name=$HOSTNAME"

Error: «Could not load type MvcApplication»

I get this problem everytime i save a file that gets dynamically compiled (ascx, aspx etc). I wait about 8-10 seconds then it goes away. It's hellishly annoying.

I thought it was perhaps an IIS Express problem so I tried in the inbuilt dev server and am still receiving it after saving a file. I'm running an MVC app, i'm also using T4MVC, maybe that is a factor...

How to convert std::string to LPCSTR?

Converting is simple:

std::string myString;

LPCSTR lpMyString = myString.c_str();

One thing to be careful of here is that c_str does not return a copy of myString, but just a pointer to the character string that std::string wraps. If you want/need a copy you'll need to make one yourself using strcpy.

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

You probably need an inner div. With css is:

.fixed {
   position: fixed;
   top: 0;
   left: 0;
   bottom: 0;
   overflow-y: auto;
   width: 200px; // your value
}
.inner {
   min-height: 100%;
}

In vb.net, how to get the column names from a datatable

You can loop through the columns collection of the datatable.

VB

Dim dt As New DataTable()
For Each column As DataColumn In dt.Columns
    Console.WriteLine(column.ColumnName)
Next

C#

DataTable dt = new DataTable();
foreach (DataColumn column in dt.Columns)
{
Console.WriteLine(column.ColumnName);
}

Hope this helps!

Two submit buttons in one form

You can also do it like this (I think it's very convenient if you have N inputs).

<input type="submit" name="row[456]" value="something">
<input type="submit" name="row[123]" value="something">
<input type="submit" name="row[789]" value="something">

A common use case would be using different ids from a database for each button, so you could later know in the server wich row was clicked.

In the server side (PHP in this example) you can read "row" as an array to get the id. $_POST['row'] will be an array with just one element, in the form [ id => value ] (for example: [ '123' => 'something' ]).

So, in order to get the clicked id, you do:

$index = key($_POST['row']);

http://php.net/manual/en/function.key.php

Fixing the order of facets in ggplot

Make your size a factor in your dataframe by:

temp$size_f = factor(temp$size, levels=c('50%','100%','150%','200%'))

Then change the facet_grid(.~size) to facet_grid(.~size_f)

Then plot: enter image description here

The graphs are now in the correct order.

Enable binary mode while restoring a Database from an SQL dump

Have you tried opening in notepad++ (or another editor) and converting/saving us to UTF-8?

See: notepad++ converting ansi encoded file to utf-8

Another option may be to use textwrangle to open and save the file as UTF-8: http://www.barebones.com/products/textwrangler/

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

Get UTC time in seconds

You say you're using:

time.asctime(time.localtime(date_in_seconds_from_bash))

where date_in_seconds_from_bash is presumably the output of date +%s.

The time.localtime function, as the name implies, gives you local time.

If you want UTC, use time.gmtime() rather than time.localtime().

As JamesNoonan33's answer says, the output of date +%s is timezone invariant, so date +%s is exactly equivalent to date -u %s. It prints the number of seconds since the "epoch", which is 1970-01-01 00:00:00 UTC. The output you show in your question is entirely consistent with that:

date -u
Thu Jul 3 07:28:20 UTC 2014

date +%s
1404372514   # 14 seconds after "date -u" command

date -u +%s
1404372515   # 15 seconds after "date -u" command

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP 2.0 is a binary protocol that multiplexes numerous streams going over a single (normally TLS-encrypted) TCP connection.

The contents of each stream are HTTP 1.1 requests and responses, just encoded and packed up differently. HTTP2 adds a number of features to manage the streams, but leaves old semantics untouched.

What is the best way to determine a session variable is null or empty in C#?

Typically I create SessionProxy with strongly typed properties for items in the session. The code that accesses these properties checks for nullity and does the casting to the proper type. The nice thing about this is that all of my session related items are kept in one place. I don't have to worry about using different keys in different parts of the code (and wondering why it doesn't work). And with dependency injection and mocking I can fully test it with unit tests. If follows DRY principles and also lets me define reasonable defaults.

public class SessionProxy
{
    private HttpSessionState session; // use dependency injection for testability
    public SessionProxy( HttpSessionState session )
    {
       this.session = session;  //might need to throw an exception here if session is null
    }

    public DateTime LastUpdate
    {
       get { return this.session["LastUpdate"] != null
                         ? (DateTime)this.session["LastUpdate"] 
                         : DateTime.MinValue; }
       set { this.session["LastUpdate"] = value; }
    }

    public string UserLastName
    {
       get { return (string)this.session["UserLastName"]; }
       set { this.session["UserLastName"] = value; }
    }
}

How to remove entry from $PATH on mac

Close the terminal(End the current session). Open it again.

How do I grant read access for a user to a database in SQL Server?

This is a two-step process:

  1. you need to create a login to SQL Server for that user, based on its Windows account

    CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
    
  2. you need to grant this login permission to access a database:

    USE (your database)
    CREATE USER (username) FOR LOGIN (your login name)
    

Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader database role to read all tables.

USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'

Counting in a FOR loop using Windows Batch script

It's not working because the entire for loop (from the for to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.

In other words, %count% is replaced with its value 1 before running the loop.

What you need is something like:

setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
  set /a count += 1
  echo !count!
)
endlocal

Delayed expansion using ! instead of % will give you the expected behaviour. See also here.


Also keep in mind that setlocal/endlocal actually limit scope of things changed inside so that they don't leak out. If you want to use count after the endlocal, you have to use a "trick" made possible by the very problem you're having:

endlocal && set count=%count%

Let's say count has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:

endlocal && set count=7

Then, when it's executed, the inner scope is closed off, returning count to it's original value. But, since the setting of count to seven happens in the outer scope, it's effectively leaking the information you need.

You can string together multiple sub-commands to leak as much information as you need:

endlocal && set count=%count% && set something_else=%something_else%

How can I install Python's pip3 on my Mac?

After upgrading to macOS v10.15 (Catalina), and upgrading all my vEnv modules, pip3 stopped working (gave error: "TypeError: 'module' object is not callable").

I found question 58386953 which led to here and solution.

  1. Exit from the vEnv (I started a fresh shell)
  2. sudo python3 -m pip uninstall pip (this is necessary, but it did not fix problem, because it removed the base Python pip, but it didn't touch my vEnv pip)
  3. sudo easy_install pip (reinstalling pip in base Python, not in vEnv)
  4. cd to your vEnv/bin and type "source activate" to get into vEnv
  5. rm pip pip3 pip3.6 (it seems to be the only way to get rid of the bogus pip's in vEnv)
  6. Now pip is gone from vEnv, and we can use the one in the base Python (I wasn't able to successfully install pip into vEnv after deleting)

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

is there a 'block until condition becomes true' function in java?

EboMike's answer and Toby's answer are both on the right track, but they both contain a fatal flaw. The flaw is called lost notification.

The problem is, if a thread calls foo.notify(), it will not do anything at all unless some other thread is already sleeping in a foo.wait() call. The object, foo, does not remember that it was notified.

There's a reason why you aren't allowed to call foo.wait() or foo.notify() unless the thread is synchronized on foo. It's because the only way to avoid lost notification is to protect the condition with a mutex. When it's done right, it looks like this:

Consumer thread:

try {
    synchronized(foo) {
        while(! conditionIsTrue()) {
            foo.wait();
        }
        doSomethingThatRequiresConditionToBeTrue();
    }
} catch (InterruptedException e) {
    handleInterruption();
}

Producer thread:

synchronized(foo) {
    doSomethingThatMakesConditionTrue();
    foo.notify();
}

The code that changes the condition and the code that checks the condition is all synchronized on the same object, and the consumer thread explicitly tests the condition before it waits. There is no way for the consumer to miss the notification and end up stuck forever in a wait() call when the condition is already true.

Also note that the wait() is in a loop. That's because, in the general case, by the time the consumer re-acquires the foo lock and wakes up, some other thread might have made the condition false again. Even if that's not possible in your program, what is possible, in some operating systems, is for foo.wait() to return even when foo.notify() has not been called. That's called a spurious wakeup, and it is allowed to happen because it makes wait/notify easier to implement on certain operating systems.

Regex date validation for yyyy-mm-dd

you can test this expression:

^\d{4}[\-\/\s]?((((0[13578])|(1[02]))[\-\/\s]?(([0-2][0-9])|(3[01])))|(((0[469])|(11))[\-\/\s]?(([0-2][0-9])|(30)))|(02[\-\/\s]?[0-2][0-9]))$

Description:
validates a yyyy-mm-dd, yyyy mm dd, or yyyy/mm/dd date

makes sure day is within valid range for the month - does NOT validate Feb. 29 on a leap year, only that Feb. Can have 29 days

Matches (tested) : 0001-12-31 | 9999 09 30 | 2002/03/03

How to calculate the running time of my program?

The general approach to this is to:

  1. Get the time at the start of your benchmark, say at the start of main().
  2. Run your code.
  3. Get the time at the end of your benchmark, say at the end of main().
  4. Subtract the start time from the end time and convert into appropriate units.

A hint: look at System.nanoTime() or System.currentTimeMillis().

How do you allow spaces to be entered using scanf?

/*reading string which contains spaces*/
#include<stdio.h>
int main()
{
   char *c,*p;
   scanf("%[^\n]s",c);
   p=c;                /*since after reading then pointer points to another 
                       location iam using a second pointer to store the base 
                       address*/ 
   printf("%s",p);
   return 0;
 }

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

Adding to this. If you use both INSERT IGNORE and ON DUPLICATE KEY UPDATE in the same statement, the update will still happen if the insert finds a duplicate key. In other words, the update takes precedence over the ignore. However, if the ON DUPLICATE KEY UPDATE clause itself causes a duplicate key error, that error will be ignored.

This can happen if you have more than one unique key, or if your update attempts to violate a foreign key constraint.

CREATE TABLE test 
 (id BIGINT (20) UNSIGNED AUTO_INCREMENT, 
  str VARCHAR(20), 
  PRIMARY KEY(id), 
  UNIQUE(str));

INSERT INTO test (str) VALUES('A'),('B');

/* duplicate key error caused not by the insert, 
but by the update: */
INSERT INTO test (str) VALUES('B') 
 ON DUPLICATE KEY UPDATE str='A'; 

/* duplicate key error is suppressed */
INSERT IGNORE INTO test (str) VALUES('B') 
 ON DUPLICATE KEY UPDATE str='A';

How to check if there exists a process with a given pid in Python?

mluebke code is not 100% correct; kill() can also raise EPERM (access denied) in which case that obviously means a process exists. This is supposed to work:

(edited as per Jason R. Coombs comments)

import errno
import os

def pid_exists(pid):
    """Check whether pid exists in the current process table.
    UNIX only.
    """
    if pid < 0:
        return False
    if pid == 0:
        # According to "man 2 kill" PID 0 refers to every process
        # in the process group of the calling process.
        # On certain systems 0 is a valid PID but we have no way
        # to know that in a portable fashion.
        raise ValueError('invalid PID 0')
    try:
        os.kill(pid, 0)
    except OSError as err:
        if err.errno == errno.ESRCH:
            # ESRCH == No such process
            return False
        elif err.errno == errno.EPERM:
            # EPERM clearly means there's a process to deny access to
            return True
        else:
            # According to "man 2 kill" possible error values are
            # (EINVAL, EPERM, ESRCH)
            raise
    else:
        return True

You can't do this on Windows unless you use pywin32, ctypes or a C extension module. If you're OK with depending from an external lib you can use psutil:

>>> import psutil
>>> psutil.pid_exists(2353)
True

How to combine two strings together in PHP?

I believe the most performant way is:

$data1 = "the color is";
$data2 = "red";
$result = $data1 . ' ' . $data2;

If you want to implement localisation, you may do something like this:

$translationText = "the color is %s";
$translationRed  = "red";
$result = sprintf($translationText, $translationRed);

It's a bit slower, but it does not assume grammar rules.

Converting JSONarray to ArrayList

In Java 8,

IntStream.range(0,jsonArray.length()).mapToObj(i->jsonArray.getString(i)).collect(Collectors.toList())

Find the most frequent number in a NumPy array

Performances (using iPython) for some solutions found here:

>>> # small array
>>> a = [12,3,65,33,12,3,123,888000]
>>> 
>>> import collections
>>> collections.Counter(a).most_common()[0][0]
3
>>> %timeit collections.Counter(a).most_common()[0][0]
100000 loops, best of 3: 11.3 µs per loop
>>> 
>>> import numpy
>>> numpy.bincount(a).argmax()
3
>>> %timeit numpy.bincount(a).argmax()
100 loops, best of 3: 2.84 ms per loop
>>> 
>>> import scipy.stats
>>> scipy.stats.mode(a)[0][0]
3.0
>>> %timeit scipy.stats.mode(a)[0][0]
10000 loops, best of 3: 172 µs per loop
>>> 
>>> from collections import defaultdict
>>> def jjc(l):
...     d = defaultdict(int)
...     for i in a:
...         d[i] += 1
...     return sorted(d.iteritems(), key=lambda x: x[1], reverse=True)[0]
... 
>>> jjc(a)[0]
3
>>> %timeit jjc(a)[0]
100000 loops, best of 3: 5.58 µs per loop
>>> 
>>> max(map(lambda val: (a.count(val), val), set(a)))[1]
12
>>> %timeit max(map(lambda val: (a.count(val), val), set(a)))[1]
100000 loops, best of 3: 4.11 µs per loop
>>> 

Best is 'max' with 'set' for small arrays like the problem.

According to @David Sanders, if you increase the array size to something like 100,000 elements, the "max w/set" algorithm ends up being the worst by far whereas the "numpy bincount" method is the best.

Request exceeded the limit of 10 internal redirects due to probable configuration error

This error occurred to me when I was debugging the PHP header() function:

header('Location: /aaa/bbb/ccc'); // error

If I use a relative path it works:

header('Location: aaa/bbb/ccc'); // success, but not what I wanted

However when I use an absolute path like /aaa/bbb/ccc, it gives the exact error:

Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

It appears the header function redirects internally without going HTTP at all which is weird. After some tests and trials, I found the solution of adding exit after header():

header('Location: /aaa/bbb/ccc');
exit;

And it works properly.

Copying files using rsync from remote server to local machine

If you have SSH access, you don't need to SSH first and then copy, just use Secure Copy (SCP) from the destination.

scp user@host:/path/file /localpath/file

Wild card characters are supported, so

scp user@host:/path/folder/* /localpath/folder

will copy all of the remote files in that folder.If copying more then one directory.

note -r will copy all sub-folders and content too.

java.lang.ClassNotFoundException: HttpServletRequest

I had this issue too, and all I did to get rid of it was to delete the existing Server (in my case Tomcat) configurations from project and eclipse workspace.

This issue in my case occurred when I played around with my Maven settings and finally screwed them too. But eventually I fixed my Maven issues to realize the tomcat server wont start and failed to load the application context(s) of various apps involved in my project. That's when I decided to drop the existing server configurations.

I then added the Apache Server once again all over afresh. Then followed with my project specific setting/additions. And it finally worked like a charm.

android:drawableLeft margin and/or padding

You should consider using layer-list

Create a drawable file like this, name it as ic_calendar.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape android:shape="rectangle">
        <solid android:color="@android:color/transparent"/>
    </shape>
</item>
<item android:right="10dp">
    <bitmap android:gravity="center_vertical|left"
        android:src="@drawable/ic_calendar_16dp"
        android:tint="@color/red"
        />
</item>
</layer-list>

Under layout file,

<TextView
         android:id="@+id/tvDate"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:drawableLeft="@drawable/ic_calendar"
         android:textColor="@color/colorGrey"
         android:textSize="14sp" 
    />

Run CRON job everyday at specific time

From cron manual http://man7.org/linux/man-pages/man5/crontab.5.html:

Lists are allowed. A list is a set of numbers (or ranges) separated by commas. Examples: "1,2,5,9", "0-4,8-12".

So in this case it would be:

30 10,14 * * *

How to solve WAMP and Skype conflict on Windows 7?

I think it is better to change default port of Skype.

Open skype. Go to Tools, Options, Connections, change the port.

How to initialize List<String> object in Java?

If you check the API for List you'll notice it says:

Interface List<E>

Being an interface means it cannot be instantiated (no new List() is possible).

If you check that link, you'll find some classes that implement List:

All Known Implementing Classes:

AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector

Those can be instantiated. Use their links to know more about them, I.E: to know which fits better your needs.

The 3 most commonly used ones probably are:

 List<String> supplierNames1 = new ArrayList<String>();
 List<String> supplierNames2 = new LinkedList<String>();
 List<String> supplierNames3 = new Vector<String>();

Bonus:
You can also instantiate it with values, in an easier way, using the Arrays class, as follows:

List<String> supplierNames = Arrays.asList("sup1", "sup2", "sup3");
System.out.println(supplierNames.get(1));

But note you are not allowed to add more elements to that list, as it's fixed-size.

How to sort a file, based on its numerical values for a field?

Well, most other answers here refer to

sort -n

However, I'm not sure this works for negative numbers. Here are the results I get with sort version 6.10 on Fedora 9.

Input file:

-0.907928466796875
-0.61614990234375
1.135406494140625
0.48614501953125
-0.4140167236328125

Output:

-0.4140167236328125
0.48614501953125
-0.61614990234375
-0.907928466796875
1.135406494140625

Which is obviously not ordered by numeric value.

Then, I guess that a more precise answer would be to use sort -n but only if all the values are positive.

P.S.: Using sort -g returns just the same results for this example

Edit:

Looks like the locale settings affect how the minus sign affects the order (see here). In order to get proper results I just did:

LC_ALL=C sort -n filename.txt