Programs & Examples On #Cox regression

The term Cox regression model (omitting proportional hazards) is sometimes used to describe the extension of the Cox model to include time-dependent factors. However, this usage is potentially ambiguous since the Cox proportional hazards model can itself be described as a regression model.

Open directory using C

You should really post your code(a), but here goes. Start with something like:

    #include <stdio.h>
    #include <dirent.h>

    int main (int argc, char *argv[]) {
        struct dirent *pDirent;
        DIR *pDir;

        // Ensure correct argument count.

        if (argc != 2) {
            printf ("Usage: testprog <dirname>\n");
            return 1;
        }

        // Ensure we can open directory.

        pDir = opendir (argv[1]);
        if (pDir == NULL) {
            printf ("Cannot open directory '%s'\n", argv[1]);
            return 1;
        }

        // Process each entry.

        while ((pDirent = readdir(pDir)) != NULL) {
            printf ("[%s]\n", pDirent->d_name);
        }

        // Close directory and exit.

        closedir (pDir);
        return 0;
    }

You need to check in your case that args[1] is both set and refers to an actual directory. A sample run, with tmp is a subdirectory off my current directory but you can use any valid directory, gives me: testprog tmp

[.]
[..]
[file1.txt]
[file1_file1.txt]
[file2.avi]
[file2_file2.avi]
[file3.b.txt]
[file3_file3.b.txt]

Note also that you have to pass a directory in, not a file. When I execute:

testprog tmp/file1.txt

I get:

Cannot open directory 'tmp/file1.txt'

That's because it's a file rather than a directory (though, if you're sneaky, you can attempt to use diropen(dirname(argv[1])) if the initial diropen fails).


(a) This has now been rectified but, since this answer has been accepted, I'm going to assume it was the issue of whatever you were passing in.

Prevent PDF file from downloading and printing

In my opinion the other proposed solution is.

  1. Convert your PDF book to HTML,
  2. Show the html book in Iframe

This approach will prevent the users to download the file.

HTTP requests and JSON parsing in Python

requests has built-in .json() method

import requests
requests.get(url).json()

pythonic way to do something N times without an index variable?

Use the _ variable, as I learned when I asked this question, for example:

# A long way to do integer exponentiation
num = 2
power = 3
product = 1
for _ in xrange(power):
    product *= num
print product

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

As nobody published a solution with CountDownLatch. What about:

public class Lockeable {
    private final CountDownLatch countDownLatch = new CountDownLatch(1);

    public void doAfterEvent(){
        countDownLatch.await();
        doSomething();
    }

    public void reportDetonatingEvent(){
        countDownLatch.countDown();
    }
}

Why can't I change my input value in React even with the onChange listener

I think it is best way for you.

You should add this: this.onTodoChange = this.onTodoChange.bind(this).

And your function has event param(e), and get value:

componentWillMount(){
        this.setState({
            updatable : false,
            name : this.props.name,
            status : this.props.status
        });
    this.onTodoChange = this.onTodoChange.bind(this)
    }
    
    
<input className="form-control" type="text" value={this.state.name} id={'todoName' + this.props.id} onChange={this.onTodoChange}/>

onTodoChange(e){
         const {name, value} = e.target;
        this.setState({[name]: value});
   
}

What is :: (double colon) in Python when subscripting sequences?

Did I miss or nobody mentioned reversing with [::-1] here?

# Operating System List
systems = ['Windows', 'macOS', 'Linux']
print('Original List:', systems)

# Reversing a list  
#Syntax: reversed_list = systems[start:stop:step] 
reversed_list = systems[::-1]

# updated list
print('Updated List:', reversed_list)

source: https://www.programiz.com/python-programming/methods/list/reverse

CSS text-align not working

Change the rule on your <a> element from:

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
}?

to

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
    width:100%;
    text-align:center;
}?

Just add two new rules (width:100%; and text-align:center;). You need to make the anchor expand to take up the full width of the list item and then text-align center it.

jsFiddle example

Get current rowIndex of table in jQuery

Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:

$('td').click(function(){
   var row_index = $(this).closest("tr").index();
   var col_index = $(this).index();
});

HTML form with two submit buttons and two "target" attributes

On each of your buttons you could have the following;

<input type="button" name="newWin" onclick="frmSubmitSameWin();">
<input type="button" name="SameWin" onclick="frmSubmitNewWin();">

Then have a few small js functions;

<script type="text/javascript">
function frmSubmitSameWin() {
form.target = '';
form.submit();
}


function frmSubmitNewWin() {
form.target = '_blank';
form.submit();
}
</script>

That should do the trick.

curl: (6) Could not resolve host: google.com; Name or service not known

Issues were:

  1. IPV6 enabled
  2. Wrong DNS server

Here is how I fixed it:

IPV6 Disabling

  • Open Terminal
  • Type su and enter to log in as the super user
  • Enter the root password
  • Type cd /etc/modprobe.d/ to change directory to /etc/modprobe.d/
  • Type vi disableipv6.conf to create a new file there
  • Press Esc + i to insert data to file
  • Type install ipv6 /bin/true on the file to avoid loading IPV6 related modules
  • Type Esc + : and then wq for save and exit
  • Type reboot to restart fedora
  • After reboot open terminal and type lsmod | grep ipv6
  • If no result, it means you properly disabled IPV6

Add Google DNS server

  • Open Terminal
  • Type su and enter to log in as the super user
  • Enter the root password
  • Type cat /etc/resolv.conf to check what DNS server your Fedora using. Mostly this will be your Modem IP address.
  • Now we have to Find a powerful DNS server. Luckily there is a open DNS server maintain by Google.
  • Go to this page and find out what are the "Google Public DNS IP addresses"
  • Today those are 8.8.8.8 and 8.8.4.4. But in future those may change.
  • Type vi /etc/resolv.conf to edit the resolv.conf file
  • Press Esc + i for insert data to file
  • Comment all the things in the file by inserting # at the begin of the each line. Do not delete anything because can be useful in future.
  • Type below two lines in the file

    nameserver 8.8.8.8
    nameserver 8.8.4.4

    -Type Esc + : and then wq for save and exit

  • Now you are done and everything works fine (Not necessary to restart).
  • But every time when you restart the computer your /etc/resolv.conf will be replaced by default. So I'll let you find a way to avoid that.

Here is my blog post about this: http://codeketchup.blogspot.sg/2014/07/how-to-fix-curl-6-could-not-resolve.html

Eclipse CDT: Symbol 'cout' could not be resolved

If all else fails, like it did in my case, then just disable annotations. I started a c++11 project with own makefile but couldn't fix all the problems. Even if you disable annotations, eclipse will still be able to help you do some autocompletion. Most importantly, the debugger still works!

How to load a model from an HDF5 file in Keras?

See the following sample code on how to Build a basic Keras Neural Net Model, save Model (JSON) & Weights (HDF5) and load them:

# create model
model = Sequential()
model.add(Dense(X.shape[1], input_dim=X.shape[1], activation='relu')) #Input Layer
model.add(Dense(X.shape[1], activation='relu')) #Hidden Layer
model.add(Dense(output_dim, activation='softmax')) #Output Layer

# Compile & Fit model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X,Y,nb_epoch=5,batch_size=100,verbose=1)    

# serialize model to JSON
model_json = model.to_json()
with open("Data/model.json", "w") as json_file:
    json_file.write(simplejson.dumps(simplejson.loads(model_json), indent=4))

# serialize weights to HDF5
model.save_weights("Data/model.h5")
print("Saved model to disk")

# load json and create model
json_file = open('Data/model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# load weights into new model
loaded_model.load_weights("Data/model.h5")
print("Loaded model from disk")

# evaluate loaded model on test data 
# Define X_test & Y_test data first
loaded_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
score = loaded_model.evaluate(X_test, Y_test, verbose=0)
print ("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))

Element-wise addition of 2 lists?

[list1[i] + list2[i] for i in range(len(list1))]

jQuery access input hidden value

There is nothing special about <input type="hidden">:

$('input[type="hidden"]').val()

MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

A "BEFORE-INSERT"-trigger is the only way to realize same-table updates on an insert, and is only possible from MySQL 5.5+. However, the value of an auto-increment field is only available to an "AFTER-INSERT" trigger - it defaults to 0 in the BEFORE-case. Therefore the following example code which would set a previously-calculated surrogate key value based on the auto-increment value id will compile, but not actually work since NEW.id will always be 0:

create table products(id int not null auto_increment, surrogatekey varchar(10), description text);
create trigger trgProductSurrogatekey before insert on product
for each row set NEW.surrogatekey = 
  (select surrogatekey from surrogatekeys where id = NEW.id);

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

A very simple example is that if you have a UserService that has @Autowired jpa resposiroty UserRepository

...
class UserService{

  @Autowired
  UserRepository userRepository;
...
}

then in the test class for UserService you will do

...
class TestUserService{
  @Mock 
  UserRepository userRepository;

  @InjectMocks
  UserService userService;

...
}

@InjectMocks tells the framework that take the @Mock UserRepository userRespository; and inject that into userService so rather than auto wiring a real instance of UserRepository a Mock of UserRepository will be injected in userService.

How to show the Project Explorer window in Eclipse

Close the current perspective:
Close the current perspective

Reopen it using Window -> Open perspective.

Should I learn C before learning C++?

I think learning C first is a good idea.

There's a reason comp sci courses still use C.

In my opinion its to avoid all the "crowding" of the subject matter the obligation to require OOP carries.

I think that procedural programming is the most natural way to first learn programming. I think that's true because at the end of the day its what you have: lines of code executing one after the other.

Many texts today are pushing an "objects first" approach and start talking about cars and gearshifts before they introduce arrays.

Split string with string as delimiter

I expanded Magoos answer to get both desired strings:

@ECHO OFF
SETLOCAL enabledelayedexpansion
SET "string=string1 by string2.txt"
SET "s2=%string:* by =%"
set "s1=!string: by %s2%=!"
set "s2=%s2:.txt=%"
ECHO +%s1%+%s2%+

EDIT: just to prove, my solution also works with the additional requirements:

@ECHO OFF
SETLOCAL enabledelayedexpansion
SET "string=string&1 more words by string&2 with spaces.txt"
SET "s2=%string:* by =%"
set "s1=!string: by %s2%=!"
set "s2=%s2:.txt=%"
ECHO "+%s1%+%s2%+"
set s1
set s2

Output:

"+string&1 more words+string&2 with spaces+"
s1=string&1 more words
s2=string&2 with spaces

Check if table exists in SQL Server

IF EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE 
TABLE_CATALOG = 'Database Name' and
TABLE_NAME = 'Table Name' and 
TABLE_SCHEMA = 'Schema Name') -- Database and Schema name in where statement can be deleted

BEGIN
--TABLE EXISTS
END

ELSE BEGIN
--TABLE DOES NOT EXISTS
END

How can I create a dynamic button click event on a dynamic button?

Button button = new Button();
button.Click += (s,e) => { your code; };
//button.Click += new EventHandler(button_Click);
container.Controls.Add(button);

//protected void button_Click (object sender, EventArgs e) { }

Split function equivalent in T-SQL?

I am tempted to squeeze in my favourite solution. The resulting table will consist of 2 columns: PosIdx for position of the found integer; and Value in integer.


create function FnSplitToTableInt
(
    @param nvarchar(4000)
)
returns table as
return
    with Numbers(Number) as 
    (
        select 1 
        union all 
        select Number + 1 from Numbers where Number < 4000
    ),
    Found as
    (
        select 
            Number as PosIdx,
            convert(int, ltrim(rtrim(convert(nvarchar(4000), 
                substring(@param, Number, 
                charindex(N',' collate Latin1_General_BIN, 
                @param + N',', Number) - Number))))) as Value
        from   
            Numbers 
        where  
            Number <= len(@param)
        and substring(N',' + @param, Number, 1) = N',' collate Latin1_General_BIN
    )
    select 
        PosIdx, 
        case when isnumeric(Value) = 1 
            then convert(int, Value) 
            else convert(int, null) end as Value 
    from 
        Found

It works by using recursive CTE as the list of positions, from 1 to 100 by default. If you need to work with string longer than 100, simply call this function using 'option (maxrecursion 4000)' like the following:


select * from FnSplitToTableInt
(
    '9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ' + 
    '9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ' +
    '9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ' +
    '9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ' +
    '9, 8, 7, 6, 5, 4, 3, 2, 1, 0'
) 
option (maxrecursion 4000)

git: undo all working dir changes including new files

For a specific folder I used:

git checkout -- FolderToClean/*

How to append strings using sprintf?

Use strcat http://www.cplusplus.com/reference/cstring/strcat/

int main ()
    {
      char str[80];
      strcpy (str,"these ");
      strcat (str,"strings ");
      strcat (str,"are ");
      strcat (str,"concatenated.");
      puts (str);
      return 0;
    }




    Output:


    these strings are concatenated. 

DateTimePicker time picker in 24 hour but displaying in 12hr?

Just this!

$(function () {
    $('#date').datetimepicker({
         format: 'H:m',
    });

});

i use v4 and work well!!

Cropping images in the browser BEFORE the upload

Yes, it can be done.
It is based on the new html5 "download" attribute of anchor tags.
The flow should be something like this :

  1. load the image
  2. draw the image into a canvas with the crop boundaries specified
  3. get the image data from the canvas and make it a href attribute for an anchor tag in the dom
  4. add the download attribute (download="desired-file-name") to that a element That's it. all the user has to do is click your "download link" and the image will be downloaded to his pc.

I'll come back with a demo when I get the chance.

Update
Here's the live demo as I promised. It takes the jsfiddle logo and crops 5px of each margin.
The code looks like this :

var img = new Image();
img.onload = function(){
    var cropMarginWidth = 5,
        canvas = $('<canvas/>')
                    .attr({
                         width: img.width - 2 * cropMarginWidth,
                         height: img.height - 2 * cropMarginWidth
                     })
                    .hide()
                    .appendTo('body'),
        ctx = canvas.get(0).getContext('2d'),
        a = $('<a download="cropped-image" title="click to download the image" />'),
        cropCoords = {
            topLeft : {
                x : cropMarginWidth,
                y : cropMarginWidth 
            },
            bottomRight :{
                x : img.width - cropMarginWidth,
                y : img.height - cropMarginWidth
            }
        };

    ctx.drawImage(img, cropCoords.topLeft.x, cropCoords.topLeft.y, cropCoords.bottomRight.x, cropCoords.bottomRight.y, 0, 0, img.width, img.height);
    var base64ImageData = canvas.get(0).toDataURL();


    a
        .attr('href', base64ImageData)
        .text('cropped image')
        .appendTo('body');

    a
        .clone()
        .attr('href', img.src)
        .text('original image')
        .attr('download','original-image')
        .appendTo('body');

    canvas.remove();
}
img.src = 'some-image-src';

Update II
Forgot to mention : of course there is a downside :(.
Because of the same-origin policy that is applied to images too, if you want to access an image's data (through the canvas method toDataUrl).
So you would still need a server-side proxy that would serve your image as if it were hosted on your domain.

Update III Although I can't provide a live demo for this (for security reasons), here is a php sample code that solves the same-origin policy :

file proxy.php :

$imgData = getimagesize($_GET['img']);
header("Content-type: " . $imgData['mime']);
echo file_get_contents($_GET['img']);  

This way, instead of loading the external image direct from it's origin :

img.src = 'http://some-domain.com/imagefile.png';

You can load it through your proxy :

img.src = 'proxy.php?img=' + encodeURIComponent('http://some-domain.com/imagefile.png');  

And here's a sample php code for saving the image data (base64) into an actual image :

file save-image.php :

$data = preg_replace('/data:image\/(png|jpg|jpeg|gif|bmp);base64/','',$_POST['data']);
$data = base64_decode($data);
$img = imagecreatefromstring($data);

$path = 'path-to-saved-images/';
// generate random name
$name  = substr(md5(time()),10);
$ext = 'png';
$imageName = $path.$name.'.'.$ext;

// write the image to disk
imagepng($img,  $imageName);
imagedestroy($img);
// return the image path
echo $imageName;

All you have to do then is post the image data to this file and it will save the image to disc and return you the existing image filename.

Of course all this might feel a bit complicated, but I wanted to show you that what you're trying to achieve is possible.

Run "mvn clean install" in Eclipse

If you want to open command prompt inside your eclipse, this can be a useful approach to link cmd with eclipse.

You can follow this link to get the steps in detail with screenshots. How to use cmd prompt inside Eclipse ?

I'm quoting the steps here:

Step 1: Setup a new External Configuration Tool

In the Eclipse tool go to Run -> External Tools -> External Tools Configurations option.

Step 2: Click New Launch Configuration option in Create, manage and run configuration screen

Step 3: New Configuration screen for configuring the command prompt

Step 4: Provide configuration details of the Command Prompt in the Main tab

Name: Give any name to your configuration (Here it is Command_Prompt)
Location: Location of the CMD.exe in your Windows
Working Directory: Any directory where you want to point the Command prompt

Step 5: Tick the check box Allocate console This will ensure the eclipse console is being used as the command prompt for any input or output.

Step 6: Click Run and you are there!! You will land up in the C: directory as a working directory

Use Mockito to mock some methods but not others

What you want is org.mockito.Mockito.CALLS_REAL_METHODS according to the docs:

/**
 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations.
 * <p>
 * This implementation can be helpful when working with legacy code.
 * When this implementation is used, unstubbed methods will delegate to the real implementation.
 * This is a way to create a partial mock object that calls real methods by default.
 * <p>
 * As usual you are going to read <b>the partial mock warning</b>:
 * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
 * How does partial mock fit into this paradigm? Well, it just doesn't... 
 * Partial mock usually means that the complexity has been moved to a different method on the same object.
 * In most cases, this is not the way you want to design your application.
 * <p>
 * However, there are rare cases when partial mocks come handy: 
 * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
 * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
 * <p>
 * Example:
 * <pre class="code"><code class="java">
 * Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
 *
 * // this calls the real implementation of Foo.getSomething()
 * value = mock.getSomething();
 *
 * when(mock.getSomething()).thenReturn(fakeValue);
 *
 * // now fakeValue is returned
 * value = mock.getSomething();
 * </code></pre>
 */

Thus your code should look like:

import org.junit.Test;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

public class StockTest {

    public class Stock {
        private final double price;
        private final int quantity;

        Stock(double price, int quantity) {
            this.price = price;
            this.quantity = quantity;
        }

        public double getPrice() {
            return price;
        }

        public int getQuantity() {
            return quantity;
        }

        public double getValue() {
            return getPrice() * getQuantity();
        }
    }

    @Test
    public void getValueTest() {
        Stock stock = mock(Stock.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
        when(stock.getPrice()).thenReturn(100.00);
        when(stock.getQuantity()).thenReturn(200);
        double value = stock.getValue();

        assertEquals("Stock value not correct", 100.00 * 200, value, .00001);
    }
}

The call to Stock stock = mock(Stock.class); calls org.mockito.Mockito.mock(Class<T>) which looks like this:

 public static <T> T mock(Class<T> classToMock) {
    return mock(classToMock, withSettings().defaultAnswer(RETURNS_DEFAULTS));
}

The docs of the value RETURNS_DEFAULTS tell:

/**
 * The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
 * Typically it just returns some empty value. 
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations. 
 * <p>
 * This implementation first tries the global configuration. 
 * If there is no global configuration then it uses {@link ReturnsEmptyValues} (returns zeros, empty collections, nulls, etc.)
 */

python dictionary sorting in descending order based on values

sort dictionary 'in_dict' by value in decreasing order

sorted_dict = {r: in_dict[r] for r in sorted(in_dict, key=in_dict.get, reverse=True)}

example above

sorted_d = {r: d[r] for r in sorted(d, key=d.get('key3'), reverse=True)}

Python date string to date object

import datetime
datetime.datetime.strptime('24052010', '%d%m%Y').date()

Android Studio SDK location

If your project is open click on Gradle Scripts >local.properties(SDK LOCATION), open it and there is the location of sdk with name

sdk.dir=C\:\\Users\\shiva\\AppData\\Local\\Android\\Sdk

Note don't forget the replace \\ to \ before coping the things(sdk location)

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

enter image description here

How about just > Format only cells that contain - in the drop down box select Blanks

SQL multiple columns in IN clause

It often ends up being easier to load your data into the database, even if it is only to run a quick query. Hard-coded data seems quick to enter, but it quickly becomes a pain if you start having to make changes.

However, if you want to code the names directly into your query, here is a cleaner way to do it:

with names (fname,lname) as (
    values
        ('John','Smith'),
        ('Mary','Jones')
)
select city from user
    inner join names on
        fname=firstName and
        lname=lastName;

The advantage of this is that it separates your data out of the query somewhat.

(This is DB2 syntax; it may need a bit of tweaking on your system).

Android image caching

To download an image and save to the memory card you can do it like this.

//First create a new URL object 
URL url = new URL("http://www.google.co.uk/logos/holiday09_2.gif")

//Next create a file, the example below will save to the SDCARD using JPEG format
File file = new File("/sdcard/example.jpg");

//Next create a Bitmap object and download the image to bitmap
Bitmap bitmap = BitmapFactory.decodeStream(url.openStream());

//Finally compress the bitmap, saving to the file previously created
bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream(file));

Don't forget to add the Internet permission to your manifest:

<uses-permission android:name="android.permission.INTERNET" />

AngularJS For Loop with Numbers & Ranges

An improvement to @Mormegil's solution

app.filter('makeRange', function() {
  return function(inp) {
    var range = [+inp[1] && +inp[0] || 0, +inp[1] || +inp[0]];
    var min = Math.min(range[0], range[1]);
    var max = Math.max(range[0], range[1]);
    var result = [];
    for (var i = min; i <= max; i++) result.push(i);
    if (range[0] > range[1]) result.reverse();
    return result;
  };
});

usage

<span ng-repeat="n in [3, -3] | makeRange" ng-bind="n"></span>

3 2 1 0 -1 -2 -3

<span ng-repeat="n in [-3, 3] | makeRange" ng-bind="n"></span>

-3 -2 -1 0 1 2 3

<span ng-repeat="n in [3] | makeRange" ng-bind="n"></span>

0 1 2 3

<span ng-repeat="n in [-3] | makeRange" ng-bind="n"></span>

0 -1 -2 -3

Owl Carousel Won't Autoplay

With version 2.3.4, you need the to add the owl.autoplay.js plugin. Then do the following

var owl = $('.owl-carousel');
owl.owlCarousel({
   items:1, //how many items you want to display
    loop:true,
    margin:10,
    autoplay:true,
    autoplayTimeout:10000,
    autoplayHoverPause:true
});

mysqli::query(): Couldn't fetch mysqli

Probably somewhere you have DBconnection->close(); and then some queries try to execute .


Hint: It's sometimes mistake to insert ...->close(); in __destruct() (because __destruct is event, after which there will be a need for execution of queries)

Exclude subpackages from Spring autowiring?

I think you should refactor your packages in more convenient hierarchy, so they are out of the base package.

But if you can't do this, try:

<context:component-scan base-package="com.example">
    ...
    <context:exclude-filter type="regex" expression="com\.example\.ignore.*"/>
</context:component-scan>

Here you could find more examples: Using filters to customize scanning

How to select an option from drop down using Selenium WebDriver C#?

This is how it works for me (selecting control by ID and option by text):

protected void clickOptionInList(string listControlId, string optionText)
{
     driver.FindElement(By.XPath("//select[@id='"+ listControlId + "']/option[contains(.,'"+ optionText +"')]")).Click();
}

use:

clickOptionInList("ctl00_ContentPlaceHolder_lbxAllRoles", "Tester");

How can I write maven build to add resources to classpath?

By default maven does not include any files from "src/main/java".

You have two possible way to that.

  1. put all your resource files (different than java files) to "src/main/resources" - this is highly recommended

  2. Add to your pom (resource plugin):

?

 <resources>
       <resource>
           <directory>src/main/resources</directory>
        </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
  </resources>

Create listview in fragment android

I guess your app crashes because of NullPointerException.

Change this

ListView lv = (ListView)getActivity().findViewById(R.id.lv_contact);

to

ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);

assuming listview belongs to the fragment layout.

The rest of the code looks alright

Edit:

Well since you said it is not working i tried it myself

enter image description here

How to get EditText value and display it on screen through TextView?

yesButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        eiteText=(EditText)findViewById(R.id.nameET);
        String result=eiteText.getText().toString();
        Log.d("TAG",result);
    }
});

Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery

I haven't been able to get it to work without specifying a width but the following css worked

.wrapper {
    background: #DDD;
    padding: 10px;
    display: inline-block;
    height: 20px;
    width: auto;
}

.contents {
    background: #c3c;
    overflow: hidden;
    white-space: nowrap;
    display: inline-block;
    visibility: hidden;
    width: 1px;
    -webkit-transition: width 1s ease-in-out, visibility 1s linear;
    -moz-transition: width 1s ease-in-out, visibility 1s linear;
    -o-transition: width 1s ease-in-out, visibility 1s linear;
    transition: width 1s ease-in-out, visibility 1s linear;
}

.wrapper:hover .contents {
    width: 200px;
    visibility: visible;
}

I'm not sure you will be able to get it working without setting a width on it.

Hiding the address bar of a browser (popup)

You might no be able to HIDE it, but if you are looking for the extra space, what I did and seems to work is a very simple thing, the address bar has 60px height, so this is my solution.

@media only screen and (max-width: 1024px){ // only from ipads down
  body{
    padding-bottom: 60px; // push your whole site same height upwards. ;)
  }
}

Select a date from date picker using Selenium webdriver

Here's a tidy solution where you provide the target date as a Calendar object.

// Used to translate the Month value of a JQuery calendar to the month value expected by a Calendar.
private static final Map<String,Integer> MONTH_TO_CALENDAR_INDEX = new HashMap<String,Integer>();
static {
    MONTH_TO_CALENDAR_INDEX.put("January",  0);
    MONTH_TO_CALENDAR_INDEX.put("February",1);
    MONTH_TO_CALENDAR_INDEX.put("March",2);
    MONTH_TO_CALENDAR_INDEX.put("April",3);
    MONTH_TO_CALENDAR_INDEX.put("May",4);
    MONTH_TO_CALENDAR_INDEX.put("June",5);
    MONTH_TO_CALENDAR_INDEX.put("July",6);
    MONTH_TO_CALENDAR_INDEX.put("August",7);
    MONTH_TO_CALENDAR_INDEX.put("September",8);
    MONTH_TO_CALENDAR_INDEX.put("October",9);
    MONTH_TO_CALENDAR_INDEX.put("November",10);
    MONTH_TO_CALENDAR_INDEX.put("December",11);
}

        // ====================================================================================================
        // setCalendarPicker
        // ====================================================================================================

        /**
         * Sets the value of specified web element while assuming the element is a JQuery calendar.
         * @param byOpen The By phrase that locates the control that opens the JQuery calendar when clicked.
         * @param byPicker The By phrase that locates the JQuery calendar.
         * @param targetDate The target date that you want set.
         * @throws AssertionError if the method is unable to set the date.
         */

        public void setCalendarPicker(By byOpen, By byPicker, Calendar targetDate) {

            // Open the JQuery calendar.
            WebElement opener = driver.findElement(byOpen);
            opener.click();

            // Locate the JQuery calendar.
            WebElement picker = driver.findElement(byPicker);

            // Calculate the target and current year-and-month as an integer where value = year*12+month.
            // The difference between the two is the number of months we have to move ahead or backward.
            int targetYearMonth = targetDate.get(Calendar.YEAR) * 12 + targetDate.get(Calendar.MONTH);
            int currentYearMonth = Integer.valueOf(picker.findElement(By.className("ui-datepicker-year")).getText()) * 12
                    + Integer.valueOf(MONTH_TO_CALENDAR_INDEX.get(picker.findElement(By.className("ui-datepicker-month")).getText()));
            // Calculate the number of months we need to move the JQuery calendar.
            int delta = targetYearMonth - currentYearMonth;
            // As a sanity check, let's not allow more than 10 years so that we don't inadvertently spin in a loop for zillions of months.
            if (Math.abs(delta) > 120) throw new AssertionError("Target date is more than 10 years away");

            // Push the JQuery calendar forward or backward as appropriate.
            if (delta > 0) {
                while (delta-- > 0) picker.findElement(By.className("ui-icon-circle-triangle-e")).click();
            } else if (delta < 0 ){
                while (delta++ < 0) picker.findElement(By.className("ui-icon-circle-triangle-w")).click();
            }

            // Select the day within the month.
            String dayOfMonth = String.valueOf(targetDate.get(Calendar.DAY_OF_MONTH));
            WebElement tableOfDays = picker.findElement(By.cssSelector("tbody:nth-child(2)"));
            for (WebElement we : tableOfDays.findElements(By.tagName("td"))) {
                if (dayOfMonth.equals(we.getText())) {
                    we.click();

                    // Send a tab to completely leave this control.  If the next control the user will access is another CalendarPicker,
                    // the picker might not get selected properly if we stay on the current control.
                    opener.sendKeys("\t");

                    return;
                }
            }

            throw new AssertionError(String.format("Unable to select specified day"));
        }

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

Update: I've since written a very detailed explanation of the various ways you can install Ruby gems on a Mac. My original recommendation to use a script still stands, but my article goes into more detail: https://www.moncefbelyamani.com/the-definitive-guide-to-installing-ruby-gems-on-a-mac/

You are correct that macOS won't let you change anything with the Ruby version that comes installed with your Mac. However, it's possible to install gems like bundler using a separate version of Ruby that doesn't interfere with the one provided by Apple.

Using sudo to install gems, or changing permissions of system files and directories is strongly discouraged, even if you know what you are doing. Can we please stop providing this bad advice? Here's a detailed article I wrote showing how sudo gem install can wipe out your computer: https://www.moncefbelyamani.com/why-you-should-never-use-sudo-to-install-ruby-gems/

The solution involves two main steps:

  1. Install a separate version of Ruby that does not interfere with the one that came with your Mac.
  2. Update your PATH such that the location of the new Ruby version is first in the PATH. Some tools do this automatically for you. If you're not familiar with the PATH and how it works, read my guide.

There are several ways to install Ruby on a Mac. The best way that I recommend, and that I wish was more prevalent in the various installation instructions out there, is to use an automated script that will set up a proper Ruby environment for you. This drastically reduces the chances of running into an error due to inadequate instructions that make the user do a bunch of stuff manually and leaving it up to them to figure out all the necessary steps.

The other route you can take is to spend extra time doing everything manually and hoping for the best. First, you will want to install Homebrew, which installs the prerequisite command line tools, and makes it easy to install other necessary tools.

Then, the two easiest ways to install a separate version of Ruby are:

If you would like the flexibility of easily switching between many Ruby versions [RECOMMENDED]

Choose one of these four options:

  • chruby and ruby-install - my personal recommendations and the ones that are automatically installed by my script. These can be installed with Homebrew:
brew install chruby ruby-install

If you chose chruby and ruby-install, you can then install the latest Ruby like this:

ruby-install ruby

Once you've installed everything and configured your .zshrc or .bash_profile according to the instructions from the tools above, quit and restart Terminal, then switch to the version of Ruby that you want. In the case of chruby, it would be something like this:

chruby 2.7.2

Whether you need to configure .zshrc or .bash_profile depends on which shell you are using. If you're not sure, read this guide: https://www.moncefbelyamani.com/which-shell-am-i-using-how-can-i-switch/

If you know for sure you don't need more than one version of Ruby at the same time (besides the one that came with macOS)

  • Install ruby with Homebrew:
brew install ruby

Then update your PATH by running (replace 2.7.0 with your newly installed version):

echo 'export PATH="/usr/local/opt/ruby/bin:/usr/local/lib/ruby/gems/2.7.0/bin:$PATH"' >> ~/.zshrc

Then "refresh" your shell for these changes to take effect:

source ~/.zshrc

Or you can open a new terminal tab, or quit and restart Terminal.

Replace .zshrc with .bash_profile if you are using Bash. If you're not sure which shell you are using, read this guide: https://www.moncefbelyamani.com/which-shell-am-i-using-how-can-i-switch/

To check that you're now using the non-system version of Ruby, you can run the following commands:

which ruby

It should be something other than /usr/bin/ruby

ruby -v

It should be something other than 2.6.3 if you're on macOS Catalina. As of today, 2.7.2 is the latest Ruby version.

Once you have this new version of Ruby installed, you can now install bundler (or any other gem):

gem install bundler

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

It basically depends on which version jersey you are using. If you are using Jersey ver.1.X.X you need to add

Jersey 1 uses "com.sun.jersey", and Jersey 2 uses org.glassfish. on servlet class tag. Also, note that also init-param starting with com.sun.jersey won't be recognized by Jersey 2.

And Add all the jar file into WEB-INF lib folder

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

This is a common issue when attempting to 'bubble' up data from a chain of stored procedures. A restriction in SQL Server is you can only have one INSERT-EXEC active at a time. I recommend looking at How to Share Data Between Stored Procedures which is a very thorough article on patterns to work around this type of problem.

For example a work around could be to turn Sp3 into a Table-valued function.

How to create/read/write JSON files in Qt5

Sadly, many JSON C++ libraries have APIs that are non trivial to use, while JSON was intended to be easy to use.

So I tried jsoncpp from the gSOAP tools on the JSON doc shown in one of the answers above and this is the code generated with jsoncpp to construct a JSON object in C++ which is then written in JSON format to std::cout:

value x(ctx);
x["appDesc"]["description"] = "SomeDescription";
x["appDesc"]["message"] = "SomeMessage";
x["appName"]["description"] = "Home";
x["appName"]["message"] = "Welcome";
x["appName"]["imp"][0] = "awesome";
x["appName"]["imp"][1] = "best";
x["appName"]["imp"][2] = "good";
std::cout << x << std::endl;

and this is the code generated by jsoncpp to parse JSON from std::cin and extract its values (replace USE_VAL as needed):

value x(ctx);
std::cin >> x;
if (x.soap->error)
  exit(EXIT_FAILURE); // error parsing JSON
#define USE_VAL(path, val) std::cout << path << " = " << val << std::endl
if (x.has("appDesc"))
{
  if (x["appDesc"].has("description"))
    USE_VAL("$.appDesc.description", x["appDesc"]["description"]);
  if (x["appDesc"].has("message"))
    USE_VAL("$.appDesc.message", x["appDesc"]["message"]);
}
if (x.has("appName"))
{
  if (x["appName"].has("description"))
    USE_VAL("$.appName.description", x["appName"]["description"]);
  if (x["appName"].has("message"))
    USE_VAL("$.appName.message", x["appName"]["message"]);
  if (x["appName"].has("imp"))
  {
    for (int i2 = 0; i2 < x["appName"]["imp"].size(); i2++)
      USE_VAL("$.appName.imp[]", x["appName"]["imp"][i2]);
  }
}

This code uses the JSON C++ API of gSOAP 2.8.28. I don't expect people to change libraries, but I think this comparison helps to put JSON C++ libraries in perspective.

Does JSON syntax allow duplicate keys in an object?

The JSON spec says this:

An object is an unordered set of name/value pairs.

The important part here is "unordered": it implies uniqueness of keys, because the only thing you can use to refer to a specific pair is its key.

In addition, most JSON libs will deserialize JSON objects to hash maps/dictionaries, where keys are guaranteed unique. What happens when you deserialize a JSON object with duplicate keys depends on the library: in most cases, you'll either get an error, or only the last value for each duplicate key will be taken into account.

For example, in Python, json.loads('{"a": 1, "a": 2}') returns {"a": 2}.

Parsing JSON with Unix tools

here's one way you can do it with awk

curl -sL 'http://twitter.com/users/username.json' | awk -F"," -v k="text" '{
    gsub(/{|}/,"")
    for(i=1;i<=NF;i++){
        if ( $i ~ k ){
            print $i
        }
    }
}'

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

I had a similar problem. Just to help out someone with the same issue:

My error was the user file attribute for the files in /var/www. After changing them back to the user "www-data", the problem was gone.

How to read a text file into a list or an array with Python

You can also use numpy loadtxt like

from numpy import loadtxt
lines = loadtxt("filename.dat", comments="#", delimiter=",", unpack=False)

"Data too long for column" - why?

If your source data is larger than your target field and you just want to cut off any extra characters, but you don't want to turn off strict mode or change the target field's size, then just cut the data down to the size you need with LEFT(field_name,size).

INSERT INTO Department VALUES
(..., LEFT('There is some text here',30),...), (..., LEFT('There is some more text over here',30),...);

I used "30" as an example of your target field's size.

In some of my code, it's easy to get the target field's size and do this. But if your code makes that hard, then go with one of the other answers.

JavaScript onclick redirect

Change the onclick from

onclick="javascript:SubmitFrm()"

to

onclick="SubmitFrm()"

How to get the current time in milliseconds from C in Linux?

Following is the util function to get current timestamp in milliseconds:

#include <sys/time.h>

long long current_timestamp() {
    struct timeval te; 
    gettimeofday(&te, NULL); // get current time
    long long milliseconds = te.tv_sec*1000LL + te.tv_usec/1000; // calculate milliseconds
    // printf("milliseconds: %lld\n", milliseconds);
    return milliseconds;
}

About timezone:

gettimeofday() support to specify timezone, I use NULL, which ignore the timezone, but you can specify a timezone, if need.


@Update - timezone

Since the long representation of time is not relevant to or effected by timezone itself, so setting tz param of gettimeofday() is not necessary, since it won't make any difference.

And, according to man page of gettimeofday(), the use of the timezone structure is obsolete, thus the tz argument should normally be specified as NULL, for details please check the man page.

How do I add an "Add to Favorites" button or link on my website?

  if (window.sidebar) { // Mozilla Firefox Bookmark
     window.sidebar.addPanel(document.title,location.href,"");

It adds the bookmark but in the sidebar.

Insertion Sort vs. Selection Sort

It's possible that the confusion is because you're comparing a description of sorting a linked list with a description of sorting an array. But I can't be sure, since you didn't cite your sources.

The easiest way to understand sorting algorithms is often to get a detailed description of the algorithm (not vague stuff like "this sort uses swap. Somewhere. I'm not saying where"), get some playing cards (5-10 should be enough for simple sort algorithms), and run the algorithm by hand.

Selection sort: scan through the unsorted data looking for the smallest remaining element, then swap it into the position immediately following the sorted data. Repeat until finished. If sorting a list, you don't need to swap the smallest element into position, you could instead remove the list node from its old position and insert it at the new.

Insertion sort: take the element immediately following the sorted data, scan through the sorted data to find the place to put it, and put it there. Repeat until finished.

Insertion sort can use swap during its "scan" phase, but doesn't have to and it's not the most efficient way unless you are sorting an array of a data type which: (a) cannot be moved, only copied or swapped; and (b) is more expensive to copy than to swap. If insertion sort does use swap, the way it works is that you simultaneously search for the place and put the new element there, by repeatedly swapping the new element with the element immediately before it, for as long as the element before it is bigger than it. Once you reach an element that isn't bigger, you've found the correct location and you move on to the next new element.

How do you open a file in C++?

#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream file;
  file.open ("codebind.txt");
  file << "Please writr this text to a file.\n this text is written using C++\n";
  file.close();
  return 0;
}

In where shall I use isset() and !empty()

Neither is a good way to check for valid input.

  • isset() is not sufficient because – as has been noted already – it considers an empty string to be a valid value.
  • ! empty() is not sufficient either because it rejects '0', which could be a valid value.

Using isset() combined with an equality check against an empty string is the bare minimum that you need to verify that an incoming parameter has a value without creating false negatives:

if( isset($_GET['gender']) and ($_GET['gender'] != '') )
{
  ...
}

But by "bare minimum", I mean exactly that. All the above code does is determine whether there is some value for $_GET['gender']. It does not determine whether the value for $_GET['gender'] is valid (e.g., one of ("Male", "Female","FileNotFound")).

For that, see Josh Davis's answer.

Convert ArrayList<String> to String[] array

I can see many answers showing how to solve problem, but only Stephen's answer is trying to explain why problem occurs so I will try to add something more on this subject. It is a story about possible reasons why Object[] toArray wasn't changed to T[] toArray where generics ware introduced to Java.


Why String[] stockArr = (String[]) stock_list.toArray(); wont work?

In Java, generic type exists at compile-time only. At runtime information about generic type (like in your case <String>) is removed and replaced with Object type (take a look at type erasure). That is why at runtime toArray() have no idea about what precise type to use to create new array, so it uses Object as safest type, because each class extends Object so it can safely store instance of any class.

Now the problem is that you can't cast instance of Object[] to String[].

Why? Take a look at this example (lets assume that class B extends A):

//B extends A
A a = new A();
B b = (B)a;

Although such code will compile, at runtime we will see thrown ClassCastException because instance held by reference a is not actually of type B (or its subtypes). Why is this problem (why this exception needs to be cast)? One of the reasons is that B could have new methods/fields which A doesn't, so it is possible that someone will try to use these new members via b reference even if held instance doesn't have (doesn't support) them. In other words we could end up trying to use data which doesn't exist, which could lead to many problems. So to prevent such situation JVM throws exception, and stop further potentially dangerous code.

You could ask now "So why aren't we stopped even earlier? Why code involving such casting is even compilable? Shouldn't compiler stop it?". Answer is: no because compiler can't know for sure what is the actual type of instance held by a reference, and there is a chance that it will hold instance of class B which will support interface of b reference. Take a look at this example:

A a = new B(); 
      //  ^------ Here reference "a" holds instance of type B
B b = (B)a;    // so now casting is safe, now JVM is sure that `b` reference can 
               // safely access all members of B class

Now lets go back to your arrays. As you see in question, we can't cast instance of Object[] array to more precise type String[] like

Object[] arr = new Object[] { "ab", "cd" };
String[] arr2 = (String[]) arr;//ClassCastException will be thrown

Here problem is a little different. Now we are sure that String[] array will not have additional fields or methods because every array support only:

  • [] operator,
  • length filed,
  • methods inherited from Object supertype,

So it is not arrays interface which is making it impossible. Problem is that Object[] array beside Strings can store any objects (for instance Integers) so it is possible that one beautiful day we will end up with trying to invoke method like strArray[i].substring(1,3) on instance of Integer which doesn't have such method.

So to make sure that this situation will never happen, in Java array references can hold only

  • instances of array of same type as reference (reference String[] strArr can hold String[])
  • instances of array of subtype (Object[] can hold String[] because String is subtype of Object),

but can't hold

  • array of supertype of type of array from reference (String[] can't hold Object[])
  • array of type which is not related to type from reference (Integer[] can't hold String[])

In other words something like this is OK

Object[] arr = new String[] { "ab", "cd" }; //OK - because
               //  ^^^^^^^^                  `arr` holds array of subtype of Object (String)
String[] arr2 = (String[]) arr; //OK - `arr2` reference will hold same array of same type as 
                                //     reference

You could say that one way to resolve this problem is to find at runtime most common type between all list elements and create array of that type, but this wont work in situations where all elements of list will be of one type derived from generic one. Take a look

//B extends A
List<A> elements = new ArrayList<A>();
elements.add(new B());
elements.add(new B());

now most common type is B, not A so toArray()

A[] arr = elements.toArray();

would return array of B class new B[]. Problem with this array is that while compiler would allow you to edit its content by adding new A() element to it, you would get ArrayStoreException because B[] array can hold only elements of class B or its subclass, to make sure that all elements will support interface of B, but instance of A may not have all methods/fields of B. So this solution is not perfect.


Best solution to this problem is explicitly tell what type of array toArray() should be returned by passing this type as method argument like

String[] arr = list.toArray(new String[list.size()]);

or

String[] arr = list.toArray(new String[0]); //if size of array is smaller then list it will be automatically adjusted.

I have created a table in hive, I would like to know which directory my table is created in?

in the 'default' directory if you have not specifically mentioned your location.

you can use describe and describe extended to know about the table structure.

CS0234: Mvc does not exist in the System.Web namespace

Check your runtime tag inside the web.config, and verify you have something like this declared:

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
.....
</runtime>

sql delete statement where date is greater than 30 days

Use DATEADD in your WHERE clause:

...
WHERE date < DATEADD(day, -30, GETDATE())

You can also use abbreviation d or dd instead of day.

Angular 2 / 4 / 5 - Set base href dynamically

Simplification of the existing answer by @sharpmachine.

import { APP_BASE_HREF } from '@angular/common';
import { NgModule } from '@angular/core';

@NgModule({
    providers: [
        {
            provide: APP_BASE_HREF,
            useValue: '/' + (window.location.pathname.split('/')[1] || '')
        }
    ]
})

export class AppModule { }

You do not have to specify a base tag in your index.html, if you are providing value for APP_BASE_HREF opaque token.

Get protocol, domain, and port from URL

For some reason all the answers are all overkills. This is all it takes:

window.location.origin

More details can be found here: https://developer.mozilla.org/en-US/docs/Web/API/window.location#Properties

How can I get the IP address from NIC in Python?

This will gather all IPs on the host and filter out loopback/link-local and IPv6. This can also be edited to allow for IPv6 only, or both IPv4 and IPv6, as well as allowing loopback/link-local in IP list.

from socket import getaddrinfo, gethostname
import ipaddress

def get_ip(ip_addr_proto="ipv4", ignore_local_ips=True):
    # By default, this method only returns non-local IPv4 Addresses
    # To return IPv6 only, call get_ip('ipv6')
    # To return both IPv4 and IPv6, call get_ip('both')
    # To return local IPs, call get_ip(None, False)
    # Can combime options like so get_ip('both', False)

    af_inet = 2
    if ip_addr_proto == "ipv6":
        af_inet = 30
    elif ip_addr_proto == "both":
        af_inet = 0

    system_ip_list = getaddrinfo(gethostname(), None, af_inet, 1, 0)
    ip_list = []

    for ip in system_ip_list:
        ip = ip[4][0]

        try:
            ipaddress.ip_address(str(ip))
            ip_address_valid = True
        except ValueError:
            ip_address_valid = False
        else:
            if ipaddress.ip_address(ip).is_loopback and ignore_local_ips or ipaddress.ip_address(ip).is_link_local and ignore_local_ips:
                pass
            elif ip_address_valid:
                ip_list.append(ip)

    return ip_list

print(f"Your IP Address is: {get_ip()}")

Returns Your IP Address is: ['192.168.1.118']

If I run get_ip('both', False), it returns

Your IP Address is: ['::1', 'fe80::1', '127.0.0.1', '192.168.1.118', 'fe80::cb9:d2dd:a505:423a']

How to export all data from table to an insertable sql format?

Quick and Easy way:

  1. Right click database
  2. Point to tasks In SSMS 2017 you need to ignore step 2 - the generate scripts options is at the top level of the context menu Thanks to Daniel for the comment to update.
  3. Select generate scripts
  4. Click next
  5. Choose tables
  6. Click next
  7. Click advanced
  8. Scroll to Types of data to script - Called types of data to script in SMSS 2014 Thanks to Ellesedil for commenting
  9. Select data only
  10. Click on 'Ok' to close the advanced script options window
  11. Click next and generate your script

I usually in cases like this generate to a new query editor window and then just do any modifications where needed.

Advantages of using display:inline-block vs float:left in CSS

While I agree that in general inline-block is better, there's one extra thing to take into account if you're using percentage widths to create a responsive grid (or if you want pixel-perfect widths):

If you're using inline-block for grids that total 100% or near to 100% width, you need to make sure your HTML markup contains no white space between columns.

With floats, this is not something you need to worry about - the columns float over any whitespace or other content between columns. This question's answers have some good tips on ways to remove HTML whitespace without making your code ugly.

If for any reason you can't control the HTML markup (e.g. a restrictive CMS), you can try the tricks described here, or you might need to compromise and use floats instead of inline-block. There are also ugly CSS tricks that should only be used in extreme circumstances, like font-size:0; on the column container then reapply font size within each column.

For example:

How to check the function's return value if true or false

false != 'false'

For good measures, put the result of validate into a variable to avoid double validation and use that in the IF statement. Like this:

var result = ValidateForm();
if(result == false) {
...
}

jQuery checkbox change and click event

simply just use click event my check box id is CheckAll

     $('#CheckAll').click(function () {

        if ($('#CheckAll').is(':checked') == true) {

             alert(";)");
      }
    }

Use CSS3 transitions with gradient backgrounds

Can't hurt to post another view since there's still not an official way to do this. Wrote a lightweight jQuery plugin with which you can define a background radial gradient and a transition speed. This basic usage will then let it fade in, optimised with requestAnimationFrame (very smooth) :

$('#element').gradientFade({

    duration: 2000,
    from: '(20,20,20,1)',
    to: '(120,120,120,0)'
});

http://codepen.io/Shikkediel/pen/xbRaZz?editors=001

Keeps original background and all properties intact. Also has highlight tracking as a setting :

http://codepen.io/Shikkediel/pen/VYRZZY?editors=001

Where is adb.exe in windows 10 located?

Mine was in: C:\NVPACK\android-sdk-windows\platform-tools

How to manually set an authenticated user in Spring Security / SpringMVC

Ultimately figured out the root of the problem.

When I create the security context manually no session object is created. Only when the request finishes processing does the Spring Security mechanism realize that the session object is null (when it tries to store the security context to the session after the request has been processed).

At the end of the request Spring Security creates a new session object and session ID. However this new session ID never makes it to the browser because it occurs at the end of the request, after the response to the browser has been made. This causes the new session ID (and hence the Security context containing my manually logged on user) to be lost when the next request contains the previous session ID.

Scala vs. Groovy vs. Clojure

Scala

Scala evolved out of a pure functional language known as Funnel and represents a clean-room implementation of almost all Java's syntax, differing only where a clear improvement could be made or where it would compromise the functional nature of the language. Such differences include singleton objects instead of static methods, and type inference.

Much of this was based on Martin Odersky's prior work with the Pizza language. The OO/FP integration goes far beyond mere closures and has led to the language being described as post-functional.

Despite this, it's the closest to Java in many ways. Mainly due to a combination of OO support and static typing, but also due to a explicit goal in the language design that it should integrate very tightly with Java.

Groovy

Groovy explicitly tackles two of Java's biggest criticisms by

  • being dynamically typed, which removes a lot of boilerplate and
  • adding closures to the language.

It's perhaps syntactically closest to Java, not offering some of the richer functional constructs that Clojure and Scala provide, but still offering a definite evolutionary improvement - especially for writing script-syle programs.

Groovy has the strongest commercial backing of the three languages, mostly via springsource.

Clojure

Clojure is a functional language in the LISP family, it's also dynamically typed.

Features such as STM support give it some of the best out-of-the-box concurrency support, whereas Scala requires a 3rd-party library such as Akka to duplicate this.

Syntactically, it's also the furthest of the three languages from typical Java code.

I also have to disclose that I'm most acquainted with Scala :)

How to map an array of objects in React

try the following snippet

const renObjData = this.props.data.map(function(data, idx) {
    return <ul key={idx}>{$.map(data,(val,ind) => {
        return (<li>{val}</li>);
    }
    }</ul>;
});

How to initialize a private static const map in C++?

A different approach to the problem:

struct A {
    static const map<int, string> * singleton_map() {
        static map<int, string>* m = NULL;
        if (!m) {
            m = new map<int, string>;
            m[42] = "42"
            // ... other initializations
        }
        return m;
    }

    // rest of the class
}

This is more efficient, as there is no one-type copy from stack to heap (including constructor, destructors on all elements). Whether this matters or not depends on your use case. Does not matter with strings! (but you may or may not find this version "cleaner")

Using cURL with a username and password?

Use the -u flag to include a username, and curl will prompt for a password:

curl -u username http://example.com

You can also include the password in the command, but then your password will be visible in bash history:

curl -u username:password http://example.com

"Cannot update paths and switch to branch at the same time"

You should go the submodule dir and run git status.

You may see a lot of files were deleted. You may run

  1. git reset .

  2. git checkout .

  3. git fetch -p

  4. git rm --cached submodules //submoudles is your name

  5. git submoudle add ....

How do I initialize a TypeScript Object with a JSON-Object?

This is my approach (very simple):

const jsonObj: { [key: string]: any } = JSON.parse(jsonStr);

for (const key in jsonObj) {
  if (!jsonObj.hasOwnProperty(key)) {
    continue;
  }

  console.log(key); // Key
  console.log(jsonObj[key]); // Value
  // Your logic...
}

nil detection in Go

In addition to Oleiade, see the spec on zero values:

When memory is allocated to store a value, either through a declaration or a call of make or new, and no explicit initialization is provided, the memory is given a default initialization. Each element of such a value is set to the zero value for its type: false for booleans, 0 for integers, 0.0 for floats, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.

As you can see, nil is not the zero value for every type but only for pointers, functions, interfaces, slices, channels and maps. This is the reason why config == nil is an error and &config == nil is not.

To check whether your struct is uninitialized you'd have to check every member for its respective zero value (e.g. host == "", port == 0, etc.) or have a private field which is set by an internal initialization method. Example:

type Config struct {
    Host string  
    Port float64
    setup bool
}

func NewConfig(host string, port float64) *Config {
    return &Config{host, port, true}
}

func (c *Config) Initialized() bool { return c != nil && c.setup }

How can I put a database under git (version control)?

I'm starting to think of a really simple solution, don't know why I didn't think of it before!!

  • Duplicate the database, (both the schema and the data).
  • In the branch for the new-major-changes, simply change the project configuration to use the new duplicate database.

This way I can switch branches without worrying about database schema changes.

EDIT:

By duplicate, I mean create another database with a different name (like my_db_2); not doing a dump or anything like that.

Java Embedded Databases Comparison

I have used Derby and i really hate it's data type conversion functions, especially date/time functions. (Number Type)<--> Varchar conversion it's a pain.

So that if you plan use data type conversions in your DB statements consider the use of othe embedded DB, i learn it too late.

Latest Derby Version data type conversions

Understanding Fragment's setRetainInstance(boolean)

setRetainInstance() - Deprecated

As Fragments Version 1.3.0-alpha01

The setRetainInstance() method on Fragments has been deprecated. With the introduction of ViewModels, developers have a specific API for retaining state that can be associated with Activities, Fragments, and Navigation graphs. This allows developers to use a normal, not retained Fragment and keep the specific state they want retained separate, avoiding a common source of leaks while maintaining the useful properties of a single creation and destruction of the retained state (namely, the constructor of the ViewModel and the onCleared() callback it receives).

Replace all occurrences of a string in a data frame

late to the party. but if you only want to get rid of leading/trailing white space, R base has a function trimws

For example:

data <- apply(X = data, MARGIN = 2, FUN = trimws) %>% as.data.frame()

Counting repeated elements in an integer array

public class DuplicationNoInArray {

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String[] args) throws Exception {
        int[] arr = { 1, 2, 3, 4, 5, 1, 2, 8 };
        int[] result = new int[10];
        int counter = 0, count = 0;
        for (int i = 0; i < arr.length; i++) {
            boolean isDistinct = false;
            for (int j = 0; j < i; j++) {
                if (arr[i] == arr[j]) {
                    isDistinct = true;
                    break;
                }
            }
            if (!isDistinct) {
                result[counter++] = arr[i];
            }
        }
        for (int i = 0; i < counter; i++) {
            count = 0;
            for (int j = 0; j < arr.length; j++) {
                if (result[i] == arr[j]) {
                    count++;
                }

            }
            System.out.println(result[i] + " = " + count);

        }
    }
}

Session timeout in ASP.NET

If you are using Authentication, I recommend adding the following in web.config file.

In my case, users are redirected to the login page upon timing out:

<authentication mode="Forms">
    <forms defaultUrl="Login.aspx" timeout="120"/>
</authentication>

Twitter Bootstrap add active class to li

Here is complete Twitter bootstrap example and applied active class based on query string.

Few steps to follow to achieve correct solution:

1) Include latest jquery.js and bootstrap.js javascript file.

2) Include latest bootstrap.css file

3) Include querystring-0.9.0.js for getting query string variable value in js.

4) HTML:

<div class="navbar">
  <div class="navbar-inner">
    <div class="container">
      <ul class="nav">
        <li class="active">
          <a href="#?page=0">
            Home
          </a>
        </li>
        <li>
          <a href="#?page=1">
            Forums
          </a>
        </li>
        <li>
          <a href="#?page=2">
            Blog
          </a>
        </li>
        <li>
          <a href="#?page=3">
            FAQ's
          </a>
        </li>
        <li>
          <a href="#?page=4">
            Item
          </a>
        </li>
        <li>
          <a href="#?page=5">
            Create
          </a>
        </li>
      </ul>
    </div>
  </div>
</div>

JQuery in Script Tag:

$(function() {
    $(".nav li").click(function() {
        $(".nav li").removeClass('active');
        setTimeout(function() {
            var page = $.QueryString("page");
            $(".nav li:eq(" + page + ")").addClass("active");
        }, 300);

    });
});

I have done complete bin, so please click here http://codebins.com/bin/4ldqpaf

How to make inactive content inside a div?

if you want to hide a whole div from the view in another screen size. You can follow bellow code as an example.

div.disabled{
  display: none;
}

Meaning of ${project.basedir} in pom.xml

There are a set of available properties to all Maven projects.

From Introduction to the POM:

project.basedir: The directory that the current project resides in.

This means this points to where your Maven projects resides on your system. It corresponds to the location of the pom.xml file. If your POM is located inside /path/to/project/pom.xml then this property will evaluate to /path/to/project.

Some properties are also inherited from the Super POM, which is the case for project.build.directory. It is the value inside the <project><build><directory> element of the POM. You can get a description of all those values by looking at the Maven model. For project.build.directory, it is:

The directory where all files generated by the build are placed. The default value is target.

This is the directory that will hold every generated file by the build.

getting "No column was specified for column 2 of 'd'" in sql server cte?

Just add an alias name as follows
sum(totalitems) as totalitems.

How can I save multiple documents concurrently in Mongoose/Node.js?

You can use the promise returned by mongoose save, Promise in mongoose does not have all, but you can add the feature with this module.

Create a module that enhance mongoose promise with all.

var Promise = require("mongoose").Promise;

Promise.all = function(promises) {
  var mainPromise = new Promise();
  if (promises.length == 0) {
    mainPromise.resolve(null, promises);
  }

  var pending = 0;
  promises.forEach(function(p, i) {
    pending++;
    p.then(function(val) {
      promises[i] = val;
      if (--pending === 0) {
        mainPromise.resolve(null, promises);
      }
    }, function(err) {
      mainPromise.reject(err);
    });
  });

  return mainPromise;
}

module.exports = Promise;

Then use it with mongoose:

var Promise = require('./promise')

...

var tasks = [];

for (var i=0; i < docs.length; i++) {
  tasks.push(docs[i].save());
}

Promise.all(tasks)
  .then(function(results) {
    console.log(results);
  }, function (err) {
    console.log(err);
  })

Post Build exited with code 1

My reason for the Code 1 was that the target folder was read only. Hope this helps someone! I had a post build event to do a copy from one directory to another and the destination was read only. So I just went and unchecked the read-only attribute on the directory and all its subdirectories! Just make sure that its a directory that's safe to do so!

What is a raw type and why shouldn't we use it?

What is saying is that your list is a List of unespecified objects. That is that Java does not know what kind of objects are inside the list. Then when you want to iterate the list you have to cast every element, to be able to access the properties of that element (in this case, String).

In general is a better idea to parametrize the collections, so you don't have conversion problems, you will only be able to add elements of the parametrized type and your editor will offer you the appropiate methods to select.

private static List<String> list = new ArrayList<String>();

Hibernate Error: a different object with the same identifier value was already associated with the session

Make Sure, your entity have same Generation Type with all Mapped Entitys

Ex : UserRole

public class UserRole extends AbstractDomain {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String longName;

private String shortName;

@Enumerated(EnumType.STRING)
private CommonStatus status;

private String roleCode;

private Long level;

@Column(columnDefinition = "integer default 0")
private Integer subRoleCount;

private String modification;

@ManyToOne(fetch = FetchType.LAZY)
private TypeOfUsers licenseType;

}

Module :

public class Modules implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String longName;

private String shortName;

}

Main Entity with Mapping

public class RoleModules implements Serializable{

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
private UserRole role;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
private Modules modules;

@Type(type = "yes_no")
private boolean isPrimaryModule;

public boolean getIsPrimaryModule() {
    return isPrimaryModule;
}

}

How do I parse a string with a decimal point to a double?

The below is less efficient, but I use this logic. This is valid only if you have two digits after decimal point.

double val;

if (temp.Text.Split('.').Length > 1)
{
    val = double.Parse(temp.Text.Split('.')[0]);

    if (temp.Text.Split('.')[1].Length == 1)
        val += (0.1 * double.Parse(temp.Text.Split('.')[1]));
    else
        val += (0.01 * double.Parse(temp.Text.Split('.')[1]));
}
else
    val = double.Parse(RR(temp.Text));

Can't use modulus on doubles?

fmod(x, y) is the function you use.

How to cast DATETIME as a DATE in mysql?

Use DATE() function:

select * from follow_queue group by DATE(follow_date)

CSS Equivalent of the "if" statement

Your stylesheet should be thought of as a static table of available variables that your html document can call on based on what you need to display. The logic should be in your javascript and html, use javascript to dynamically apply attributes based on conditions if you really need to. Stylesheets are not the place for logic.

How to open the default webbrowser using java

You can also use the Runtime to create a cross platform solution:

import java.awt.Desktop;
import java.net.URI;

public class App {

    public static void main(String[] args) throws Exception {
        String url = "http://stackoverflow.com";

        if (Desktop.isDesktopSupported()) {
            // Windows
            Desktop.getDesktop().browse(new URI(url));
        } else {
            // Ubuntu
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("/usr/bin/firefox -new-window " + url);
        }
    }
}

Is there a way to reduce the size of the git folder?

Run:

git remote prune origin

Deletes all stale tracking branches which have already been removed at origin but are still locally available in remotes/origin.

git gc --auto

'G arbage C ollection' - runs housekeeping tasks (compresses revisions, removes loose/inaccessible objects). The --auto flag first determines whether any work is required, and exits without doing anything if not.

How do I create a slug in Django?

You can look at the docs for the SlugField to get to know more about it in more descriptive way.

How to place the ~/.composer/vendor/bin directory in your PATH?

Open the Mac Terminal:

vi ~/.bashrc

If you haven't used vi, it may look a little funny at first, so enter the following code carefully, in order:

i
export PATH="$PATH:$HOME/.composer/vendor/bin"

PRESS ESC

:
w

PRESS ENTER

:
q

PRESS ENTER

Now you should have returned to the normal terminal view.

Check that composer now has the correct path:

cd ~/.composer
echo $PATH

If you see the path including your file directory, (e.g. /Users/JeffStrongman/.composer/vendor/bin), you're good to go.

cd

Then run your installation. I ran into this problem, while configuring my Mac to use Laravel Valet.

Example (optional)

valet install

python pip: force install ignoring dependencies

When I were trying install librosa package with pip (pip install librosa), this error were appeared:

ERROR: Cannot uninstall 'llvmlite'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.

I tried to remove llvmlite, but pip uninstall could not remove it. So, I used capability of ignore of pip by this code:

pip install librosa --ignore-installed llvmlite

Indeed, you can use this rule for ignoring a package you don't want to consider:

pip install {package you want to install} --ignore-installed {installed package you don't want to consider}

Regular Expression to get a string between parentheses in Javascript

To match a substring inside parentheses excluding any inner parentheses you may use

\(([^()]*)\)

pattern. See the regex demo.

In JavaScript, use it like

var rx = /\(([^()]*)\)/g;

Pattern details

  • \( - a ( char
  • ([^()]*) - Capturing group 1: a negated character class matching any 0 or more chars other than ( and )
  • \) - a ) char.

To get the whole match, grab Group 0 value, if you need the text inside parentheses, grab Group 1 value.

Most up-to-date JavaScript code demo (using matchAll):

_x000D_
_x000D_
const strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
const rx = /\(([^()]*)\)/g;
strs.forEach(x => {
  const matches = [...x.matchAll(rx)];
  console.log( Array.from(matches, m => m[0]) ); // All full match values
  console.log( Array.from(matches, m => m[1]) ); // All Group 1 values
});
_x000D_
_x000D_
_x000D_

Legacy JavaScript code demo (ES5 compliant):

_x000D_
_x000D_
var strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
var rx = /\(([^()]*)\)/g;


for (var i=0;i<strs.length;i++) {
  console.log(strs[i]);

  // Grab Group 1 values:
  var res=[], m;
  while(m=rx.exec(strs[i])) {
    res.push(m[1]);
  }
  console.log("Group 1: ", res);

  // Grab whole values
  console.log("Whole matches: ", strs[i].match(rx));
}
_x000D_
_x000D_
_x000D_

Ruby on Rails generates model field:type - what are the options for field:type?

:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp,
:time, :date, :binary, :boolean, :references

See the table definitions section.

How to update a value in a json file and save it through node.js

// read file and make object
let content = JSON.parse(fs.readFileSync('file.json', 'utf8'));
// edit or add property
content.expiry_date = 999999999999;
//write file
fs.writeFileSync('file.json', JSON.stringify(content));

Interview Question: Merge two sorted singly linked lists without creating new nodes

I show below an iterative solution. A recursive solution would be more compact, but since we don't know the length of the lists, recursion runs the risk of stack overflow.

The basic idea is similar to the merge step in merge sort; we keep a pointer corresponding to each input list; at each iteration, we advance the pointer corresponding to the smaller element. However, there's one crucial difference where most people get tripped. In merge sort, since we use a result array, the next position to insert is always the index of the result array. For a linked list, we need to keep a pointer to the last element of the sorted list. The pointer may jump around from one input list to another depending on which one has the smaller element for the current iteration.

With that, the following code should be self-explanatory.

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    if (l1 == null) {
        return l2;
    }
    if (l2 == null) {
        return l1;
    }
    ListNode first = l1;
    ListNode second = l2;
    ListNode head = null;
    ListNode last = null;

    while (first != null && second != null) {
        if (first.val < second.val) {
            if (last != null) {
                last.next = first;
            }
            last = first;
            first = first.next;
        } else {
            if (last != null) {
                last.next = second;
            }
            last = second;
            second = second.next;
        }
        if (head == null) {
            head = last;
        }
    }

    if (first == null) {
        last.next = second;
    }
    if (second == null) {
        last.next = first;
    }

    return head;
}

Best way to get hostname with php

I am running PHP version 5.4 on shared hosting and both of these both successfully return the same results:

php_uname('n');

gethostname();

Extract values in Pandas value_counts()

If anyone missed it out in the comments, try this:

dataframe[column].value_counts().to_frame()

OSError: [WinError 193] %1 is not a valid Win32 application

Python installers usually register .py files with the system. If you run the shell explicitly, it works:

import subprocess
subprocess.call(['hello.py', 'htmlfilename.htm'], shell=True)
# --- or ----
subprocess.call('hello.py htmlfilename.htm', shell=True)

You can check your file associations on the command line with

C:\>assoc .py
.py=Python.File

C:\>ftype Python.File
Python.File="C:\Python27\python.exe" "%1" %*

How to use ConcurrentLinkedQueue?

No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.

First, create your queue:

Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();

Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):

YourProducer producer = new YourProducer(queue);

and:

YourConsumer consumer = new YourConsumer(queue);

and add stuff to it in your producer:

queue.offer(myObject);

and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):

YourObject myObject = queue.poll();

For more info see the Javadoc

EDIT:

If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.

If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:

Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());

A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.

Finally:

Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:

BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();

queue.put(myObject); // Blocks until queue isn't full.

YourObject myObject = queue.take(); // Blocks until queue isn't empty.

Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.

Change Placeholder Text using jQuery

Moving your first line to the bottom does it for me: http://jsfiddle.net/tcloninger/SEmNX/

$(function () {
    $('#serMemdd').change(function () {
        var k = $(this).val();
        if (k == 1) {
            $("#serMemtb").attr("placeholder", "Type a name (Lastname, Firstname)").placeholder();
        }
        else if (k == 2) {
            $("#serMemtb").attr("placeholder", "Type an ID").placeholder();
        }
        else if (k == 3) {
            $("#serMemtb").attr("placeholder", "Type a Location").placeholder();
        }
    });
    $('input[placeholder], textarea[placeholder]').placeholder();
});

Removing Java 8 JDK from Mac

Managing Java versions on Mac OSX is a nightmare. I recently switched over to using JDK 1.7, deleting JDK 6 from my MacBook entirely (I also had traces of JDK 5 - this laptop has been updated a few times).

Here's what I did to move to JDK 7.

1) download the latest from Oracle (http://www.oracle.com/technetwork/java/javase/downloads/index.html) and install it.

2) Remove (using rm - if you've got backups, you can revert if you make a mistake) all the JDK6 and JRE6 files.

At this stage, you should see:

% ls /Library/Java/JavaVirtualMachines/
jdk1.7.0_nn.jdk

(and nothing else)

3) In the folder /Library/Java/Extensions/, you'll need to remove all the old jar files, the ones that correspond to other releases of Java. If you don't, you'll get the infamous message about the wrong version of tools.jar (see Builds failing after upgrading to Java7, Missing Tools.jar and bad class versions). It is not enough to rename the jar files, because Java will open every jar in that folder - I moved mine into a sub-directory. It's safe to remove them once you know everything else works.

I haven't found I need to set JAVA_HOME for simple things.

Note: I just tried running IntelliJ and it will not start unless you have Apple's JDK 6 installed (see http://youtrack.jetbrains.com/issue/IDEA-93710). Same is true for Eclipse. Netbeans works fine.

Statically rotate font-awesome icons

This works perfectly

<i class="fa fa-power-off text-gray" style="transform: rotate(90deg);"></i>

align divs to the bottom of their container

You can cheat! Say your div is 20px high, place the div at the top of the next container and set

position: absolute;
top: -20px;

It may not be semantically clean but does scale with responsive designs

Oracle SELECT TOP 10 records

try

SELECT * FROM users FETCH NEXT 10 ROWS ONLY;

How Spring Security Filter Chain works

UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

No, UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter, and this contains a RequestMatcher, that means you can define your own processing url, this filter only handle the RequestMatcher matches the request url, the default processing url is /login.

Later filters can still handle the request, if the UsernamePasswordAuthenticationFilter executes chain.doFilter(request, response);.

More details about core fitlers

Does the form-login namespace element auto-configure these filters?

UsernamePasswordAuthenticationFilter is created by <form-login>, these are Standard Filter Aliases and Ordering

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

It depends on whether the before fitlers are successful, but FilterSecurityInterceptor is the last fitler normally.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, every fitlerChain has a RequestMatcher, if the RequestMatcher matches the request, the request will be handled by the fitlers in the fitler chain.

The default RequestMatcher matches all request if you don't config the pattern, or you can config the specific url (<http pattern="/rest/**").

If you want to konw more about the fitlers, I think you can check source code in spring security. doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)

How to delete all files from a specific folder?

Add the following namespace,

using System.IO;

and use the Directory class to reach on the specific folder:

string[] fileNames = Directory.GetFiles(@"your directory path");
foreach (string fileName in fileNames)
    File.Delete(fileName);

Implementing two interfaces in a class with same method. Which interface method is overridden?

This was marked as a duplicate to this question https://stackoverflow.com/questions/24401064/understanding-and-solving-the-diamond-problems-in-java

You need Java 8 to get a multiple inheritance problem, but it is still not a diamon problem as such.

interface A {
    default void hi() { System.out.println("A"); }
}

interface B {
    default void hi() { System.out.println("B"); }
}

class AB implements A, B { // won't compile
}

new AB().hi(); // won't compile.

As JB Nizet comments you can fix this my overriding.

class AB implements A, B {
    public void hi() { A.super.hi(); }
}

However, you don't have a problem with

interface D extends A { }

interface E extends A { }

interface F extends A {
    default void hi() { System.out.println("F"); }
}

class DE implement D, E { }

new DE().hi(); // prints A

class DEF implement D, E, F { }

new DEF().hi(); // prints F as it is closer in the heirarchy than A.

UITableView example for Swift

For completeness sake, and for those that do not wish to use the Interface Builder, here's a way of creating the same table as in Suragch's answer entirely programatically - albeit with a different size and position.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {

    var tableView: UITableView = UITableView()
    let animals = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
    let cellReuseIdentifier = "cell"

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.frame = CGRectMake(0, 50, 320, 200)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)

        self.view.addSubview(tableView)
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return animals.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!

        cell.textLabel?.text = animals[indexPath.row]

        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("You tapped cell number \(indexPath.row).")
    }

}

Make sure you have remembered to import UIKit.

Foreign key referencing a 2 columns primary key in SQL Server

Note that the fields must be in the same order. If the Primary Key you are referencing is specified as (Application, ID) then your foreign key must reference (Application, ID) and NOT (ID, Application) as they are seen as two different keys.

Convert JSON String to JSON Object c#

if you don't want or need a typed object try:

using Newtonsoft.Json;
// ...   
dynamic json  = JsonConvert.DeserializeObject(str);

or try for a typed object try:

Foo json  = JsonConvert.DeserializeObject<Foo>(str)

Android: install .apk programmatically

For ICS I´ve implemented your code and made a class that extends AsyncTask. I hope you appreciate it! Thanks for your code and solution.

public class UpdateApp extends AsyncTask<String,Void,Void>{
    private Context context;
    public void setContext(Context contextf){
        context = contextf;
    }

    @Override
    protected Void doInBackground(String... arg0) {
        try {
            URL url = new URL(arg0[0]);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            String PATH = "/mnt/sdcard/Download/";
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, "update.apk");
            if(outputFile.exists()){
                outputFile.delete();
            }
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/Download/update.apk")), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
            context.startActivity(intent);


        } catch (Exception e) {
            Log.e("UpdateAPP", "Update error! " + e.getMessage());
        }
        return null;
    }
}   

To use it, in your main activity call by this way:

atualizaApp = new UpdateApp();
atualizaApp.setContext(getApplicationContext());
atualizaApp.execute("http://serverurl/appfile.apk");

How to call a method in MainActivity from another class?

Use this code in sub Fragment of MainActivity to call the method on it.

((MainActivity) getActivity()).startChronometer();

How to implement a property in an interface

You should use abstract class to initialize a property. You can't inititalize in Inteface .

How to count the frequency of the elements in an unordered list?

def frequencyDistribution(data):
    return {i: data.count(i) for i in data}   

print frequencyDistribution([1,2,3,4])

...

 {1: 1, 2: 1, 3: 1, 4: 1}   # originalNumber: count

In which conda environment is Jupyter executing?

If the above ans doesn't work then try running conda install ipykernel in new env and then run jupyter notebook from any env, you will be able to see or switch between those kernels.

JavaScript: SyntaxError: missing ) after argument list

just posting in case anyone else has the same error...

I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.

The solution was to make the function asynchronous

function functionName(args) {}

becomes

async function functionName(args) {}

Get Filename Without Extension in Python

In most cases, you shouldn't use a regex for that.

os.path.splitext(filename)[0]

This will also handle a filename like .bashrc correctly by keeping the whole name.

Generate JSON string from NSDictionary in iOS

This will work in swift4 and swift5.

let dataDict = "the dictionary you want to convert in jsonString" 

let jsonData = try! JSONSerialization.data(withJSONObject: dataDict, options: JSONSerialization.WritingOptions.prettyPrinted)

let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String

print(jsonString)

how to find array size in angularjs

Just use the length property of a JavaScript array like so:

$scope.names.length

Also, I don't see a starting <script> tag in your code.

If you want the length inside your view, do it like so:

{{ names.length }}

PIL image to array (numpy array to array) - Python

I highly recommend you use the tobytes function of the Image object. After some timing checks this is much more efficient.

def jpg_image_to_array(image_path):
  """
  Loads JPEG image into 3D Numpy array of shape 
  (width, height, channels)
  """
  with Image.open(image_path) as image:         
    im_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
    im_arr = im_arr.reshape((image.size[1], image.size[0], 3))                                   
  return im_arr

The timings I ran on my laptop show

In [76]: %timeit np.fromstring(im.tobytes(), dtype=np.uint8)
1000 loops, best of 3: 230 µs per loop

In [77]: %timeit np.array(im.getdata(), dtype=np.uint8)
10 loops, best of 3: 114 ms per loop

```

Moving from position A to position B slowly with animation

Use jquery animate and give it a long duration say 2000

$("#Friends").animate({ 
        top: "-=30px",
      }, duration );

The -= means that the animation will be relative to the current top position.

Note that the Friends element must have position set to relative in the css:

#Friends{position:relative;}

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

Simply use the "utf-8-sig" codec:

fp = open("file.txt")
s = fp.read()
u = s.decode("utf-8-sig")

That gives you a unicode string without the BOM. You can then use

s = u.encode("utf-8")

to get a normal UTF-8 encoded string back in s. If your files are big, then you should avoid reading them all into memory. The BOM is simply three bytes at the beginning of the file, so you can use this code to strip them out of the file:

import os, sys, codecs

BUFSIZE = 4096
BOMLEN = len(codecs.BOM_UTF8)

path = sys.argv[1]
with open(path, "r+b") as fp:
    chunk = fp.read(BUFSIZE)
    if chunk.startswith(codecs.BOM_UTF8):
        i = 0
        chunk = chunk[BOMLEN:]
        while chunk:
            fp.seek(i)
            fp.write(chunk)
            i += len(chunk)
            fp.seek(BOMLEN, os.SEEK_CUR)
            chunk = fp.read(BUFSIZE)
        fp.seek(-BOMLEN, os.SEEK_CUR)
        fp.truncate()

It opens the file, reads a chunk, and writes it out to the file 3 bytes earlier than where it read it. The file is rewritten in-place. As easier solution is to write the shorter file to a new file like newtover's answer. That would be simpler, but use twice the disk space for a short period.

As for guessing the encoding, then you can just loop through the encoding from most to least specific:

def decode(s):
    for encoding in "utf-8-sig", "utf-16":
        try:
            return s.decode(encoding)
        except UnicodeDecodeError:
            continue
    return s.decode("latin-1") # will always work

An UTF-16 encoded file wont decode as UTF-8, so we try with UTF-8 first. If that fails, then we try with UTF-16. Finally, we use Latin-1 — this will always work since all 256 bytes are legal values in Latin-1. You may want to return None instead in this case since it's really a fallback and your code might want to handle this more carefully (if it can).

Installing Pandas on Mac OSX

Install pip.

Then install pandas with pip:

pip install pandas

Annotations from javax.validation.constraints not working

I came across this problem recently in a very similar situation: Met all requirements as the top-rated answer listed but still got the wrong result.

So I looked at my dependencies and found I was missing some of them. I corrected it by adding the missing dependencies.

I was using hibernate, the required dependencies were: Dependencies Snapshot

*Snapshot taken in class "Spring & Hibernate for Beginners" @ Udemy

How to include jQuery in ASP.Net project?

You might be looking for this Microsoft Ajax Content Delivery Network So you could just add

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>

To your aspx page.

Mongoose: findOneAndUpdate doesn't return updated document

Below shows the query for mongoose's findOneAndUpdate. Here new: true is used to get the updated doc and fields is used for specific fields to get.

eg. findOneAndUpdate(conditions, update, options, callback)

await User.findOneAndUpdate({
      "_id": data.id,
    }, { $set: { name: "Amar", designation: "Software Developer" } }, {
      new: true,
      fields: {
        'name': 1,
        'designation': 1
      }
    }).exec();

clearInterval() not working

The setInterval method returns an interval ID that you need to pass to clearInterval in order to clear the interval. You're passing a function, which won't work. Here's an example of a working setInterval/clearInterval

var interval_id = setInterval(myMethod,500);
clearInterval(interval_id);

Sequence Permission in Oracle

To grant a permission:

grant select on schema_name.sequence_name to user_or_role_name;

To check which permissions have been granted

select * from all_tab_privs where TABLE_NAME = 'sequence_name'

Google Maps API v3: InfoWindow not sizing correctly

Just to summarize all the solutions that worked for me in all browsers:

  • Don't use margins inside the infowindow, only padding.
  • Set a max-width for the infowindow:

    this.infowindow = new google.maps.InfoWindow({ maxWidth: 200 });

  • Wrap the contents of the infowindow with

    <div style="overflow:hidden;line-height:1.35;min-width:200px;">*CONTENT*</div>

    (change the min-width for the value you set on the infowindow maxWidth)

I have tested it and it worked on every browser, and I had over 400 markers...

Excel "External table is not in the expected format."

I had the same problem. which as resolved using these steps:

1.) Click File

2.) Select "save as"

3.) Click on drop down (Save as type)

enter image description here

4.) Select Excel 97-2003 Workbook

enter image description here

5.) Click on Save button

enter image description here

Python: Removing list element while iterating over list

Why not rewrite it to be

for element in somelist: 
   do_action(element)  

if check(element): 
    remove_element_from_list

See this question for how to remove from the list, though it looks like you've already seen that Remove items from a list while iterating

Another option is to do this if you really want to keep this the same

newlist = [] 
for element in somelist: 
   do_action(element)  

   if not check(element): 
      newlst.append(element)

App store link for "rate/review this app"

Swift 2 version

func jumpToAppStore(appId: String) {
    let url = "itms-apps://itunes.apple.com/app/id\(appId)"
    UIApplication.sharedApplication().openURL(NSURL(string: url)!)
}

Show/hide forms using buttons and JavaScript

Use the following code fragment to hide the form on button click.

document.getElementById("your form id").style.display="none";

And the following code to display it:

document.getElementById("your form id").style.display="block";

Or you can use the same function for both purposes:

function asd(a)
{
    if(a==1)
        document.getElementById("asd").style.display="none";
    else
        document.getElementById("asd").style.display="block";
}

And the HTML:

<form id="asd">form </form>
<button onclick="asd(1)">Hide</button>
<button onclick="asd(2)">Show</button>

Update div with jQuery ajax response html

It's also possible to use jQuery's .load()

$('#submitform').click(function() {
  $('#showresults').load('getinfo.asp #showresults', {
    txtsearch: $('#appendedInputButton').val()
  }, function() {
    // alert('Load was performed.')
    // $('#showresults').slideDown('slow')
  });
});

unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

We could modify the example above to use only part of the document that is fetched:

$( "#result" ).load( "ajax/test.html #container" );

When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.

In the shell, what does " 2>&1 " mean?

The numbers refer to the file descriptors (fd).

  • Zero is stdin
  • One is stdout
  • Two is stderr

2>&1 redirects fd 2 to 1.

This works for any number of file descriptors if the program uses them.

You can look at /usr/include/unistd.h if you forget them:

/* Standard file descriptors.  */
#define STDIN_FILENO    0   /* Standard input.  */
#define STDOUT_FILENO   1   /* Standard output.  */
#define STDERR_FILENO   2   /* Standard error output.  */

That said I have written C tools that use non-standard file descriptors for custom logging so you don't see it unless you redirect it to a file or something.

Can you get a Windows (AD) username in PHP?

This is a simple NTLM AD integration example, allows single sign on with Internet Explorer, requires login/configuration in other browsers.

PHP Example

<?php 
$user = $_SERVER['REMOTE_USER'];
$domain = getenv('USERDOMAIN');

?>

In your apache httpd.conf file

LoadModule authnz_sspi_module modules/mod_authnz_sspi.so

<Directory "/path/to/folder">
    AllowOverride     All
    Options           ExecCGI
    AuthName          "SSPI Authentication"
    AuthType          SSPI
    SSPIAuth          On
    SSPIAuthoritative On
    SSPIOmitDomain    On
    Require           valid-user
    Require           user "NT AUTHORITY\ANONYMOUS LOGON" denied
</Directory>

And if you need the module, this link is useful:

https://www.apachehaus.net/modules/mod_authnz_sspi/

Cast object to T

Actually, the responses bring up an interesting question, which is what you want your function to do in the case of error.

Maybe it would make more sense to construct it in the form of a TryParse method that attempts to read into T, but returns false if it can't be done?

    private static bool ReadData<T>(XmlReader reader, string value, out T data)
    {
        bool result = false;
        try
        {
            reader.MoveToAttribute(value);
            object readData = reader.ReadContentAsObject();
            data = readData as T;
            if (data == null)
            {
                // see if we can convert to the requested type
                data = (T)Convert.ChangeType(readData, typeof(T));
            }
            result = (data != null);
        }
        catch (InvalidCastException) { }
        catch (Exception ex)
        {
            // add in any other exception handling here, invalid xml or whatnot
        }
        // make sure data is set to a default value
        data = (result) ? data : default(T);
        return result;
    }

edit: now that I think about it, do I really need to do the convert.changetype test? doesn't the as line already try to do that? I'm not sure that doing that additional changetype call actually accomplishes anything. Actually, it might just increase the processing overhead by generating exception. If anyone knows of a difference that makes it worth doing, please post!

In Python try until no error

It won't get much cleaner. This is not a very clean thing to do. At best (which would be more readable anyway, since the condition for the break is up there with the while), you could create a variable result = None and loop while it is None. You should also adjust the variables and you can replace continue with the semantically perhaps correct pass (you don't care if an error occurs, you just want to ignore it) and drop the break - this also gets the rest of the code, which only executes once, out of the loop. Also note that bare except: clauses are evil for reasons given in the documentation.

Example incorporating all of the above:

result = None
while result is None:
    try:
        # connect
        result = get_data(...)
    except:
         pass
# other code that uses result but is not involved in getting it

PermGen elimination in JDK 8

Oracle's JVM implementation for Java 8 got rid of the PermGen model and replaced it with Metaspace.

z-index issue with twitter bootstrap dropdown menu

Solved by removing the -webkit-transform from the navbar:

-webkit-transform: translate3d(0, 0, 0);

pillaged from https://stackoverflow.com/a/12653766/391925

How do you run multiple programs in parallel from a bash script?

There is a very useful program that calls nohup.

     nohup - run a command immune to hangups, with output to a non-tty

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

As the previous answers exhaustively covered the theory behind the value categories, there is just another thing I'd like to add: you can actually play with it and test it.

For some hands-on experimentation with the value categories, you can make use of the decltype specifier. Its behavior explicitly distinguishes between the three primary value categories (xvalue, lvalue, and prvalue).

Using the preprocessor saves us some typing ...

Primary categories:

#define IS_XVALUE(X) std::is_rvalue_reference<decltype((X))>::value
#define IS_LVALUE(X) std::is_lvalue_reference<decltype((X))>::value
#define IS_PRVALUE(X) !std::is_reference<decltype((X))>::value

Mixed categories:

#define IS_GLVALUE(X) (IS_LVALUE(X) || IS_XVALUE(X))
#define IS_RVALUE(X) (IS_PRVALUE(X) || IS_XVALUE(X))

Now we can reproduce (almost) all the examples from cppreference on value category.

Here are some examples with C++17 (for terse static_assert):

void doesNothing(){}
struct S
{
    int x{0};
};
int x = 1;
int y = 2;
S s;

static_assert(IS_LVALUE(x));
static_assert(IS_LVALUE(x+=y));
static_assert(IS_LVALUE("Hello world!"));
static_assert(IS_LVALUE(++x));

static_assert(IS_PRVALUE(1));
static_assert(IS_PRVALUE(x++));
static_assert(IS_PRVALUE(static_cast<double>(x)));
static_assert(IS_PRVALUE(std::string{}));
static_assert(IS_PRVALUE(throw std::exception()));
static_assert(IS_PRVALUE(doesNothing()));

static_assert(IS_XVALUE(std::move(s)));
// The next one doesn't work in gcc 8.2 but in gcc 9.1. Clang 7.0.0 and msvc 19.16 are doing fine.
static_assert(IS_XVALUE(S().x)); 

The mixed categories are kind of boring once you figured out the primary category.

For some more examples (and experimentation), check out the following link on compiler explorer. Don't bother reading the assembly, though. I added a lot of compilers just to make sure it works across all the common compilers.

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

This seems to be an issue with local Maven repository. (i.e. .m2 folder) may be due to some corrupt .jar file

For me, the following actions helped to overcome this issue.

  1. On my local file system, I've deleted the directory .m2 (Maven local repository)

  2. In Eclipse, updated the project (select Maven > Update Project)

  3. Ran the app again on Tomcat server.

IP to Location using Javascript

Either one of the following links should take care of this:

http://ipinfodb.com/ip_location_api_json.php

http://www.adam-mcfarland.net/2009/11/19/simple-ip-geolocation-using-javascript-and-the-google-ajax-search-api/

Those links have tutorials for getting a users location through Javascript. However, they do so through an API to an external data service. If you have an extremely high traffic site, you might want to hosting the data yourself (or getting a premium api service). To host everything yourself, you will have to host a database with IP Geolocation and use ajax to feed the users location into Javascript. If this is the approach you want to take, you can get a free database of IP information below:

http://www.ipinfodb.com/ip_database.php

Please note that this method entails having to periodically update the database to stay accurate in tracing ips to locations.

Setting the Vim background colors

Try adding

set background=dark

to your .gvimrc too. This work well for me.

String is immutable. What exactly is the meaning?

Hope the below code would clarify your doubts :

public static void testString() {
    String str = "Hello";
    System.out.println("Before String Concat: "+str);
    str.concat("World");
    System.out.println("After String Concat: "+str);
    StringBuffer sb = new StringBuffer("Hello");
    System.out.println("Before StringBuffer Append: "+sb);
    sb.append("World");
    System.out.println("After StringBuffer Append: "+sb);
}

Before String Concat: Hello
After String Concat: Hello
Before StringBuffer Append: Hello
After StringBuffer Append: HelloWorld

How to use Checkbox inside Select Option

Alternate Vanilla JS version with click outside to hide checkboxes:

let expanded = false;
const multiSelect = document.querySelector('.multiselect');

multiSelect.addEventListener('click', function(e) {
  const checkboxes = document.getElementById("checkboxes");
    if (!expanded) {
    checkboxes.style.display = "block";
    expanded = true;
  } else {
    checkboxes.style.display = "none";
    expanded = false;
  }
  e.stopPropagation();
}, true)

document.addEventListener('click', function(e){
  if (expanded) {
    checkboxes.style.display = "none";
    expanded = false;
  }
}, false)

I'm using addEventListener instead of onClick in order to take advantage of the capture/bubbling phase options along with stopPropagation(). You can read more about the capture/bubbling here: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

The rest of the code matches vitfo's original answer (but no need for onclick() in the html). A couple of people have requested this functionality sans jQuery.

Here's codepen example https://codepen.io/davidysoards/pen/QXYYYa?editors=1010

Sorting an ArrayList of objects using a custom sorting order

BalusC and bguiz have already given very complete answers on how to use Java's built-in Comparators.

I just want to add that google-collections has an Ordering class which is more "powerful" than the standard Comparators. It might be worth checking out. You can do cool things such as compounding Orderings, reversing them, ordering depending on a function's result for your objects...

Here is a blog post that mentions some of its benefits.

Using LINQ to group by multiple properties and sum

Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
                   });

Determine if map contains a value for a key?

As long as the map is not a multimap, one of the most elegant ways would be to use the count method

if (m.count(key))
    // key exists

The count would be 1 if the element is indeed present in the map.

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Start by figuring out what your current working directory is for your running script.
Add this line at the beginning:

puts Dir.pwd.

This will tell you in which current working directory ruby is running your script. You will most likely see it's not where you assume it is. Then make sure you're specifying pathnames properly for windows. See the docs here how to properly format pathnames for windows:

http://www.ruby-doc.org/core/classes/IO.html

Then either use Dir.chdir to change the working directory to the place where text.txt is, or specify the absolute pathname to the file according to the instructions in the IO docs above. That SHOULD do it...

EDIT

Adding a 3rd solution which might be the most convenient one, if you're putting the text files among your script files:

Dir.chdir(File.dirname(__FILE__))

This will automatically change the current working directory to the same directory as the .rb file that is running the script.

Execute SQL script from command line

Take a look at the sqlcmd utility. It allows you to execute SQL from the command line.

http://msdn.microsoft.com/en-us/library/ms162773.aspx

It's all in there in the documentation, but the syntax should look something like this:

sqlcmd -U myLogin -P myPassword -S MyServerName -d MyDatabaseName 
    -Q "DROP TABLE MyTable"

Check if inputs are empty using jQuery

A clean CSS-only solution this would be:

input[type="radio"]:read-only {
        pointer-events: none;
}

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

I'm using this:

var isIframe = (self.frameElement && (self.frameElement+"").indexOf("HTMLIFrameElement") > -1);

How can I reference a dll in the GAC from Visual Studio?

Assuming you alredy tried to "Add Reference..." as explained above and did not succeed, you can have a look here. They say you have to meet some prerequisites: - .NET 3.5 SP1 - Windows Installer 4.5

EDIT: According to this post it is a known issue.

And this could be the solution you're looking for :)

presenting ViewController with NavigationViewController swift

My navigation bar was not showing, so I have used the following method in Swift 2 iOS 9

let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("Dashboard") as! Dashboard

// Creating a navigation controller with viewController at the root of the navigation stack.
let navController = UINavigationController(rootViewController: viewController)
self.presentViewController(navController, animated:true, completion: nil)

What is the best way to add a value to an array in state

For functional components with hooks

const [searches, setSearches] = useState([]);

// Using .concat(), no wrapper function (not recommended)
setSearches(searches.concat(query));

// Using .concat(), wrapper function (recommended)
setSearches(searches => searches.concat(query));

// Spread operator, no wrapper function (not recommended)
setSearches([...searches, query]);

// Spread operator, wrapper function (recommended)
setSearches(searches => [...searches, query]);

source: https://medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc

Convert JS object to JSON string

In angularJS

angular.toJson(obj, pretty);

obj: Input to be serialized into JSON.

pretty(optional):
If set to true, the JSON output will contain newlines and whitespace. If set to an integer, the JSON output will contain that many spaces per indentation.

(default: 2)

Pandas How to filter a Series

If you like a chained operation, you can also use compress function:

test = pd.Series({
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
})

test.compress(lambda x: x != 1)

# 383    3.000000
# 737    9.000000
# 833    8.166667
# dtype: float64

Getting time difference between two times in PHP

You can also use DateTime class:

$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');

Result:

1 second(s)

Store query result in a variable using in PL/pgSQL

You can use the following example to store a query result in a variable using PL/pgSQL:

 select * into demo from maintenanceactivitytrack ; 
    raise notice'p_maintenanceid:%',demo;

How to substitute shell variables in complex text files

Call the perl binary, in search and replace per line mode ( the -pi ) by running the perl code ( the -e) in the single quotes, which iterates over the keys of the special %ENV hash containing the exported variable names as keys and the exported variable values as the keys' values and for each iteration simple replace a string containing a $<<key>> with its <<value>>.

 perl -pi -e 'foreach $key(sort keys %ENV){ s/\$$key/$ENV{$key}/g}' file

Caveat: An additional logic handling is required for cases in which two or more vars start with the same string ...

How to create RecyclerView with multiple view type?

I recommend this library from Hannes Dorfmann. It encapsulates all the logic related to particular view type in a separate object called "AdapterDelegate". https://github.com/sockeqwe/AdapterDelegates

public class CatAdapterDelegate extends AdapterDelegate<List<Animal>> {

  private LayoutInflater inflater;

  public CatAdapterDelegate(Activity activity) {
    inflater = activity.getLayoutInflater();
  }

  @Override public boolean isForViewType(@NonNull List<Animal> items, int position) {
    return items.get(position) instanceof Cat;
  }

  @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {
    return new CatViewHolder(inflater.inflate(R.layout.item_cat, parent, false));
  }

  @Override public void onBindViewHolder(@NonNull List<Animal> items, int position,
      @NonNull RecyclerView.ViewHolder holder, @Nullable List<Object> payloads) {

    CatViewHolder vh = (CatViewHolder) holder;
    Cat cat = (Cat) items.get(position);

    vh.name.setText(cat.getName());
  }

  static class CatViewHolder extends RecyclerView.ViewHolder {

    public TextView name;

    public CatViewHolder(View itemView) {
      super(itemView);
      name = (TextView) itemView.findViewById(R.id.name);
    }
  }
}

public class AnimalAdapter extends ListDelegationAdapter<List<Animal>> {

  public AnimalAdapter(Activity activity, List<Animal> items) {

    // DelegatesManager is a protected Field in ListDelegationAdapter
    delegatesManager.addDelegate(new CatAdapterDelegate(activity))
                    .addDelegate(new DogAdapterDelegate(activity))
                    .addDelegate(new GeckoAdapterDelegate(activity))
                    .addDelegate(23, new SnakeAdapterDelegate(activity));

    // Set the items from super class.
    setItems(items);
  }
}

How to call javascript function on page load in asp.net

use your code within

  <script type="text/javascript">
     function window.onload()
       {

        var d = new Date()
        var gmtOffSet = -d.getTimezoneOffset();
        var gmtHours = Math.floor(gmtOffSet / 60);
        var GMTMin = Math.abs(gmtOffSet % 60);
        var dot = ".";
        var retVal = "" + gmtHours + dot + GMTMin;
       document.getElementById('<%= offSet.ClientID%>').value = retVal;

      }
  </script>

JavaScript math, round to two decimal places

To get the result with two decimals, you can do like this :

var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;

The value to be rounded is multiplied by 100 to keep the first two digits, then we divide by 100 to get the actual result.

What is AndroidX?

AndroidX is the open-source project that the Android team uses to develop, test, package, version and release libraries within Jetpack.

After hours of struggling, I solved it by including the following within app/build.gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

Put these flags in your gradle.properties

android.enableJetifier=true
android.useAndroidX=true

Changes in gradle:

implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0-alpha04'

When migrating on Android studio, the app/gradle file is automatically updated with the correction library impleemntations from the standard library

Refer to: https://developer.android.com/jetpack/androidx/migrate

How to make matrices in Python?

The answer to your question depends on what your learning goals are. If you are trying to get matrices to "click" so you can use them later, I would suggest looking at a Numpy array instead of a list of lists. This will let you slice out rows and columns and subsets easily. Just try to get a column from a list of lists and you will be frustrated.

Using a list of lists as a matrix...

Let's take your list of lists for example:

L = [list("ABCDE") for i in range(5)]

It is easy to get sub-elements for any row:

>>> L[1][0:3]
['A', 'B', 'C']

Or an entire row:

>>> L[1][:]
['A', 'B', 'C', 'D', 'E']

But try to flip that around to get the same elements in column format, and it won't work...

>>> L[0:3][1]
['A', 'B', 'C', 'D', 'E']

>>> L[:][1]
['A', 'B', 'C', 'D', 'E']

You would have to use something like list comprehension to get all the 1th elements....

>>> [x[1] for x in L]
['B', 'B', 'B', 'B', 'B']

Enter matrices

If you use an array instead, you will get the slicing and indexing that you expect from MATLAB or R, (or most other languages, for that matter):

>>> import numpy as np
>>> Y = np.array(list("ABCDE"*5)).reshape(5,5)
>>> print Y
[['A' 'B' 'C' 'D' 'E']
 ['A' 'B' 'C' 'D' 'E']
 ['A' 'B' 'C' 'D' 'E']
 ['A' 'B' 'C' 'D' 'E']
 ['A' 'B' 'C' 'D' 'E']]
>>> print Y.transpose()
[['A' 'A' 'A' 'A' 'A']
 ['B' 'B' 'B' 'B' 'B']
 ['C' 'C' 'C' 'C' 'C']
 ['D' 'D' 'D' 'D' 'D']
 ['E' 'E' 'E' 'E' 'E']]

Grab row 1 (as with lists):

>>> Y[1,:]
array(['A', 'B', 'C', 'D', 'E'], 
      dtype='|S1')

Grab column 1 (new!):

>>> Y[:,1]
array(['B', 'B', 'B', 'B', 'B'], 
      dtype='|S1')

So now to generate your printed matrix:

for mycol in Y.transpose():
    print " ".join(mycol)


A A A A A
B B B B B
C C C C C
D D D D D
E E E E E

Spring Boot Adding Http Request Interceptors

I had the same issue of WebMvcConfigurerAdapter being deprecated. When I searched for examples, I hardly found any implemented code. Here is a piece of working code.

create a class that extends HandlerInterceptorAdapter

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import me.rajnarayanan.datatest.DataTestApplication;
@Component
public class EmployeeInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(DataTestApplication.class);
    @Override
    public boolean preHandle(HttpServletRequest request, 
            HttpServletResponse response, Object handler) throws Exception {

            String x = request.getMethod();
            logger.info(x + "intercepted");
        return true;
    }

}

then Implement WebMvcConfigurer interface

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import me.rajnarayanan.datatest.interceptor.EmployeeInterceptor;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Autowired
    EmployeeInterceptor employeeInterceptor ;

    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(employeeInterceptor).addPathPatterns("/employee");
    }
}

How do I run a spring boot executable jar in a Production environment?

Please note that since Spring Boot 1.3.0.M1, you are able to build fully executable jars using Maven and Gradle.

For Maven, just include the following in your pom.xml:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <executable>true</executable>
    </configuration>
</plugin>

For Gradle add the following snippet to your build.gradle:

springBoot {
    executable = true
}

The fully executable jar contains an extra script at the front of the file, which allows you to just symlink your Spring Boot jar to init.d or use a systemd script.

init.d example:

$ln -s /var/yourapp/yourapp.jar /etc/init.d/yourapp

This allows you to start, stop and restart your application like:

$/etc/init.d/yourapp start|stop|restart

Or use a systemd script:

[Unit]
Description=yourapp
After=syslog.target

[Service]
ExecStart=/var/yourapp/yourapp.jar
User=yourapp
WorkingDirectory=/var/yourapp
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

More information at the following links:

Python speed testing - Time Difference - milliseconds

I know this is late, but I actually really like using:

import time
start = time.time()

##### your timed code here ... #####

print "Process time: " + (time.time() - start)

time.time() gives you seconds since the epoch. Because this is a standardized time in seconds, you can simply subtract the start time from the end time to get the process time (in seconds). time.clock() is good for benchmarking, but I have found it kind of useless if you want to know how long your process took. For example, it's much more intuitive to say "my process takes 10 seconds" than it is to say "my process takes 10 processor clock units"

>>> start = time.time(); sum([each**8.3 for each in range(1,100000)]) ; print (time.time() - start)
3.4001404476250935e+45
0.0637760162354
>>> start = time.clock(); sum([each**8.3 for each in range(1,100000)]) ; print (time.clock() - start)
3.4001404476250935e+45
0.05

In the first example above, you are shown a time of 0.05 for time.clock() vs 0.06377 for time.time()

>>> start = time.clock(); time.sleep(1) ; print "process time: " + (time.clock() - start)
process time: 0.0
>>> start = time.time(); time.sleep(1) ; print "process time: " + (time.time() - start)
process time: 1.00111794472

In the second example, somehow the processor time shows "0" even though the process slept for a second. time.time() correctly shows a little more than 1 second.

add onclick function to a submit button

html:

<form method="post" name="form1" id="form1">    
    <input id="submit" name="submit" type="submit" value="Submit" onclick="eatFood();" />
</form>

Javascript: to submit the form using javascript

function eatFood() {
document.getElementById('form1').submit();
}

to show onclick message

function eatFood() {
alert('Form has been submitted');
}

What is the difference between task and thread?

A task is something you want done.

A thread is one of the many possible workers which performs that task.

In .NET 4.0 terms, a Task represents an asynchronous operation. Thread(s) are used to complete that operation by breaking the work up into chunks and assigning to separate threads.

Start / Stop a Windows Service from a non-Administrator user account

Below I have put together everything I learned about Starting/Stopping a Windows Service from a non-Admin user account, if anyone needs to know.

Primarily, there are two ways in which to Start / Stop a Windows Service. 1. Directly accessing the service through logon Windows user account. 2. Accessing the service through IIS using Network Service account.

Command line command to start / stop services:

C:/> net start <SERVICE_NAME>
C:/> net stop <SERVICE_NAME>

C# Code to start / stop services:

ServiceController service = new ServiceController(SERVICE_NAME);

//Start the service
if (service.Status == ServiceControllerStatus.Stopped)
{
      service.Start();
      service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10.0));
}

//Stop the service
if (service.Status == ServiceControllerStatus.Running)
{
      service.Stop();
      service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10.0));
}

Note 1: When accessing the service through IIS, create a Visual Studio C# ASP.NET Web Application and put the code in there. Deploy the WebService to IIS Root Folder (C:\inetpub\wwwroot\) and you're good to go. Access it by the url http:///.

1. Direct Access Method

If the Windows User Account from which either you give the command or run the code is a non-Admin account, then you need to set the privileges to that particular user account so it has the ability to start and stop Windows Services. This is how you do it. Login to an Administrator account on the computer which has the non-Admin account from which you want to Start/Stop the service. Open up the command prompt and give the following command:

C:/>sc sdshow <SERVICE_NAME>

Output of this will be something like this:

D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)

It lists all the permissions each User / Group on this computer has with regards to .

A description of one part of above command is as follows:

    D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)

It has the default owner, default group, and it has the Security descriptor control flags (A;;CCLCSWRPWPDTLOCRRC;;;SY):

ace_type - "A": ACCESS_ALLOWED_ACE_TYPE,
ace_flags - n/a,
rights - CCLCSWRPWPDTLOCRRC,  please refer to the Access Rights and Access Masks and Directory Services Access Rights
CC: ADS_RIGHT_DS_CREATE_CHILD - Create a child DS object.
LC: ADS_RIGHT_ACTRL_DS_LIST - Enumerate a DS object.
SW: ADS_RIGHT_DS_SELF - Access allowed only after validated rights checks supported by the object are performed. This flag can be used alone to perform all validated rights checks of the object or it can be combined with an identifier of a specific validated right to perform only that check.
RP: ADS_RIGHT_DS_READ_PROP - Read the properties of a DS object.
WP: ADS_RIGHT_DS_WRITE_PROP - Write properties for a DS object.
DT: ADS_RIGHT_DS_DELETE_TREE - Delete a tree of DS objects.
LO: ADS_RIGHT_DS_LIST_OBJECT - List a tree of DS objects.
CR: ADS_RIGHT_DS_CONTROL_ACCESS - Access allowed only after extended rights checks supported by the object are performed. This flag can be used alone to perform all extended rights checks on the object or it can be combined with an identifier of a specific extended right to perform only that check.
RC: READ_CONTROL - The right to read the information in the object's security descriptor, not including the information in the system access control list (SACL). (This is a Standard Access Right, please read more http://msdn.microsoft.com/en-us/library/aa379607(VS.85).aspx)
object_guid - n/a,
inherit_object_guid - n/a,
account_sid - "SY": Local system. The corresponding RID is SECURITY_LOCAL_SYSTEM_RID.

Now what we need to do is to set the appropriate permissions to Start/Stop Windows Services to the groups or users we want. In this case we need the current non-Admin user be able to Start/Stop the service so we are going to set the permissions to that user. To do that, we need the SID of that particular Windows User Account. To obtain it, open up the Registry (Start > regedit) and locate the following registry key.

LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList

Under that there is a seperate Key for each an every user account in this computer, and the key name is the SID of each account. SID are usually of the format S-1-5-21-2103278432-2794320136-1883075150-1000. Click on each Key, and you will see on the pane to the right a list of values for each Key. Locate "ProfileImagePath", and by it's value you can find the User Name that SID belongs to. For instance, if the user name of the account is SACH, then the value of "ProfileImagePath" will be something like "C:\Users\Sach". So note down the SID of the user account you want to set the permissions to.

Note2: Here a simple C# code sample which can be used to obtain a list of said Keys and it's values.

//LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList RegistryKey
RegistryKey profileList = Registry.LocalMachine.OpenSubKey(keyName);

//Get a list of SID corresponding to each account on the computer
string[] sidList = profileList.GetSubKeyNames();

foreach (string sid in sidList)
{
    //Based on above names, get 'Registry Keys' corresponding to each SID
    RegistryKey profile = Registry.LocalMachine.OpenSubKey(Path.Combine(keyName, sid));

    //SID
    string strSID = sid;
    //UserName which is represented by above SID    
    string strUserName = (string)profile.GetValue("ProfileImagePath");
}

Now that we have the SID of the user account we want to set the permissions to, let's get down to it. Let's assume the SID of the user account is S-1-5-21-2103278432-2794320136-1883075150-1000. Copy the output of the [sc sdshow ] command to a text editor. It will look like this:

D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)

Now, copy the (A;;CCLCSWRPWPDTLOCRRC;;;SY) part of the above text, and paste it just before the S:(AU;... part of the text. Then change that part to look like this: (A;;RPWPCR;;;S-1-5-21-2103278432-2794320136-1883075150-1000)

Then add sc sdset at the front, and enclose the above part with quotes. Your final command should look something like the following:

sc sdset <SERVICE_NAME> "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPCR;;;S-1-5-21-2103278432-2794320136-1883075150-1000)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"

Now execute this in your command prompt, and it should give the output as follows if successful:

[SC] SetServiceObjectSecurity SUCCESS

Now we're good to go! Your non-Admin user account has been granted permissions to Start/Stop your service! Try loggin in to the user account and Start/Stop the service and it should let you do that.

2. Access through IIS Method

In this case, we need to grant the permission to the IIS user "Network Services" instead of the logon Windows user account. The procedure is the same, only the parameters of the command will be changed. Since we set the permission to "Network Services", replace SID with the string "NS" in the final sdset command we used previously. The final command should look something like this:

sc sdset <SERVICE_NAME> "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPCR;;;NS)S:(AU;FA;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;WD)"

Execute it in the command prompt from an Admin user account, and voila! You have the permission to Start / Stop the service from any user account (irrespective of whether it ia an Admin account or not) using a WebMethod. Refer to Note1 to find out how to do so.

Append to the end of a file in C

Open with append:

pFile2 = fopen("myfile2.txt", "a");

then just write to pFile2, no need to fseek().

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

Excerpt from PostgreSQL documentation:

Restricting and cascading deletes are the two most common options. [...] CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well.

This means that if you delete a category – referenced by books – the referencing book will also be deleted by ON DELETE CASCADE.

Example:

CREATE SCHEMA shire;

CREATE TABLE shire.clans (
    id serial PRIMARY KEY,
    clan varchar
);

CREATE TABLE shire.hobbits (
    id serial PRIMARY KEY,
    hobbit varchar,
    clan_id integer REFERENCES shire.clans (id) ON DELETE CASCADE
);

DELETE FROM clans will CASCADE to hobbits by REFERENCES.

sauron@mordor> psql
sauron=# SELECT * FROM shire.clans;
 id |    clan    
----+------------
  1 | Baggins
  2 | Gamgi
(2 rows)

sauron=# SELECT * FROM shire.hobbits;
 id |  hobbit  | clan_id 
----+----------+---------
  1 | Bilbo    |       1
  2 | Frodo    |       1
  3 | Samwise  |       2
(3 rows)

sauron=# DELETE FROM shire.clans WHERE id = 1 RETURNING *;
 id |  clan   
----+---------
  1 | Baggins
(1 row)

DELETE 1
sauron=# SELECT * FROM shire.hobbits;
 id |  hobbit  | clan_id 
----+----------+---------
  3 | Samwise  |       2
(1 row)

If you really need the opposite (checked by the database), you will have to write a trigger!

How do I get the base URL with PHP?

Try this:

<?php echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>

Learn more about the $_SERVER predefined variable.

If you plan on using https, you can use this:

function url(){
  return sprintf(
    "%s://%s%s",
    isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
    $_SERVER['SERVER_NAME'],
    $_SERVER['REQUEST_URI']
  );
}

echo url();
#=> http://127.0.0.1/foo

Per this answer, please make sure to configure your Apache properly so you can safely depend on SERVER_NAME.

<VirtualHost *>
    ServerName example.com
    UseCanonicalName on
</VirtualHost>

NOTE: If you're depending on the HTTP_HOST key (which contains user input), you still have to make some cleanup, remove spaces, commas, carriage return, etc. Anything that is not a valid character for a domain. Check the PHP builtin parse_url function for an example.

How to name an object within a PowerPoint slide?

THIS IS NOT AN ANSWER TO THE ORIGINAL QUESTION, IT'S AN ANSWER TO @Teddy's QUESTION IN @Dudi's ANSWER'S COMMENTS

Here's a way to list id's in the active presentation to the immediate window (Ctrl + G) in VBA editor:

Sub ListAllShapes()

    Dim curSlide As Slide
    Dim curShape As Shape

    For Each curSlide In ActivePresentation.Slides
        Debug.Print curSlide.SlideID
        For Each curShape In curSlide.Shapes

                If curShape.TextFrame.HasText Then
                    Debug.Print curShape.Id
                End If

        Next curShape
    Next curSlide
End Sub

How can I implement prepend and append with regular JavaScript?

Here's a snippet to get you going:

theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.innerHTML = 'Are we there yet?';

// append theKid to the end of theParent
theParent.appendChild(theKid);

// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);

theParent.firstChild will give us a reference to the first element within theParent and put theKid before it.

How to clear the entire array?

Find a better use for myself: I usually test if a variant is empty, and all of the above methods fail with the test. I found that you can actually set a variant to empty:

Dim aTable As Variant
If IsEmpty(aTable) Then
    'This is true
End If
ReDim aTable(2)
If IsEmpty(aTable) Then
    'This is False
End If
ReDim aTable(2)
aTable = Empty
If IsEmpty(aTable) Then
    'This is true
End If
ReDim aTable(2)
Erase aTable
If IsEmpty(aTable) Then
    'This is False
End If

this way i get the behaviour i want

Use basic authentication with jQuery and Ajax

The examples above are a bit confusing, and this is probably the best way:

$.ajaxSetup({
  headers: {
    'Authorization': "Basic " + btoa(USERNAME + ":" + PASSWORD)
  }
});

I took the above from a combination of Rico and Yossi's answer.

The btoa function Base64 encodes a string.

count number of rows in a data frame in R based on group

Just for completion the data.table solution:

library(data.table)

mydf <- structure(list(ID = c(110L, 111L, 121L, 131L, 141L), 
                       MONTH.YEAR = c("JAN. 2012", "JAN. 2012", 
                                      "FEB. 2012", "FEB. 2012", 
                                      "MAR. 2012"), 
                       VALUE = c(1000L, 2000L, 3000L, 4000L, 5000L)), 
                  .Names = c("ID", "MONTH.YEAR", "VALUE"), 
                  class = "data.frame", row.names = c(NA, -5L))

setDT(mydf)
mydf[, .(`Number of rows` = .N), by = MONTH.YEAR]

   MONTH.YEAR Number of rows
1:  JAN. 2012              2
2:  FEB. 2012              2
3:  MAR. 2012              1

What is the effect of encoding an image in base64?

Here's a really helpful overview of when to base64 encode and when not to by David Calhoun.

Basic answer = gzipped base64 encoded files will be roughly comparable in file size to standard binary (jpg/png). Gzip'd binary files will have a smaller file size.

Takeaway = There's some advantage to encoding and gzipping your UI icons, etc, but unwise to do this for larger images.