Programs & Examples On #Bearing

0

Haversine Formula in Python (Bearing and Distance between two GPS points)

Refer to this link :https://gis.stackexchange.com/questions/84885/whats-the-difference-between-vincenty-and-great-circle-distance-calculations

this actually gives two ways of getting distance. They are Haversine and Vincentys. From my research I came to know that Vincentys is relatively accurate. Also use import statement to make the implementation.

Calculate compass bearing / heading to location in Android

I'm no expert in map-reading / navigation and so on but surely 'directions' are absolute and not relative or in reality, they are relative to N or S which themselves are fixed/absolute.

Example: Suppose an imaginary line drawn between you and your destination corresponds with 'absolute' SE (a bearing of 135 degrees relative to magnetic N). Now suppose your phone is pointing NW - if you draw an imaginary line from an imaginary object on the horizon to your destination, it will pass through your location and have an angle of 180 degrees. Now 180 degrees in the sense of a compass actually refers to S but the destination is not 'due S' of the imaginary object your phone is pointing at and, moreover, if you travelled to that imaginary point, your destination would still be SE of where you moved to.

In reality, the 180 degree line actually tells you the destination is 'behind you' relative to the way the phone (and presumably you) are pointing.

Having said that, however, if calculating the angle of a line from the imaginary point to your destination (passing through your location) in order to draw a pointer towards your destination is what you want...simply subtract the (absolute) bearing of the destination from the absolute bearing of the imaginary object and ignore a negation (if present). e.g., NW - SE is 315 - 135 = 180 so draw the pointer to point at the bottom of the screen indicating 'behind you'.

EDIT: I got the Maths slightly wrong...subtract the smaller of the bearings from the larger then subtract the result from 360 to get the angle in which to draw the pointer on the screen.

Unknown Column In Where Clause

I had the same problem, I found this useful.

mysql_query("SELECT * FROM `users` WHERE `user_name`='$user'");

remember to put $user in ' ' single quotes.

Is it a good practice to use try-except-else in Python?

Is it a good practice to use try-except-else in python?

The answer to this is that it is context dependent. If you do this:

d = dict()
try:
    item = d['item']
except KeyError:
    item = 'default'

It demonstrates that you don't know Python very well. This functionality is encapsulated in the dict.get method:

item = d.get('item', 'default')

The try/except block is a much more visually cluttered and verbose way of writing what can be efficiently executing in a single line with an atomic method. There are other cases where this is true.

However, that does not mean that we should avoid all exception handling. In some cases it is preferred to avoid race conditions. Don't check if a file exists, just attempt to open it, and catch the appropriate IOError. For the sake of simplicity and readability, try to encapsulate this or factor it out as apropos.

Read the Zen of Python, understanding that there are principles that are in tension, and be wary of dogma that relies too heavily on any one of the statements in it.

Converting cv::Mat to IplImage*

According to OpenCV cheat-sheet this can be done as follows:

IplImage* oldC0 = cvCreateImage(cvSize(320,240),16,1);
Mat newC = cvarrToMat(oldC0);

The cv::cvarrToMat function takes care of the conversion issues.

In CSS how do you change font size of h1 and h2

What have you tried? This should work.

h1 { font-size: 20pt; }
h2 { font-size: 16pt; }

Python recursive folder read

TL;DR: This is the equivalent to find -type f to go over all files in all folders below and including the current one:

for currentpath, folders, files in os.walk('.'):
    for file in files:
        print(os.path.join(currentpath, file))

As already mentioned in other answers, os.walk() is the answer, but it could be explained better. It's quite simple! Let's walk through this tree:

docs/
+-- doc1.odt
pics/
todo.txt

With this code:

for currentpath, folders, files in os.walk('.'):
    print(currentpath)

The currentpath is the current folder it is looking at. This will output:

.
./docs
./pics

So it loops three times, because there are three folders: the current one, docs, and pics. In every loop, it fills the variables folders and files with all folders and files. Let's show them:

for currentpath, folders, files in os.walk('.'):
    print(currentpath, folders, files)

This shows us:

# currentpath  folders           files
.              ['pics', 'docs']  ['todo.txt']
./pics         []                []
./docs         []                ['doc1.odt']

So in the first line, we see that we are in folder ., that it contains two folders namely pics and docs, and that there is one file, namely todo.txt. You don't have to do anything to recurse into those folders, because as you see, it recurses automatically and just gives you the files in any subfolders. And any subfolders of that (though we don't have those in the example).

If you just want to loop through all files, the equivalent of find -type f, you can do this:

for currentpath, folders, files in os.walk('.'):
    for file in files:
        print(os.path.join(currentpath, file))

This outputs:

./todo.txt
./docs/doc1.odt

Check if datetime instance falls in between other two datetime objects

Write yourself a Helper function:

public static bool IsBewteenTwoDates(this DateTime dt, DateTime start, DateTime end)
{
    return dt >= start && dt <= end;
}

Then call: .IsBewteenTwoDates(DateTime.Today ,new DateTime(,,));

Problems after upgrading to Xcode 10: Build input file cannot be found

File>Project Settings>Change Build Systems to Legacy Build Systems

How to make a rest post call from ReactJS code?

Another recently popular packages is : axios

Install : npm install axios --save

Simple Promise based requests


axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

How do I put text on ProgressBar?

Alliteratively you can try placing a Label control and placing it on top of the progress bar control. Then you can set whatever the text you want to the label. I haven't done this my self. If it works it should be a simpler solution than overriding onpaint.

How can I run a windows batch file but hide the command window?

This little VBScript from technet does the trick:

Const HIDDEN_WINDOW = 12

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objStartup = objWMIService.Get("Win32_ProcessStartup")

Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = HIDDEN_WINDOW
Set objProcess = GetObject("winmgmts:root\cimv2:Win32_Process")
errReturn = objProcess.Create("mybatch.bat", null, objConfig, intProcessID)

Edit mybatch.bat to your bat file name, save as a vbs, run it.

Doc says it's not tested in Win7, but I just tested it, it works fine. Won't show any window for whatever process you run

CSS content generation before or after 'input' elements

Something like this works:

_x000D_
_x000D_
input + label::after {_x000D_
  content: 'click my input';_x000D_
  color: black;_x000D_
}_x000D_
_x000D_
input:focus + label::after {_x000D_
  content: 'not valid yet';_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
input:valid + label::after {_x000D_
  content: 'looks good';_x000D_
  color: green;_x000D_
}
_x000D_
<input id="input" type="number" required />_x000D_
<label for="input"></label>
_x000D_
_x000D_
_x000D_

Then add some floats or positioning to order stuff.

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

USE This Assembly Referance in your Project

Add a reference to System.Net.Http.Formatting.dll

How to extract the decimal part from a floating point number in C?

Suppose A is your integer then (int)A, means casting the number to an integer and will be the integer part, the other is (A - (int)A)*10^n, here n is the number of decimals to keep.

How to get current memory usage in android?

final long usedMemInMB=(runtime.totalMemory() - runtime.freeMemory()) / 1048576L;
final long maxHeapSizeInMB=runtime.maxMemory() / 1048576L;
final long availHeapSizeInMB = maxHeapSizeInMB - usedMemInMB;

It is a strange code. It return MaxMemory - (totalMemory - freeMemory). If freeMemory equals 0, then the code will return MaxMemory - totalMemory, so it can more or equals 0. Why freeMemory not used?

How can I commit a single file using SVN over a network?

cd myapp/trunk
svn commit -m "commit message" page1.html

For more information, see:

svn commit --help

I also recommend this free book, if you're just getting started with Subversion.

While loop to test if a file exists in bash

works with bash and sh both:

touch /tmp/testfile
sleep 10 && rm /tmp/testfile &
until ! [ -f /tmp/testfile ]
do
   echo "testfile still exist..."
   sleep 1
done
echo "now testfile is deleted.."

How to redirect DNS to different ports

You can use SRV records:

_service._proto.name. TTL class SRV priority weight port target.

Service: the symbolic name of the desired service.

Proto: the transport protocol of the desired service; this is usually either TCP or UDP.

Name: the domain name for which this record is valid, ending in a dot.

TTL: standard DNS time to live field.

Class: standard DNS class field (this is always IN).

Priority: the priority of the target host, lower value means more preferred.

Weight: A relative weight for records with the same priority.

Port: the TCP or UDP port on which the service is to be found.

Target: the canonical hostname of the machine providing the service, ending in a dot.

Example:

_sip._tcp.example.com. 86400 IN SRV 0 5 5060 sipserver.example.com.

So what I think you're looking for is to add something like this to your DNS hosts file:

_sip._tcp.arboristal.com. 86400 IN SRV 10 40 25565 mc.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25566 tekkit.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25567 pvp.arboristal.com.

On a side note, I highly recommend you go with a hosting company rather than hosting the servers yourself. It's just asking for trouble with your home connection (DDoS and Bandwidth/Connection Speed), but it's up to you.

get number of columns of a particular row in given excel using Java

There are two Things you can do

use

int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();

or

int noOfColumns = sh.getRow(0).getLastCellNum();

There is a fine difference between them

  1. Option 1 gives the no of columns which are actually filled with contents(If the 2nd column of 10 columns is not filled you will get 9)
  2. Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'

What is the default lifetime of a session?

You can use something like ini_set('session.gc_maxlifetime', 28800); // 8 * 60 * 60 too.

Why I can't access remote Jupyter Notebook server?

From your command line, we can see your jupyter server is running normally.The reason you can't access your remote jupyter server is that your remote centos6.5 server's firewall rules block the incoming request from your local browser,i.e. block your tcp:8045 port.
sudo ufw allow 80 # enable http server
sudo ufw allow 443 # enable https server
sudo ufw allow 8045 # enable your tcp:8045 port
then try to access your jupyter again.


Maybe you also need to uncomment and edit that place in your jupyter_notebook_config.py file:

c.NotebookApp.allow_remote_access = True

and even shut down your VPN if you have one.

Decoding base64 in batch

Actually Windows does have a utility that encodes and decodes base64 - CERTUTIL

I'm not sure what version of Windows introduced this command.

To encode a file:

certutil -encode inputFileName encodedOutputFileName

To decode a file:

certutil -decode encodedInputFileName decodedOutputFileName

There are a number of available verbs and options available to CERTUTIL.

To get a list of nearly all available verbs:

certutil -?

To get help on a particular verb (-encode for example):

certutil -encode -?

To get complete help for nearly all verbs:

certutil -v -?

Mysteriously, the -encodehex verb is not listed with certutil -? or certutil -v -?. But it is described using certutil -encodehex -?. It is another handy function :-)

Update

Regarding David Morales' comment, there is a poorly documented type option to the -encodehex verb that allows creation of base64 strings without header or footer lines.

certutil [Options] -encodehex inFile outFile [type]

A type of 1 will yield base64 without the header or footer lines.

See https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p56536 for a brief listing of the available type formats. And for a more in depth look at the available formats, see https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p57918.

Not investigated, but the -decodehex verb also has an optional trailing type argument.

Making TextView scrollable on Android

Use it like this

<TextView  
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:maxLines = "AN_INTEGER"
    android:scrollbars = "vertical"
/>

Android change SDK version in Eclipse? Unable to resolve target android-x

Goto project -->properties --> (in the dialog box that opens goto Java build path), and in order and export select android 4.1 (your new version) and select dependencies.

How to convert milliseconds into human readable form?

function convertTime(time) {        
    var millis= time % 1000;
    time = parseInt(time/1000);
    var seconds = time % 60;
    time = parseInt(time/60);
    var minutes = time % 60;
    time = parseInt(time/60);
    var hours = time % 24;
    var out = "";
    if(hours && hours > 0) out += hours + " " + ((hours == 1)?"hr":"hrs") + " ";
    if(minutes && minutes > 0) out += minutes + " " + ((minutes == 1)?"min":"mins") + " ";
    if(seconds && seconds > 0) out += seconds + " " + ((seconds == 1)?"sec":"secs") + " ";
    if(millis&& millis> 0) out += millis+ " " + ((millis== 1)?"msec":"msecs") + " ";
    return out.trim();
}

How to make a DIV not wrap?

<div style="height:200px;width:200px;border:; white-space: nowrap;overflow-x: scroll;overflow-y: hidden;">
   <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.The quick brown fox jumps over the lazy dog.The quick brown fox jumps over the lazy dog.
   The quick brown fox jumps over the lazy dog.The quick brown fox jumps over the lazy dog.The quick brown fox jumps over the lazy dog.The quick brown fox jumps over the lazy dog.
   The quick brown fox jumps over the lazy dog.
   The quick brown fox jumps over the lazy dog.The quick brown fox jumps over the lazy dog.The quick brown fox jumps over the lazy dog.The quick brown fox jumps over the lazy dog.
   The quick brown fox jumps over the lazy dog.The quick brown fox jumps over the lazy dog.</p>
</div>

Finding median of list in Python

Here's the tedious way to find median without using the median function:

def median(*arg):
    order(arg)
    numArg = len(arg)
    half = int(numArg/2)
    if numArg/2 ==half:
        print((arg[half-1]+arg[half])/2)
    else:
        print(int(arg[half]))

def order(tup):
    ordered = [tup[i] for i in range(len(tup))]
    test(ordered)
    while(test(ordered)):
        test(ordered)
    print(ordered)


def test(ordered):
    whileloop = 0 
    for i in range(len(ordered)-1):
        print(i)
        if (ordered[i]>ordered[i+1]):
            print(str(ordered[i]) + ' is greater than ' + str(ordered[i+1]))
            original = ordered[i+1]
            ordered[i+1]=ordered[i]
            ordered[i]=original
            whileloop = 1 #run the loop again if you had to switch values
    return whileloop

How do you return a JSON object from a Java Servlet

Close to BalusC answer in 4 simple lines using Google Gson lib. Add this lines to the servlet method:

User objToSerialize = new User("Bill", "Gates");    
ServletOutputStream outputStream = response.getOutputStream();

response.setContentType("application/json;charset=UTF-8");
outputStream.print(new Gson().toJson(objToSerialize));

Good luck!

What does the clearfix class do in css?

clearfix is the same as overflow:hidden. Both clear floated children of the parent, but clearfix will not cut off the element which overflow to it's parent. It also works in IE8 & above.

There is no need to define "." in content & .clearfix. Just write like this:

.clr:after {
    clear: both;
    content: "";
    display: block;
}

HTML

<div class="parent clr"></div>

Read these links for more

http://css-tricks.com/snippets/css/clear-fix/,

What methods of ‘clearfix’ can I use?

How to run Gradle from the command line on Mac bash

./gradlew

Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. . means "current directory".

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

In my case this was actually a symptom of the server, hosted on AWS, lacking an IP for the external network. It would attempt to download namespaces from springframework.org and fail to make a connection.

Initializing default values in a struct

You can do it by using a constructor, like this:

struct Date
{
int day;
int month;
int year;

Date()
{
    day=0;
    month=0;
    year=0;
}
};

or like this:

struct Date
{
int day;
int month;
int year;

Date():day(0),
       month(0),
       year(0){}
};

In your case bar.c is undefined,and its value depends on the compiler (while a and b were set to true).

error: function returns address of local variable

a is an array local to the function.Once the function returns it does not exist anymore and hence you should not return the address of a local variable.
In other words the lifetime of a is within the scope({,}) of the function and if you return a pointer to it what you have is a pointer pointing to some memory which is not valid. Such variables are also called automatic variabels because their lifetime is automatically managed you do not need to manage it explicitly.

Since you need to extend the variable to persist beyond the scope of the function you You need to allocate a array on heap and return a pointer to it.

char *a = malloc(1000); 

This way the array a resides in memory untill you call a free() on the same address.
Do not forget to do so or you end up with a memory leak.

Open File in Another Directory (Python)

If you know the full path to the file you can just do something similar to this. However if you question directly relates to relative paths, that I am unfamiliar with and would have to research and test.

path = 'C:\\Users\\Username\\Path\\To\\File'

with open(path, 'w') as f:
    f.write(data)

Edit:

Here is a way to do it relatively instead of absolute. Not sure if this works on windows, you will have to test it.

import os

cur_path = os.path.dirname(__file__)

new_path = os.path.relpath('..\\subfldr1\\testfile.txt', cur_path)
with open(new_path, 'w') as f:
    f.write(data)

Edit 2: One quick note about __file__, this will not work in the interactive interpreter due it being ran interactively and not from an actual file.

Can I set text box to readonly when using Html.TextBoxFor?

<%= Html.TextBoxFor(m => Model.Events.Subscribed[i].Action, new { @readonly = true })%>

Difference between window.location.href and top.location.href

top object makes more sense inside frames. Inside a frame, window refers to current frame's window while top refers to the outermost window that contains the frame(s). So:

window.location.href = 'somepage.html'; means loading somepage.html inside the frame.

top.location.href = 'somepage.html'; means loading somepage.html in the main browser window.

Two other interesting objects are self and parent.

Convert hours:minutes:seconds into total minutes in excel

Just use the formula

120 = (HOUR(A8)*3600+MINUTE(A8)*60+SECOND(A8))/60

Auto-loading lib files in Rails 4

Use config.to_prepare to load you monkey patches/extensions for every request in development mode.

config.to_prepare do |action_dispatcher|
 # More importantly, will run upon every request in development, but only once (during boot-up) in production and test.
 Rails.logger.info "\n--- Loading extensions for #{self.class} "
 Dir.glob("#{Rails.root}/lib/extensions/**/*.rb").sort.each do |entry|
   Rails.logger.info "Loading extension(s): #{entry}"
   require_dependency "#{entry}"
 end
 Rails.logger.info "--- Loaded extensions for #{self.class}\n"

end

Center content vertically on Vuetify

In Vuetify 2.x, v-layout and v-flex are replaced by v-row and v-col respectively. To center the content both vertically and horizontally, we have to instruct the v-row component to do it:

<v-container fill-height>
    <v-row justify="center" align="center">
        <v-col cols="12" sm="4">
            Centered both vertically and horizontally
        </v-col>
    </v-row>
</v-container>
  • align="center" will center the content vertically inside the row
  • justify="center" will center the content horizontally inside the row
  • fill-height will center the whole content compared to the page.

Understanding REST: Verbs, error codes, and authentication

REST Basics

REST have an uniform interface constraint, which states that the REST client must rely on standards instead of application specific details of the actual REST service, so the REST client won't break by minor changes, and it will probably be reusable.

So there is a contract between the REST client and the REST service. If you use HTTP as the underlying protocol, then the following standards are part of the contract:

  • HTTP 1.1
    • method definitions
    • status code definitions
    • cache control headers
    • accept and content-type headers
    • auth headers
  • IRI (utf8 URI)
  • body (pick one)
    • registered application specific MIME type, e.g. maze+xml
    • vendor specific MIME type, e.g. vnd.github+json
    • generic MIME type with
  • hyperlinks
    • what should contain them (pick one)
      • sending in link headers
      • sending in a hypermedia response, e.g. html, atom+xml, hal+json, ld+json&hydra, etc...
    • semantics
      • use IANA link relations and probably custom link relations
      • use an application specific RDF vocab

REST has a stateless constraint, which declares that the communication between the REST service and client must be stateless. This means that the REST service cannot maintain the client states, so you cannot have a server side session storage. You have to authenticate every single request. So for example HTTP basic auth (part of the HTTP standard) is okay, because it sends the username and password with every request.

To answer you questions

  1. Yes, it can be.

    Just to mention, the clients do not care about the IRI structure, they care about the semantics, because they follow links having link relations or linked data (RDF) attributes.

    The only thing important about the IRIs, that a single IRI must identify only a single resource. It is allowed to a single resource, like an user, to have many different IRIs.

    It is pretty simple why we use nice IRIs like /users/123/password; it is much easier to write the routing logic on the server when you understand the IRI simply by reading it.

  2. You have more verbs, like PUT, PATCH, OPTIONS, and even more, but you don't need more of them... Instead of adding new verbs you have to learn how to add new resources.

    activate_login -> PUT /login/active true deactivate_login -> PUT /login/active false change_password -> PUT /user/xy/password "newpass" add_credit -> POST /credit/raise {details: {}}

    (The login does not make sense from REST perspective, because of the stateless constraint.)

  3. Your users do not care about why the problem exist. They want to know only if there is success or error, and probably an error message which they can understand, for example: "Sorry, but we weren't able to save your post.", etc...

    The HTTP status headers are your standard headers. Everything else should be in the body I think. A single header is not enough to describe for example detailed multilingual error messages.

  4. The stateless constraint (along with the cache and layered system constraints) ensures that the service scales well. You surely don't wan't to maintain millions of sessions on the server, when you can do the same on the clients...

    The 3rd party client gets an access token if the user grants access to it using the main client. After that the 3rd party client sends the access token with every request. There are more complicated solutions, for example you can sign every single request, etc. For further details check the OAuth manual.

Related literature

MySQL: What's the difference between float and double?

Perhaps this example could explain.

CREATE TABLE `test`(`fla` FLOAT,`flb` FLOAT,`dba` DOUBLE(10,2),`dbb` DOUBLE(10,2)); 

We have a table like this:

+-------+-------------+
| Field | Type        |
+-------+-------------+
| fla   | float       |
| flb   | float       |
| dba   | double(10,2)|
| dbb   | double(10,2)|
+-------+-------------+

For first difference, we try to insert a record with '1.2' to each field:

INSERT INTO `test` values (1.2,1.2,1.2,1.2);

The table showing like this:

SELECT * FROM `test`;

+------+------+------+------+
| fla  | flb  | dba  | dbb  |
+------+------+------+------+
|  1.2 |  1.2 | 1.20 | 1.20 |
+------+------+------+------+

See the difference?

We try to next example:

SELECT fla+flb, dba+dbb FROM `test`;

Hola! We can find the difference like this:

+--------------------+---------+
| fla+flb            | dba+dbb |
+--------------------+---------+
| 2.4000000953674316 |    2.40 |
+--------------------+---------+

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

System like Ubuntu prefers to use auth_socket plugin. It will try to authenticate by comparing your username in DB and process which makes mysql request; it is described in here

The socket plugin checks whether the socket user name (the operating system user name) matches the MySQL user name specified by the client program to the server, and permits the connection only if the names match.

Instead you may want to back with the mysql_native_password, which will require user/password to authenticate.

About the method to achieve that, I recommend this instead.

JavaScript: How do I print a message to the error console?

Here is a solution to the literal question of how to print a message to the browser's error console, not the debugger console. (There might be good reasons to bypass the debugger.)

As I noted in comments about the suggestion to throw an error to get a message in the error console, one problem is that this will interrupt the thread of execution. If you don't want to interrupt the thread, you can throw the error in a separate thread, one created using setTimeout. Hence my solution (which turns out to be an elaboration of the one by Ivo Danihelka):

var startTime = (new Date()).getTime();
function logError(msg)
{
  var milliseconds = (new Date()).getTime() - startTime;
  window.setTimeout(function () {
    throw( new Error(milliseconds + ': ' + msg, "") );
  });
}
logError('testing');

I include the time in milliseconds since the start time because the timeout could skew the order in which you might expect to see the messages.

The second argument to the Error method is for the filename, which is an empty string here to prevent output of the useless filename and line number. It is possible to get the caller function but not in a simple browser independent way.

It would be nice if we could display the message with a warning or message icon instead of the error icon, but I can't find a way to do that.

Another problem with using throw is that it could be caught and thrown away by an enclosing try-catch, and putting the throw in a separate thread avoids that obstacle as well. However, there is yet another way the error could be caught, which is if the window.onerror handler is replaced with one that does something different. Can't help you there.

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

Is your type really arbitrary? If you know it is just going to be a int float or string you could just do

 if val.dtype == float and np.isnan(val):

assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN

Checking cin input stream produces an integer

There is a function in c called isdigit(). That will suit you just fine. Example:

int var1 = 'h';
int var2 = '2';

if( isdigit(var1) )
{
   printf("var1 = |%c| is a digit\n", var1 );
}
else
{
   printf("var1 = |%c| is not a digit\n", var1 );
}
if( isdigit(var2) )
{
  printf("var2 = |%c| is a digit\n", var2 );
}
else
{
   printf("var2 = |%c| is not a digit\n", var2 );
}

From here

Return index of highest value in an array

$newarr=arsort($arr);
$max_key=array_shift(array_keys($new_arr));

How to Scroll Down - JQuery

If you want to scroll down to the div (id="div1"). Then you can use this code.

 $('html, body').animate({
     scrollTop: $("#div1").offset().top
 }, 1500);

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

The stupid simple answer

Connect and Express are web servers for nodejs. Unlike Apache and IIS, they can both use the same modules, referred to as "middleware".

Convert string to hex-string in C#

For Unicode support:

public class HexadecimalEncoding
{
    public static string ToHexString(string str)
    {
        var sb = new StringBuilder();

        var bytes = Encoding.Unicode.GetBytes(str);
        foreach (var t in bytes)
        {
            sb.Append(t.ToString("X2"));
        }

        return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
    }

    public static string FromHexString(string hexString)
    {
        var bytes = new byte[hexString.Length / 2];
        for (var i = 0; i < bytes.Length; i++)
        {
            bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        }

        return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
    }
}

How should I unit test multithreaded code?

I spent most of last week at a university library studying debugging of concurrent code. The central problem is concurrent code is non-deterministic. Typically, academic debugging has fallen into one of three camps here:

  1. Event-trace/replay. This requires an event monitor and then reviewing the events that were sent. In a UT framework, this would involve manually sending the events as part of a test, and then doing post-mortem reviews.
  2. Scriptable. This is where you interact with the running code with a set of triggers. "On x > foo, baz()". This could be interpreted into a UT framework where you have a run-time system triggering a given test on a certain condition.
  3. Interactive. This obviously won't work in an automatic testing situation. ;)

Now, as above commentators have noticed, you can design your concurrent system into a more deterministic state. However, if you don't do that properly, you're just back to designing a sequential system again.

My suggestion would be to focus on having a very strict design protocol about what gets threaded and what doesn't get threaded. If you constrain your interface so that there is minimal dependancies between elements, it is much easier.

Good luck, and keep working on the problem.

How to use radio on change event?

<input type="radio" name="radio"  value="upi">upi
<input type="radio" name="radio"  value="bankAcc">Bank

<script type="text/javascript">
$(document).ready(function() {
 $('input[type=radio][name=radio]').change(function() {
   if (this.value == 'upi') {
    //write your logic here

    }
  else if (this.value == 'bankAcc') {
    //write your logic here
 }
 });
 </script>

How do I install g++ on MacOS X?

Installing XCode requires:

  • Enrolling on the Apple website (not fun)
  • Downloading a 4.7G installer

To install g++ *WITHOUT* having to download the MASSIVE 4.7G xCode install, try this package:

https://github.com/kennethreitz/osx-gcc-installer

The DMG files linked on that page are ~270M and much quicker to install. This was perfect for me, getting homebrew up and running with a minimum of hassle.

The github project itself is basically a script that repackages just the critical chunks of xCode for distribution. In order to run that script and build the DMG files, you'd need to already have an XCode install, which would kind of defeat the point, so the pre-built DMG files are hosted on the project page.

What is the max size of VARCHAR2 in PL/SQL and SQL?

As per official documentation link shared by Andre Kirpitch, Oracle 10g gives a maximum size of 4000 bytes or characters for varchar2. If you are using a higher version of oracle (for example Oracle 12c), you can get a maximum size upto 32767 bytes or characters for varchar2. To utilize the extended datatype feature of oracle 12, you need to start oracle in upgrade mode. Follow the below steps in command prompt:

1) Login as sysdba (sqlplus / as sysdba)

2) SHUTDOWN IMMEDIATE;

3) STARTUP UPGRADE;

4) ALTER SYSTEM SET max_string_size=extended;

5) Oracle\product\12.1.0.2\rdbms\admin\utl32k.sql

6) SHUTDOWN IMMEDIATE;

7) STARTUP;

Regular expression to match a line that doesn't contain a word

If you're just using it for grep, you can use grep -v hede to get all lines which do not contain hede.

ETA Oh, rereading the question, grep -v is probably what you meant by "tools options".

fs.writeFile in a promise, asynchronous-synchronous stuff

If you want to import the promise based version of fs as an ES module you can do:

import { promises as fs } from 'fs'

await fs.writeFile(...)

As soon as node v14 is released (see this PR), you can also use

import { writeFile } from 'fs/promises'

How to compile Go program consisting of multiple files?

You can use

go build *.go 
go run *.go

both will work also you may use

go build .
go run .

Using DISTINCT inner join in SQL

SELECT DISTINCT C.valueC 
FROM C 
  LEFT JOIN B ON C.id = B.lookupC
  LEFT JOIN A ON B.id = A.lookupB
WHERE C.id IS NOT NULL

I don't see a good reason why you want to limit the result sets of A and B because what you want to have is a list of all C's that are referenced by A. I did a distinct on C.valueC because i guessed you wanted a unique list of C's.


EDIT: I agree with your argument. Even if your solution looks a bit nested it seems to be the best and fastest way to use your knowledge of the data and reduce the result sets.

There is no distinct join construct you could use so just stay with what you already have :)

"React.Children.only expected to receive a single React element child" error when putting <Image> and <TouchableHighlight> in a <View>

I had this same error, even when I only had one child under the TouchableHighlight. The issue was that I had a few others commented out but incorrectly. Make sure you are commenting out appropriately: http://wesbos.com/react-jsx-comments/

SimpleDateFormat parsing date with 'Z' literal

tl;dr

Instant.parse ( "2010-04-05T17:16:00Z" )

ISO 8601 Standard

Your String complies with the ISO 8601 standard (of which the mentioned RFC 3339 is a profile).

Avoid java.util.Date

The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them.

Instead use either the Joda-Time library or the new java.time package in Java 8. Both use ISO 8601 as their defaults for parsing and generating string representations of date-time values.

java.time

The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.

The Instant class in java.time represents a moment on the timeline in UTC time zone.

The Z at the end of your input string means Zulu which stands for UTC. Such a string can be directly parsed by the Instant class, with no need to specify a formatter.

String input = "2010-04-05T17:16:00Z";
Instant instant = Instant.parse ( input );

Dump to console.

System.out.println ( "instant: " + instant );

instant: 2010-04-05T17:16:00Z

From there you can apply a time zone (ZoneId) to adjust this Instant into a ZonedDateTime. Search Stack Overflow for discussion and examples.

If you must use a java.util.Date object, you can convert by calling the new conversion methods added to the old classes such as the static method java.util.Date.from( Instant ).

java.util.Date date = java.util.Date.from( instant );

Joda-Time

Example in Joda-Time 2.5.

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" ):
DateTime dateTime = new DateTime( "2010-04-05T17:16:00Z", timeZone );

Convert to UTC.

DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );

Convert to a java.util.Date if necessary.

java.util.Date date = dateTime.toDate();

Convert List<String> to List<Integer> directly

No, you will have to iterate over each element:

for(String number : numbers) {
   numberList.add(Integer.parseInt(number)); 
}

The reason this happens is that there is no straightforward way to convert a list of one type into any other type. Some conversions are not possible, or need to be done in a specific way. Essentially the conversion depends on the objects involved and the context of the conversion so there is no "one size fits all" solution. For example, what if you had a Car object and a Person object. You can't convert a List<Car> into a List<Person> directly since it doesn't really make sense.

How do I get the SharedPreferences from a PreferenceActivity in Android?

Declare these methods first..

public static void putPref(String key, String value, Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(key, value);
    editor.commit();
}

public static String getPref(String key, Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(key, null);
}

Then call this when you want to put a pref:

putPref("myKey", "mystring", getApplicationContext());

call this when you want to get a pref:

getPref("myKey", getApplicationContext());

Or you can use this object https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo which simplifies everything even further

Example:

TinyDB tinydb = new TinyDB(context);

tinydb.putInt("clickCount", 2);
tinydb.putFloat("xPoint", 3.6f);
tinydb.putLong("userCount", 39832L);

tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true); 

tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);

How to directly move camera to current location in Google Maps Android API v2?

Just change moveCamera to animateCamera like below

Googlemap.animateCamera(CameraUpdateFactory.newLatLngZoom(locate, 16F))

Simple file write function in C++

Your main doesn't know about writeFile() and can't call it.

Move writefile to be before main, or declare a function prototype int writeFile(); before main.

Add image to layout in ruby on rails

When using the new ruby, the image folder will go to asset folder on folder app

after placing your images in image folder, use

<%=image_tag("example_image.png", alt: "Example Image")%>

Centos/Linux setting logrotate to maximum file size for all logs

As mentioned by Zeeshan, the logrotate options size, minsize, maxsize are triggers for rotation.

To better explain it. You can run logrotate as often as you like, but unless a threshold is reached such as the filesize being reached or the appropriate time passed, the logs will not be rotated.

The size options do not ensure that your rotated logs are also of the specified size. To get them to be close to the specified size you need to call the logrotate program sufficiently often. This is critical.

For log files that build up very quickly (e.g. in the hundreds of MB a day), unless you want them to be very large you will need to ensure logrotate is called often! this is critical.

Therefore to stop your disk filling up with multi-gigabyte log files you need to ensure logrotate is called often enough, otherwise the log rotation will not work as well as you want.

on Ubuntu, you can easily switch to hourly rotation by moving the script /etc/cron.daily/logrotate to /etc/cron.hourly/logrotate

Or add

*/5 * * * * /etc/cron.daily/logrotate 

To your /etc/crontab file. To run it every 5 minutes.

The size option ignores the daily, weekly, monthly time options. But minsize & maxsize take it into account.

The man page is a little confusing there. Here's my explanation.

minsize rotates only when the file has reached an appropriate size and the set time period has passed. e.g. minsize 50MB + daily If file reaches 50MB before daily time ticked over, it'll keep growing until the next day.

maxsize will rotate when the log reaches a set size or the appropriate time has passed. e.g. maxsize 50MB + daily. If file is 50MB and we're not at the next day yet, the log will be rotated. If the file is only 20MB and we roll over to the next day then the file will be rotated.

size will rotate when the log > size. Regardless of whether hourly/daily/weekly/monthly is specified. So if you have size 100M - it means when your log file is > 100M the log will be rotated if logrotate is run when this condition is true. Once it's rotated, the main log will be 0, and a subsequent run will do nothing.

So in the op's case. Specficially 50MB max I'd use something like the following:

/var/log/logpath/*.log {
    maxsize 50M
    hourly
    missingok
    rotate 8
    compress
    notifempty
    nocreate
}

Which means he'd create 8hrs of logs max. And there would be 8 of them at no more than 50MB each. Since he's saying that he's getting multi gigabytes each day and assuming they build up at a fairly constant rate, and maxsize is used he'll end up with around close to the max reached for each file. So they will be likely close to 50MB each. Given the volume they build, he would need to ensure that logrotate is run often enough to meet the target size.

Since I've put hourly there, we'd need logrotate to be run a minimum of every hour. But since they build up to say 2 gigabytes per day and we want 50MB... assuming a constant rate that's 83MB per hour. So you can imagine if we run logrotate every hour, despite setting maxsize to 50 we'll end up with 83MB log's in that case. So in this instance set the running to every 30 minutes or less should be sufficient.

Ensure logrotate is run every 30 mins.

*/30 * * * * /etc/cron.daily/logrotate 

Regular expression for extracting tag attributes

Although the advice not to parse HTML via regexp is valid, here's a expression that does pretty much what you asked:

/
   \G                     # start where the last match left off
   (?>                    # begin non-backtracking expression
       .*?                # *anything* until...
       <[Aa]\b            # an anchor tag
    )??                   # but look ahead to see that the rest of the expression
                          #    does not match.
    \s+                   # at least one space
    ( \p{Alpha}           # Our first capture, starting with one alpha
      \p{Alnum}*          # followed by any number of alphanumeric characters
    )                     # end capture #1
    (?: \s* = \s*         # a group starting with a '=', possibly surrounded by spaces.
        (?: (['"])        # capture a single quote character
            (.*?)         # anything else
             \2           # which ever quote character we captured before
        |   ( [^>\s'"]+ ) # any number of non-( '>', space, quote ) chars
        )                 # end group
     )?                   # attribute value was optional
/msx;

"But wait," you might say. "What about *comments?!?!" Okay, then you can replace the . in the non-backtracking section with: (It also handles CDATA sections.)

(?:[^<]|<[^!]|<![^-\[]|<!\[(?!CDATA)|<!\[CDATA\[.*?\]\]>|<!--(?:[^-]|-[^-])*-->)
  • Also if you wanted to run a substitution under Perl 5.10 (and I think PCRE), you can put \K right before the attribute name and not have to worry about capturing all the stuff you want to skip over.

When do you use POST and when do you use GET?

Apart from the length constraints difference in many web browsers, there is also a semantic difference. GETs are supposed to be "safe" in that they are read-only operations that don't change the server state. POSTs will typically change state and will give warnings on resubmission. Search engines' web crawlers may make GETs but should never make POSTs.

Use GET if you want to read data without changing state, and use POST if you want to update state on the server.

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

In your Info.plist, Right click in the properties table, click Add Row, add key name App Uses Non-Exempt Encryption with Type Boolean and set value NO.

enter image description here

How to concatenate two layers in keras?

You're getting the error because result defined as Sequential() is just a container for the model and you have not defined an input for it.

Given what you're trying to build set result to take the third input x3.

first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))

second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))

third = Sequential()
# of course you must provide the input to result which will be your x3
third.add(Dense(1, input_shape=(1,), activation='sigmoid'))

# lets say you add a few more layers to first and second.
# concatenate them
merged = Concatenate([first, second])

# then concatenate the two outputs

result = Concatenate([merged,  third])

ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)

result.compile(optimizer=ada_grad, loss='binary_crossentropy',
               metrics=['accuracy'])

However, my preferred way of building a model that has this type of input structure would be to use the functional api.

Here is an implementation of your requirements to get you started:

from keras.models import Model
from keras.layers import Concatenate, Dense, LSTM, Input, concatenate
from keras.optimizers import Adagrad

first_input = Input(shape=(2, ))
first_dense = Dense(1, )(first_input)

second_input = Input(shape=(2, ))
second_dense = Dense(1, )(second_input)

merge_one = concatenate([first_dense, second_dense])

third_input = Input(shape=(1, ))
merge_two = concatenate([merge_one, third_input])

model = Model(inputs=[first_input, second_input, third_input], outputs=merge_two)
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
model.compile(optimizer=ada_grad, loss='binary_crossentropy',
               metrics=['accuracy'])

To answer the question in the comments:

  1. How are result and merged connected? Assuming you mean how are they concatenated.

Concatenation works like this:

  a        b         c
a b c   g h i    a b c g h i
d e f   j k l    d e f j k l

i.e rows are just joined.

  1. Now, x1 is input to first, x2 is input into second and x3 input into third.

what does the __file__ variable mean/do?

When a module is loaded from a file in Python, __file__ is set to its path. You can then use that with other functions to find the directory that the file is located in.

Taking your examples one at a time:

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

You can see the various values returned from these here:

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

and make sure you run it from different locations (such as ./text.py, ~/python/text.py and so forth) to see what difference that makes.


I just want to address some confusion first. __file__ is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.

http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.

In this case __file__ is an attribute of a module (a module object). In Python a .py file is a module. So import amodule will have an attribute of __file__ which means different things under difference circumstances.

Taken from the docs:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

In your case the module is accessing it's own __file__ attribute in the global namespace.

To see this in action try:

# file: test.py

print globals()
print __file__

And run:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

Filter df when values matches part of a string in pyspark

When filtering a DataFrame with string values, I find that the pyspark.sql.functions lower and upper come in handy, if your data could have column entries like "foo" and "Foo":

import pyspark.sql.functions as sql_fun
result = source_df.filter(sql_fun.lower(source_df.col_name).contains("foo"))

redirect COPY of stdout to log file from within bash script itself

Can't say I'm comfortable with any of the solutions based on exec. I prefer to use tee directly, so I make the script call itself with tee when requested:

# my script: 

check_tee_output()
{
    # copy (append) stdout and stderr to log file if TEE is unset or true
    if [[ -z $TEE || "$TEE" == true ]]; then 
        echo '-------------------------------------------' >> log.txt
        echo '***' $(date) $0 $@ >> log.txt
        TEE=false $0 $@ 2>&1 | tee --append log.txt
        exit $?
    fi 
}

check_tee_output $@

rest of my script

This allows you to do this:

your_script.sh args           # tee 
TEE=true your_script.sh args  # tee 
TEE=false your_script.sh args # don't tee
export TEE=false
your_script.sh args           # tee

You can customize this, e.g. make tee=false the default instead, make TEE hold the log file instead, etc. I guess this solution is similar to jbarlow's, but simpler, maybe mine has limitations that I have not come across yet.

Java 8, Streams to find the duplicate elements

the creating of an additional map or stream is time- and space-consuming…

Set<Integer> duplicates = numbers.stream().collect( Collectors.collectingAndThen(
  Collectors.groupingBy( Function.identity(), Collectors.counting() ),
  map -> {
    map.values().removeIf( cnt -> cnt < 2 );
    return( map.keySet() );
  } ) );  // [1, 4]


…and for the question of which is claimed to be a [duplicate]

public static int[] getDuplicatesStreamsToArray( int[] input ) {
  return( IntStream.of( input ).boxed().collect( Collectors.collectingAndThen(
      Collectors.groupingBy( Function.identity(), Collectors.counting() ),
      map -> {
        map.values().removeIf( cnt -> cnt < 2 );
        return( map.keySet() );
      } ) ).stream().mapToInt( i -> i ).toArray() );
}

Can jQuery provide the tag name?

Consider the fast FILTER method:

$('.rnd').filter('h2,h4')

returns:

[<h2 id=?"foo" class=?"rnd">?Second?</h2>?, <h4 id=?"bar" class=?"rnd">?Fourth?</h4>?]

so:

$('.rnd').filter('h2,h4').each(function() { /*...$(this)...*/ });

Align div with fixed position on the right side

You can use two imbricated div. But you need a fixed width for your content, that's the only limitation.

<div style='float:right; width: 180px;'>
 <div style='position: fixed'>
   <!-- Your content -->
 </div>
</div>

Add swipe to delete UITableViewCell

here See my result Swift with fully customizable button supported

Advance bonus for use this only one method implementation and you get a perfect button!!!

 func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let action = UIContextualAction(
            style: .destructive,
            title: "",
            handler: { (action, view, completion) in

                let alert = UIAlertController(title: "", message: "Are you sure you want to delete this incident?", preferredStyle: .actionSheet)

                alert.addAction(UIAlertAction(title: "Delete", style: .destructive , handler:{ (UIAlertAction)in
                    let model = self.incedentArry[indexPath.row] as! HFIncedentModel
                    print(model.incent_report_id)
                    self.incedentArry.remove(model)
                    tableView.deleteRows(at: [indexPath], with: .fade)
                    delete_incedentreport_data(param: ["incent_report_id": model.incent_report_id])
                    completion(true)
                }))

                alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:{ (UIAlertAction)in
                    tableView.reloadData()
                }))

                self.present(alert, animated: true, completion: {

                })


        })
        action.image = HFAsset.ic_trash.image
        action.backgroundColor = UIColor.red
        let configuration = UISwipeActionsConfiguration(actions: [action])
        configuration.performsFirstActionWithFullSwipe = true
        return configuration
}

displayname attribute vs display attribute

I think the current answers are neglecting to highlight the actual important and significant differences and what that means for the intended usage. While they might both work in certain situations because the implementer built in support for both, they have different usage scenarios. Both can annotate properties and methods but here are some important differences:

DisplayAttribute

  • defined in the System.ComponentModel.DataAnnotations namespace in the System.ComponentModel.DataAnnotations.dll assembly
  • can be used on parameters and fields
  • lets you set additional properties like Description or ShortName
  • can be localized with resources

DisplayNameAttribute

  • DisplayName is in the System.ComponentModel namespace in System.dll
  • can be used on classes and events
  • cannot be localized with resources

The assembly and namespace speaks to the intended usage and localization support is the big kicker. DisplayNameAttribute has been around since .NET 2 and seems to have been intended more for naming of developer components and properties in the legacy property grid, not so much for things visible to end users that may need localization and such.

DisplayAttribute was introduced later in .NET 4 and seems to be designed specifically for labeling members of data classes that will be end-user visible, so it is more suitable for DTOs, entities, and other things of that sort. I find it rather unfortunate that they limited it so it can't be used on classes though.

EDIT: Looks like latest .NET Core source allows DisplayAttribute to be used on classes now as well.

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

Here's the clincher on importing utf8-encoded CSV into Excel 2011 for Mac: Microsoft says: "Excel for Mac does not currently support UTF-8." Excel for Mac 2011 and UTF-8

Yay, way to go MS!

Nested ifelse statement

If you are using any spreadsheet application there is a basic function if() with syntax:

if(<condition>, <yes>, <no>)

Syntax is exactly the same for ifelse() in R:

ifelse(<condition>, <yes>, <no>)

The only difference to if() in spreadsheet application is that R ifelse() is vectorized (takes vectors as input and return vector on output). Consider the following comparison of formulas in spreadsheet application and in R for an example where we would like to compare if a > b and return 1 if yes and 0 if not.

In spreadsheet:

  A  B C
1 3  1 =if(A1 > B1, 1, 0)
2 2  2 =if(A2 > B2, 1, 0)
3 1  3 =if(A3 > B3, 1, 0)

In R:

> a <- 3:1; b <- 1:3
> ifelse(a > b, 1, 0)
[1] 1 0 0

ifelse() can be nested in many ways:

ifelse(<condition>, <yes>, ifelse(<condition>, <yes>, <no>))

ifelse(<condition>, ifelse(<condition>, <yes>, <no>), <no>)

ifelse(<condition>, 
       ifelse(<condition>, <yes>, <no>), 
       ifelse(<condition>, <yes>, <no>)
      )

ifelse(<condition>, <yes>, 
       ifelse(<condition>, <yes>, 
              ifelse(<condition>, <yes>, <no>)
             )
       )

To calculate column idnat2 you can:

df <- read.table(header=TRUE, text="
idnat idbp idnat2
french mainland mainland
french colony overseas
french overseas overseas
foreign foreign foreign"
)

with(df, 
     ifelse(idnat=="french",
       ifelse(idbp %in% c("overseas","colony"),"overseas","mainland"),"foreign")
     )

R Documentation

What is the condition has length > 1 and only the first element will be used? Let's see:

> # What is first condition really testing?
> with(df, idnat=="french")
[1]  TRUE  TRUE  TRUE FALSE
> # This is result of vectorized function - equality of all elements in idnat and 
> # string "french" is tested.
> # Vector of logical values is returned (has the same length as idnat)
> df$idnat2 <- with(df,
+   if(idnat=="french"){
+   idnat2 <- "xxx"
+   }
+   )
Warning message:
In if (idnat == "french") { :
  the condition has length > 1 and only the first element will be used
> # Note that the first element of comparison is TRUE and that's whay we get:
> df
    idnat     idbp idnat2
1  french mainland    xxx
2  french   colony    xxx
3  french overseas    xxx
4 foreign  foreign    xxx
> # There is really logic in it, you have to get used to it

Can I still use if()? Yes, you can, but the syntax is not so cool :)

test <- function(x) {
  if(x=="french") {
    "french"
  } else{
    "not really french"
  }
}

apply(array(df[["idnat"]]),MARGIN=1, FUN=test)

If you are familiar with SQL, you can also use CASE statement in sqldf package.

Bash Templating: How to build configuration files from templates with Bash?

I'd have done it this way, probably less efficient, but easier to read/maintain.

TEMPLATE='/path/to/template.file'
OUTPUT='/path/to/output.file'

while read LINE; do
  echo $LINE |
  sed 's/VARONE/NEWVALA/g' |
  sed 's/VARTWO/NEWVALB/g' |
  sed 's/VARTHR/NEWVALC/g' >> $OUTPUT
done < $TEMPLATE

Increasing the maximum post size

I had been facing similar problem in downloading big files this works fine for me now:

safe_mode = off
max_input_time = 9000
memory_limit = 1073741824
post_max_size = 1073741824
file_uploads = On
upload_max_filesize = 1073741824
max_file_uploads = 100
allow_url_fopen = On

Hope this helps.

What is the behavior of integer division?

Dirkgently gives an excellent description of integer division in C99, but you should also know that in C89 integer division with a negative operand has an implementation-defined direction.

From the ANSI C draft (3.3.5):

If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

So watch out with negative numbers when you are stuck with a C89 compiler.

It's a fun fact that C99 chose truncation towards zero because that was how FORTRAN did it. See this message on comp.std.c.

How do you add a timer to a C# console application

doc

There you have it :)

public static void Main()
   {
      SetTimer();

      Console.WriteLine("\nPress the Enter key to exit the application...\n");
      Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now);
      Console.ReadLine();
      aTimer.Stop();
      aTimer.Dispose();

      Console.WriteLine("Terminating the application...");
   }

   private static void SetTimer()
   {
        // Create a timer with a two second interval.
        aTimer = new System.Timers.Timer(2000);
        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;
        aTimer.AutoReset = true;
        aTimer.Enabled = true;
    }

    private static void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                          e.SignalTime);
    }

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

The way i fix this problem is transforming the id into a string

i like it fancy with backtick: `${id}`

this should fix the problem with no overhead

How do I use floating-point division in bash?

As an alternative to bc, you can use awk within your script.

For example:

echo "$IMG_WIDTH $IMG2_WIDTH" | awk '{printf "%.2f \n", $1/$2}'

In the above, " %.2f " tells the printf function to return a floating point number with two digits after the decimal place. I used echo to pipe in the variables as fields since awk operates properly on them. " $1 " and " $2 " refer to the first and second fields input into awk.

And you can store the result as some other variable using:

RESULT = `echo ...`

How to make/get a multi size .ico file?

ImageMagick, the free and open source image manipulation toolkit, can easily do this:

Note: Since ImageMagick 7, the CLI has changed slightly, you need to add magick in front of any commands.

magick convert icon-16.png icon-32.png icon-64.png icon-128.png icon.ico

See also http://www.imagemagick.org/Usage/thumbnails/#favicon, that has the example:

magick convert image.png -bordercolor white -border 0 \
          \( -clone 0 -resize 16x16 \) \
          \( -clone 0 -resize 32x32 \) \
          \( -clone 0 -resize 48x48 \) \
          \( -clone 0 -resize 64x64 \) \
          -delete 0 -alpha off -colors 256 favicon.ico

There is also now the shorter:

magick convert image.png -define icon:auto-resize="256,128,96,64,48,32,16" favicon.ico

Floating Point Exception C++ Why and what is it?

Problem is in the for loop in the code snippet:
for (i > 0; i--;)

Here, your intention seems to be entering the loop if (i > 0) and decrement the value of i by one after the completion of for loop.

Does it work like that? lets see.

Look at the for() loop syntax:

**for ( initialization; condition check; increment/decrement ) {  
    statements;  
}**

Initialization gets executed only once in the beginning of the loop. Pay close attention to ";" in your code snippet and map it with for loop syntax.

Initialization : i > 0 : Gets executed only once. Doesn't have any impact in your code.

Condition check : i -- : post decrement.

              Here, i is used for condition check and then it is decremented. 
              Decremented value will be used in statements within for loop. 
              This condition check is working as increment/decrement too in your code. 

Lets stop here and see floating point exception.

what is it? One easy example is Divide by 0. Same is happening with your code.

When i reaches 1 in condition check, condition check validates to be true.
Because of post decrement i will be 0 when it enters for loop.

Modulo operation at line #9 results in divide by zero operation.  

With this background you should be able to fix the problem in for loop.

Algorithm to detect overlapping periods

This code checks if two intervals overlap.

---------|---|
---|---|                > FALSE
xxxxxxxxxxxxxxxxxxxxxxxxx
-------|---|
---|---|                > FALSE
xxxxxxxxxxxxxxxxxxxxxxxxx
------|---|
---|---|                > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
---|--|                 > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
----|---|
---|-----|              > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
----|-|                 > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
----|--|                > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
---|---|                > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
----|---|               > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
-------|---|            > FALSE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
--------|---|           > FALSE

Algorithm:

x1 < y2
and
x2 > y1

example 12:00 - 12:30 is not overlapping with 12:30 13:00

VBA Public Array : how to?

Option Explicit
     Public myarray (1 To 10)
     Public Count As Integer
     myarray(1) = "A"
     myarray(2) = "B"
     myarray(3) = "C"
     myarray(4) = "D"
     myarray(5) = "E"
     myarray(6) = "F"
     myarray(7) = "G"
     myarray(8) = "H"
     myarray(9) = "I"
     myarray(10) = "J"
Private Function unwrapArray()
     For Count = 1 to UBound(myarray)
       MsgBox "Letters of the Alphabet : " & myarray(Count)
     Next 
End Function

Concatenating date with a string in Excel

This is the numerical representation of the date. The thing you get when referring to dates from formulas like that.

You'll have to do:

= A1 & TEXT(A2, "mm/dd/yyyy")

The biggest problem here is that the format specifier is locale-dependent. It will not work/produce not what expected if the file is opened with a differently localized Excel.

Now, you could have a user-defined function:

public function AsDisplayed(byval c as range) as string
  AsDisplayed = c.Text
end function

and then

= A1 & AsDisplayed(A2)

But then there's a bug (feature?) in Excel because of which the .Text property is suddenly not available during certain stages of the computation cycle, and your formulas display #VALUE instead of what they should.

That is, it's bad either way.

Creating a new DOM element from an HTML string using built-in DOM methods or Prototype

Use insertAdjacentHTML(). It works with all current browsers, even with IE11.

_x000D_
_x000D_
var mylist = document.getElementById('mylist');_x000D_
mylist.insertAdjacentHTML('beforeend', '<li>third</li>');
_x000D_
<ul id="mylist">_x000D_
 <li>first</li>_x000D_
 <li>second</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Why do we need virtual functions in C++?

Need for Virtual Function explained [Easy to understand]

#include<iostream>

using namespace std;

class A{
public: 
        void show(){
        cout << " Hello from Class A";
    }
};

class B :public A{
public:
     void show(){
        cout << " Hello from Class B";
    }
};


int main(){

    A *a1 = new B; // Create a base class pointer and assign address of derived object.
    a1->show();

}

Output will be:

Hello from Class A.

But with virtual function:

#include<iostream>

using namespace std;

class A{
public:
    virtual void show(){
        cout << " Hello from Class A";
    }
};

class B :public A{
public:
    virtual void show(){
        cout << " Hello from Class B";
    }
};


int main(){

    A *a1 = new B;
    a1->show();

}

Output will be:

Hello from Class B.

Hence with virtual function you can achieve runtime polymorphism.

jQuery if Element has an ID?

I seemed to have been able to solve it with:

if( $('your-selector-here').attr('id') === undefined){
    console.log( 'has no ID' )
}

How to fast get Hardware-ID in C#?

We use a combination of the processor id number (ProcessorID) from Win32_processor and the universally unique identifier (UUID) from Win32_ComputerSystemProduct:

ManagementObjectCollection mbsList = null;
ManagementObjectSearcher mos = new ManagementObjectSearcher("Select ProcessorID From Win32_processor");
mbsList = mos.Get();
string processorId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
    processorId = mo["ProcessorID"] as string;
}

mos = new ManagementObjectSearcher("SELECT UUID FROM Win32_ComputerSystemProduct");
mbsList = mos.Get();
string systemId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
    systemId = mo["UUID"] as string;
}

var compIdStr = $"{processorId}{systemId}";

Previously, we used a combination: processor ID ("Select ProcessorID From Win32_processor") and the motherboard serial number ("SELECT SerialNumber FROM Win32_BaseBoard"), but then we found out that the serial number of the motherboard may not be filled in, or it may be filled in with uniform values:

  • To be filled by O.E.M.
  • None
  • Default string

Therefore, it is worth considering this situation.

Also keep in mind that the ProcessorID number may be the same on different computers.

Best way to unselect a <select> in jQuery?

Thanks a lot for the solution.

The solution for single choice combo list works perfectly. I found this after searching on many sites.

$("#selectID").attr('selectedIndex', '-1').children("option:selected").removeAttr("selected");

What is the purpose of Node.js module.exports and how do you use it?

What is the purpose of a module system?

It accomplishes the following things:

  1. Keeps our files from bloating to really big sizes. Having files with e.g. 5000 lines of code in it are usually real hard to deal with during development.
  2. Enforces separation of concerns. Having our code split up into multiple files allows us to have appropriate file names for every file. This way we can easily identify what every module does and where to find it (assuming we made a logical directory structure which is still your responsibility).

Having modules makes it easier to find certain parts of code which makes our code more maintainable.

How does it work?

NodejS uses the CommomJS module system which works in the following manner:

  1. If a file wants to export something it has to declare it using module.export syntax
  2. If a file wants to import something it has to declare it using require('file') syntax

Example:

test1.js

const test2 = require('./test2');    // returns the module.exports object of a file

test2.Func1(); // logs func1
test2.Func2(); // logs func2

test2.js

module.exports.Func1 = () => {console.log('func1')};

exports.Func2 = () => {console.log('func2')};

Other useful things to know:

  1. Modules are getting cached. When you are loading the same module in 2 different files the module only has to be loaded once. The second time a require() is called on the same module the is pulled from the cache.
  2. Modules are loaded in synchronous. This behavior is required, if it was asynchronous we couldn't access the object retrieved from require() right away.

Random number generator only generating one random number

Mark's solution can be quite expensive since it needs to synchronize everytime.

We can get around the need for synchronization by using the thread-specific storage pattern:


public class RandomNumber : IRandomNumber
{
    private static readonly Random Global = new Random();
    [ThreadStatic] private static Random _local;

    public int Next(int max)
    {
        var localBuffer = _local;
        if (localBuffer == null) 
        {
            int seed;
            lock(Global) seed = Global.Next();
            localBuffer = new Random(seed);
            _local = localBuffer;
        }
        return localBuffer.Next(max);
    }
}

Measure the two implementations and you should see a significant difference.

Maven: mvn command not found

  1. Run 'path' in command prompt and ensure that the maven installation directory is listed.
  2. Ensure the maven is installed in 'C:\Program Files\Maven'.

How to save final model using keras?

The model has a save method, which saves all the details necessary to reconstitute the model. An example from the keras documentation:

from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

Connect to external server by using phpMyAdmin

in the config.inc.php, remove all lines with "$cfg['Servers']" , and keep ONLY the "$cfg['Servers'][$i]['host']"

How to list all the available keyspaces in Cassandra?

  1. login to cqlsh

  2. use below command to get names/list of keyspaces present

         SELECT keyspace_name FROM system_schema.keyspaces;
    

Codeigniter LIKE with wildcard(%)

$this->db->like()

This method enables you to generate LIKE clauses, useful for doing searches.

$this->db->like('title', 'match');

Produces: WHERE title LIKE '%match%'

If you want to control where the wildcard (%) is placed, you can use an optional third argument. Your options are ‘before’, ‘after’, ‘none’ and ‘both’ (which is the default).

$this->db->like('title', 'match', 'before');

Produces: WHERE title LIKE '%match'

$this->db->like('title', 'match', 'after');

Produces: WHERE title LIKE 'match%'

$this->db->like('title', 'match', 'none');

Produces: WHERE title LIKE 'match'

$this->db->like('title', 'match', 'both');

Produces: WHERE title LIKE '%match%'

How to merge two sorted arrays into a sorted array?

Any improvements that could be made would be micro-optimizations, the overall algorithm is correct.

adding css class to multiple elements

You need to qualify the a part of the selector too:

.button input, .button a {
    //css stuff here
}

Basically, when you use the comma to create a group of selectors, each individual selector is completely independent. There is no relationship between them.

Your original selector therefore matched "all elements of type 'input' that are descendants of an element with the class name 'button', and all elements of type 'a'".

How can I remove the extension of a filename in a shell script?

If your filename contains a dot (other than the one of the extension) then use this:

echo $filename | rev | cut -f 2- -d '.' | rev

Define make variable at rule execution time

Another possibility is to use separate lines to set up Make variables when a rule fires.

For example, here is a makefile with two rules. If a rule fires, it creates a temp dir and sets TMP to the temp dir name.

PHONY = ruleA ruleB display

all: ruleA

ruleA: TMP = $(shell mktemp -d testruleA_XXXX)
ruleA: display

ruleB: TMP = $(shell mktemp -d testruleB_XXXX)
ruleB: display

display:
    echo ${TMP}

Running the code produces the expected result:

$ ls
Makefile
$ make ruleB
echo testruleB_Y4Ow
testruleB_Y4Ow
$ ls
Makefile  testruleB_Y4Ow

how to check and set max_allowed_packet mysql variable

The following PHP worked for me (using mysqli extension but queries should be the same for other extensions):

$db = new mysqli( 'localhost', 'user', 'pass', 'dbname' );
// to get the max_allowed_packet
$maxp = $db->query( 'SELECT @@global.max_allowed_packet' )->fetch_array();
echo $maxp[ 0 ];
// to set the max_allowed_packet to 500MB
$db->query( 'SET @@global.max_allowed_packet = ' . 500 * 1024 * 1024 );

So if you've got a query you expect to be pretty long, you can make sure that mysql will accept it with something like:

$sql = "some really long sql query...";
$db->query( 'SET @@global.max_allowed_packet = ' . strlen( $sql ) + 1024 );
$db->query( $sql );

Notice that I added on an extra 1024 bytes to the length of the string because according to the manual,

The value should be a multiple of 1024; nonmultiples are rounded down to the nearest multiple.

That should hopefully set the max_allowed_packet size large enough to handle your query. I haven't tried this on a shared host, so the same caveat as @Glebushka applies.

Comparing strings in C# with OR in an if statement

The code provided is correct, I don't see any reason why it wouldn't work. You could also try if (string1.Equals(string2)) as suggested.

To do if (something OR something else), use ||:

if (condition_1 || condition_2) { ... }

How can I make a list of installed packages in a certain virtualenv?

In my case the flask version was only visible under so I had to go to C:\Users\\AppData\Local\flask\venv\Scripts>pip freeze --local

How do I declare and initialize an array in Java?

If by "array" you meant using java.util.Arrays, you can do it like that :

List<String> number = Arrays.asList("1", "2", "3");

Out: ["1", "2", "3"]

This one is pretty simple and straightforward.

Navigation Controller Push View Controller

Swift 4 & 5

let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "yourController") as! AlgoYoViewController
        navigationController?.pushViewController(vc,
                                                 animated: true)

How Can I Truncate A String In jQuery?

The solution above won't work if the original string has no spaces.

Try this:

var title = "This is your title";
var shortText = jQuery.trim(title).substring(0, 10)
                          .trim(this) + "...";

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can do it faster without any imports just by using magics:

%env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=0

Notice that all env variable are strings, so no need to use ". You can verify that env-variable is set up by running: %env <name_of_var>. Or check all of them with %env.

Connection pooling options with JDBC: DBCP vs C3P0

Another alternative, Proxool, is mentioned in this article.

You might be able to find out why Hibernate bundles c3p0 for its default connection pool implementation?

Why does ++[[]][+[]]+[+[]] return the string "10"?

  1. Unary plus given string converts to number
  2. Increment operator given string converts and increments by 1
  3. [] == ''. Empty String
  4. +'' or +[] evaluates 0.

    ++[[]][+[]]+[+[]] = 10 
    ++[''][0] + [0] : First part is gives zeroth element of the array which is empty string 
    1+0 
    10
    

In Tkinter is there any way to make a widget not visible?

For hiding a widget you can use function pack_forget() and to again show it you can use pack() function and implement them both in separate functions.

from Tkinter import *
root = Tk()
label=Label(root,text="I was Hidden")
def labelactive():
    label.pack()
def labeldeactive():
    label.pack_forget()
Button(root,text="Show",command=labelactive).pack()
Button(root,text="Hide",command=labeldeactive).pack()
root.mainloop()

Difference between onStart() and onResume()

onStart() called when the activity is becoming visible to the user. onResume() called when the activity will start interacting with the user. You may want to do different things in this cases.

See this link for reference.

Keep background image fixed during scroll using css

Just add background-attachment to your code

body {
    background-position: center;
    background-image: url(../images/images5.jpg);
    background-attachment: fixed;
}

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

How do I print debug messages in the Google Chrome JavaScript Console?

Personally I use this, which is similar to tarek11011's:

// Use a less-common namespace than just 'log'
function myLog(msg)
{
    // Attempt to send a message to the console
    try
    {
        console.log(msg);
    }
    // Fail gracefully if it does not exist
    catch(e){}
}

The main point is that it's a good idea to at least have some practice of logging other than just sticking console.log() right into your JavaScript code, because if you forget about it, and it's on a production site, it can potentially break all of the JavaScript code for that page.

Java using enum with switch statement

The enums should not be qualified within the case label like what you have NDroid.guideView.GUIDE_VIEW_SEVEN_DAY, instead you should remove the qualification and use GUIDE_VIEW_SEVEN_DAY

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

Just worth mentioning that while others suggest tempering with files, I was able to resolve this issue by installing a missing plugin (ionic framework)

Hopefully it helps someone.

cordova plugin add cordova-support-google-services --save

A hex viewer / editor plugin for Notepad++?

The hex editor plugin mentioned by ellak still works, but it seems that you need the TextFX Characters plugin as well.

I initially installed only the hex plugin and Notepad++ would no longer pop up; instead it started eating memory (killed it at 1.2 GB). I removed it again and for other reasons installed the TextFX plugin (based on Find multiple lines in Notepad++)

Out of curiosity I installed the hex plugin again and now it works.

Note that this is on a fresh install of Windows 7 64 bit.

What is the purpose of willSet and didSet in Swift?

In your own (base) class, willSet and didSet are quite reduntant , as you could instead define a calculated property (i.e get- and set- methods) that access a _propertyVariable and does the desired pre- and post- prosessing.

If, however, you override a class where the property is already defined, then the willSet and didSet are useful and not redundant!

Center div on the middle of screen

Your code is correct you just used .div instead of div

HTML

<div class="ui grid container">
<div class="ui center aligned three column grid">
  <div class="column">
  </div>
  <div class="column">
    </div>
  </div>

CSS

div{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
}

Check out this Fiddle

How to configure Visual Studio to use Beyond Compare

I use BC3 for my git diff, but I'd also add vscode to the list of useful git diff tools. Some users prefer vscode over vs ide experience.

Using VS Code for Git Diff

git config --global diff.tool vscode
git config --global difftool.vscode.cmd "code --wait --diff $LOCAL $REMOTE"

Looping through all rows in a table column, Excel-VBA

You can search column before assignments:

Dim col_n as long
for i = 1 to NumCols
    if Cells(1, i).Value = "column header you are looking for" Then col_n = i
next

for i = 1 to NumRows
    Cells(i, col_n).Value = "PHEV"
next i

jQuery: click function exclude children.

Or you can do also:

$('.example').on('click', function(e) { 
   if( e.target != this ) 
       return false;

   // ... //
});

How to convert int to char with leading zeros?

Use REPLICATE so you don't have to hard code all the leading zeros:

DECLARE @InputStr int
       ,@Size     int
SELECT @InputStr=123
      ,@Size=10

PRINT REPLICATE('0',@Size-LEN(RTRIM(CONVERT(varchar(8000),@InputStr)))) + CONVERT(varchar(8000),@InputStr)

OUTPUT:

0000000123

Converting dict to OrderedDict

Most of the time we go for OrderedDict when we required a custom order not a generic one like ASC etc.

Here is the proposed solution:

import collections
ship = {"NAME": "Albatross",
         "HP":50,
         "BLASTERS":13,
         "THRUSTERS":18,
         "PRICE":250}

ship = collections.OrderedDict(ship)

print ship


new_dict = collections.OrderedDict()
new_dict["NAME"]=ship["NAME"]
new_dict["HP"]=ship["HP"]
new_dict["BLASTERS"]=ship["BLASTERS"]
new_dict["THRUSTERS"]=ship["THRUSTERS"]
new_dict["PRICE"]=ship["PRICE"]


print new_dict

This will be output:

OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)])
OrderedDict([('NAME', 'Albatross'), ('HP', 50), ('BLASTERS', 13), ('THRUSTERS', 18), ('PRICE', 250)])

Note: The new sorted dictionaries maintain their sort order when entries are deleted. But when new keys are added, the keys are appended to the end and the sort is not maintained.(official doc)

data type not understood

Try:

mmatrix = np.zeros((nrows, ncols))

Since the shape parameter has to be an int or sequence of ints

http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html

Otherwise you are passing ncols to np.zeros as the dtype.

How to grep Git commit diffs or contents for a certain word?

git log's pickaxe will find commits with changes including "word" with git log -Sword

How can I convert an HTML table to CSV?

I'm not sure if there is pre-made library for this, but if you're willing to get your hands dirty with a little Perl, you could likely do something with Text::CSV and HTML::Parser.

Can I use tcpdump to get HTTP requests, response header and response body?

There are tcpdump filters for HTTP GET & HTTP POST (or for both plus message body):

  • Run man tcpdump | less -Ip examples to see some examples

  • Here’s a tcpdump filter for HTTP GET (GET = 0x47, 0x45, 0x54, 0x20):

    sudo tcpdump -s 0 -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'
    
  • Here’s a tcpdump filter for HTTP POST (POST = 0x50, 0x4f, 0x53, 0x54):

    sudo tcpdump -s 0 -A 'tcp dst port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)'
    
  • Monitor HTTP traffic including request and response headers and message body (source):

    tcpdump -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
    tcpdump -X -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
    

For more information on the bit-twiddling in the TCP header see: String-Matching Capture Filter Generator (link to Sake Blok's explanation).

How to fix UITableView separator on iOS 7?

This is default by iOS7 design. try to do the below:

[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

You can set the 'Separator Inset' from the storyboard:

enter image description here

enter image description here

Git clone particular version of remote repository

You Can use simply

git checkout  commithash

in this sequence

git clone `URLTORepository`
cd `into your cloned folder`
git checkout commithash

commit hash looks like this "45ef55ac20ce2389c9180658fdba35f4a663d204"

How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?

DBMS_OUTPUT is not the best tool to debug, since most environments don't use it natively. If you want to capture the output of DBMS_OUTPUT however, you would simply use the DBMS_OUTPUT.get_line procedure.

Here is a small example:

SQL> create directory tmp as '/tmp/';

Directory created

SQL> CREATE OR REPLACE PROCEDURE write_log AS
  2     l_line VARCHAR2(255);
  3     l_done NUMBER;
  4     l_file utl_file.file_type;
  5  BEGIN
  6     l_file := utl_file.fopen('TMP', 'foo.log', 'A');
  7     LOOP
  8        EXIT WHEN l_done = 1;
  9        dbms_output.get_line(l_line, l_done);
 10        utl_file.put_line(l_file, l_line);
 11     END LOOP;
 12     utl_file.fflush(l_file);
 13     utl_file.fclose(l_file);
 14  END write_log;
 15  /

Procedure created

SQL> BEGIN
  2     dbms_output.enable(100000);
  3     -- write something to DBMS_OUTPUT
  4     dbms_output.put_line('this is a test');
  5     -- write the content of the buffer to a file
  6     write_log;
  7  END;
  8  /

PL/SQL procedure successfully completed

SQL> host cat /tmp/foo.log

this is a test

Java Error opening registry key

I had the same:

Error opening registry key 'Software\JavaSoft\Java Runtime Environment

Clearing Windows\SysWOW64 doesn't help for Win7

In my case it installing JDK8 offline helped (from link)

What is the difference between a strongly typed language and a statically typed language?

What is the difference between a strongly typed language and a statically typed language?

A statically typed language has a type system that is checked at compile time by the implementation (a compiler or interpreter). The type check rejects some programs, and programs that pass the check usually come with some guarantees; for example, the compiler guarantees not to use integer arithmetic instructions on floating-point numbers.

There is no real agreement on what "strongly typed" means, although the most widely used definition in the professional literature is that in a "strongly typed" language, it is not possible for the programmer to work around the restrictions imposed by the type system. This term is almost always used to describe statically typed languages.

Static vs dynamic

The opposite of statically typed is "dynamically typed", which means that

  1. Values used at run time are classified into types.
  2. There are restrictions on how such values can be used.
  3. When those restrictions are violated, the violation is reported as a (dynamic) type error.

For example, Lua, a dynamically typed language, has a string type, a number type, and a Boolean type, among others. In Lua every value belongs to exactly one type, but this is not a requirement for all dynamically typed languages. In Lua, it is permissible to concatenate two strings, but it is not permissible to concatenate a string and a Boolean.

Strong vs weak

The opposite of "strongly typed" is "weakly typed", which means you can work around the type system. C is notoriously weakly typed because any pointer type is convertible to any other pointer type simply by casting. Pascal was intended to be strongly typed, but an oversight in the design (untagged variant records) introduced a loophole into the type system, so technically it is weakly typed. Examples of truly strongly typed languages include CLU, Standard ML, and Haskell. Standard ML has in fact undergone several revisions to remove loopholes in the type system that were discovered after the language was widely deployed.

What's really going on here?

Overall, it turns out to be not that useful to talk about "strong" and "weak". Whether a type system has a loophole is less important than the exact number and nature of the loopholes, how likely they are to come up in practice, and what are the consequences of exploiting a loophole. In practice, it's best to avoid the terms "strong" and "weak" altogether, because

  • Amateurs often conflate them with "static" and "dynamic".

  • Apparently "weak typing" is used by some persons to talk about the relative prevalance or absence of implicit conversions.

  • Professionals can't agree on exactly what the terms mean.

  • Overall you are unlikely to inform or enlighten your audience.

The sad truth is that when it comes to type systems, "strong" and "weak" don't have a universally agreed on technical meaning. If you want to discuss the relative strength of type systems, it is better to discuss exactly what guarantees are and are not provided. For example, a good question to ask is this: "is every value of a given type (or class) guaranteed to have been created by calling one of that type's constructors?" In C the answer is no. In CLU, F#, and Haskell it is yes. For C++ I am not sure—I would like to know.

By contrast, static typing means that programs are checked before being executed, and a program might be rejected before it starts. Dynamic typing means that the types of values are checked during execution, and a poorly typed operation might cause the program to halt or otherwise signal an error at run time. A primary reason for static typing is to rule out programs that might have such "dynamic type errors".

Does one imply the other?

On a pedantic level, no, because the word "strong" doesn't really mean anything. But in practice, people almost always do one of two things:

  • They (incorrectly) use "strong" and "weak" to mean "static" and "dynamic", in which case they (incorrectly) are using "strongly typed" and "statically typed" interchangeably.

  • They use "strong" and "weak" to compare properties of static type systems. It is very rare to hear someone talk about a "strong" or "weak" dynamic type system. Except for FORTH, which doesn't really have any sort of a type system, I can't think of a dynamically typed language where the type system can be subverted. Sort of by definition, those checks are bulit into the execution engine, and every operation gets checked for sanity before being executed.

Either way, if a person calls a language "strongly typed", that person is very likely to be talking about a statically typed language.

How can I present a file for download from an MVC controller?

Although standard action results FileContentResult or FileStreamResult may be used for downloading files, for reusability, creating a custom action result might be the best solution.

As an example let's create a custom action result for exporting data to Excel files on the fly for download.

ExcelResult class inherits abstract ActionResult class and overrides the ExecuteResult method.

We are using FastMember package for creating DataTable from IEnumerable object and ClosedXML package for creating Excel file from the DataTable.

public class ExcelResult<T> : ActionResult
{
    private DataTable dataTable;
    private string fileName;

    public ExcelResult(IEnumerable<T> data, string filename, string[] columns)
    {
        this.dataTable = new DataTable();
        using (var reader = ObjectReader.Create(data, columns))
        {
            dataTable.Load(reader);
        }
        this.fileName = filename;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context != null)
        {
            var response = context.HttpContext.Response;
            response.Clear();
            response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            response.AddHeader("content-disposition", string.Format(@"attachment;filename=""{0}""", fileName));
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dataTable, "Sheet1");
                using (MemoryStream stream = new MemoryStream())
                {
                    wb.SaveAs(stream);
                    response.BinaryWrite(stream.ToArray());
                }
            }
        }
    }
}

In the Controller use the custom ExcelResult action result as follows

[HttpGet]
public async Task<ExcelResult<MyViewModel>> ExportToExcel()
{
    var model = new Models.MyDataModel();
    var items = await model.GetItems();
    string[] columns = new string[] { "Column1", "Column2", "Column3" };
    string filename = "mydata.xlsx";
    return new ExcelResult<MyViewModel>(items, filename, columns);
}

Since we are downloading the file using HttpGet, create an empty View without model and empty layout.

Blog post about custom action result for downloading files that are created on the fly:

https://acanozturk.blogspot.com/2019/03/custom-actionresult-for-files-in-aspnet.html

Search and replace a line in a file in Python

Based on the answer by Thomas Watnedal. However, this does not answer the line-to-line part of the original question exactly. The function can still replace on a line-to-line basis

This implementation replaces the file contents without using temporary files, as a consequence file permissions remain unchanged.

Also re.sub instead of replace, allows regex replacement instead of plain text replacement only.

Reading the file as a single string instead of line by line allows for multiline match and replacement.

import re

def replace(file, pattern, subst):
    # Read contents from file as a single string
    file_handle = open(file, 'r')
    file_string = file_handle.read()
    file_handle.close()

    # Use RE package to allow for replacement (also allowing for (multiline) REGEX)
    file_string = (re.sub(pattern, subst, file_string))

    # Write contents to file.
    # Using mode 'w' truncates the file.
    file_handle = open(file, 'w')
    file_handle.write(file_string)
    file_handle.close()

How to convert a string Date to long millseconds

Easiest way is used the Date Using Date() and getTime()

    Date dte=new Date();
    long milliSeconds = dte.getTime();
    String strLong = Long.toString(milliSeconds);
    System.out.println(milliSeconds)

Make a phone call programmatically

If you are using Xamarin to develop an iOS application, here is the C# equivalent to make a phone call within your application:

string phoneNumber = "1231231234";
NSUrl url = new NSUrl(string.Format(@"telprompt://{0}", phoneNumber));
UIApplication.SharedApplication.OpenUrl(url);

pip install from git repo branch

Using pip with git+ to clone a repository can be extremely slow (test with https://github.com/django/django@stable/1.6.x for example, it will take a few minutes). The fastest thing I've found, which works with GitHub and BitBucket, is:

pip install https://github.com/user/repository/archive/branch.zip

which becomes for Django master:

pip install https://github.com/django/django/archive/master.zip

for Django stable/1.7.x:

pip install https://github.com/django/django/archive/stable/1.7.x.zip

With BitBucket it's about the same predictable pattern:

pip install https://bitbucket.org/izi/django-admin-tools/get/default.zip

Here, the master branch is generally named default. This will make your requirements.txt installing much faster.

Some other answers mention variations required when placing the package to be installed into your requirements.txt. Note that with this archive syntax, the leading -e and trailing #egg=blah-blah are not required, and you can just simply paste the URL, so your requirements.txt looks like:

https://github.com/user/repository/archive/branch.zip

JavaScript moving element in the DOM

There's no need to use a library for such a trivial task:

var divs = document.getElementsByTagName("div");   // order: first, second, third
divs[2].parentNode.insertBefore(divs[2], divs[0]); // order: third, first, second
divs[2].parentNode.insertBefore(divs[2], divs[1]); // order: third, second, first

This takes account of the fact that getElementsByTagName returns a live NodeList that is automatically updated to reflect the order of the elements in the DOM as they are manipulated.

You could also use:

var divs = document.getElementsByTagName("div");   // order: first, second, third
divs[0].parentNode.appendChild(divs[0]);           // order: second, third, first
divs[1].parentNode.insertBefore(divs[0], divs[1]); // order: third, second, first

and there are various other possible permutations, if you feel like experimenting:

divs[0].parentNode.appendChild(divs[0].parentNode.replaceChild(divs[2], divs[0]));

for example :-)

python - if not in list

if I got it right, you can try

for item in [x for x in checklist if x not in mylist]:
    print (item)

PHP include relative path

You could always include it using __DIR__:

include(dirname(__DIR__).'/config.php');

__DIR__ is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__. In this case, as we need to ascend a directory we use PHP's dirname which ascends the file tree, and from here we can access config.php.

You could set the root path in this method too:

define('ROOT_PATH', dirname(__DIR__) . '/');

in test.php would set your root to be at the /root/ level.

include(ROOT_PATH.'config.php');

Should then work to include the config file from where you want.

How can I go back/route-back on vue-router?

This works like a clock for me:

methods: {
 hasHistory () { return window.history.length > 2 }
}

Then, in the template:

<button 
  type="button"    
  @click="hasHistory() 
    ? $router.go(-1) 
    : $router.push('/')" class="my-5 btn btn-outline-success">&laquo; 
  Back
</button>

PHP - If variable is not empty, echo some html code

Your problem is in your use of the_field(), which is for Advanced Custom Fields, a wordpress plugin.

If you want to use a field in a variable you have to use this: $web = get_field('website');.

How do I convert a string to a number in PHP?

You can change the data type as follows

$number = "1.234";

echo gettype ($number) . "\n"; //Returns string

settype($number , "float");

echo gettype ($number) . "\n"; //Returns float

For historical reasons "double" is returned in case of a float.

PHP Documentation

How to push elements in JSON from javascript array

If you want to stick with the way you're populating the values array, you can then assign this array like so:

BODY.values = values;

after the loop.

It should look like this:

var BODY = {
    "recipients": {
      "values": [
     ]
    },
   "subject": title,
   "body": message
}

var values = [];
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
    "person": {
            "_path": "/people/"+names[ln],
            },
};
values.push(item1);
}
BODY.values = values;
alert(BODY);

JSON.stringify() will be useful once you pass it as parameter for an AJAX call. Remember: the values array in your BODY object is different from the var values = []. You must assign that outer values[] to BODY.values. This is one of the good things about OOP.

Set Label Text with JQuery

You can try:

<label id ="label_id"></label>
 $("#label_id").html('value');

Modifying a subset of rows in a pandas dataframe

Here is from pandas docs on advanced indexing:

The section will explain exactly what you need! Turns out df.loc (as .ix has been deprecated -- as many have pointed out below) can be used for cool slicing/dicing of a dataframe. And. It can also be used to set things.

df.loc[selection criteria, columns I want] = value

So Bren's answer is saying 'find me all the places where df.A == 0, select column B and set it to np.nan'

Error: Selection does not contain a main type

You must place all your files (file.java) under the root folder SRC.

Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials

While I don't know myself, I would certainly hope that #2 is incorrect...I'd like to think that Windows isn't going to AUTOMATICALLY give out my login information (least of all my password!) to any machine, let alone one that isn't part of my trust.

Regardless, have you explored the impersonation architecture? Your code is going to look similar to this:

using (System.Security.Principal.WindowsImpersonationContext context = System.Security.Principal.WindowsIdentity.Impersonate(token))
{
    // Do network operations here

    context.Undo();
}

In this case, the token variable is an IntPtr. In order to get a value for this variable, you'll have to call the unmanaged LogonUser Windows API function. A quick trip to pinvoke.net gives us the following signature:

[System.Runtime.InteropServices.DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
    string lpszUsername,
    string lpszDomain,
    string lpszPassword,
    int dwLogonType,
    int dwLogonProvider,
    out IntPtr phToken
);

Username, domain, and password should seem fairly obvious. Have a look at the various values that can be passed to dwLogonType and dwLogonProvider to determine the one that best suits your needs.

This code hasn't been tested, as I don't have a second domain here where I can verify, but this should hopefully put you on the right track.

Convert HTML to NSAttributedString in iOS

This is a String extension written in Swift to return a HTML string as NSAttributedString.

extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.dataUsingEncoding(NSUTF16StringEncoding, allowLossyConversion: false) else { return nil }
        guard let html = try? NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) else { return nil }
        return html
    }
}

To use,

label.attributedText = "<b>Hello</b> \u{2022} babe".htmlAttributedString()

In the above, I have purposely added a unicode \u2022 to show that it renders unicode correctly.

A trivial: The default encoding that NSAttributedString uses is NSUTF16StringEncoding (not UTF8!).

No resource found - Theme.AppCompat.Light.DarkActionBar

dependencies {
    implementation 'com.android.support:appcompat-v7:28.0.0'
}

compile has been replaced by implementation, don't know why.

C++ Array Of Pointers

If you don't use the STL, then the code looks a lot bit like C.

#include <cstdlib>
#include <new>

template< class T >
void append_to_array( T *&arr, size_t &n, T const &obj ) {
    T *tmp = static_cast<T*>( std::realloc( arr, sizeof(T) * (n+1) ) );
    if ( tmp == NULL ) throw std::bad_alloc( __FUNCTION__ );
       // assign things now that there is no exception
    arr = tmp;
    new( &arr[ n ] ) T( obj ); // placement new
    ++ n;
}

T can be any POD type, including pointers.

Note that arr must be allocated by malloc, not new[].

Default FirebaseApp is not initialized

I'm guessing there are compatibility problems with the version of google-services and firebase versions.

I changed in the Project's build.gradle file, the dependency

classpath 'com.google.gms:google-services:4.1.0' to 4.2.0

and then updated the module's build.gradle dependencies to:

implementation 'com.google.firebase:firebase-database:16.0.6'

implementation 'com.google.firebase:firebase-core:16.0.7'

Everything works like a charm, no need to type FirebaseApp.initializeApp(this);

Disable validation of HTML5 form elements

Instead of trying to do an end run around the browser's validation, you could put the http:// in as placeholder text. This is from the very page you linked:

Placeholder Text

The first improvement HTML5 brings to web forms is the ability to set placeholder text in an input field. Placeholder text is displayed inside the input field as long as the field is empty and not focused. As soon as you click on (or tab to) the input field, the placeholder text disappears.

You’ve probably seen placeholder text before. For example, Mozilla Firefox 3.5 now includes placeholder text in the location bar that reads “Search Bookmarks and History”:

enter image description here

When you click on (or tab to) the location bar, the placeholder text disappears:

enter image description here

Ironically, Firefox 3.5 does not support adding placeholder text to your own web forms. C’est la vie.

Placeholder Support

IE  FIREFOX SAFARI  CHROME  OPERA   IPHONE  ANDROID
·   3.7+    4.0+    4.0+    ·       ·       ·

Here’s how you can include placeholder text in your own web forms:

<form>
  <input name="q" placeholder="Search Bookmarks and History">
  <input type="submit" value="Search">
</form>

Browsers that don’t support the placeholder attribute will simply ignore it. No harm, no foul. See whether your browser supports placeholder text.

It wouldn't be exactly the same since it wouldn't provide that "starting point" for the user, but it's halfway there at least.

BeanFactory vs ApplicationContext

To me, the primary difference to choose BeanFactory over ApplicationContext seems to be that ApplicationContext will pre-instantiate all of the beans. From the Spring docs:

Spring sets properties and resolves dependencies as late as possible, when the bean is actually created. This means that a Spring container which has loaded correctly can later generate an exception when you request an object if there is a problem creating that object or one of its dependencies. For example, the bean throws an exception as a result of a missing or invalid property. This potentially delayed visibility of some configuration issues is why ApplicationContext implementations by default pre-instantiate singleton beans. At the cost of some upfront time and memory to create these beans before they are actually needed, you discover configuration issues when the ApplicationContext is created, not later. You can still override this default behavior so that singleton beans will lazy-initialize, rather than be pre-instantiated.

Given this, I initially chose BeanFactory for use in integration/performance tests since I didn't want to load the entire application for testing isolated beans. However -- and somebody correct me if I'm wrong -- BeanFactory doesn't support classpath XML configuration. So BeanFactory and ApplicationContext each provide a crucial feature I wanted, but neither did both.

Near as I can tell, the note in the documentation about overriding default instantiation behavior takes place in the configuration, and it's per-bean, so I can't just set the "lazy-init" attribute in the XML file or I'm stuck maintaining a version of it for test and one for deployment.

What I ended up doing was extending ClassPathXmlApplicationContext to lazily load beans for use in tests like so:

public class LazyLoadingXmlApplicationContext extends ClassPathXmlApplicationContext {

    public LazyLoadingXmlApplicationContext(String[] configLocations) {
        super(configLocations);
    }

    /**
     * Upon loading bean definitions, force beans to be lazy-initialized.
     * @see org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.xml.XmlBeanDefinitionReader)
     */

    @Override
    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {
        super.loadBeanDefinitions(reader);
        for (String name: reader.getBeanFactory().getBeanDefinitionNames()) {
            AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) reader.getBeanFactory().getBeanDefinition(name);
            beanDefinition.setLazyInit(true);
        }
    }

}

Creating a Facebook share button with customized url, title and image

Crude, but it works on our system:

<div class="block-share spread-share p-t-md">
  <a href="http://www.facebook.com/share.php?u=http://www.voteleavetakecontrol.org/our_affiliates&title=Farmers+for+Britain+have+made+the+sensible+decision+to+Vote+Leave.+Be+part+of+a+better+future+for+us+all.+Please+share!" 
     target="_blank">
    <button class="btn btn-social btn-facebook">
      <span class="icon icon-facebook">
      </span> 
      Share on Facebook
    </button>
  </a>

  <a href="https://www.facebook.com/FarmersForBritain" target="_blank">
    <button class="btn btn-social btn-facebook">
      <span class="icon icon-facebook">
      </span>
      Like  on Facebook
    </button>
  </a>
</div>

How to access POST form fields

Express v4.17.0

app.use(express.urlencoded( {extended: true} ))

app.post('/userlogin', (req, res) => {    

   console.log(req.body) // object

   var email = req.body.email;

}

Demo Form

Another Answer Related

C++ wait for user input

There is no "standard" library function to do this. The standard (perhaps surprisingly) does not actually recognise the concept of a "keyboard", albeit it does have a standard for "console input".

There are various ways to achieve it on different operating systems (see herohuyongtao's solution) but it is not portable across all platforms that support keyboard input.

Remember that C++ (and C) are devised to be languages that can run on embedded systems that do not have keyboards. (Having said that, an embedded system might not have various other devices that the standard library supports).

This matter has been debated for a long time.

How do you express binary literals in Python?

I am pretty sure this is one of the things due to change in Python 3.0 with perhaps bin() to go with hex() and oct().

EDIT: lbrandy's answer is correct in all cases.

Difference between HttpModule and HttpClientModule

There is a library which allows you to use HttpClient with strongly-typed callbacks.

The data and the error are available directly via these callbacks.

A reason for existing

When you use HttpClient with Observable, you have to use .subscribe(x=>...) in the rest of your code.

This is because Observable<HttpResponse<T>> is tied to HttpResponse.

This tightly couples the http layer with the rest of your code.

This library encapsulates the .subscribe(x => ...) part and exposes only the data and error through your Models.

With strongly-typed callbacks, you only have to deal with your Models in the rest of your code.

The library is called angular-extended-http-client.

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

Very easy to use.

Sample usage

The strongly-typed callbacks are

Success:

  • IObservable<T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse<T>

Failure:

  • IObservableError<TError>
  • IObservableHttpError
  • IObservableHttpCustomError<TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client';

and in the @NgModule imports

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

Your Models

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core'
import { RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    getRaceInfo(success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        this.client.get(url, ResponseType.IObservable, success, ErrorType.IObservableError, failure);
    }
}

Your Component

In your Component, your Service is injected and the getRaceInfo API called as shown below.

  ngOnInit() {    
    this.service.getRaceInfo(response => this.result = response.result,
                                error => this.errorMsg = error.className);

  }

Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.

You only deal with your Models in these strongly-typed callbacks.

Hence, The rest of your code only knows about your Models.

Also, you can still use the traditional route and return Observable<HttpResponse<T>> from Service API.

Design DFA accepting binary strings divisible by a number 'n'

Below, I have written an answer for n equals to 5, but you can apply same approach to draw DFAs for any value of n and 'any positional number system' e.g binary, ternary...

First lean the term 'Complete DFA', A DFA defined on complete domain in d:Q × S?Q is called 'Complete DFA'. In other words we can say; in transition diagram of complete DFA there is no missing edge (e.g. from each state in Q there is one outgoing edge present for every language symbol in S). Note: Sometime we define partial DFA as d ? Q × S?Q (Read: How does “d:Q × S?Q” read in the definition of a DFA).

Design DFA accepting Binary numbers divisible by number 'n':

Step-1: When you divide a number ? by n then reminder can be either 0, 1, ..., (n - 2) or (n - 1). If remainder is 0 that means ? is divisible by n otherwise not. So, in my DFA there will be a state qr that would be corresponding to a remainder value r, where 0 <= r <= (n - 1), and total number of states in DFA is n.
After processing a number string ? over S, the end state is qr implies that ? % n => r (% reminder operator).

In any automata, the purpose of a state is like memory element. A state in an atomata stores some information like fan's switch that can tell whether the fan is in 'off' or in 'on' state. For n = 5, five states in DFA corresponding to five reminder information as follows:

  1. State q0 reached if reminder is 0. State q0 is the final state(accepting state). It is also an initial state.
  2. State q1 reaches if reminder is 1, a non-final state.
  3. State q2 if reminder is 2, a non-final state.
  4. State q3 if reminder is 3, a non-final state.
  5. State q4 if reminder is 4, a non-final state.

Using above information, we can start drawing transition diagram TD of five states as follows:

fig-1
Figure-1

So, 5 states for 5 remainder values. After processing a string ? if end-state becomes q0 that means decimal equivalent of input string is divisible by 5. In above figure q0 is marked final state as two concentric circle.
Additionally, I have defined a transition rule d:(q0, 0)?q0 as a self loop for symbol '0' at state q0, this is because decimal equivalent of any string consist of only '0' is 0 and 0 is a divisible by n.

Step-2: TD above is incomplete; and can only process strings of '0's. Now add some more edges so that it can process subsequent number's strings. Check table below, shows new transition rules those can be added next step:

+-------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦
+------+------+-------------+---------¦
¦One   ¦1     ¦1            ¦q1       ¦
+------+------+-------------+---------¦
¦Two   ¦10    ¦2            ¦q2       ¦
+------+------+-------------+---------¦
¦Three ¦11    ¦3            ¦q3       ¦
+------+------+-------------+---------¦
¦Four  ¦100   ¦4            ¦q4       ¦
+-------------------------------------+
  1. To process binary string '1' there should be a transition rule d:(q0, 1)?q1
  2. Two:- binary representation is '10', end-state should be q2, and to process '10', we just need to add one more transition rule d:(q1, 0)?q2
    Path: ?(q0)-1?(q1)-0?(q2)
  3. Three:- in binary it is '11', end-state is q3, and we need to add a transition rule d:(q1, 1)?q3
    Path: ?(q0)-1?(q1)-1?(q3)
  4. Four:- in binary '100', end-state is q4. TD already processes prefix string '10' and we just need to add a new transition rule d:(q2, 0)?q4
    Path: ?(q0)-1?(q1)-0?(q2)-0?(q4)

fig-2 Figure-2

Step-3: Five = 101
Above transition diagram in figure-2 is still incomplete and there are many missing edges, for an example no transition is defined for d:(q2, 1)-?. And the rule should be present to process strings like '101'.
Because '101' = 5 is divisible by 5, and to accept '101' I will add d:(q2, 1)?q0 in above figure-2.
Path: ?(q0)-1?(q1)-0?(q2)-1?(q0)
with this new rule, transition diagram becomes as follows:

fig-3 Figure-3

Below in each step I pick next subsequent binary number to add a missing edge until I get TD as a 'complete DFA'.

Step-4: Six = 110.

We can process '11' in present TD in figure-3 as: ?(q0)-11?(q3) -0?(?). Because 6 % 5 = 1 this means to add one rule d:(q3, 0)?q1.

fig-4 Figure-4

Step-5: Seven = 111

+--------------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path       ¦ Add       ¦
+------+------+-------------+---------+------------+-----------¦
¦Seven ¦111   ¦7 % 5 = 2    ¦q2       ¦ q0-11?q3   ¦ q3-1?q2    ¦
+--------------------------------------------------------------+

fig-5 Figure-5

Step-6: Eight = 1000

+----------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path     ¦ Add     ¦
+------+------+-------------+---------+----------+---------¦
¦Eight ¦1000  ¦8 % 5 = 3    ¦q3       ¦q0-100?q4 ¦ q4-0?q3  ¦
+----------------------------------------------------------+

fig-6 Figure-6

Step-7: Nine = 1001

+----------------------------------------------------------+
¦Number¦Binary¦Remainder(%5)¦End-state¦ Path     ¦ Add     ¦
+------+------+-------------+---------+----------+---------¦
¦Nine  ¦1001  ¦9 % 5 = 4    ¦q4       ¦q0-100?q4 ¦ q4-1?q4  ¦
+----------------------------------------------------------+

fig-7 Figure-7

In TD-7, total number of edges are 10 == Q × S = 5 × 2. And it is a complete DFA that can accept all possible binary strings those decimal equivalent is divisible by 5.

Design DFA accepting Ternary numbers divisible by number n:

Step-1 Exactly same as for binary, use figure-1.

Step-2 Add Zero, One, Two

+------------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦   Add        ¦
+-------+-------+-------------+---------+--------------¦
¦Zero   ¦0      ¦0            ¦q0       ¦ d:(q0,0)?q0  ¦
+-------+-------+-------------+---------+--------------¦
¦One    ¦1      ¦1            ¦q1       ¦ d:(q0,1)?q1  ¦
+-------+-------+-------------+---------+--------------¦
¦Two    ¦2      ¦2            ¦q2       ¦ d:(q0,2)?q3  ¦
+------------------------------------------------------+

fig-8
Figure-8

Step-3 Add Three, Four, Five

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Three  ¦10     ¦3            ¦q3       ¦ d:(q1,0)?q3 ¦
+-------+-------+-------------+---------+-------------¦
¦Four   ¦11     ¦4            ¦q4       ¦ d:(q1,1)?q4 ¦
+-------+-------+-------------+---------+-------------¦
¦Five   ¦12     ¦0            ¦q0       ¦ d:(q1,2)?q0 ¦
+-----------------------------------------------------+

fig-9
Figure-9

Step-4 Add Six, Seven, Eight

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Six    ¦20     ¦1            ¦q1       ¦ d:(q2,0)?q1 ¦
+-------+-------+-------------+---------+-------------¦
¦Seven  ¦21     ¦2            ¦q2       ¦ d:(q2,1)?q2 ¦
+-------+-------+-------------+---------+-------------¦
¦Eight  ¦22     ¦3            ¦q3       ¦ d:(q2,2)?q3 ¦
+-----------------------------------------------------+

fig-10
Figure-10

Step-5 Add Nine, Ten, Eleven

+-----------------------------------------------------+
¦Decimal¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+-------+-------+-------------+---------+-------------¦
¦Nine   ¦100    ¦4            ¦q4       ¦ d:(q3,0)?q4 ¦
+-------+-------+-------------+---------+-------------¦
¦Ten    ¦101    ¦0            ¦q0       ¦ d:(q3,1)?q0 ¦
+-------+-------+-------------+---------+-------------¦
¦Eleven ¦102    ¦1            ¦q1       ¦ d:(q3,2)?q1 ¦
+-----------------------------------------------------+

fig-11
Figure-11

Step-6 Add Twelve, Thirteen, Fourteen

+------------------------------------------------------+
¦Decimal ¦Ternary¦Remainder(%5)¦End-state¦  Add        ¦
+--------+-------+-------------+---------+-------------¦
¦Twelve  ¦110    ¦2            ¦q2       ¦ d:(q4,0)?q2 ¦
+--------+-------+-------------+---------+-------------¦
¦Thirteen¦111    ¦3            ¦q3       ¦ d:(q4,1)?q3 ¦
+--------+-------+-------------+---------+-------------¦
¦Fourteen¦112    ¦4            ¦q4       ¦ d:(q4,2)?q4 ¦
+------------------------------------------------------+

fig-12
Figure-12

Total number of edges in transition diagram figure-12 are 15 = Q × S = 5 * 3 (a complete DFA). And this DFA can accept all strings consist over {0, 1, 2} those decimal equivalent is divisible by 5.
If you notice at each step, in table there are three entries because at each step I add all possible outgoing edge from a state to make a complete DFA (and I add an edge so that qr state gets for remainder is r)!

To add further, remember union of two regular languages are also a regular. If you need to design a DFA that accepts binary strings those decimal equivalent is either divisible by 3 or 5, then draw two separate DFAs for divisible by 3 and 5 then union both DFAs to construct target DFA (for 1 <= n <= 10 your have to union 10 DFAs).

If you are asked to draw DFA that accepts binary strings such that decimal equivalent is divisible by 5 and 3 both then you are looking for DFA of divisible by 15 ( but what about 6 and 8?).

Note: DFAs drawn with this technique will be minimized DFA only when there is no common factor between number n and base e.g. there is no between 5 and 2 in first example, or between 5 and 3 in second example, hence both DFAs constructed above are minimized DFAs. If you are interested to read further about possible mini states for number n and base b read paper: Divisibility and State Complexity.

below I have added a Python script, I written it for fun while learning Python library pygraphviz. I am adding it I hope it can be helpful for someone in someway.

Design DFA for base 'b' number strings divisible by number 'n':

So we can apply above trick to draw DFA to recognize number strings in any base 'b' those are divisible a given number 'n'. In that DFA total number of states will be n (for n remainders) and number of edges should be equal to 'b' * 'n' — that is complete DFA: 'b' = number of symbols in language of DFA and 'n' = number of states.

Using above trick, below I have written a Python Script to Draw DFA for input base and number. In script, function divided_by_N populates DFA's transition rules in base * number steps. In each step-num, I convert num into number string num_s using function baseN(). To avoid processing each number string, I have used a temporary data-structure lookup_table. In each step, end-state for number string num_s is evaluated and stored in lookup_table to use in next step.

For transition graph of DFA, I have written a function draw_transition_graph using Pygraphviz library (very easy to use). To use this script you need to install graphviz. To add colorful edges in transition diagram, I randomly generates color codes for each symbol get_color_dict function.

#!/usr/bin/env python
import pygraphviz as pgv
from pprint import pprint
from random import choice as rchoice

def baseN(n, b, syms="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
    """ converts a number `n` into base `b` string """
    return ((n == 0) and syms[0]) or (
        baseN(n//b, b, syms).lstrip(syms[0]) + syms[n % b])

def divided_by_N(number, base):
    """
    constructs DFA that accepts given `base` number strings
    those are divisible by a given `number`
    """
    ACCEPTING_STATE = START_STATE = '0'
    SYMBOL_0 = '0'
    dfa = {
        str(from_state): {
            str(symbol): 'to_state' for symbol in range(base)
        }
        for from_state in range(number)
    }
    dfa[START_STATE][SYMBOL_0] = ACCEPTING_STATE
    # `lookup_table` keeps track: 'number string' -->[dfa]--> 'end_state'
    lookup_table = { SYMBOL_0: ACCEPTING_STATE }.setdefault
    for num in range(number * base):
        end_state = str(num % number)
        num_s = baseN(num, base)
        before_end_state = lookup_table(num_s[:-1], START_STATE)
        dfa[before_end_state][num_s[-1]] = end_state
        lookup_table(num_s, end_state)
    return dfa

def symcolrhexcodes(symbols):
    """
    returns dict of color codes mapped with alphabets symbol in symbols
    """
    return {
        symbol: '#'+''.join([
            rchoice("8A6C2B590D1F4E37") for _ in "FFFFFF"
        ])
        for symbol in symbols
    }

def draw_transition_graph(dfa, filename="filename"):
    ACCEPTING_STATE = START_STATE = '0'
    colors = symcolrhexcodes(dfa[START_STATE].keys())
    # draw transition graph
    tg = pgv.AGraph(strict=False, directed=True, decorate=True)
    for from_state in dfa:
        for symbol, to_state in dfa[from_state].iteritems():
            tg.add_edge("Q%s"%from_state, "Q%s"%to_state,
                        label=symbol, color=colors[symbol],
                        fontcolor=colors[symbol])

    # add intial edge from an invisible node!
    tg.add_node('null', shape='plaintext', label='start')
    tg.add_edge('null', "Q%s"%START_STATE,)

    # make end acception state as 'doublecircle'
    tg.get_node("Q%s"%ACCEPTING_STATE).attr['shape'] = 'doublecircle'
    tg.draw(filename, prog='circo')
    tg.close()

def print_transition_table(dfa):
    print("DFA accepting number string in base '%(base)s' "
            "those are divisible by '%(number)s':" % {
                'base': len(dfa['0']),
                'number': len(dfa),})
    pprint(dfa)

if __name__ == "__main__":
    number = input ("Enter NUMBER: ")
    base = input ("Enter BASE of number system: ")
    dfa = divided_by_N(number, base)

    print_transition_table(dfa)
    draw_transition_graph(dfa)

Execute it:

~/study/divide-5/script$ python script.py 
Enter NUMBER: 5
Enter BASE of number system: 4
DFA accepting number string in base '4' those are divisible by '5':
{'0': {'0': '0', '1': '1', '2': '2', '3': '3'},
 '1': {'0': '4', '1': '0', '2': '1', '3': '2'},
 '2': {'0': '3', '1': '4', '2': '0', '3': '1'},
 '3': {'0': '2', '1': '3', '2': '4', '3': '0'},
 '4': {'0': '1', '1': '2', '2': '3', '3': '4'}}
~/study/divide-5/script$ ls
script.py filename.png
~/study/divide-5/script$ display filename

Output:

base_4_divided_5_best
DFA accepting number strings in base 4 those are divisible by 5

Similarly, enter base = 4 and number = 7 to generate - dfa accepting number string in base '4' those are divisible by '7'
Btw, try changing filename to .png or .jpeg.

References those I use to write this script:
➊ Function baseN from "convert integer to a string in a given numeric base in python"
➋ To install "pygraphviz": "Python does not see pygraphviz"
➌ To learn use of Pygraphviz: "Python-FSM"
➍ To generate random hex color codes for each language symbol: "How would I make a random hexdigit code generator using .join and for loops?"

Which is the best library for XML parsing in java

Java supports two methods for XML parsing out of the box.

SAXParser

You can use this parser if you want to parse large XML files and/or don't want to use a lot of memory.

http://download.oracle.com/javase/6/docs/api/javax/xml/parsers/SAXParserFactory.html

Example: http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/

DOMParser

You can use this parser if you need to do XPath queries or need to have the complete DOM available.

http://download.oracle.com/javase/6/docs/api/javax/xml/parsers/DocumentBuilderFactory.html

Example: http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/

Create a new workspace in Eclipse

In Window->Preferences->General->Startup and Shutdown->Workspaces, make sure that 'Prompt for Workspace on startup' is checked.

Then close eclipse and reopen.

Then you'll be prompted for a workspace to open. You can create a new workspace from that dialogue.

Or File->Switch Workspace->Other...

how to rotate text left 90 degree and cell size is adjusted according to text in html

Without calculating height. Strict CSS and HTML. <span/> only for Chrome, because the chrome isn't able change text direction for <th/>.

_x000D_
_x000D_
th _x000D_
{_x000D_
  vertical-align: bottom;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
th span _x000D_
{_x000D_
  -ms-writing-mode: tb-rl;_x000D_
  -webkit-writing-mode: vertical-rl;_x000D_
  writing-mode: vertical-rl;_x000D_
  transform: rotate(180deg);_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <th><span>Rotated text by 90 deg.</span></th>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

JavaScript check if value is only undefined, null or false

Another solution:

Based on the document, Boolean object will return true if the value is not 0, undefined, null, etc. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean

If value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false.

So

if(Boolean(val))
{
//executable...
}

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

Finally I got it:

as3:/usr/local/lib/python2.7/site-packages# cat sitecustomize.py
# encoding=utf8  
import sys  

reload(sys)  
sys.setdefaultencoding('utf8')

Let me check:

as3:~/ngokevin-site# python
Python 2.7.6 (default, Dec  6 2013, 14:49:02)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.getdefaultencoding()
'utf8'
>>>

The above shows the default encoding of python is utf8. Then the error is no more.

Difference between a class and a module

I'm surprised anyone hasn't said this yet.

Since the asker came from a Java background (and so did I), here's an analogy that helps.

Classes are simply like Java classes.

Modules are like Java static classes. Think about Math class in Java. You don't instantiate it, and you reuse the methods in the static class (eg. Math.random()).

how to replace characters in hive?

regexp_replace UDF performs my task. Below is the definition and usage from apache Wiki.

regexp_replace(string INITIAL_STRING, string PATTERN, string REPLACEMENT):

This returns the string resulting from replacing all substrings in INITIAL_STRING that match the java regular expression syntax defined in PATTERN with instances of REPLACEMENT,

e.g.: regexp_replace("foobar", "oo|ar", "") returns fb

Get the IP Address of local computer

I suggest my code.

DllExport void get_local_ips(boost::container::vector<wstring>& ips)
{
   IP_ADAPTER_ADDRESSES*       adapters  = NULL;
   IP_ADAPTER_ADDRESSES*       adapter       = NULL;
   IP_ADAPTER_UNICAST_ADDRESS* adr           = NULL;
   ULONG                       adapter_size = 0;
   ULONG                       err           = 0;
   SOCKADDR_IN*                sockaddr  = NULL;

   err = ::GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME, NULL, NULL, &adapter_size);
   adapters = (IP_ADAPTER_ADDRESSES*)malloc(adapter_size);
   err = ::GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME, NULL, adapters, &adapter_size);

   for (adapter = adapters; NULL != adapter; adapter = adapter->Next)
   {
       if (adapter->IfType     == IF_TYPE_SOFTWARE_LOOPBACK) continue; // Skip Loopback
       if (adapter->OperStatus != IfOperStatusUp) continue;            // Live connection only  

       for (adr = adapter->FirstUnicastAddress;adr != NULL; adr = adr->Next)
       {
           sockaddr = (SOCKADDR_IN*)(adr->Address.lpSockaddr);
           char    ipstr [INET6_ADDRSTRLEN] = { 0 };
           wchar_t ipwstr[INET6_ADDRSTRLEN] = { 0 };
           inet_ntop(AF_INET, &(sockaddr->sin_addr), ipstr, INET_ADDRSTRLEN);
           mbstowcs(ipwstr, ipstr, INET6_ADDRSTRLEN);
           wstring wstr(ipwstr);
           if (wstr != "0.0.0.0") ips.push_back(wstr);                      
       }
   }

   free(adapters);
   adapters = NULL; }

Catching KeyboardInterrupt in Python during program shutdown

You could ignore SIGINTs after shutdown starts by calling signal.signal(signal.SIGINT, signal.SIG_IGN) before you start your cleanup code.

Read Content from Files which are inside Zip file

My way of achieving this is by creating ZipInputStream wrapping class that would handle that would provide only the stream of current entry:

The wrapper class:

public class ZippedFileInputStream extends InputStream {

    private ZipInputStream is;

    public ZippedFileInputStream(ZipInputStream is){
        this.is = is;
    }

    @Override
    public int read() throws IOException {
        return is.read();
    }

    @Override
    public void close() throws IOException {
        is.closeEntry();
    }

}

The use of it:

    ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream("SomeFile.zip"));

    while((entry = zipInputStream.getNextEntry())!= null) {

     ZippedFileInputStream archivedFileInputStream = new ZippedFileInputStream(zipInputStream);

     //... perform whatever logic you want here with ZippedFileInputStream 

     // note that this will only close the current entry stream and not the ZipInputStream
     archivedFileInputStream.close();

    }
    zipInputStream.close();

One advantage of this approach: InputStreams are passed as an arguments to methods that process them and those methods have a tendency to immediately close the input stream after they are done with it.

Best way to test exceptions with Assert to ensure they will be thrown

Now, 2017, you can do it easier with the new MSTest V2 Framework:

Assert.ThrowsException<Exception>(() => myClass.MyMethodWithError());

//async version
await Assert.ThrowsExceptionAsync<SomeException>(
  () => myObject.SomeMethodAsync()
);

"unary operator expected" error in Bash if condition

Try assigning a value to $aug1 before use it in if[] statements; the error message will disappear afterwards.

how to use python2.7 pip instead of default pip

An alternative is to call the pip module by using python2.7, as below:

python2.7 -m pip <commands>

For example, you could run python2.7 -m pip install <package> to install your favorite python modules. Here is a reference: https://stackoverflow.com/a/50017310/4256346.

In case the pip module has not yet been installed for this version of python, you can run the following:

python2.7 -m ensurepip

Running this command will "bootstrap the pip installer". Note that running this may require administrative privileges (i.e. sudo). Here is a reference: https://docs.python.org/2.7/library/ensurepip.html and another reference https://stackoverflow.com/a/46631019/4256346.

How to undo a SQL Server UPDATE query?

If you already have a full backup from your database, fortunately, you have an option in SQL Management Studio. In this case, you can use the following steps:

  1. Right click on database -> Tasks -> Restore -> Database.

  2. In General tab, click on Timeline -> select Specific date and time option.

  3. Move the timeline slider to before update command time -> click OK.

  4. In the destination database name, type a new name.

  5. In the Files tab, check in Reallocate all files to folder and then select a new path to save your recovered database.

  6. In the options tab, check in Overwrite ... and remove Take tail-log... check option.

  7. Finally, click on OK and wait until the recovery process is over.

I have used this method myself in an operational database and it was very useful.

How to drop all tables in a SQL Server database?

I know this is an old post now but I have tried all the answers on here on a multitude of databases and I have found they all work sometimes but not all of the time for various (I can only assume) quirks of SQL Server.

Eventually I came up with this. I have tested this everywhere (generally speaking) I can and it works (without any hidden store procedures).

For note mostly on SQL Server 2014. (but most of the other versions I tried it also seems to worked fine).

I have tried while loops and nulls etc etc, cursors and various other forms but they always seem to fail on some databases but not others for no obvious reason.

Getting a count and using that to iterate always seems to work on everything Ive tested.

USE [****YOUR_DATABASE****]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

-- Drop all referential integrity constraints --
-- Drop all Primary Key constraints.          --

DECLARE @sql  NVARCHAR(296)
DECLARE @table_name VARCHAR(128)

DECLARE @constraint_name VARCHAR(128)
SET @constraint_name = ''

DECLARE @row_number INT

SELECT @row_number = Count(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME = rc1.CONSTRAINT_NAME

WHILE @row_number > 0
BEGIN
    BEGIN
        SELECT TOP 1 @table_name = tc2.TABLE_NAME, @constraint_name = rc1.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
        LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME = rc1.CONSTRAINT_NAME
        AND rc1.CONSTRAINT_NAME > @constraint_name
        ORDER BY rc1.CONSTRAINT_NAME
        SELECT @sql = 'ALTER TABLE [dbo].[' + RTRIM(@table_name) +'] DROP CONSTRAINT [' + RTRIM(@constraint_name)+']'
        EXEC (@sql)
        PRINT 'Dropped Constraint: ' + @constraint_name + ' on ' + @table_name
        SET @row_number = @row_number - 1
    END
END
GO

-- Drop all tables --

DECLARE @sql  NVARCHAR(156)
DECLARE @name VARCHAR(128)
SET @name = ''

DECLARE @row_number INT

SELECT @row_number = Count(*) FROM sysobjects WHERE [type] = 'U' AND category = 0

WHILE @row_number > 0
BEGIN
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
    SELECT @sql = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
    EXEC (@sql)
    PRINT 'Dropped Table: ' + @name
    SET @row_number = @row_number - 1
END
GO

"git pull" or "git merge" between master and development branches

Be careful with rebase. If you're sharing your develop branch with anybody, rebase can make a mess of things. Rebase is good only for your own local branches.

Rule of thumb, if you've pushed the branch to origin, don't use rebase. Instead, use merge.

process.start() arguments

Try fully qualifying the filenames in the arguments - I notice you're specifying the path in the FileName part, so it's possible that the process is being started elsewhere, then not finding the arguments and causing an error.

If that works, then setting the WorkingDirectory property on the StartInfo may be of use.

Actually, according to the link

The WorkingDirectory property must be set if UserName and Password are provided. If the property is not set, the default working directory is %SYSTEMROOT%\system32.

Using JQuery hover with HTML image map

Although jQuery Maphilight plugin does the job, it relies on the outdated verbose imagemap in your html. I would prefer to keep the mapcoordinates external. This could be as JS with the jquery imagemap plugin but it lacks hover states. A nice solution is googles geomap visualisation in flash and JS. But the opensource future for this kind of vectordata however is svg, considering svg support accross all modern browsers, and googles svgweb for a flash convert for IE, why not a jquery plugin to add links and hoverstates to a svg map, like the JS demo here? That way you also avoid the complex step of transforming a vectormap to a imagemap coordinates.

Installing a plain plugin jar in Eclipse 3.5

For Eclipse Mars (I've just verified that) you to do this (assuming that C:\eclipseMarsEE is root folder of your Eclipse):

  1. Add plugins folder to C:\eclipseMarsEE\dropins so that it looks like: C:\eclipseMarsEE\dropins\plugins
  2. Then add plugin you want to install into that folder: C:\eclipseMarsEE\dropins\plugins\someplugin.jar
  3. Start Eclipse with clean option.
  4. If you are using shortcut on desktop then just right click on Eclipse icon > Properties and in Target field add: -clean like this: C:\eclipseMarsEE\eclipse.exe -clean

enter image description here

  1. Start Eclipse and verify that your plugin works.
  2. Remove -clean option from Target field.

grabbing first row in a mysql query only

You can get the total number of rows containing a specific name using:

SELECT COUNT(*) FROM tbl_foo WHERE name = 'sarmen'

Given the count, you can now get the nth row using:

SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT (n - 1), 1

Where 1 <= n <= COUNT(*) from the first query.

Example:

getting the 3rd row

SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT 2, 1

GoTo Next Iteration in For Loop in java

If you want to skip current iteration, use continue;.

for(int i = 0; i < 5; i++){
    if (i == 2){
        continue;
    }
 }

Need to break out of the whole loop? Use break;

for(int i = 0; i < 5; i++){
    if (i == 2){
        break;
    }
}

If you need to break out of more than one loop use break someLabel;

outerLoop:                                           // Label the loop
for(int j = 0; j < 5; j++){
     for(int i = 0; i < 5; i++){
        if (i==2){
          break outerLoop;
        }
     }
  }

*Note that in this case you are not marking a point in code to jump to, you are labeling the loop! So after the break the code will continue right after the loop!

When you need to skip one iteration in nested loops use continue someLabel;, but you can also combine them all.

outerLoop:
for(int j = 0; j < 10; j++){
     innerLoop:
     for(int i = 0; i < 10; i++){
        if (i + j == 2){
          continue innerLoop;
        }
        if (i + j == 4){
          continue outerLoop;
        }
        if (i + j == 6){
          break innerLoop;
        }
        if (i + j == 8){
          break outerLoop;
        }
     }
  }

Simple WPF RadioButton Binding?

I am very suprised nobody came up with this kind of solution to bind it against bool array. It might not be the cleanest, but it can be used very easily:

private bool[] _modeArray = new bool[] { true, false, false};
public bool[] ModeArray
{
    get { return _modeArray ; }
}
public int SelectedMode
{
    get { return Array.IndexOf(_modeArray, true); }
}

in XAML:

<RadioButton GroupName="Mode" IsChecked="{Binding Path=ModeArray[0], Mode=TwoWay}"/>
<RadioButton GroupName="Mode" IsChecked="{Binding Path=ModeArray[1], Mode=TwoWay}"/>
<RadioButton GroupName="Mode" IsChecked="{Binding Path=ModeArray[2], Mode=TwoWay}"/>

NOTE: you dont need two-way binding if you dont want to one checked by default. TwoWay binding is the biggest cons of this solution.

Pros:

  • No need for code behind
  • No need for extra class (IValue Converter)
  • No Need for extra enums
  • doesnt require bizzare binding
  • straightforward and easy to understand
  • doesnt violate MVVM (heh, at least I hope so)

What is the most accurate way to retrieve a user's correct IP address in PHP?

You pretty much answered your own question! :)

function getRealIpAddr() {
    if(!empty($_SERVER['HTTP_CLIENT_IP']))   //Check IP address from shared Internet
    {
        $IPaddress = $_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //To check IP address is passed from the proxy
    {
        $IPaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
        $IPaddress = $_SERVER['REMOTE_ADDR'];
    }
    return $IPaddress;
}

Source

Java Multiple Inheritance

you can have an interface hierarchy and then extend your classes from selected interfaces :

public interface IAnimal {
}

public interface IBird implements IAnimal {
}

public  interface IHorse implements IAnimal {
}

public interface IPegasus implements IBird,IHorse{
}

and then define your classes as needed, by extending a specific interface :

public class Bird implements IBird {
}

public class Horse implements IHorse{
}

public class Pegasus implements IPegasus {
}

How do you get a timestamp in JavaScript?

var timestamp = Number(new Date()); // current time as number

Must declare the scalar variable

Here is a simple example :

Create or alter PROCEDURE getPersonCountByLastName (
@lastName varchar(20),
@count int OUTPUT
)
As
Begin
select @count = count(personSid) from Person where lastName like @lastName
End;

Execute below statements in one batch (by selecting all)

1. Declare @count int
2. Exec getPersonCountByLastName kumar, @count output
3. Select @count

When i tried to execute statements 1,2,3 individually, I had the same error. But when executed them all at one time, it worked fine.

The reason is that SQL executes declare, exec statements in different sessions.

Open to further corrections.

click or change event on radio using jquery

Try

$(document).ready(

instead of

$('document').ready(

or you can use a shorthand form

$(function(){
});

How to add many functions in ONE ng-click?

You can call multiple functions with ';'

ng-click="edit($index); open()"

How to use SQL Order By statement to sort results case insensitive?

You can also do ORDER BY TITLE COLLATE NOCASE.

Edit: If you need to specify ASC or DESC, add this after NOCASE like

ORDER BY TITLE COLLATE NOCASE ASC

or

ORDER BY TITLE COLLATE NOCASE DESC

Where's my JSON data in my incoming Django request?

request.POST is just a dictionary-like object, so just index into it with dict syntax.

Assuming your form field is fred, you could do something like this:

if 'fred' in request.POST:
    mydata = request.POST['fred']

Alternately, use a form object to deal with the POST data.

Get the current file name in gulp.src()

I found this plugin to be doing what I was expecting: gulp-using

Simple usage example: Search all files in project with .jsx extension

gulp.task('reactify', function(){
        gulp.src(['../**/*.jsx']) 
            .pipe(using({}));
        ....
    });

Output:

[gulp] Using gulpfile /app/build/gulpfile.js
[gulp] Starting 'reactify'...
[gulp] Finished 'reactify' after 2.92 ms
[gulp] Using file /app/staging/web/content/view/logon.jsx
[gulp] Using file /app/staging/web/content/view/components/rauth.jsx

Non-Static method cannot be referenced from a static context with methods and variables

You can either

1) Declare printMenu(), getUserchoice() and input as static

OR

2) If you want to design it better, move the logic from your main into a separate instance method. And then from the main create a new instance of your class and call your instance method(s)