Programs & Examples On #Ribbon control

How to write text on a image in windows using python opencv2

This code uses cv2.putText to overlay text on an image. You need NumPy and OpenCV installed.

import numpy as np
import cv2

# Create a black image
img = np.zeros((512,512,3), np.uint8)

# Write some Text

font                   = cv2.FONT_HERSHEY_SIMPLEX
bottomLeftCornerOfText = (10,500)
fontScale              = 1
fontColor              = (255,255,255)
lineType               = 2

cv2.putText(img,'Hello World!', 
    bottomLeftCornerOfText, 
    font, 
    fontScale,
    fontColor,
    lineType)

#Display the image
cv2.imshow("img",img)

#Save image
cv2.imwrite("out.jpg", img)

cv2.waitKey(0)

Showing percentages above bars on Excel column graph

Either

  1. Use a line series to show the %
  2. Update the data labels above the bars to link back directly to other cells

Method 2 by step

  • add data-lables
  • right-click the data lable
  • goto the edit bar and type in a refence to a cell (C4 in this example)
  • this changes the data lable from the defulat value (2000) to a linked cell with the 15%

enter image description here

Convert xlsx to csv in Linux with command line

Using the Gnumeric spreadsheet application which comes which a commandline utility called ssconvert is indeed super simple:

find . -name '*.xlsx' -exec ssconvert -T Gnumeric_stf:stf_csv {} \;

and you're done!

A weighted version of random.choice

I'm probably too late to contribute anything useful, but here's a simple, short, and very efficient snippet:

def choose_index(probabilies):
    cmf = probabilies[0]
    choice = random.random()
    for k in xrange(len(probabilies)):
        if choice <= cmf:
            return k
        else:
            cmf += probabilies[k+1]

No need to sort your probabilities or create a vector with your cmf, and it terminates once it finds its choice. Memory: O(1), time: O(N), with average running time ~ N/2.

If you have weights, simply add one line:

def choose_index(weights):
    probabilities = weights / sum(weights)
    cmf = probabilies[0]
    choice = random.random()
    for k in xrange(len(probabilies)):
        if choice <= cmf:
            return k
        else:
            cmf += probabilies[k+1]

Form onSubmit determine which submit button was pressed

All of the answers above are very good but I cleaned it up a little bit.

This solution automatically puts the name of the submit button pressed into the action hidden field. Both the javascript on the page and the server code can check the action hidden field value as needed.

The solution uses jquery to automatically apply to all submit buttons.

<input type="hidden" name="action" id="action" />
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        //when a submit button is clicked, put its name into the action hidden field
        $(":submit").click(function () { $("#action").val(this.name); });
    });
</script>
<input type="submit" class="bttn" value="<< Back" name="back" />
<input type="submit" class="bttn" value="Finish" name="finish" />
<input type="submit" class="bttn" value="Save" name="save" />
<input type="submit" class="bttn" value="Next >>" name="next" />
<input type="submit" class="bttn" value="Delete" name="delete" />
<input type="button" class="bttn" name="cancel" value="Cancel" onclick="window.close();" />

Then write code like this into your form submit handler.

 if ($("#action").val() == "delete") {
     return confirm("Are you sure you want to delete the selected item?");
 }

Get the value of checked checkbox?

<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="3" name="mailId[]">

<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="1" name="mailId[]">
function getValue(value){
    alert(value);
}

C# looping through an array

Not too difficult. Just increment the counter of the for loop by 3 each iteration and then offset the indexer to get the batch of 3 at a time:

for(int i=0; i < theData.Length; i+=3)
{
    var item1 = theData[i];
    var item2 = theData[i+1];
    var item3 = theData[i+2];
}

If the length of the array wasn't garuanteed to be a multiple of three, you would need to check the upper bound with theData.Length - 2 instead.

Disabling Strict Standards in PHP 5.4

If you would need to disable E_DEPRACATED also, use:

php_value error_reporting 22527

In my case CMS Made Simple was complaining "E_STRICT is enabled in the error_reporting" as well as "E_DEPRECATED is enabled". Adding that one line to .htaccess solved both misconfigurations.

Pandas KeyError: value not in index

please try this to clean and format your column names:

df.columns = (df.columns.str.strip().str.upper()
              .str.replace(' ', '_')
              .str.replace('(', '')
              .str.replace(')', ''))

How to correctly link php-fpm and Nginx Docker containers?

I know it is kind an old post, but I've had the same problem and couldn't understand why your code didn't work. After a LOT of tests I've found out why.

It seems like fpm receives the full path from nginx and tries to find the files in the fpm container, so it must be the exactly the same as server.root in the nginx config, even if it doesn't exist in the nginx container.

To demonstrate:

docker-compose.yml

nginx:
    build: .
    ports:
        - "80:80"
    links:
        - fpm
fpm:
    image: php:fpm
    ports:
        - ":9000"

    # seems like fpm receives the full path from nginx
    # and tries to find the files in this dock, so it must
    # be the same as nginx.root
    volumes:
        - ./:/complex/path/to/files/

/etc/nginx/conf.d/default.conf

server {
    listen  80;

    # this path MUST be exactly as docker-compose.fpm.volumes,
    # even if it doesn't exist in this dock.
    root /complex/path/to/files;

    location / {
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/.+\.php(/|$) {
        fastcgi_pass fpm:9000;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

Dockerfile

FROM nginx:latest
COPY ./default.conf /etc/nginx/conf.d/

usr/bin/ld: cannot find -l<nameOfTheLibrary>

I had this problem with compiling LXC on a fresh VM with Centos 7.8. I tried all the above and failed. Some suggested removing the -static flag from the compiler configuration but I didn't want to change anything.

The only thing that helped was to install glibc-static and retry. Hope that helps someone.

Cannot find Dumpbin.exe

Dumpbin.exe of VS2005 generally presents in C:\Program Files\Microsoft Visual Studio 8\VC\bin. If you would have installed VS2005 in drive other the C, please search in that. And then set that path in the system variable PATH.

What does DIM stand for in Visual Basic and BASIC?

Dim have had different meanings attributed to it.

I've found references about Dim meaning "Declare In Memory", the more relevant reference is a document on Dim Statement published Oracle as part of the Siebel VB Language Reference. Of course, you may argue that if you do not declare the variables in memory where do you do it? Maybe "Declare in Module" is a good alternative considering how Dim is used.

In my opinion, "Declare In Memory" is actually a mnemonic, created to make easier to learn how to use Dim. I see "Declare in Memory" as a better meaning as it describes what it does in current versions of the language, but it is not the proper meaning.

In fact, at the origins of Basic Dim was only used to declare arrays. For regular variables no keyword was used, instead their type was inferred from their name. For instance, if the name of the variable ends with $ then it is a string (this is something that you could see even in method names up to VB6, for example Mid$). And so, you used Dim only to give dimension to the arrays (notice that ReDim resizes arrays).


Really, Does It Matter? I mean, it is a keyword it has its meaning inside an artificial language. It doesn't have to be a word in English or any other natural language. So it could just mean whatever you want, all that matters is that it works.

Anyhow, that is not completely true. As BASIC is part of our culture, and understanding why it came to be as it is - I hope - will help improve our vision of the world.


I sit in from of my computer with a desire to help preserve this little piece of our culture that seems lost, replaced by our guessing of what it was. And so, I have dug MSDN both current and the old CDs from the 1998 version. I have also searched the documention for the old QBasic [Had to use DOSBox] and managed to get some Darthmouth manual, all to find how they talk about Dim. For my disappointment, they don't say what does Dim stand for, and only say how it is used.

But before my hope was dim, I managed to find this BBC Microcomputer System Used Guide (that claims to be from 1984, and I don't want to doubt it). The BBC Microcomputer used a variant of BASIC called BBC BASIC and it is described in the document. Even though, it doesn't say what does Dim stand for, it says (on page 104):

... you can dimension N$ to have as many entries as you want. For example, DIM N$(1000) would create a string array with space for 1000 different names.

As I said, it doesn't say that Dim stands for dimension, but serves as proof to show that associating Dim with Dimension was a common thing at the time of writing that document.

Now, I got a rewarding surprise later on (at page 208), the title for the section that describes the DIM keyword (note: that is not listed in the contents) says:

DIM dimension of an array

So, I didn't get the quote "Dim stands for..." but I guess it is clear that any decent human being that is able to read those document will consider that Dim means dimension.


With renewed hope, I decided to search about how Dim was chosen. Again, I didn't find an account on the subject, still I was able to find a definitive quote:

Before you can use an array, you must define it in a DIM (dimension) statement.

You can find this as part of the True BASIC Online User's Guides at the web page of True BASIC inc, a company founded by Thomas Eugene Kurtz, co-author of BASIC.


So, In reallity, Dim is a shorthand for DIMENSION, and yes. That existed in FORTRAN before, so it is likely that it was picked by influence of FORTRAN as Patrick McDonald said in his answer.


Dim sum as string = "this is not a chinese meal" REM example usage in VB.NET ;)

onclick open window and specific size

Using function in typescript

openWindow(){
    //you may choose to deduct some value from current screen size
    let height = window.screen.availHeight-100;
    let width = window.screen.availWidth-150;
    window.open("http://your_url",`width=${width},height=${height}`);
}

What Vim command(s) can be used to quote/unquote words?

VIM for vscode does it awsomely. It's based one vim-surround if you don't use vscode.

Some examples:

"test" with cursor inside quotes type cs"' to end up with 'test'

"test" with cursor inside quotes type ds" to end up with test

"test" with cursor inside quotes type cs"t and enter 123> to end up with <123>test

test with cursor on word test type ysaw) to end up with (test)

How do I include a pipe | in my linux find -exec command?

You can also pipe to a while loop that can do multiple actions on the file which find locates. So here is one for looking in jar archives for a given java class file in folder with a large distro of jar files

find /usr/lib/eclipse/plugins -type f -name \*.jar | while read jar; do echo $jar; jar tf $jar | fgrep IObservableList ; done

the key point being that the while loop contains multiple commands referencing the passed in file name separated by semicolon and these commands can include pipes. So in that example I echo the name of the matching file then list what is in the archive filtering for a given class name. The output looks like:

/usr/lib/eclipse/plugins/org.eclipse.core.contenttype.source_3.4.1.R35x_v20090826-0451.jar /usr/lib/eclipse/plugins/org.eclipse.core.databinding.observable_1.2.0.M20090902-0800.jar org/eclipse/core/databinding/observable/list/IObservableList.class /usr/lib/eclipse/plugins/org.eclipse.search.source_3.5.1.r351_v20090708-0800.jar /usr/lib/eclipse/plugins/org.eclipse.jdt.apt.core.source_3.3.202.R35x_v20091130-2300.jar /usr/lib/eclipse/plugins/org.eclipse.cvs.source_1.0.400.v201002111343.jar /usr/lib/eclipse/plugins/org.eclipse.help.appserver_3.1.400.v20090429_1800.jar

in my bash shell (xubuntu10.04/xfce) it really does make the matched classname bold as the fgrep highlights the matched string; this makes it really easy to scan down the list of hundreds of jar files that were searched and easily see any matches.

on windows you can do the same thing with:

for /R %j in (*.jar) do @echo %j & @jar tf %j | findstr IObservableList

note that in that on windows the command separator is '&' not ';' and that the '@' suppresses the echo of the command to give a tidy output just like the linux find output above; although findstr is not make the matched string bold so you have to look a bit closer at the output to see the matched class name. It turns out that the windows 'for' command knows quite a few tricks such as looping through text files...

enjoy

Sorting a List<int>

Keeping it simple is the key.

Try Below.

var values = new int[5,7,3];
values = values.OrderBy(p => p).ToList();

adding noise to a signal in python

For those who want to add noise to a multi-dimensional dataset loaded within a pandas dataframe or even a numpy ndarray, here's an example:

import pandas as pd
# create a sample dataset with dimension (2,2)
# in your case you need to replace this with 
# clean_signal = pd.read_csv("your_data.csv")   
clean_signal = pd.DataFrame([[1,2],[3,4]], columns=list('AB'), dtype=float) 
print(clean_signal)
"""
print output: 
    A    B
0  1.0  2.0
1  3.0  4.0
"""
import numpy as np 
mu, sigma = 0, 0.1 
# creating a noise with the same dimension as the dataset (2,2) 
noise = np.random.normal(mu, sigma, [2,2]) 
print(noise)

"""
print output: 
array([[-0.11114313,  0.25927152],
       [ 0.06701506, -0.09364186]])
"""
signal = clean_signal + noise
print(signal)
"""
print output: 
          A         B
0  0.888857  2.259272
1  3.067015  3.906358
""" 

jQuery textbox change event

$('#input').on("input",function () {alert('changed');});

works for me.

How to exclude 0 from MIN formula Excel

Try this formula

=SMALL((A1,C1,E1),INDEX(FREQUENCY((A1,C1,E1),0),1)+1)

Both SMALL and FREQUENCY functions accept "unions" as arguments, i.e. single cell references separated by commas and enclosed in brackets like (A1,C1,E1).

So the formula uses FREQUENCY and INDEX to find the number of zeroes in a range and if you add 1 to that you get the k value such that the kth smallest is always the minimum value excluding zero.

I'm assuming you don't have negative numbers.....

Is there a way to get a list of all current temporary tables in SQL Server?

If you need to 'see' the list of temporary tables, you could simply log the names used. (and as others have noted, it is possible to directly query this information)

If you need to 'see' the content of temporary tables, you will need to create real tables with a (unique) temporary name.

You can trace the SQL being executed using SQL Profiler:

[These articles target SQL Server versions later than 2000, but much of the advice is the same.]

If you have a lengthy process that is important to your business, it's a good idea to log various steps (step name/number, start and end time) in the process. That way you have a baseline to compare against when things don't perform well, and you can pinpoint which step(s) are causing the problem more quickly.

How to select element using XPATH syntax on Selenium for Python?

HTML

<div id='a'>
  <div>
    <a class='click'>abc</a>
  </div>
</div>

You could use the XPATH as :

//div[@id='a']//a[@class='click']

output

<a class="click">abc</a>

That said your Python code should be as :

driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")

How to return value from function which has Observable subscription inside?

In the single-threaded,asynchronous,promise-oriented,reactive-trending world of javascript async/await is the imperative-style programmer's best friend:

(async()=>{

    const store = of("someValue");
    function getValueFromObservable () {
        return store.toPromise();
    }
    console.log(await getValueFromObservable())

})();

And in case store is a sequence of multiple values:

  const aiFrom = require('ix/asynciterable').from;
  (async function() {

     const store = from(["someValue","someOtherValue"]);
     function getValuesFromObservable () {
        return aiFrom(store);
     }
     for await (let num of getValuesFromObservable()) {
       console.log(num);
     }
  })();

div inside php echo

Try this,

<?php  if ( ($cart->count_product) > 0) { ?>
         <div class="my_class"><?php print $cart->count_product; ?></div>
<?php } else { 
          print ''; 
}  ?>

Finding an element in an array in Java

You might want to consider using a Collection implementation instead of a flat array.

The Collection interface defines a contains(Object o) method, which returns true/false.

ArrayList implementation defines an indexOf(Object o), which gives an index, but that method is not on all collection implementations.

Both these methods require proper implementations of the equals() method, and you probably want a properly implemented hashCode() method just in case you are using a hash based Collection (e.g. HashSet).

Change Title of Javascript Alert

As others have said, you can't do that either using alert()or confirm().

You can, however, create an external HTML document containing your error message and an OK button, set its <title> element to whatever you want, then display it in a modal dialog box using showModalDialog().

How to determine whether an object has a given property in JavaScript

Since question was regarding clunkiness of property checking, and one regular usecase for that being validation of function argument options objects, thought I'd mention a library-free short way of testing existence of multiple properties. Disclaimer: It does require ECMAScript 5 (but IMO anyone still using IE8 deserves a broken web).

function f(opts) {
  if(!["req1","req2"].every(opts.hasOwnProperty, opts)) {
      throw new Error("IllegalArgumentException");
  }
  alert("ok");
}
f({req1: 123});  // error
f({req1: 123, req2: 456});  // ok

How can I make directory writable?

To make the parent directory as well as all other sub-directories writable, just add -R

chmod -R a+w <directory>

Better way to generate array of all letters in the alphabet

Using Java 8 streams

  char [] alphabets = Stream.iterate('a' , x -> (char)(x + 1))
            .limit(26)
            .map(c -> c.toString())
            .reduce("", (u , v) -> u + v).toCharArray();

How to convert integer to char in C?

To convert int to char use:

int a=8;  
char c=a+'0';
printf("%c",c);       //prints 8  

To Convert char to int use:

char c='5';
int a=c-'0';
printf("%d",a);        //prints 5

How to convert a Datetime string to a current culture datetime string

This works for me,

DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;
DateTimeFormatInfo ukDtfi = new CultureInfo("en-GB", false).DateTimeFormat;
string result = Convert.ToDateTime("26/09/2015",ukDtfi).ToString(usDtfi.ShortDatePattern);

How do I check whether a file exists without exceptions?

use os.path.exists() to get file exist or not.

path = '/home/ie/SachinSaga/scripts/subscription_unit_reader_file/'
def file_check_at_location(filename):
    return os.path.exists(path + str(filename).replace(' ',''))


file_name="dummy.txt"
responce = file_check_at_location(file_name)

if responce:
   print('file found at location')
else:
   print('file not found at location')

How do CSS triangles work?

If you want to apply border to the triangle read this: Create a triangle with CSS?

Almost all the answers focus on the triangle built using border so I am going to elaborate the linear-gradient method (as started in the answer of @lima_fil).

Using a degree value like 45° will force us to respect a specific ratio of height/width in order to obtain the triangle we want and this won't be responsive:

_x000D_
_x000D_
.tri {_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background:linear-gradient(45deg, transparent 49.5%,red 50%);_x000D_
  _x000D_
  /*To illustrate*/_x000D_
  border:1px solid;_x000D_
}
_x000D_
Good one_x000D_
<div class="tri"></div>_x000D_
bad one_x000D_
<div class="tri" style="width:150px"></div>_x000D_
bad one_x000D_
<div class="tri" style="height:30px"></div>
_x000D_
_x000D_
_x000D_

Instead of doing this we should consider predefined values of direction like to bottom, to top, etc. In this case we can obtain any kind of triangle shape while keeping it responsive.

1) Rectangle triangle

To obtain such triangle we need one linear-gradient and a diagonal direction like to bottom right, to top left, to bottom left, etc

_x000D_
_x000D_
.tri-1,.tri-2 {_x000D_
  display:inline-block;_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background:linear-gradient(to bottom left, transparent 49.5%,red 50%);_x000D_
  border:1px solid;_x000D_
  animation:change 2s linear infinite alternate;_x000D_
}_x000D_
.tri-2 {_x000D_
  background:linear-gradient(to top right, transparent 49.5%,red 50%);_x000D_
  border:none;_x000D_
}_x000D_
_x000D_
@keyframes change {_x000D_
  from {_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
  }_x000D_
  to {_x000D_
    height:50px;_x000D_
    width:180px;_x000D_
  }_x000D_
}
_x000D_
<div class="tri-1"></div>_x000D_
<div class="tri-2"></div>
_x000D_
_x000D_
_x000D_

2) isosceles triangle

For this one we will need 2 linear-gradient like above and each one will take half the width (or the height). It's like we create a mirror image of the first triangle.

_x000D_
_x000D_
.tri {_x000D_
  display:inline-block;_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  background-image:_x000D_
  linear-gradient(to bottom right, transparent 49.5%,red 50%),_x000D_
  linear-gradient(to bottom left,  transparent 49.5%,red 50%);_x000D_
  background-size:50.3% 100%; /* I use a value slightly bigger than 50% to avoid having a small gap between both gradient*/_x000D_
  background-position:left,right;_x000D_
  background-repeat:no-repeat;_x000D_
  _x000D_
  animation:change 2s linear infinite alternate;_x000D_
}_x000D_
_x000D_
_x000D_
@keyframes change {_x000D_
  from {_x000D_
    width:100px;_x000D_
    height:100px;_x000D_
  }_x000D_
  to {_x000D_
    height:50px;_x000D_
    width:180px;_x000D_
  }_x000D_
}
_x000D_
<div class="tri"></div>
_x000D_
_x000D_
_x000D_

3) equilateral triangle

This one is a bit tricky to handle as we need to keep a relation between the height and width of the gradient. We will have the same triangle as above but we will make the calculation more complex in order to transform the isosceles triangle to an equilateral one.

To make it easy, we will consider that the width of our div is known and the height is big enough to be able to draw our triangle inside (height >= width).

CSS triangle with gradient

We have our two gradient g1 and g2, the blue line is the width of the div w and each gradient will have 50% of it (w/2) and each side of the triangle sould be equal to w. The green line is the height of both gradient hg and we can easily obtain the formula below:

(w/2)² + hg² = w² ---> hg = (sqrt(3)/2) * w ---> hg = 0.866 * w

We can rely on calc() in order to do our calculation and to obtain the needed result:

_x000D_
_x000D_
.tri {_x000D_
  --w:100px;_x000D_
  width:var(--w);_x000D_
  height:100px;_x000D_
  display:inline-block;_x000D_
  background-image:_x000D_
  linear-gradient(to bottom right, transparent 49.5%,red 50%),_x000D_
  linear-gradient(to bottom left,  transparent 49.5%,red 50%);_x000D_
  background-size:calc(var(--w)/2 + 0.5px)  calc(0.866 * var(--w));_x000D_
  background-position:_x000D_
    left bottom,right bottom;_x000D_
  background-repeat:no-repeat;_x000D_
  _x000D_
}
_x000D_
<div class="tri"></div>_x000D_
<div class="tri" style="--w:80px"></div>_x000D_
<div class="tri" style="--w:50px"></div>
_x000D_
_x000D_
_x000D_

Another way is to control the height of div and keep the syntax of gradient easy:

_x000D_
_x000D_
.tri {_x000D_
  --w:100px;_x000D_
  width:var(--w);_x000D_
  height:calc(0.866 * var(--w));_x000D_
  display:inline-block;_x000D_
  background:_x000D_
   linear-gradient(to bottom right, transparent 49.8%,red 50%) left,_x000D_
   linear-gradient(to bottom left,  transparent 49.8%,red 50%) right;_x000D_
  background-size:50.2% 100%;_x000D_
  background-repeat:no-repeat;_x000D_
  _x000D_
}
_x000D_
<div class="tri"></div>_x000D_
<div class="tri" style="--w:80px"></div>_x000D_
<div class="tri" style="--w:50px"></div>
_x000D_
_x000D_
_x000D_

4) Random triangle

To obtain a random triangle, it's easy as we simply need to remove the condition of 50% of each one BUT we should keep two condition (both should have the same height and the sum of both width should be 100%).

_x000D_
_x000D_
.tri-1 {_x000D_
  width:100px;_x000D_
  height:100px;_x000D_
  display:inline-block;_x000D_
  background-image:_x000D_
  linear-gradient(to bottom right, transparent 50%,red 0),_x000D_
  linear-gradient(to bottom left, transparent 50%,red 0);_x000D_
  background-size:20% 60%,80% 60%;_x000D_
  background-position:_x000D_
    left bottom,right bottom;_x000D_
  background-repeat:no-repeat;_x000D_
  _x000D_
 _x000D_
}
_x000D_
<div class="tri-1"></div>
_x000D_
_x000D_
_x000D_

But what if we want to define a value for each side? We simply need to do calculation again!

CSS triangle with gradient

Let's define hg1 and hg2 as the height of our gradient (both are equal to the red line) then wg1 and wg2 as the width of our gradient (wg1 + wg2 = a). I will not going to detail the calculation but at then end we will have:

wg2 = (a²+c²-b²)/(2a)
wg1 = a - wg2
hg1 = hg2 = sqrt(b² - wg1²) = sqrt(c² - wg2²)

Now we have reached the limit of CSS as even with calc() we won't be able to implement this so we simply need to gather the final result manually and use them as fixed size:

_x000D_
_x000D_
.tri {_x000D_
  --wg1: 20px; _x000D_
  --wg2: 60px;_x000D_
  --hg:30px; _x000D_
  width:calc(var(--wg1) + var(--wg2));_x000D_
  height:100px;_x000D_
  display:inline-block;_x000D_
  background-image:_x000D_
  linear-gradient(to bottom right, transparent 49.5%,red 50%),_x000D_
  linear-gradient(to bottom left,  transparent 49.5%,red 50%);_x000D_
_x000D_
  background-size:var(--wg1) var(--hg),var(--wg2) var(--hg);_x000D_
  background-position:_x000D_
    left bottom,right bottom;_x000D_
  background-repeat:no-repeat;_x000D_
  _x000D_
}
_x000D_
<div class="tri" ></div>_x000D_
_x000D_
<div class="tri" style="--wg1:80px;--wg2:60px;--hg:100px;" ></div>
_x000D_
_x000D_
_x000D_

Bonus

We should not forget that we can also apply rotation and/or skew and we have more option to obtain more triangle:

_x000D_
_x000D_
.tri {_x000D_
  --wg1: 20px; _x000D_
  --wg2: 60px;_x000D_
  --hg:30px; _x000D_
  width:calc(var(--wg1) + var(--wg2) - 0.5px);_x000D_
  height:100px;_x000D_
  display:inline-block;_x000D_
  background-image:_x000D_
  linear-gradient(to bottom right, transparent 49%,red 50%),_x000D_
  linear-gradient(to bottom left,  transparent 49%,red 50%);_x000D_
_x000D_
  background-size:var(--wg1) var(--hg),var(--wg2) var(--hg);_x000D_
  background-position:_x000D_
    left bottom,right bottom;_x000D_
  background-repeat:no-repeat;_x000D_
  _x000D_
}
_x000D_
<div class="tri" ></div>_x000D_
_x000D_
<div class="tri" style="transform:skewY(25deg)"></div>_x000D_
_x000D_
<div class="tri" style="--wg1:80px;--wg2:60px;--hg:100px;" ></div>_x000D_
_x000D_
_x000D_
<div class="tri" style="--wg1:80px;--wg2:60px;--hg:100px;transform:rotate(20deg)" ></div>
_x000D_
_x000D_
_x000D_

And of course we should keep in mind the SVG solution which can be more suitable in some situation:

_x000D_
_x000D_
svg {_x000D_
 width:100px;_x000D_
 height:100px;_x000D_
}_x000D_
_x000D_
polygon {_x000D_
  fill:red;_x000D_
}
_x000D_
<svg viewBox="0 0 100 100"><polygon points="0,100 0,0 100,100" /></svg>_x000D_
<svg viewBox="0 0 100 100"><polygon points="0,100 50,0 100,100" /></svg>_x000D_
<svg viewBox="0 0 100 100"><polygon points="0,100 50,23 100,100" /></svg>_x000D_
<svg viewBox="0 0 100 100"><polygon points="20,60 50,43 80,100" /></svg>
_x000D_
_x000D_
_x000D_

How to convert entire dataframe to numeric while preserving decimals?

You might need to do some checking. You cannot safely convert factors directly to numeric. as.character must be applied first. Otherwise, the factors will be converted to their numeric storage values. I would check each column with is.factor then coerce to numeric as necessary.

df1[] <- lapply(df1, function(x) {
    if(is.factor(x)) as.numeric(as.character(x)) else x
})
sapply(df1, class)
#         a         b 
# "numeric" "numeric" 

How to do scanf for single char in C

Here is a similiar thing that I would like to share,

while you're working on Visual Studio you could get an error like:

'scanf': function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS

To prevent this, you should write it in the following format

A single character may be read as follows:

char c;
scanf_s("%c", &c, 1);

When multiple characters for non-null terminated strings are read, integers are used as the width specification and the buffer size.

char c[4];
scanf_s("%4c", &c, _countof(c));

OpenCV with Network Cameras

#include <stdio.h>
#include "opencv.hpp"


int main(){

    CvCapture *camera=cvCaptureFromFile("http://username:pass@cam_address/axis-cgi/mjpg/video.cgi?resolution=640x480&req_fps=30&.mjpg");
    if (camera==NULL)
        printf("camera is null\n");
    else
        printf("camera is not null");

    cvNamedWindow("img");
    while (cvWaitKey(10)!=atoi("q")){
        double t1=(double)cvGetTickCount();
        IplImage *img=cvQueryFrame(camera);
        double t2=(double)cvGetTickCount();
        printf("time: %gms  fps: %.2g\n",(t2-t1)/(cvGetTickFrequency()*1000.), 1000./((t2-t1)/(cvGetTickFrequency()*1000.)));
        cvShowImage("img",img);
    }
    cvReleaseCapture(&camera);
}

How to parse a string to an int in C++?

If you have C++11, the appropriate solutions nowadays are the C++ integer conversion functions in <string>: stoi, stol, stoul, stoll, stoull. They throw appropriate exceptions when given incorrect input and use the fast and small strto* functions under the hood.

If you are stuck with an earlier revision of C++, it would be forward-portable of you to mimic these functions in your implementation.

What are Java command line options to set to allow JVM to be remotely debugged?

For java 1.5 or greater:

java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>

For java 1.4:

java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>

For java 1.3:

java -Xnoagent -Djava.compiler=NONE -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>

Here is output from a simple program:

java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044 HelloWhirled
Listening for transport dt_socket at address: 1044
Hello whirled

Inserting Data into Hive Table

It's a limitation of hive.

1.You cannot update data after it is inserted

2.There is no "insert into table values ... " statement

3.You can only load data using bulk load

4.There is not "delete from " command

5.You can only do bulk delete

But you still want to insert record from hive console than you can do select from statck. refer this

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

If you happen to use CRA with default yarn package manager use the following. Worked for me.

yarn remove node-sass 
yarn add [email protected]

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

Reading a .txt file using Scanner class in Java

The file you read in must have exactly the file name you specify: "10_random" not "10_random.txt" not "10_random.blah", it must exactly match what you are asking for. You can change either one to match so that they line up, but just be sure they do. It may help to show the file extensions in whatever OS you're using.

Also, for file location, it must be located in the working directory (same level) as the final executable (the .class file) that is the result of compilation.

What tool can decompile a DLL into C++ source code?

There really isn't any way of doing this as most of the useful information is discarded in the compilation process. However, you may want to take a look at this site to see if you can find some way of extracting something from the DLL.

What is @RenderSection in asp.net MVC

Here the defination of Rendersection from MSDN

In layout pages, renders the content of a named section.MSDN

In _layout.cs page put

@RenderSection("Bottom",false)

Here render the content of bootom section and specifies false boolean property to specify whether the section is required or not.

@section Bottom{
       This message form bottom.
}

That meaning if you want to bottom section in all pages, then you must use false as the second parameter at Rendersection method.

How do I assert equality on two classes without an equals method?

From your comments to other answers, I don't understand what you want.

Just for the sake of discussion, lets say that the the class did override the equals method.

So your UT will look something like:

SomeType expected = // bla
SomeType actual = // bli

Assert.assertEquals(expected, actual). 

And you are done. Moreover, you can not get the "full equality picture" if the assertion fails.

From what I understand, you are saying that even if the type did override equals, you would not be interested in it, since you want to get the "full equality picture". So there is no point in extending and overriding equals either.

So you have to options: either compare property by property, using reflection or hard-coded checks, I would suggest the latter. Or: compare human readable representations of these objects.

For example, you can create a helper class that serializes the type you wish tocompare to an XML document and than compare the resulting XML! in this case, you can visually see what exactly is equal and what is not.

This approach will give you the opportunity to look at the full picture but it is also relatively cumbersome (and a little error prone at first).

Get records with max value for each group of grouped SQL results

My simple solution for SQLite (and probably MySQL):

SELECT *, MAX(age) FROM mytable GROUP BY `Group`;

However it doesn't work in PostgreSQL and maybe some other platforms.

In PostgreSQL you can use DISTINCT ON clause:

SELECT DISTINCT ON ("group") * FROM "mytable" ORDER BY "group", "age" DESC;

How to add elements of a string array to a string array list?

I prefer this,

List<String> temp = Arrays.asList(speciesArr);
species.addAll(temp);

The reason is Arrays.asList() method will create a fixed sized List. So if you directly store it into species then you will not be able to add any more element, still its not read-only. You can surely edit your items. So take it into temporary list.

Alternative for this is,

Collections.addAll(species, speciesArr);

In this case, you can add, edit, remove your items.

What does 'low in coupling and high in cohesion' mean

An example might be helpful. Imagine a system which generates data and puts it into a data store, either a file on disk or a database.

High Cohesion can be achieved by separate the data store code from the data production code. (and in fact separating the disk storage from the database storage).

Low Coupling can be achieved by making sure that the data production doesn't have any unnecessary knowledge of the data store (e.g. doesn't ask the data store about filenames or db connections).

Java: how to add image to Jlabel?

the shortest code is :

JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));

stringPictureURL is PATH of image .

Mean per group in a data.frame

This type of operation is exactly what aggregate was designed for:

d <- read.table(text=
'Name     Month  Rate1     Rate2
Aira       1      12        23
Aira       2      18        73
Aira       3      19        45
Ben        1      53        19
Ben        2      22        87
Ben        3      19        45
Cat        1      22        87
Cat        2      67        43
Cat        3      45        32', header=TRUE)

aggregate(d[, 3:4], list(d$Name), mean)

  Group.1    Rate1    Rate2
1    Aira 16.33333 47.00000
2     Ben 31.33333 50.33333
3     Cat 44.66667 54.00000

Here we aggregate columns 3 and 4 of data.frame d, grouping by d$Name, and applying the mean function.


Or, using a formula interface:

aggregate(. ~ Name, d[-2], mean)

Rounding integer division (instead of truncating)

Borrowing from @ericbn I prefere defines like

#define DIV_ROUND_INT(n,d) ((((n) < 0) ^ ((d) < 0)) ? (((n) - (d)/2)/(d)) : (((n) + (d)/2)/(d)))
or if you work only with unsigned ints
#define DIV_ROUND_UINT(n,d) ((((n) + (d)/2)/(d)))

How to convert SQL Server's timestamp column to datetime format

Works fine, except this message:

Implicit conversion from data type varchar to timestamp is not allowed. Use the CONVERT function to run this query

So yes, TIMESTAMP (RowVersion) is NOT a DATE :)

To be honest, I fidddled around quite some time myself to find a way to convert it to a date.

Best way is to convert it to INT and compare. That's what this type is meant to be.

If you want a date - just add a Datetime column and live happily ever after :)

cheers mac

How to get screen dimensions as pixels in Android

Kotlin

fun getScreenHeight(activity: Activity): Int {
    val metrics = DisplayMetrics()
    activity.windowManager.defaultDisplay.getMetrics(metrics)
    return metrics.heightPixels
}

fun getScreenWidth(activity: Activity): Int {
    val metrics = DisplayMetrics()
    activity.windowManager.defaultDisplay.getMetrics(metrics)
    return metrics.widthPixels
}

Fast way to discover the row count of a table in PostgreSQL

You can get the count by the below query (without * or any column names).

select from table_name;

How do I run a batch script from within a batch script?

Run parallelly on separate command windows in minimized state

dayStart.bat

start "startOfficialSoftwares" /min cmd /k call startOfficialSoftwares.bat
start "initCodingEnvironment" /min cmd /k call initCodingEnvironment.bat
start "updateProjectSource" /min cmd /k call updateProjectSource.bat
start "runCoffeeMachine" /min cmd /k call runCoffeeMachine.bat

Run sequentially on same window

release.bat

call updateDevelVersion.bat
call mergeDevelIntoMaster.bat
call publishProject.bat

jQuery OR Selector?

Daniel A. White Solution works great for classes.

I've got a situation where I had to find input fields like donee_1_card where 1 is an index.

My solution has been

$("input[name^='donee']" && "input[name*='card']")

Though I am not sure how optimal it is.

How to display HTML in TextView?

If you want to be able to configure it through xml without any modification in java code you may find this idea helpful. Simply you call init from constructor and set the text as html

public class HTMLTextView extends TextView {
    ... constructors calling init...
    private void init(){
       setText(Html.fromHtml(getText().toString()));
    }    
}

xml:

<com.package.HTMLTextView
android:text="@string/about_item_1"/>

could not access the package manager. is the system running while installing android application

Once you see this error, wait for emulator to show lock screen. And then relaunch the app in your IDE and check the emulator again. It works for me always.

In Android studio, you can relaunch by clicking the green play button or ctrl + r.

How would I access variables from one class to another?

Can you explain why you want to do this?

You're playing around with instance variables/attributes which won't migrate from one class to another (they're bound not even to ClassA, but to a particular instance of ClassA that you created when you wrote ClassA()). If you want to have changes in one class show up in another, you can use class variables:

class ClassA(object):
   var1 = 1
   var2 = 2
   @classmethod
   def method(cls):
       cls.var1 = cls.var1 + cls.var2
       return cls.var1

In this scenario, ClassB will pick up the values on ClassA from inheritance. You can then access the class variables via ClassA.var1, ClassB.var1 or even from an instance ClassA().var1 (provided that you haven't added an instance method var1 which will be resolved before the class variable in attribute lookup.

I'd have to know a little bit more about your particular use case before I know if this is a course of action that I would actually recommend though...

Configuring angularjs with eclipse IDE

Netbeans 8.0 (beta at the time of this post) has Angular support as well as HTML5 support.

Check out this Oracle article: https://blogs.oracle.com/geertjan/entry/integrated_angularjs_development

How do I add space between two variables after a print in Python

You can do it this way in python3:

print(a,b,end=" ")

Retrieving the output of subprocess.call()

The following captures stdout and stderr of the process in a single variable. It is Python 2 and 3 compatible:

from subprocess import check_output, CalledProcessError, STDOUT

command = ["ls", "-l"]
try:
    output = check_output(command, stderr=STDOUT).decode()
    success = True 
except CalledProcessError as e:
    output = e.output.decode()
    success = False

If your command is a string rather than an array, prefix this with:

import shlex
command = shlex.split(command)

How can I load storyboard programmatically from class?

The extension below will allow you to load a Storyboard and it's associated UIViewController. Example: If you have a UIViewController named ModalAlertViewController and a storyboard named "ModalAlert" e.g.

let vc: ModalAlertViewController = UIViewController.loadStoryboard("ModalAlert")

Will load both the Storyboard and UIViewController and vc will be of type ModalAlertViewController. Note Assumes that the storyboard's Storyboard ID has the same name as the storyboard and that the storyboard has been marked as Is Initial View Controller.

extension UIViewController {
    /// Loads a `UIViewController` of type `T` with storyboard. Assumes that the storyboards Storyboard ID has the same name as the storyboard and that the storyboard has been marked as Is Initial View Controller.
    /// - Parameter storyboardName: Name of the storyboard without .xib/nib suffix.
    static func loadStoryboard<T: UIViewController>(_ storyboardName: String) -> T? {
        let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
        if let vc = storyboard.instantiateViewController(withIdentifier: storyboardName) as? T {
            vc.loadViewIfNeeded() // ensures vc.view is loaded before returning
            return vc
        }
        return nil
    }
}

How can I convert tabs to spaces in every file of a directory?

No body mentioned rpl? Using rpl you can replace any string. To convert tabs to spaces,

rpl -R -e "\t" "    "  .

very simple.

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

Adding rows dynamically with jQuery

Untested. Modify to suit:

$form = $('#my-form');

$rows = $form.find('.person-input-row');

$('button#add-new').click(function() {

    $rows.find(':first').clone().insertAfter($rows.find(':last'));

    $justInserted = $rows.find(':last');
    $justInserted.hide();
    $justInserted.find('input').val(''); // it may copy values from first one
    $justInserted.slideDown(500);


});

This is better than copying innerHTML because you will lose all attached events etc.

What is the correct way to do a CSS Wrapper?

You don't need a wrapper, just use the body as the wrapper.

CSS:

body {
    margin:0 auto;
    width:200px;
}

HTML:

<body>
    <p>some content</p>
<body>

How can I wait for a thread to finish with .NET?

I took a little different approach. There is a counter option in previous answers, and I just applied it a bit differently. I was spinning off numerous threads and incremented a counter and decremented a counter as a thread started and stopped. Then in the main method I wanted to pause and wait for threads to complete I did.

while (threadCounter > 0)
{
    Thread.Sleep(500); // Make it pause for half second so that we don’t spin the CPU out of control.
}

This is documented in my blog post: http://www.adamthings.com/post/2012/07/11/ensure-threads-have-finished-before-method-continues-in-c/

Where value in column containing comma delimited values

The solution tbaxter120 suggested worked for me but I needed something that will be supported both in MySQL & Oracle & MSSQL, and here it is:

WHERE (CONCAT(',' ,CONCAT(RTRIM(MyColumn), ','))) LIKE CONCAT('%,' , CONCAT(@search , ',%'))

formGroup expects a FormGroup instance

There are a few issues in your code

  • <div [formGroup]="form"> outside of a <form> tag
  • <form [formGroup]="form"> but the name of the property containing the FormGroup is loginForm therefore it should be <form [formGroup]="loginForm">
  • [formControlName]="dob" which passes the value of the property dob which doesn't exist. What you need is to pass the string dob like [formControlName]="'dob'" or simpler formControlName="dob"

Plunker example

How to get href value using jQuery?

It works... Tested in IE8 (don't forget to allow javascript to run if you're testing the file from your computer) and chrome.

invalid use of non-static member function

The simplest fix is to make the comparator function be static:

static int comparator (const Bar & first, const Bar & second);
^^^^^^

When invoking it in Count, its name will be Foo::comparator.

The way you have it now, it does not make sense to be a non-static member function because it does not use any member variables of Foo.

Another option is to make it a non-member function, especially if it makes sense that this comparator might be used by other code besides just Foo.

How can I declare dynamic String array in Java

no, there is no way to make array length dynamic in java. you can use ArrayList or other List implementations instead.

How to open URL in Microsoft Edge from the command line?

Personally, I use this function which I created and put in my profile script ...\Documents\WindowsPowerShell\….profile, feel free to use it. As I am from the UK, I prefer to go to .co.uk where possible, if you are from another area, you can add your own country code.

# Function taking parameter add (address) and opens in edge.
Function edge {
    param($add)
    if (-not ($add -contains "https://www." -or $add -contains "http://www.")) {
        if ($add[0] -eq "w" -and $add[1] -eq "w" -and $add[2] -eq "w") {
            $add = "https://" + $add
        } else {
            $add = "https://www." + $add
        }
    }

    # If no domain, tries to add .co.uk, if fails uses .com
    if (-not ($add -match ".co" -or $add -match ".uk" -or $add -match ".com")) {
        try {
            $test = $add + ".co.uk"
            $HTTP_Request  = [System.Net.WebRequest]::Create($test)
            $HTTP_Response = $HTTP_Request.GetResponse()
            $add = $add + ".co.uk"
        } catch{
            $add = $add + ".com"
        }
    }
    Write-Host "Taking you to $add"
    start microsoft-edge:$add
}

Then you just have to call: edge google in powershell to go to https://www.google.co.uk

Why a function checking if a string is empty always returns true?

Well here is the short method to check whether the string is empty or not.

$input; //Assuming to be the string


if(strlen($input)==0){
return false;//if the string is empty
}
else{
return true; //if the string is not empty
}

How do I retrieve my MySQL username and password?

An improvement to the most useful answer here:

1] No need to restart the mysql server
2] Security concern for a MySQL server connected to a network

There is no need to restart the MySQL server.

use FLUSH PRIVILEGES; after the update mysql.user statement for password change.

The FLUSH statement tells the server to reload the grant tables into memory so that it notices the password change.

The --skip-grant-options enables anyone to connect without a password and with all privileges. Because this is insecure, you might want to

use --skip-grant-tables in conjunction with --skip-networking to prevent remote clients from connecting.

from: reference: resetting-permissions-generic

Ant is using wrong java version

Use the following 2 properties for javac tag:

fork="yes"  
executable="full-path-to-the-javac-you-want-to-use".

Explaination of the properties can be found here

Making a Bootstrap table column fit to content

Make a class that will fit table cell width to content

.table td.fit, 
.table th.fit {
    white-space: nowrap;
    width: 1%;
}

How do I sort a Set to a List in Java?

Always safe to use either Comparator or Comparable interface to provide sorting implementation (if the object is not a String or Wrapper classes for primitive data types) . As an example for a comparator implementation to sort employees based on name

    List<Employees> empList = new LinkedList<Employees>(EmpSet);

    class EmployeeComparator implements Comparator<Employee> {

            public int compare(Employee e1, Employee e2) {
                return e1.getName().compareTo(e2.getName());
            }

        }

   Collections.sort(empList , new EmployeeComparator ());

Comparator is useful when you need to have different sorting algorithm on same object (Say emp name, emp salary, etc). Single mode sorting can be implemented by using Comparable interface in to the required object.

HashMap - getting First Key value

You can try this:

 Map<String,String> map = new HashMap<>();
 Map.Entry<String,String> entry = map.entrySet().iterator().next();
 String key = entry.getKey();
 String value = entry.getValue();

Keep in mind, HashMap does not guarantee the insertion order. Use a LinkedHashMap to keep the order intact.

Eg:

 Map<String,String> map = new LinkedHashMap<>();
 map.put("Active","33");
 map.put("Renewals Completed","3");
 map.put("Application","15");
 Map.Entry<String,String> entry = map.entrySet().iterator().next();
 String key= entry.getKey();
 String value=entry.getValue();
 System.out.println(key);
 System.out.println(value);

Output:

 Active
 33

Angular2 multiple router-outlet in the same template

Yes you can as said by @tomer above. i want to add some point to @tomer answer.

  • firstly you need to provide name to the router-outlet where you want to load the second routing view in your view. (aux routing angular2.)
  • In angular2 routing few important points are here.

    • path or aux (requires exactly one of these to give the path you have to show as the url).
    • component, loader, redirectTo (requires exactly one of these, which component you want to load on routing)
    • name or as (optional) (requires exactly one of these, the name which specify at the time of routerLink)
    • data (optional, whatever you want to send with the routing that you have to get using routerParams at the receiver end.)

for more info read out here and here.

import {RouteConfig, AuxRoute} from 'angular2/router';
@RouteConfig([
  new AuxRoute({path: '/home', component: HomeCmp})
])
class MyApp {}

Best way of invoking getter by reflection

You can invoke reflections and also, set order of sequence for getter for values through annotations

public class Student {

    private String grade;

    private String name;

    private String id;

    private String gender;

    private Method[] methods;

    @Retention(RetentionPolicy.RUNTIME)
    public @interface Order {
        int value();
    }

    /**
     * Sort methods as per Order Annotations
     * 
     * @return
     */
    private void sortMethods() {

        methods = Student.class.getMethods();

        Arrays.sort(methods, new Comparator<Method>() {
            public int compare(Method o1, Method o2) {
                Order or1 = o1.getAnnotation(Order.class);
                Order or2 = o2.getAnnotation(Order.class);
                if (or1 != null && or2 != null) {
                    return or1.value() - or2.value();
                }
                else if (or1 != null && or2 == null) {
                    return -1;
                }
                else if (or1 == null && or2 != null) {
                    return 1;
                }
                return o1.getName().compareTo(o2.getName());
            }
        });
    }

    /**
     * Read Elements
     * 
     * @return
     */
    public void readElements() {
        int pos = 0;
        /**
         * Sort Methods
         */
        if (methods == null) {
            sortMethods();
        }
        for (Method method : methods) {
            String name = method.getName();
            if (name.startsWith("get") && !name.equalsIgnoreCase("getClass")) {
                pos++;
                String value = "";
                try {
                    value = (String) method.invoke(this);
                }
                catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    e.printStackTrace();
                }
                System.out.println(name + " Pos: " + pos + " Value: " + value);
            }
        }
    }

    // /////////////////////// Getter and Setter Methods

    /**
     * @param grade
     * @param name
     * @param id
     * @param gender
     */
    public Student(String grade, String name, String id, String gender) {
        super();
        this.grade = grade;
        this.name = name;
        this.id = id;
        this.gender = gender;
    }

    /**
     * @return the grade
     */
    @Order(value = 4)
    public String getGrade() {
        return grade;
    }

    /**
     * @param grade the grade to set
     */
    public void setGrade(String grade) {
        this.grade = grade;
    }

    /**
     * @return the name
     */
    @Order(value = 2)
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the id
     */
    @Order(value = 1)
    public String getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * @return the gender
     */
    @Order(value = 3)
    public String getGender() {
        return gender;
    }

    /**
     * @param gender the gender to set
     */
    public void setGender(String gender) {
        this.gender = gender;
    }

    /**
     * Main
     * 
     * @param args
     * @throws IOException
     * @throws SQLException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static void main(String args[]) throws IOException, SQLException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        Student student = new Student("A", "Anand", "001", "Male");
        student.readElements();
    }
  }

Output when sorted

getId Pos: 1 Value: 001
getName Pos: 2 Value: Anand
getGender Pos: 3 Value: Male
getGrade Pos: 4 Value: A

Insert NULL value into INT column

If column is not NOT NULL (nullable).

You just put NULL instead of value in INSERT statement.

Set UILabel line spacing

From Interface Builder:

enter image description here

Programmatically:

SWift 4

Using label extension

extension UILabel {

    func setLineSpacing(lineSpacing: CGFloat = 0.0, lineHeightMultiple: CGFloat = 0.0) {

        guard let labelText = self.text else { return }

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpacing
        paragraphStyle.lineHeightMultiple = lineHeightMultiple

        let attributedString:NSMutableAttributedString
        if let labelattributedText = self.attributedText {
            attributedString = NSMutableAttributedString(attributedString: labelattributedText)
        } else {
            attributedString = NSMutableAttributedString(string: labelText)
        }

        // Line spacing attribute
        attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))

        self.attributedText = attributedString
    }
}

Now call extension function

let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"

// Pass value for any one argument - lineSpacing or lineHeightMultiple
label.setLineSpacing(lineSpacing: 2.0) .  // try values 1.0 to 5.0

// or try lineHeightMultiple
//label.setLineSpacing(lineHeightMultiple = 2.0) // try values 0.5 to 2.0


Or using label instance (Just copy & execute this code to see result)

let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40

// Line spacing attribute
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.characters.count))

// Character spacing attribute
attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))

label.attributedText = attrString

Swift 3

let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString

How do I link to part of a page? (hash?)

If there is any tag with an id (e.g., <div id="foo">), then you can simply append #foo to the URL. Otherwise, you can't arbitrarily link to portions of a page.

Here's a complete example: <a href="http://example.com/page.html#foo">Jump to #foo on page.html</a>

Linking content on the same page example: <a href="#foo">Jump to #foo on same page</a>

It is called a URI fragment.

how to bind img src in angular 2 in ngFor?

I hope i am understanding your question correctly, as the above comment says you need to provide more information.

In order to bind it to your view you would use property binding which is using [property]="value". Hope this helps.

<div *ngFor="let student of students">  
 {{student.id}}
 {{student.name}}

 <img [src]="student.image">

</div>  

Maven project version inheritance - do I have to specify the parent version?

<parent>
    <groupId>com.dummy.bla</groupId>
    <artifactId>parent</artifactId>
    <version>0.1-SNAPSHOT</version>     
 </parent>

 <groupId>com.dummy.bla.sub</groupId>
 <artifactId>kid</artifactId>

You mean you want to remove the version from parent block of B's pom, I think you can not do it, the groupId, artifactId, and version specified the parent's pom coordinate's, what you can omit is child's version.

Apache giving 403 forbidden errors

In my case it was failing as the IP of my source server was not whitelisted in the target server.

For e.g. I was trying to access https://prodcat.ref.test.co.uk from application running on my source server. On source server find IP by ifconfig

This IP should be whitelisted in the target Server's apache config file. If its not then get it whitelist.

Steps to add a IP for whitelisting (if you control the target server as well) ssh to the apache server sudo su - cd /usr/local/apache/conf/extra (actual directories can be different based on your config)

Find the config file for the target application for e.g. prodcat-443.conf

RewriteCond %{REMOTE_ADDR} <YOUR Server's IP> 
for e.g.
RewriteCond %{REMOTE_ADDR} !^192\.68\.2\.98

Hope this helps someone

JavaScript check if variable exists (is defined/initialized)

I'm surprised this wasn't mentioned yet...

here are a couple of additional variations using this['var_name']

the benefit of using this method that it can be used before a variable is defined.

if (this['elem']) {...}; // less safe than the res but works as long as you're note expecting a falsy value
if (this['elem'] !== undefined) {...}; // check if it's been declared
if (this['elem'] !== undefined && elem !== null) {...}; // check if it's not null, you can use just elem for the second part

// these will work even if you have an improper variable definition declared here
elem = null; // <-- no var here!! BAD!

TypeError: 'float' object is not subscriptable

PriceList[0][1][2][3][4][5][6]

This says: go to the 1st item of my collection PriceList. That thing is a collection; get its 2nd item. That thing is a collection; get its 3rd...

Instead, you want slicing:

PriceList[:7] = [PizzaChange]*7

How to use table variable in a dynamic sql statement?

Using Temp table solves the problem but I ran into issues using Exec so I went with the following solution of using sp_executesql:

Create TABLE #tempJoin ( Old_ID int, New_ID int);

declare @table_name varchar(128);

declare @strSQL nvarchar(3072);

set @table_name = 'Object';

--build sql sting to execute
set @strSQL='INSERT INTO '+@table_name+' SELECT '+@columns+' FROM #tempJoin CJ
                        Inner Join '+@table_name+' sourceTbl On CJ.Old_ID = sourceTbl.Object_ID'

**exec sp_executesql @strSQL;**

CSS3 Continuous Rotate Animation (Just like a loading sundial)

I made a small library that lets you easily use a throbber without images.

It uses CSS3 but falls back onto JavaScript if the browser doesn't support it.

// First argument is a reference to a container element in which you
// wish to add a throbber to.
// Second argument is the duration in which you want the throbber to
// complete one full circle.
var throbber = throbbage(document.getElementById("container"), 1000);

// Start the throbber.
throbber.play();

// Pause the throbber.
throbber.pause();

Example.

Remove carriage return from string

Since you're using VB.NET, you'll need the following code:

Dim newString As String = origString.Replace(vbCr, "").Replace(vbLf, "")

You could use escape characters (\r and \n) in C#, but these won't work in VB.NET. You have to use the equivalent constants (vbCr and vbLf) instead.

Add border-bottom to table row <tr>

Add border-collapse:collapse to your table rule:

table { 
    border-collapse: collapse; 
}

Example

_x000D_
_x000D_
table {
  border-collapse: collapse;
}

tr {
  border-bottom: 1pt solid black;
}
_x000D_
<table>
  <tr><td>A1</td><td>B1</td><td>C1</td></tr>
  <tr><td>A2</td><td>B2</td><td>C2</td></tr>
  <tr><td>A2</td><td>B2</td><td>C2</td></tr>
</table>
_x000D_
_x000D_
_x000D_

Link

Setting Timeout Value For .NET Web Service

Try setting the timeout value in your web service proxy class:

WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds

Laravel Request::all() Should Not Be Called Statically

also it happens when you import following library to api.php file. this happens by some IDE's suggestion to import it for not finding the Route Class.

just remove it and everything going to work fine.

use Illuminate\Routing\Route;

update:

seems if you add this library it wont lead to error

use Illuminate\Support\Facades\Route;

Setting top and left CSS attributes

You can also use the setProperty method like below

document.getElementById('divName').style.setProperty("top", "100px");

Init array of structs in Go

It looks like you are trying to use (almost) straight up C code here. Go has a few differences.

  • First off, you can't initialize arrays and slices as const. The term const has a different meaning in Go, as it does in C. The list should be defined as var instead.
  • Secondly, as a style rule, Go prefers basenameOpts as opposed to basename_opts.
  • There is no char type in Go. You probably want byte (or rune if you intend to allow unicode codepoints).
  • The declaration of the list must have the assignment operator in this case. E.g.: var x = foo.
  • Go's parser requires that each element in a list declaration ends with a comma. This includes the last element. The reason for this is because Go automatically inserts semi-colons where needed. And this requires somewhat stricter syntax in order to work.

For example:

type opt struct {
    shortnm      byte
    longnm, help string
    needArg      bool
}

var basenameOpts = []opt { 
    opt {
        shortnm: 'a', 
        longnm: "multiple", 
        needArg: false, 
        help: "Usage for a",
    },
    opt {
        shortnm: 'b', 
        longnm: "b-option", 
        needArg: false, 
        help: "Usage for b",
    },
}

An alternative is to declare the list with its type and then use an init function to fill it up. This is mostly useful if you intend to use values returned by functions in the data structure. init functions are run when the program is being initialized and are guaranteed to finish before main is executed. You can have multiple init functions in a package, or even in the same source file.

    type opt struct {
        shortnm      byte
        longnm, help string
        needArg      bool
    }

    var basenameOpts []opt

    func init() { 
        basenameOpts = []opt{
            opt {
                shortnm: 'a', 
                longnm: "multiple", 
                needArg: false, 
                help: "Usage for a",
            },
            opt {
                shortnm: 'b', 
                longnm: "b-option", 
                needArg: false, 
               help: "Usage for b",
            },
        }
    }

Since you are new to Go, I strongly recommend reading through the language specification. It is pretty short and very clearly written. It will clear a lot of these little idiosyncrasies up for you.

Can you write virtual functions / methods in Java?

Can you write virtual functions in Java?

Yes. In fact, all instance methods in Java are virtual by default. Only certain methods are not virtual:

  • Class methods (because typically each instance holds information like a pointer to a vtable about its specific methods, but no instance is available here).
  • Private instance methods (because no other class can access the method, the calling instance has always the type of the defining class itself and is therefore unambiguously known at compile time).

Here are some examples:

"Normal" virtual functions

The following example is from an old version of the wikipedia page mentioned in another answer.

import java.util.*;

public class Animal 
{
   public void eat() 
   { 
      System.out.println("I eat like a generic Animal."); 
   }

   public static void main(String[] args) 
   {
      List<Animal> animals = new LinkedList<Animal>();

      animals.add(new Animal());
      animals.add(new Fish());
      animals.add(new Goldfish());
      animals.add(new OtherAnimal());

      for (Animal currentAnimal : animals) 
      {
         currentAnimal.eat();
      }
   }
}

class Fish extends Animal 
{
   @Override
   public void eat() 
   { 
      System.out.println("I eat like a fish!"); 
   }
}

class Goldfish extends Fish 
{
   @Override
   public void eat() 
   { 
      System.out.println("I eat like a goldfish!"); 
   }
}

class OtherAnimal extends Animal {}

Output:

I eat like a generic Animal.
I eat like a fish!
I eat like a goldfish!
I eat like a generic Animal.

Example with virtual functions with interfaces

Java interface methods are all virtual. They must be virtual because they rely on the implementing classes to provide the method implementations. The code to execute will only be selected at run time.

For example:

interface Bicycle {         //the function applyBrakes() is virtual because
    void applyBrakes();     //functions in interfaces are designed to be 
}                           //overridden.

class ACMEBicycle implements Bicycle {
    public void applyBrakes(){               //Here we implement applyBrakes()
       System.out.println("Brakes applied"); //function
    }
}

Example with virtual functions with abstract classes.

Similar to interfaces Abstract classes must contain virtual methods because they rely on the extending classes' implementation. For Example:

abstract class Dog {                   
    final void bark() {               //bark() is not virtual because it is 
        System.out.println("woof");   //final and if you tried to override it
    }                                 //you would get a compile time error.

    abstract void jump();             //jump() is a "pure" virtual function 
}                                     
class MyDog extends Dog{
    void jump(){
        System.out.println("boing");    //here jump() is being overridden
    }                                  
}
public class Runner {
    public static void main(String[] args) {
        Dog dog = new MyDog();       // Create a MyDog and assign to plain Dog variable
        dog.jump();                  // calling the virtual function.
                                     // MyDog.jump() will be executed 
                                     // although the variable is just a plain Dog.
    }
}

SSRS chart does not show all labels on Horizontal axis

Go to Horizontal axis properties,choose 'Category' in AXIS type,choose "Disabled" in SIDE Margin option

CSS image resize percentage of itself?

Try zoom property

<img src="..." style="zoom: 0.5" />

Edit: Apparently, FireFox doesn't support zoom property. You should use;

-moz-transform: scale(0.5);

for FireFox.

Selected tab's color in Bottom Navigation View

I am using a com.google.android.material.bottomnavigation.BottomNavigationView (not the same as OP's) and I tried a variety of the suggested solutions above, but the only thing that worked was setting app:itemBackground and app:itemIconTint to my selector color worked for me.

        <com.google.android.material.bottomnavigation.BottomNavigationView
            style="@style/BottomNavigationView"
            android:foreground="?attr/selectableItemBackground"
            android:theme="@style/BottomNavigationView"
            app:itemBackground="@color/tab_color"
            app:itemIconTint="@color/tab_color"
            app:itemTextColor="@color/bottom_navigation_text_color"
            app:labelVisibilityMode="labeled"
            app:menu="@menu/bottom_navigation" />

My color/tab_color.xml uses android:state_checked

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/grassSelected" android:state_checked="true" />
    <item android:color="@color/grassBackground" />
</selector>

and I am also using a selected state color for color/bottom_navigation_text_color.xml

enter image description here

Not totally relevant here but for full transparency, my BottomNavigationView style is as follows:

    <style name="BottomNavigationView" parent="Widget.Design.BottomNavigationView">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">@dimen/bottom_navigation_height</item>
        <item name="android:layout_gravity">bottom</item>
        <item name="android:textSize">@dimen/bottom_navigation_text_size</item>
    </style>

How to validate an e-mail address in swift?

This a new version for "THE REASONABLE SOLUTION" by @Fattie, tested on Swift 4.1 in a new file called String+Email.swift:

import Foundation

extension String {
    private static let __firstpart = "[A-Z0-9a-z]([A-Z0-9a-z._%+-]{0,30}[A-Z0-9a-z])?"
    private static let __serverpart = "([A-Z0-9a-z]([A-Z0-9a-z-]{0,30}[A-Z0-9a-z])?\\.){1,5}"
    private static let __emailRegex = __firstpart + "@" + __serverpart + "[A-Za-z]{2,6}"

    public var isEmail: Bool {
        let predicate = NSPredicate(format: "SELF MATCHES %@", type(of:self).__emailRegex)
        return predicate.evaluate(with: self)
    }
}

So its usage is simple:

let str = "[email protected]"
if str.isEmail {
    print("\(str) is a valid e-mail address")
} else {
    print("\(str) is not a valid e-mail address")
}

I simply don't like to add a func to the String objects, as being an e-mail address is inherent to them (or not). So a Bool property would fit better than a func, from my understanding.

How do I check if a C++ string is an int?

Here is another solution.

try
{
  (void) std::stoi(myString); //cast to void to ignore the return value   
  //Success! myString contained an integer
} 
catch (const std::logic_error &e)
{   
  //Failure! myString did not contain an integer
}

Difference in days between two dates in Java?

Hundred lines of code for this basic function???

Just a simple method:

protected static int calculateDayDifference(Date dateAfter, Date dateBefore){
    return (int)(dateAfter.getTime()-dateBefore.getTime())/(1000 * 60 * 60 * 24); 
    // MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
}

Android emulator shows nothing except black screen and adb devices shows "device offline"

I too got the same problem. When i changed the Eclipse from EE to Eclipse Classic it worked fine. in Win professional 64Bit. Have a try it may work for you too..

Calculate time difference in minutes in SQL Server

You can use DATEDIFF(it is a built-in function) and % (for scale calculation) and CONCAT for make result to only one column

select CONCAT('Month: ',MonthDiff,' Days: ' , DayDiff,' Minutes: ',MinuteDiff,' Seconds: ',SecondDiff) as T  from 
(SELECT DATEDIFF(MONTH, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 12 as MonthDiff,
        DATEDIFF(DAY, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 30 as DayDiff,
        DATEDIFF(HOUR, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 24 as HourDiff,
        DATEDIFF(MINUTE, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 60 AS MinuteDiff,
        DATEDIFF(SECOND, '2017-10-15 19:39:47' , '2017-12-31 23:59:59') % 60 AS SecondDiff) tbl

Set 4 Space Indent in Emacs in Text Mode

Try this:

(add-hook 'text-mode-hook
  (function
   (lambda ()
     (setq tab-width 4)
     (define-key text-mode-map "\C-i" 'self-insert-command)
     )))

That will make TAB always insert a literal TAB character with tab stops every 4 characters (but only in Text mode). If that's not what you're asking for, please describe the behavior you'd like to see.

Bootstrap: adding gaps between divs

An alternative way to accomplish what you are asking, without having problems on the mobile version of your website, (Remember that the margin attribute will brake your responsive layout on mobile version thus you have to add on your element a supplementary attribute like @media (min-width:768px){ 'your-class'{margin:0}} to override the previous margin)

is to nest your class in your preferred div and then add on your class the margin option you want

like the following example: HTML

<div class="container">
  <div class="col-md-3 col-xs-12">
   <div class="events">
     <img src="..."  class="img-responsive" alt="...."/>
     <div class="figcaption">
       <h2>Event Title</h2>
       <p>Event Description.</p>
     </div>
   </div>
  </div>
  <div class="col-md-3 col-xs-12">
   <div class="events">
    <img src="..."  class="img-responsive" alt="...."/>
    <div class="figcaption">
     <h2>Event Title</h2>
     <p>Event Description. </p>
    </div>
   </div>
  </div>
  <div class="col-md-3 col-xs-12">
   <div class="events">
    <img src="..."  class="img-responsive" alt="...."/>
    <div class="figcaption">
     <h2>Event Title</h2>
     <p>Event Description. </p>
    </div>
   </div>
  </div>
</div>

And on your CSS you just add the margin option on your class which in this example is "events" like:

.events{
margin: 20px 10px;
}

By this method you will have all the wanted space between your divs making sure you do not brake anything on your website's mobile and tablet versions.

Fastest way to convert Image to Byte array

public static byte[] ReadImageFile(string imageLocation)
    {
        byte[] imageData = null;
        FileInfo fileInfo = new FileInfo(imageLocation);
        long imageFileLength = fileInfo.Length;
        FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        imageData = br.ReadBytes((int)imageFileLength);
        return imageData;
    }

How to compare two JSON objects with the same elements in a different order equal?

For the following two dicts 'dictWithListsInValue' and 'reorderedDictWithReorderedListsInValue' which are simply reordered versions of each other

dictObj = {"foo": "bar", "john": "doe"}
reorderedDictObj = {"john": "doe", "foo": "bar"}
dictObj2 = {"abc": "def"}
dictWithListsInValue = {'A': [{'X': [dictObj2, dictObj]}, {'Y': 2}], 'B': dictObj2}
reorderedDictWithReorderedListsInValue = {'B': dictObj2, 'A': [{'Y': 2}, {'X': [reorderedDictObj, dictObj2]}]}
a = {"L": "M", "N": dictWithListsInValue}
b = {"L": "M", "N": reorderedDictWithReorderedListsInValue}

print(sorted(a.items()) == sorted(b.items()))  # gives false

gave me wrong result i.e. false .

So I created my own cutstom ObjectComparator like this:

def my_list_cmp(list1, list2):
    if (list1.__len__() != list2.__len__()):
        return False

    for l in list1:
        found = False
        for m in list2:
            res = my_obj_cmp(l, m)
            if (res):
                found = True
                break

        if (not found):
            return False

    return True


def my_obj_cmp(obj1, obj2):
    if isinstance(obj1, list):
        if (not isinstance(obj2, list)):
            return False
        return my_list_cmp(obj1, obj2)
    elif (isinstance(obj1, dict)):
        if (not isinstance(obj2, dict)):
            return False
        exp = set(obj2.keys()) == set(obj1.keys())
        if (not exp):
            # print(obj1.keys(), obj2.keys())
            return False
        for k in obj1.keys():
            val1 = obj1.get(k)
            val2 = obj2.get(k)
            if isinstance(val1, list):
                if (not my_list_cmp(val1, val2)):
                    return False
            elif isinstance(val1, dict):
                if (not my_obj_cmp(val1, val2)):
                    return False
            else:
                if val2 != val1:
                    return False
    else:
        return obj1 == obj2

    return True


dictObj = {"foo": "bar", "john": "doe"}
reorderedDictObj = {"john": "doe", "foo": "bar"}
dictObj2 = {"abc": "def"}
dictWithListsInValue = {'A': [{'X': [dictObj2, dictObj]}, {'Y': 2}], 'B': dictObj2}
reorderedDictWithReorderedListsInValue = {'B': dictObj2, 'A': [{'Y': 2}, {'X': [reorderedDictObj, dictObj2]}]}
a = {"L": "M", "N": dictWithListsInValue}
b = {"L": "M", "N": reorderedDictWithReorderedListsInValue}

print(my_obj_cmp(a, b))  # gives true

which gave me the correct expected output!

Logic is pretty simple:

If the objects are of type 'list' then compare each item of the first list with the items of the second list until found , and if the item is not found after going through the second list , then 'found' would be = false. 'found' value is returned

Else if the objects to be compared are of type 'dict' then compare the values present for all the respective keys in both the objects. (Recursive comparison is performed)

Else simply call obj1 == obj2 . It by default works fine for the object of strings and numbers and for those eq() is defined appropriately .

(Note that the algorithm can further be improved by removing the items found in object2, so that the next item of object1 would not compare itself with the items already found in the object2)

Set Text property of asp:label in Javascript PROPER way

Place HiddenField Control in your Form.

<asp:HiddenField ID="hidden" runat="server" />

Create a Property in the Form

protected String LabelProperty
{
    get
    {
        return hidden.Value;
    }
    set
    {
        hidden.Value = value;
    }
}

Update the Hidden Field value from JavaScript

<script>
   function UpdateControl() {
            document.getElementById('<%=hidden.ClientID %>').value = '12';
   }
</script>

Now you can access the Property directly across the Postback. The Label Control updated value will be Lost across PostBack in case it is being used directly in code behind .

How to swap String characters in Java?

String.replaceAll() or replaceFirst()

String s = "abcde".replaceAll("ab", "ba")

Link to the JavaDocs String API

How to hide the keyboard when I press return key in a UITextField?

First make your file delegate for UITextField

@interface MYLoginViewController () <UITextFieldDelegate>

@end

Then add this method to your code.

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

Also add self.textField.delegate = self;

Calculate RSA key fingerprint

If your SSH agent is running, it is

ssh-add -l

to list RSA fingerprints of all identities, or -L for listing public keys.

If your agent is not running, try:

ssh-agent sh -c 'ssh-add; ssh-add -l'

And for your public keys:

ssh-agent sh -c 'ssh-add; ssh-add -L'

If you get the message: 'The agent has no identities.', then you have to generate your RSA key by ssh-keygen first.

What's the difference between interface and @interface in java?

interface:

In general, an interface exposes a contract without exposing the underlying implementation details. In Object Oriented Programming, interfaces define abstract types that expose behavior, but contain no logic. Implementation is defined by the class or type that implements the interface.

@interface : (Annotation type)

Take the below example, which has a lot of comments:

public class Generation3List extends Generation2List {

   // Author: John Doe
   // Date: 3/17/2002
   // Current revision: 6
   // Last modified: 4/12/2004
   // By: Jane Doe
   // Reviewers: Alice, Bill, Cindy

   // class code goes here

}

Instead of this, you can declare an annotation type

 @interface ClassPreamble {
   String author();
   String date();
   int currentRevision() default 1;
   String lastModified() default "N/A";
   String lastModifiedBy() default "N/A";
   // Note use of array
   String[] reviewers();
}

which can then annotate a class as follows:

@ClassPreamble (
   author = "John Doe",
   date = "3/17/2002",
   currentRevision = 6,
   lastModified = "4/12/2004",
   lastModifiedBy = "Jane Doe",
   // Note array notation
   reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {

// class code goes here

}

PS: Many annotations replace comments in code.

Reference: http://docs.oracle.com/javase/tutorial/java/annotations/declaring.html

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

SELECT 
table1.*
, table2.*
INNER JOIN table2 ON table2.SomeFkId = table1.SomeId

That gets you a result set where child rows in table2 cause duplication by returning the table1 results for each child row in table2. O/R mappers should differentiate table1 instances based on a unique key field, then use all the table2 columns to populate child instances.

SELECT table1.*

SELECT table2.* WHERE SomeFkId = #

The N+1 is where the first query populates the primary object and the second query populates all the child objects for each of the unique primary objects returned.

Consider:

class House
{
    int Id { get; set; }
    string Address { get; set; }
    Person[] Inhabitants { get; set; }
}

class Person
{
    string Name { get; set; }
    int HouseId { get; set; }
}

and tables with a similar structure. A single query for the address "22 Valley St" may return:

Id Address      Name HouseId
1  22 Valley St Dave 1
1  22 Valley St John 1
1  22 Valley St Mike 1

The O/RM should fill an instance of Home with ID=1, Address="22 Valley St" and then populate the Inhabitants array with People instances for Dave, John, and Mike with just one query.

A N+1 query for the same address used above would result in:

Id Address
1  22 Valley St

with a separate query like

SELECT * FROM Person WHERE HouseId = 1

and resulting in a separate data set like

Name    HouseId
Dave    1
John    1
Mike    1

and the final result being the same as above with the single query.

The advantages to single select is that you get all the data up front which may be what you ultimately desire. The advantages to N+1 is query complexity is reduced and you can use lazy loading where the child result sets are only loaded upon first request.

Error: Can't set headers after they are sent to the client

I ran into this error as well for a while. I think (hope) I've wrapped my head around it, wanted to write it here for reference.

When you add middleware to connect or express (which is built on connect) using the app.use method, you're appending items to Server.prototype.stack in connect (At least with the current npm install connect, which looks quite different from the one github as of this post). When the server gets a request, it iterates over the stack, calling the (request, response, next) method.

The problem is, if in one of the middleware items writes to the response body or headers (it looks like it's either/or for some reason), but doesn't call response.end() and you call next() then as the core Server.prototype.handle method completes, it's going to notice that:

  1. there are no more items in the stack, and/or
  2. that response.headerSent is true.

So, it throws an error. But the error it throws is just this basic response (from the connect http.js source code:

res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('Cannot ' + req.method + ' ' + req.url);

Right there, it's calling res.setHeader('Content-Type', 'text/plain');, which you are likely to have set in your render method, without calling response.end(), something like:

response.setHeader("Content-Type", "text/html");
response.write("<p>Hello World</p>");

The way everything needs to be structured is like this:

Good Middleware

// middleware that does not modify the response body
var doesNotModifyBody = function(request, response, next) {
  request.params = {
    a: "b"
  };
  // calls next because it hasn't modified the header
  next();
};

// middleware that modify the response body
var doesModifyBody = function(request, response, next) {
  response.setHeader("Content-Type", "text/html");
  response.write("<p>Hello World</p>");
  response.end();
  // doesn't call next()
};

app.use(doesNotModifyBody);
app.use(doesModifyBody);

Problematic Middleware

var problemMiddleware = function(request, response, next) {
  response.setHeader("Content-Type", "text/html");
  response.write("<p>Hello World</p>");
  next();
};

The problematic middleware sets the response header without calling response.end() and calls next(), which confuses connect's server.

Reset identity seed after deleting records in SQL Server

I use the following script to do this. There's only one scenario in which it will produce an "error", which is if you have deleted all rows from the table, and IDENT_CURRENT is currently set to 1, i.e. there was only one row in the table to begin with.

DECLARE @maxID int = (SELECT MAX(ID) FROM dbo.Tbl)
;

IF @maxID IS NULL
    IF (SELECT IDENT_CURRENT('dbo.Tbl')) > 1
        DBCC CHECKIDENT ('dbo.Tbl', RESEED, 0)
    ELSE
        DBCC CHECKIDENT ('dbo.Tbl', RESEED, 1)
    ;
ELSE
    DBCC CHECKIDENT ('dbo.Tbl', RESEED, @maxID)
;

Clang vs GCC for my Linux Development project

I use both Clang and GCC, I find Clang has some useful warnings, but for my own ray-tracing benchmarks - its consistently 5-15% slower then GCC (take that with grain of salt of course, but attempted to use similar optimization flags for both).

So for now I use Clang static analysis and its warnings with complex macros: (though now GCC's warnings are pretty much as good - gcc4.8 - 4.9).

Some considerations:

  • Clang has no OpenMP support, only matters if you take advantage of that but since I do, its a limitation for me. (*****)
  • Cross compilation may not be as well supported (FreeBSD 10 for example still use GCC4.x for ARM), gcc-mingw for example is available on Linux... (YMMV).
  • Some IDE's don't yet support parsing Clangs output (QtCreator for example *****). EDIT: QtCreator now supports Clang's output
  • Some aspects of GCC are better documented and since GCC has been around for longer and is widely used, you might find it easier to get help with warnings / error messages.

***** - these areas are in active development and may soon be supported

How to set default values for Angular 2 component properties?

That is interesting subject. You can play around with two lifecycle hooks to figure out how it works: ngOnChanges and ngOnInit.

Basically when you set default value to Input that's mean it will be used only in case there will be no value coming on that component. And the interesting part it will be changed before component will be initialized.

Let's say we have such components with two lifecycle hooks and one property coming from input.

@Component({
  selector: 'cmp',
})
export class Login implements OnChanges, OnInit {
  @Input() property: string = 'default';

  ngOnChanges(changes) {
    console.log('Changed', changes.property.currentValue, changes.property.previousValue);
  }

  ngOnInit() {
    console.log('Init', this.property);
  }

}

Situation 1

Component included in html without defined property value

As result we will see in console: Init default

That's mean onChange was not triggered. Init was triggered and property value is default as expected.

Situation 2

Component included in html with setted property <cmp [property]="'new value'"></cmp>

As result we will see in console:

Changed new value Object {}

Init new value

And this one is interesting. Firstly was triggered onChange hook, which setted property to new value, and previous value was empty object! And only after that onInit hook was triggered with new value of property.

Get first line of a shell command's output

I would use:

awk 'FNR <= 1' file_*.txt

As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1 may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i' to 'FNR <= i' allows to obtain the first i lines.

For example, if you have n files named file_1.txt, ... file_n.txt:

awk 'FNR <= 1' file_*.txt

hello
...
bye

But with head wildcards print the name of the file:

head -1 file_*.txt

==> file_1.csv <==
hello
...
==> file_n.csv <==
bye

Ajax success event not working

I'm using XML to carry the result back from the php on the server to the webpage and I have had the same behaviour.

In my case the reason was , that the closing tag did not match the opening tag.

<?php
....
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>
    <result>
        <status>$status</status>
        <OPENING_TAG>$message</CLOSING_TAG>
    </result>";
?>

Best lightweight web server (only static content) for Windows

I played a bit with Rupy. It's a pretty neat, open source (GPL) Java application and weighs less than 60KB. Give it a try!

how to set default method argument values?

It's not possible to default values in Java. My preferred way to deal with this is to overload the method so you might have something like:

public class MyClass
{
  public int doSomething(int arg1, int arg2)
  {
    ...
  }

  public int doSomething()
  {
    return doSomething(<default value>, <default value>);
  }
}

SQL Server Profiler - How to filter trace to only display events from one database?

Under Trace properties > Events Selection tab > select show all columns. Now under column filters, you should see the database name. Enter the database name for the Like section and you should see traces only for that database.

How do I find out which settings.xml file maven is using

Use the Maven debug option, ie mvn -X :

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...

In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml.

Found a swap file by the name

I've also had this error when trying to pull the changes into a branch which is not created from the upstream branch from which I'm trying to pull.

Eg - This creates a new branch matching night-version of upstream

git checkout upstream/night-version -b testnightversion

This creates a branch testmaster in local which matches the master branch of upstream.

git checkout upstream/master -b testmaster 

Now if I try to pull the changes of night-version into testmaster branch leads to this error.

git pull upstream night-version //while I'm in `master` cloned branch

I managed to solve this by navigating to proper branch and pull the changes.

git checkout testnightversion
git pull upstream night-version // works fine.

Have a div cling to top of screen if scrolled down past it

There was a previous question today (no answers) that gave a good example of this functionality. You can check the relevant source code for specifics (search for "toolbar"), but basically they use a combination of webdestroya's solution and a bit of JavaScript:

  1. Page loads and element is position: static
  2. On scroll, the position is measured, and if the element is position: static and it's off the page then the element is flipped to position: fixed.

I'd recommend checking the aforementioned source code though, because they do handle some "gotchas" that you might not immediately think of, such as adjusting scroll position when clicking on anchor links.

Eclipse: How do you change the highlight color of the currently selected method/expression?

After running around in the Preferences dialog, the following is the location at which the highlight color for "occurrences" can be changed:

General -> Editors -> Text Editors -> Annotations

Look for Occurences from the Annotation types list.

Then, be sure that Text as highlighted is selected, then choose the desired color.


And, a picture is worth a thousand words...

Preferences dialog
(source: coobird.net)

Image showing occurences highlighted in orange.
(source: coobird.net)

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

Change

<serviceMetadata httpsGetEnabled="true"/>

to

<serviceMetadata httpsGetEnabled="false"/>

You're telling WCF to use https for the metadata endpoint and I see that your'e exposing your service on http, and then you get the error in the title.

You also have to set <security mode="None" /> if you want to use HTTP as your URL suggests.

Problems with local variable scope. How to solve it?

Firstly, we just CAN'T make the variable final as its state may be changing during the run of the program and our decisions within the inner class override may depend on its current state.

Secondly, good object-oriented programming practice suggests using only variables/constants that are vital to the class definition as class members. This means that if the variable we are referencing within the anonymous inner class override is just a utility variable, then it should not be listed amongst the class members.

But – as of Java 8 – we have a third option, described here :

https://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html

Starting in Java SE 8, if you declare the local class in a method, it can access the method's parameters.

So now we can simply put the code containing the new inner class & its method override into a private method whose parameters include the variable we call from inside the override. This static method is then called after the btnInsert declaration statement :-

 . . . .
 . . . .

 Statement statement = null;                                 

 . . . .
 . . . .

 Button btnInsert = new Button(shell, SWT.NONE);
 addMouseListener(Button btnInsert, Statement statement);    // Call new private method

 . . . 
 . . .
 . . . 

 private static void addMouseListener(Button btn, Statement st) // New private method giving access to statement 
 {
    btn.addMouseListener(new MouseAdapter() 
    {
      @Override
      public void mouseDown(MouseEvent e) 
      {
        String name = text.getText();
        String from = text_1.getText();
        String to = text_2.getText();
        String price = text_3.getText();
        String query = "INSERT INTO booking (name, fromst, tost,price) VALUES ('"+name+"', '"+from+"', '"+to+"', '"+price+"')";
        try 
        {
            st.executeUpdate(query);
        } 
        catch (SQLException e1) 
        {
            e1.printStackTrace();                                    // TODO Auto-generated catch block
        }
    }
  });
  return;
}

 . . . .
 . . . .
 . . . .

Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>

Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.3</version>
  <scope>runtime</scope>
</dependency>

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>3.0.0</version>
  <scope>runtime</scope>
</dependency>

Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

UTF-8, UTF-16, and UTF-32

Unicode defines a single huge character set, assigning one unique integer value to every graphical symbol (that is a major simplification, and isn't actually true, but it's close enough for the purposes of this question). UTF-8/16/32 are simply different ways to encode this.

In brief, UTF-32 uses 32-bit values for each character. That allows them to use a fixed-width code for every character.

UTF-16 uses 16-bit by default, but that only gives you 65k possible characters, which is nowhere near enough for the full Unicode set. So some characters use pairs of 16-bit values.

And UTF-8 uses 8-bit values by default, which means that the 127 first values are fixed-width single-byte characters (the most significant bit is used to signify that this is the start of a multi-byte sequence, leaving 7 bits for the actual character value). All other characters are encoded as sequences of up to 4 bytes (if memory serves).

And that leads us to the advantages. Any ASCII-character is directly compatible with UTF-8, so for upgrading legacy apps, UTF-8 is a common and obvious choice. In almost all cases, it will also use the least memory. On the other hand, you can't make any guarantees about the width of a character. It may be 1, 2, 3 or 4 characters wide, which makes string manipulation difficult.

UTF-32 is opposite, it uses the most memory (each character is a fixed 4 bytes wide), but on the other hand, you know that every character has this precise length, so string manipulation becomes far simpler. You can compute the number of characters in a string simply from the length in bytes of the string. You can't do that with UTF-8.

UTF-16 is a compromise. It lets most characters fit into a fixed-width 16-bit value. So as long as you don't have Chinese symbols, musical notes or some others, you can assume that each character is 16 bits wide. It uses less memory than UTF-32. But it is in some ways "the worst of both worlds". It almost always uses more memory than UTF-8, and it still doesn't avoid the problem that plagues UTF-8 (variable-length characters).

Finally, it's often helpful to just go with what the platform supports. Windows uses UTF-16 internally, so on Windows, that is the obvious choice.

Linux varies a bit, but they generally use UTF-8 for everything that is Unicode-compliant.

So short answer: All three encodings can encode the same character set, but they represent each character as different byte sequences.

How to run a class from Jar which is not the Main-Class in its Manifest file

First of all jar creates a jar, and does not run it. Try java -jar instead.

Second, why do you pass the class twice, as FQCN (com.mycomp.myproj.dir2.MainClass2) and as file (com/mycomp/myproj/dir2/MainClass2.class)?

Edit:

It seems as if java -jar requires a main class to be specified. You could try java -cp your.jar com.mycomp.myproj.dir2.MainClass2 ... instead. -cp sets the jar on the classpath and enables java to look up the main class there.

Flash CS4 refuses to let go

Try deleting your ASO files.

ASO files are cached compiled versions of your class files. Although the IDE is a lot better at letting go of old caches when changes are made, sometimes you have to manually delete them. To delete ASO files: Control>Delete ASO Files.

This is also the cause of the "I-am-not-seeing-my-changes-so-let-me-add-a-trace-now-everything-works" bug that was introduced in CS3.

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

No you are not using it correctly.

See here for details.

DateTime t1 = new DateTime(100);
DateTime t2 = new DateTime(20);

if (DateTime.Compare(t1, t2) >  0) Console.WriteLine("t1 > t2"); 
if (DateTime.Compare(t1, t2) == 0) Console.WriteLine("t1 == t2"); 
if (DateTime.Compare(t1, t2) <  0) Console.WriteLine("t1 < t2");

How can I position my div at the bottom of its container?

Its an old question, but this is a unique approach that can help in several cases.

Pure CSS, Without Absolute positioning, Without Fixing any Height, Cross-Browser (IE9+)

check out that Working Fiddle

Because normal flow is 'top-to-bottom' we can't simply ask the #copyright div to stick to the bottom of his parent without absolutely positioning of some sort, But if we wanted the #copyright div to stick to the top of his parent, it will be very simple - because this is the normal flow way.

So we will use this in our advantage. we will change the order of the divs in the HTML, now the #copyright div is at the top, and the content follow it right away. we also make the content div stretch all the way (using pseudo elements and clearing techniques)

now it's just a matter of inverting that order back in the view. that can be easily done with CSS transform.

We rotate the container by 180deg, and now: up-is-down. (and we inverse back the content to look normal again)

If we want to have a scroolbar within the content area, we need to apply a little bit more of CSS magic. as can be showed Here [in that example, the content is below a header - but its the same idea]

_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
html,_x000D_
body,_x000D_
#Container {_x000D_
  height: 100%;_x000D_
  color: white;_x000D_
}_x000D_
_x000D_
#Container:before {_x000D_
  content: '';_x000D_
  height: 100%;_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
#Copyright {_x000D_
  background-color: green;_x000D_
}_x000D_
_x000D_
#Stretch {_x000D_
  background-color: blue;_x000D_
}_x000D_
_x000D_
#Stretch:after {_x000D_
  content: '';_x000D_
  display: block;_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
#Container,_x000D_
#Container>div {_x000D_
  -moz-transform: rotateX(180deg);_x000D_
  -ms-transform: rotateX(180deg);_x000D_
  -o-transform: rotate(180deg);_x000D_
  -webkit-transform: rotateX(180deg);_x000D_
  transform: rotateX(180deg);_x000D_
}
_x000D_
<div id="Container">_x000D_
  <div id="Copyright">_x000D_
    Copyright Foo web designs_x000D_
  </div>_x000D_
  <div id="Stretch">_x000D_
    <!-- Other elements here -->_x000D_
    <div>Element 1</div>_x000D_
    <div>Element 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to set the environmental variable LD_LIBRARY_PATH in linux

Keep the previous path, don't overwrite it:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/your/custom/path/

You can add it to your ~/.bashrc:

echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/your/custom/path/' >> ~/.bashrc

Typescript: Type 'string | undefined' is not assignable to type 'string'

You trying to set variable name1, witch type set as strict string (it MUST be string) with value from object field name, witch value type set as optional string (it can be string or undefined, because of question sign). If you really need this behavior, you have to change type of name1 like this:

let name1: string | undefined = person.name;

And it'll be ok;

How to preserve insertion order in HashMap?

LinkedHashMap is precisely what you're looking for.

It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.

Java Returning method which returns arraylist?

MyClass obj = new MyClass();
ArrayList<Integer> numbers = obj.myNumbers();

How to convert string to XML using C#

xDoc.LoadXML("<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer>                    
                    </body></head>");

How can I add a background thread to flask?

Your additional threads must be initiated from the same app that is called by the WSGI server.

The example below creates a background thread that executes every 5 seconds and manipulates data structures that are also available to Flask routed functions.

import threading
import atexit
from flask import Flask

POOL_TIME = 5 #Seconds

# variables that are accessible from anywhere
commonDataStruct = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
yourThread = threading.Thread()

def create_app():
    app = Flask(__name__)

    def interrupt():
        global yourThread
        yourThread.cancel()

    def doStuff():
        global commonDataStruct
        global yourThread
        with dataLock:
        # Do your stuff with commonDataStruct Here

        # Set the next thread to happen
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()   

    def doStuffStart():
        # Do initialisation stuff here
        global yourThread
        # Create your thread
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()

    # Initiate
    doStuffStart()
    # When you kill Flask (SIGTERM), clear the trigger for the next thread
    atexit.register(interrupt)
    return app

app = create_app()          

Call it from Gunicorn with something like this:

gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app

"Multiple definition", "first defined here" errors

The problem here is that you are including commands.c in commands.h before the function prototype. Therefore, the C pre-processor inserts the content of commands.c into commands.h before the function prototype. commands.c contains the function definition. As a result, the function definition ends up before than the function declaration causing the error.

The content of commands.h after the pre-processor phase looks like this:

#ifndef COMMANDS_H_
#define COMMANDS_H_

// function definition
void f123(){

}

// function declaration
void f123();

#endif /* COMMANDS_H_ */

This is an error because you can't declare a function after its definition in C. If you swapped #include "commands.c" and the function declaration the error shouldn't happen because, now, the function prototype comes before the function declaration.

However, including a .c file is a bad practice and should be avoided. A better solution for this problem would be to include commands.h in commands.c and link the compiled version of command to the main file. For example:

commands.h

#ifndef COMMANDS_H_
#define COMMANDS_H_

void f123(); // function declaration

#endif

commands.c

#include "commands.h"

void f123(){} // function definition

Error TF30063: You are not authorized to access ... \DefaultCollection

For me the error came after changing my password for my AD account.

I had to remove the line from credential manager (which contained the previous password.)

Then it worked again.

How to access Session variables and set them in javascript?

Here is what worked for me. Javascript has this.

<script type="text/javascript">
var deptname = '';
</script>

C# Code behind has this - it could be put on the master page so it reset var on ever page change.

        String csname1 = "LoadScript";
        Type cstype = p.GetType();

        // Get a ClientScriptManager reference from the Page class.
        ClientScriptManager cs = p.ClientScript;

        // Check to see if the startup script is already registered.
        if (!cs.IsStartupScriptRegistered(cstype, csname1))
        {
            String cstext1 = funct;
            cs.RegisterStartupScript(cstype, csname1, "deptname = 'accounting'", true);
        }
        else
        {
            String cstext = funct;
            cs.RegisterClientScriptBlock(cstype, csname1, "deptname ='accounting'",true);
        }

Add this code to a button click to confirm deptname changed.

alert(deptname);

Why does modern Perl avoid UTF-8 by default?

I think you misunderstand Unicode and its relationship to Perl. No matter which way you store data, Unicode, ISO-8859-1, or many other things, your program has to know how to interpret the bytes it gets as input (decoding) and how to represent the information it wants to output (encoding). Get that interpretation wrong and you garble the data. There isn't some magic default setup inside your program that's going to tell the stuff outside your program how to act.

You think it's hard, most likely, because you are used to everything being ASCII. Everything you should have been thinking about was simply ignored by the programming language and all of the things it had to interact with. If everything used nothing but UTF-8 and you had no choice, then UTF-8 would be just as easy. But not everything does use UTF-8. For instance, you don't want your input handle to think that it's getting UTF-8 octets unless it actually is, and you don't want your output handles to be UTF-8 if the thing reading from them can't handle UTF-8. Perl has no way to know those things. That's why you are the programmer.

I don't think Unicode in Perl 5 is too complicated. I think it's scary and people avoid it. There's a difference. To that end, I've put Unicode in Learning Perl, 6th Edition, and there's a lot of Unicode stuff in Effective Perl Programming. You have to spend the time to learn and understand Unicode and how it works. You're not going to be able to use it effectively otherwise.

What is the difference between char array and char pointer in C?

Let's see:

#include <stdio.h>
#include <string.h>

int main()
{
    char *p = "hello";
    char q[] = "hello"; // no need to count this

    printf("%zu\n", sizeof(p)); // => size of pointer to char -- 4 on x86, 8 on x86-64
    printf("%zu\n", sizeof(q)); // => size of char array in memory -- 6 on both

    // size_t strlen(const char *s) and we don't get any warnings here:
    printf("%zu\n", strlen(p)); // => 5
    printf("%zu\n", strlen(q)); // => 5

    return 0;
}

foo* and foo[] are different types and they are handled differently by the compiler (pointer = address + representation of the pointer's type, array = pointer + optional length of the array, if known, for example, if the array is statically allocated), the details can be found in the standard. And at the level of runtime no difference between them (in assembler, well, almost, see below).

Also, there is a related question in the C FAQ:

Q: What is the difference between these initializations?

char a[] = "string literal";   
char *p  = "string literal";   

My program crashes if I try to assign a new value to p[i].

A: A string literal (the formal term for a double-quoted string in C source) can be used in two slightly different ways:

  1. As the initializer for an array of char, as in the declaration of char a[] , it specifies the initial values of the characters in that array (and, if necessary, its size).
  2. Anywhere else, it turns into an unnamed, static array of characters, and this unnamed array may be stored in read-only memory, and which therefore cannot necessarily be modified. In an expression context, the array is converted at once to a pointer, as usual (see section 6), so the second declaration initializes p to point to the unnamed array's first element.

Some compilers have a switch controlling whether string literals are writable or not (for compiling old code), and some may have options to cause string literals to be formally treated as arrays of const char (for better error catching).

See also questions 1.31, 6.1, 6.2, 6.8, and 11.8b.

References: K&R2 Sec. 5.5 p. 104

ISO Sec. 6.1.4, Sec. 6.5.7

Rationale Sec. 3.1.4

H&S Sec. 2.7.4 pp. 31-2

What does "#pragma comment" mean?

The answers and the documentation provided by MSDN is the best, but I would like to add one typical case that I use a lot which requires the use of #pragma comment to send a command to the linker at link time for example

#pragma comment(linker,"/ENTRY:Entry")

tell the linker to change the entry point form WinMain() to Entry() after that the CRTStartup going to transfer controll to Entry()

How to create a HTML Table from a PHP array?

echo '<table><tr><th>Title</th><th>Price</th><th>Number</th></tr>';
foreach($shop as $id => $item) {
    echo '<tr><td>'.$item[0].'</td><td>'.$item[1].'</td><td>'.$item[2].'</td></tr>';
}
echo '</table>';

What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone

Well considering there's no overhead difference between a varchar(30) and a varchar(100) if you're only storing 20 characters in each, err on the side of caution and just make it 50.

Using a custom (ttf) font in CSS

You need to use the css-property font-face to declare your font. Have a look at this fancy site: http://www.font-face.com/

Example:

@font-face {
  font-family: MyHelvetica;
  src: local("Helvetica Neue Bold"),
       local("HelveticaNeue-Bold"),
       url(MgOpenModernaBold.ttf);
  font-weight: bold;
}

See also: MDN @font-face

Remove Safari/Chrome textinput/textarea glow

If you want to remove the glow from buttons in Bootstrap (which is not necessarily bad UX in my opinion), you'll need the following code:

.btn:focus, .btn:active:focus, .btn.active:focus{
  outline-color: transparent;
  outline-style: none;
}

VirtualBox and vmdk vmx files

Actually, for the configuration of the machine, just open the .vmx file with a text editor (e.g. notepad, gedit, etc.). You will be able to see the OS type, memsize, ethernet.connectionType, and other settings. Then when you make your machine, just look in the text editor for the corresponding settings. When it asks for the disk, select the .vmdk disk as mentioned above.

How do I merge my local uncommitted changes into another Git branch?

The answers given so far are not ideal because they require a lot of needless work resolving merge conflicts, or they make too many assumptions which are frequently false. This is how to do it perfectly. The link is to my own site.

How to Commit to a Different Branch in git

You have uncommited changes on my_branch that you want to commit to master, without committing all the changes from my_branch.

Example

git merge master
git stash -u
git checkout master
git stash apply
git reset
git add example.js
git commit
git checkout .
git clean -f -d
git checkout my_branch
git merge master
git stash pop

Explanation

Start by merging master into your branch, since you'll have to do that eventually anyway, and now is the best time to resolve any conflicts.

The -u option (aka --include-untracked) in git stash -u prevents you from losing untracked files when you later do git clean -f -d within master.

After git checkout master it is important that you do NOT git stash pop, because you will need this stash later. If you pop the stash created in my_branch and then do git stash in master, you will cause needless merge conflicts when you later apply that stash in my_branch.

git reset unstages everything resulting from git stash apply. For example, files that have been modified in the stash but do not exist in master get staged as "deleted by us" conflicts.

git checkout . and git clean -f -d discard everything that isn't committed: all changes to tracked files, and all untracked files and directories. They are already saved in the stash and if left in master would cause needless merge conflicts when switching back to my_branch.

The last git stash pop will be based on the original my_branch, and so will not cause any merge conflicts. However, if your stash contains untracked files which you have committed to master, git will complain that it "Could not restore untracked files from stash". To resolve this conflict, delete those files from your working tree, then git stash pop, git add ., and git reset.

Accessing MP3 metadata with Python

using https://github.com/nicfit/eyeD3

import eyed3
import os

for root,  dirs, files in os.walk(folderp):
    for file in files:
        try:
            if file.find(".mp3") < 0:
                continue
            path = os.path.abspath(os.path.join(root , file))
            t = eyed3.load(path)
            print(t.tag.title , t.tag.artist)
            #print(t.getArtist())
        except Exception as e:
            print(e)
            continue

if (boolean condition) in Java

Booleans default value is false only for classes' fields. If within a method, you have to initialize your variable by true or false. Thus for example in your case, you'll have a compilation error.

Moreover, I don't really get the point, but the only way to enter within a if is to evaluate the condition to true.

Can you center a Button in RelativeLayout?

It's pretty simple, just use Android:CenterInParent="true" to center both in horizontal and vertical, or use Android:Horizontal="true" to center in horizontal and Android:Vertical="true"

And make sure you write all this in RelaytiveLayout

How to install Android SDK on Ubuntu?

sudo add-apt-repository -y ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer oracle-java7-set-default
wget https://dl.google.com/dl/android/studio/ide-zips/2.2.0.12/android-studio-ide-145.3276617-linux.zip
unzip android-studio-ide-145.3276617-linux.zip
cd android-studio/bin
./studio.sh

a href link for entire div in HTML/CSS

Two things you can do:

  1. Change #childdivimage to a span element, and change #parentdivimage to an anchor tag. This may require you to add some more styling to get things looking perfect. This is preffered, since it uses semantic markup, and does not rely on javascript.

  2. Use Javascript to bind a click event to #parentdivimage. You must redirect the browser window by modifying window.location inside this event. This is TheEasyWayTM, but will not degrade gracefully.

How can I delete a user in linux when the system says its currently used in a process

It worked i used userdell --force USERNAME Some times eventhough -f and --force is same -f is not working sometimes After i removed the account i exit back to that removed username which i removed from root then what happened is this

image description here

PHP CURL Enable Linux

if you have used curl above the page and below your html is present and unfortunately your html page is not able to view then just enable your curl. But in order to check CURL is enable or not in php you need to write following code:

echo 'Curl: ', function_exists('curl_version') ? 'Enabled' : 'Disabled';

Changing an AIX password via script?

You can try :

echo -e "newpasswd123\nnnewpasswd123" | passwd user

Good Hash Function for Strings

You should probably use String.hashCode().

If you really want to implement hashCode yourself:

Do not be tempted to exclude significant parts of an object from the hash code computation to improve performance -- Joshua Bloch, Effective Java

Using only the first five characters is a bad idea. Think about hierarchical names, such as URLs: they will all have the same hash code (because they all start with "http://", which means that they are stored under the same bucket in a hash map, exhibiting terrible performance.

Here's a war story paraphrased on the String hashCode from "Effective Java":

The String hash function implemented in all releases prior to 1.2 examined at most sixteen characters, evenly spaced throughout the string, starting with the first character. For large collections of hierarchical names, such as URLs, this hash function displayed terrible behavior.

Function not defined javascript

important: in this kind of error you should look for simple mistakes in most cases

besides syntax error, I should say once I had same problem and it was because of bad name I have chosen for function. I have never searched for the reason but I remember that I copied another function and change it to use. I add "1" after the name to changed the function name and I got this error.

Failed to load resource: net::ERR_INSECURE_RESPONSE

Offering another potential solution to this error.

If you have a frontend application that makes API calls to the backend, make sure you reference the domain name that the certificate has been issued to.

e.g.

https://example.com/api/etc

and not

https://123.4.5.6/api/etc

In my case, I was making API calls to a secure server with a certificate, but using the IP instead of the domain name. This threw a Failed to load resource: net::ERR_INSECURE_RESPONSE.

Render Partial View Using jQuery in ASP.NET MVC

@tvanfosson rocks with his answer.

However, I would suggest an improvement within js and a small controller check.

When we use @Url helper to call an action, we are going to receive a formatted html. It would be better to update the content (.html) not the actual element (.replaceWith).

More about at: What's the difference between jQuery's replaceWith() and html()?

$.get( '@Url.Action("details","user", new { id = Model.ID } )', function(data) {
    $('#detailsDiv').html(data);
}); 

This is specially useful in trees, where the content can be changed several times.

At the controller we can reuse the action depending on requester:

public ActionResult Details( int id )
{
    var model = GetFooModel();
    if (Request.IsAjaxRequest())
    {
        return PartialView( "UserDetails", model );
    }
    return View(model);
}

How to print a int64_t type in C

Coming from the embedded world, where even uclibc is not always available, and code like

uint64_t myval = 0xdeadfacedeadbeef; printf("%llx", myval);

is printing you crap or not working at all -- i always use a tiny helper, that allows me to dump properly uint64_t hex:

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

char* ullx(uint64_t val)
{
    static char buf[34] = { [0 ... 33] = 0 };
    char* out = &buf[33];
    uint64_t hval = val;
    unsigned int hbase = 16;

    do {
        *out = "0123456789abcdef"[hval % hbase];
        --out;
        hval /= hbase;
    } while(hval);

    *out-- = 'x', *out = '0';

    return out;
}

Unresponsive KeyListener for JFrame

KeyListener is low level and applies only to a single component. Despite attempts to make it more usable JFrame creates a number of component components, the most obvious being the content pane. JComboBox UI is also often implemented in a similar manner.

It's worth noting the mouse events work in a strange way slightly different to key events.

For details on what you should do, see my answer on Application wide keyboard shortcut - Java Swing.

SQL Server 2008: how do I grant privileges to a username?

If you really want them to have ALL rights:

use YourDatabase
go
exec sp_addrolemember 'db_owner', 'UserName'
go

Access key value from Web.config in Razor View-MVC3 ASP.NET

@System.Configuration.ConfigurationManager.AppSettings["myKey"]

How to strip HTML tags with jQuery?

If you want to keep the innerHTML of the element and only strip the outermost tag, you can do this:

$(".contentToStrip").each(function(){
  $(this).replaceWith($(this).html());
});

Automatically scroll down chat div

    var l = document.getElementsByClassName("chatMessages").length;
    document.getElementsByClassName("chatMessages")[l-1].scrollIntoView();

this should work

How to send Basic Auth with axios

There is an "auth" parameter for Basic Auth:

auth: {
  username: 'janedoe',
  password: 's00pers3cret'
}

Source/Docs: https://github.com/mzabriskie/axios

Example:

await axios.post(session_url, {}, {
  auth: {
    username: uname,
    password: pass
  }
});

Is it possible to forward-declare a function in Python?

If you kick-start your script through the following:

if __name__=="__main__":
   main()

then you probably do not have to worry about things like "forward declaration". You see, the interpreter would go loading up all your functions and then start your main() function. Of course, make sure you have all the imports correct too ;-)

Come to think of it, I've never heard such a thing as "forward declaration" in python... but then again, I might be wrong ;-)

Getting URL parameter in java and extract a specific text from that URL

I wrote this last month for Joomla Module when implementing youtube videos (with the Gdata API). I've since converted it to java.

Import These Libraries

    import java.net.URL;
    import java.util.regex.*;

Copy/Paste this function

    public String getVideoId( String videoId ) throws Exception {
        String pattern = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(videoId);
        int youtu = videoId.indexOf("youtu");
        if(m.matches() && youtu != -1){
            int ytu = videoId.indexOf("http://youtu.be/");
            if(ytu != -1) { 
                String[] split = videoId.split(".be/");
                return split[1];
            }
            URL youtube = new URL(videoId);
            String[] split = youtube.getQuery().split("=");
            int query = split[1].indexOf("&");
            if(query != -1){
                String[] nSplit = split[1].split("&");
                return nSplit[0];
            } else return split[1];
        }
        return null; //throw something or return what you want
    }

URL's it will work with

http://www.youtube.com/watch?v=k0BWlvnBmIE (General URL)
http://youtu.be/k0BWlvnBmIE (Share URL)
http://www.youtube.com/watch?v=UWb5Qc-fBvk&list=FLzH5IF4Lwgv-DM3CupM3Zog&index=2 (Playlist URL)

Slicing a dictionary

set intersection and dict comprehension can be used here

# the dictionary
d = {1:2, 3:4, 5:6, 7:8}

# the subset of keys I'm interested in
l = (1,5)

>>>{key:d[key] for key in set(l) & set(d)}
{1: 2, 5: 6}

Remove directory from remote repository after adding them to .gitignore

The answer from Blundell should work, but for some bizarre reason it didn't do with me. I had to pipe first the filenames outputted by the first command into a file and then loop through that file and delete that file one by one.

git ls-files -i --exclude-from=.gitignore > to_remove.txt
while read line; do `git rm -r --cached "$line"`; done < to_remove.txt
rm to_remove.txt
git commit -m 'Removed all files that are in the .gitignore' 
git push origin master

How do I analyze a program's core dump file with GDB when it has command-line parameters?

Simply type the command:

$ gdb <Binary> <codeDump>

Or

$ gdb <binary>

$ gdb) core <coreDump>

There isn't any need to provide any command line argument. The code dump generated due to an earlier exercise.

Remove element of a regular array

As usual, I'm late to the party...

I'd like to add another option to the nice solutions list already present. =)
I would see this as a good opportunity for Extensions.

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

So, we define some static class and in it, our Method.
After that, we can use our extended method willy-nilly. =)

using System;

namespace FunctionTesting {

    // The class doesn't matter, as long as it's static
    public static class SomeRandomClassWhoseNameDoesntMatter {

        // Here's the actual method that extends arrays
        public static T[] RemoveAt<T>( this T[] oArray, int idx ) {
            T[] nArray = new T[oArray.Length - 1];
            for( int i = 0; i < nArray.Length; ++i ) {
                nArray[i] = ( i < idx ) ? oArray[i] : oArray[i + 1];
            }
            return nArray;
        }
    }

    // Sample usage...
    class Program {
        static void Main( string[] args ) {
            string[] myStrArray = { "Zero", "One", "Two", "Three" };
            Console.WriteLine( String.Join( " ", myStrArray ) );
            myStrArray = myStrArray.RemoveAt( 2 );
            Console.WriteLine( String.Join( " ", myStrArray ) );
            /* Output
             * "Zero One Two Three"
             * "Zero One Three"
             */

            int[] myIntArray = { 0, 1, 2, 3 };
            Console.WriteLine( String.Join( " ", myIntArray ) );
            myIntArray = myIntArray.RemoveAt( 2 );
            Console.WriteLine( String.Join( " ", myIntArray ) );
            /* Output
             * "0 1 2 3"
             * "0 1 3"
             */
        }
    }
}

Numpy Resize/Rescale Image

import cv2
import numpy as np

image_read = cv2.imread('filename.jpg',0) 
original_image = np.asarray(image_read)
width , height = 452,452
resize_image = np.zeros(shape=(width,height))

for W in range(width):
    for H in range(height):
        new_width = int( W * original_image.shape[0] / width )
        new_height = int( H * original_image.shape[1] / height )
        resize_image[W][H] = original_image[new_width][new_height]

print("Resized image size : " , resize_image.shape)

cv2.imshow(resize_image)
cv2.waitKey(0)

Dynamically load a function from a DLL

This is not exactly a hot topic, but I have a factory class that allows a dll to create an instance and return it as a DLL. It is what I came looking for but couldn't find exactly.

It is called like,

IHTTP_Server *server = SN::SN_Factory<IHTTP_Server>::CreateObject();
IHTTP_Server *server2 =
      SN::SN_Factory<IHTTP_Server>::CreateObject(IHTTP_Server_special_entry);

where IHTTP_Server is the pure virtual interface for a class created either in another DLL, or the same one.

DEFINE_INTERFACE is used to give a class id an interface. Place inside interface;

An interface class looks like,

class IMyInterface
{
    DEFINE_INTERFACE(IMyInterface);

public:
    virtual ~IMyInterface() {};

    virtual void MyMethod1() = 0;
    ...
};

The header file is like this

#if !defined(SN_FACTORY_H_INCLUDED)
#define SN_FACTORY_H_INCLUDED

#pragma once

The libraries are listed in this macro definition. One line per library/executable. It would be cool if we could call into another executable.

#define SN_APPLY_LIBRARIES(L, A)                          \
    L(A, sn, "sn.dll")                                    \
    L(A, http_server_lib, "http_server_lib.dll")          \
    L(A, http_server, "")

Then for each dll/exe you define a macro and list its implementations. Def means that it is the default implementation for the interface. If it is not the default, you give a name for the interface used to identify it. Ie, special, and the name will be IHTTP_Server_special_entry.

#define SN_APPLY_ENTRYPOINTS_sn(M)                                     \
    M(IHTTP_Handler, SNI::SNI_HTTP_Handler, sn, def)                   \
    M(IHTTP_Handler, SNI::SNI_HTTP_Handler, sn, special)

#define SN_APPLY_ENTRYPOINTS_http_server_lib(M)                        \
    M(IHTTP_Server, HTTP::server::server, http_server_lib, def)

#define SN_APPLY_ENTRYPOINTS_http_server(M)

With the libraries all setup, the header file uses the macro definitions to define the needful.

#define APPLY_ENTRY(A, N, L) \
    SN_APPLY_ENTRYPOINTS_##N(A)

#define DEFINE_INTERFACE(I) \
    public: \
        static const long Id = SN::I##_def_entry; \
    private:

namespace SN
{
    #define DEFINE_LIBRARY_ENUM(A, N, L) \
        N##_library,

This creates an enum for the libraries.

    enum LibraryValues
    {
        SN_APPLY_LIBRARIES(DEFINE_LIBRARY_ENUM, "")
        LastLibrary
    };

    #define DEFINE_ENTRY_ENUM(I, C, L, D) \
        I##_##D##_entry,

This creates an enum for interface implementations.

    enum EntryValues
    {
        SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_ENUM)
        LastEntry
    };

    long CallEntryPoint(long id, long interfaceId);

This defines the factory class. Not much to it here.

    template <class I>
    class SN_Factory
    {
    public:
        SN_Factory()
        {
        }

        static I *CreateObject(long id = I::Id )
        {
            return (I *)CallEntryPoint(id, I::Id);
        }
    };
}

#endif //SN_FACTORY_H_INCLUDED

Then the CPP is,

#include "sn_factory.h"

#include <windows.h>

Create the external entry point. You can check that it exists using depends.exe.

extern "C"
{
    __declspec(dllexport) long entrypoint(long id)
    {
        #define CREATE_OBJECT(I, C, L, D) \
            case SN::I##_##D##_entry: return (int) new C();

        switch (id)
        {
            SN_APPLY_CURRENT_LIBRARY(APPLY_ENTRY, CREATE_OBJECT)
        case -1:
        default:
            return 0;
        }
    }
}

The macros set up all the data needed.

namespace SN
{
    bool loaded = false;

    char * libraryPathArray[SN::LastLibrary];
    #define DEFINE_LIBRARY_PATH(A, N, L) \
        libraryPathArray[N##_library] = L;

    static void LoadLibraryPaths()
    {
        SN_APPLY_LIBRARIES(DEFINE_LIBRARY_PATH, "")
    }

    typedef long(*f_entrypoint)(long id);

    f_entrypoint libraryFunctionArray[LastLibrary - 1];
    void InitlibraryFunctionArray()
    {
        for (long j = 0; j < LastLibrary; j++)
        {
            libraryFunctionArray[j] = 0;
        }

        #define DEFAULT_LIBRARY_ENTRY(A, N, L) \
            libraryFunctionArray[N##_library] = &entrypoint;

        SN_APPLY_CURRENT_LIBRARY(DEFAULT_LIBRARY_ENTRY, "")
    }

    enum SN::LibraryValues libraryForEntryPointArray[SN::LastEntry];
    #define DEFINE_ENTRY_POINT_LIBRARY(I, C, L, D) \
            libraryForEntryPointArray[I##_##D##_entry] = L##_library;
    void LoadLibraryForEntryPointArray()
    {
        SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_POINT_LIBRARY)
    }

    enum SN::EntryValues defaultEntryArray[SN::LastEntry];
        #define DEFINE_ENTRY_DEFAULT(I, C, L, D) \
            defaultEntryArray[I##_##D##_entry] = I##_def_entry;

    void LoadDefaultEntries()
    {
        SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_DEFAULT)
    }

    void Initialize()
    {
        if (!loaded)
        {
            loaded = true;
            LoadLibraryPaths();
            InitlibraryFunctionArray();
            LoadLibraryForEntryPointArray();
            LoadDefaultEntries();
        }
    }

    long CallEntryPoint(long id, long interfaceId)
    {
        Initialize();

        // assert(defaultEntryArray[id] == interfaceId, "Request to create an object for the wrong interface.")
        enum SN::LibraryValues l = libraryForEntryPointArray[id];

        f_entrypoint f = libraryFunctionArray[l];
        if (!f)
        {
            HINSTANCE hGetProcIDDLL = LoadLibraryA(libraryPathArray[l]);

            if (!hGetProcIDDLL) {
                return NULL;
            }

            // resolve function address here
            f = (f_entrypoint)GetProcAddress(hGetProcIDDLL, "entrypoint");
            if (!f) {
                return NULL;
            }
            libraryFunctionArray[l] = f;
        }
        return f(id);
    }
}

Each library includes this "cpp" with a stub cpp for each library/executable. Any specific compiled header stuff.

#include "sn_pch.h"

Setup this library.

#define SN_APPLY_CURRENT_LIBRARY(L, A) \
    L(A, sn, "sn.dll")

An include for the main cpp. I guess this cpp could be a .h. But there are different ways you could do this. This approach worked for me.

#include "../inc/sn_factory.cpp"

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

Each GROUP BY expression must contain at least one column that is not an outer reference

I just found this error., while using GETDATE() [i.e outer reference] in the group by clause in a select query.

When replaced it with date column from the respective table it cleared.

Thought to share as a simple example. cheers ;)

How to extract multiple JSON objects from one file?

So, as was mentioned in a couple comments containing the data in an array is simpler but the solution does not scale well in terms of efficiency as the data set size increases. You really should only use an iterator when you want to access a random object in the array, otherwise, generators are the way to go. Below I have prototyped a reader function which reads each json object individually and returns a generator.

The basic idea is to signal the reader to split on the carriage character "\n" (or "\r\n" for Windows). Python can do this with the file.readline() function.

import json
def json_reader(filename):
    with open(filename) as f:
        for line in f:
            yield json.loads(line)

However, this method only really works when the file is written as you have it -- with each object separated by a newline character. Below I wrote an example of a writer that separates an array of json objects and saves each one on a new line.

def json_writer(file, json_objects):
    with open(file, "w") as f:
        for jsonobj in json_objects:
            jsonstr = json.dumps(jsonobj)
            f.write(jsonstr + "\n")

You could also do the same operation with file.writelines() and a list comprehension:

...
    json_strs = [json.dumps(j) + "\n" for j in json_objects]
    f.writelines(json_strs)
...

And if you wanted to append the data instead of writing a new file just change open(file, "w") to open(file, "a").

In the end I find this helps a great deal not only with readability when I try and open json files in a text editor but also in terms of using memory more efficiently.

On that note if you change your mind at some point and you want a list out of the reader, Python allows you to put a generator function inside of a list and populate the list automatically. In other words, just write

lst = list(json_reader(file))

Getting around the Max String size in a vba function?

Are you sure? This forum thread suggests it might be your watch window. Try outputting the string to a MsgBox, which can display a maximum of 1024 characters:

MsgBox RunMacros

Most efficient way to get table row count

If it's only about getting the number of records (rows) I'd suggest using:

SELECT TABLE_ROWS
FROM information_schema.tables 
WHERE table_name='the_table_you_want' -- Can end here if only 1 DB 
  AND table_schema = DATABASE();      -- See comment below if > 1 DB

(at least for MySQL) instead.

Which terminal command to get just IP address and nothing else?

I prefer not to use awk and such in scripts.. ip has the option to output in JSON.

If you leave out $interface then you get all of the ip addresses:

ip -json addr show $interface | \
  jq -r '.[] | .addr_info[] | select(.family == "inet") | .local'

Waiting until two async blocks are executed before starting another block

Another GCD alternative is a barrier:

dispatch_queue_t queue = dispatch_queue_create("com.company.app.queue", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue, ^{ 
    NSLog(@"start one!\n");  
    sleep(4);  
    NSLog(@"end one!\n");
});

dispatch_async(queue, ^{  
    NSLog(@"start two!\n");  
    sleep(2);  
    NSLog(@"end two!\n"); 
});

dispatch_barrier_async(queue, ^{  
    NSLog(@"Hi, I'm the final block!\n");  
});

Just create a concurrent queue, dispatch your two blocks, and then dispatch the final block with barrier, which will make it wait for the other two to finish.

Searching for file in directories recursively

You should have the loop over the files either before or after the loop over the directories, but not nested inside it as you have done.

foreach (string f in Directory.GetFiles(d, "*.xml"))
{
    string extension = Path.GetExtension(f);
    if (extension != null && (extension.Equals(".xml")))
    {
        fileList.Add(f);
    }
} 

foreach (string d in Directory.GetDirectories(sDir))
{
    DirSearch(d);
}

Dynamic Web Module 3.0 -- 3.1

I was running on Win7, Tomcat7 with maven-pom setup on Eclipse Mars with maven project enabled. On a NOT running server I only had to change from 3.1 to 3.0 on this screen: enter image description here

For me it was important to have Dynamic Web Module disabled! Then change the version and then enable Dynamic Web Module again.

Saving a high resolution image in R

You can do the following. Add your ggplot code after the first line of code and end with dev.off().

tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()

res=300 specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.

Change width and height in the code above depending on the desired output.

Note that this also works for other R plots including plot, image, and pheatmap.

Other file formats

In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.

Git reset --hard and push to remote repository

If forcing a push doesn't help ("git push --force origin" or "git push --force origin master" should be enough), it might mean that the remote server is refusing non fast-forward pushes either via receive.denyNonFastForwards config variable (see git config manpage for description), or via update / pre-receive hook.

With older Git you can work around that restriction by deleting "git push origin :master" (see the ':' before branch name) and then re-creating "git push origin master" given branch.

If you can't change this, then the only solution would be instead of rewriting history to create a commit reverting changes in D-E-F:

A-B-C-D-E-F-[(D-E-F)^-1]   master

A-B-C-D-E-F                             origin/master