Programs & Examples On #Synchronizationcontext

A .NET target to dispatch some work to. In winforms and WPF this is usually to the main UI thread.

WCF Service, the type provided as the service attribute values…could not be found

I had the same problem. Make sure you include assembly name in Factory property in your .svc file. Maybe you need to clean IIS cache if you had renamed project assembly name.

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

I had the same problem - my scenario was that I was referencing the new System.Web.Mvc.dll from a lib folder and I did not have "Copy Local" set to true. The application was then reverting back to the version in the GAC which didn't have the correct namespaces (Html, Ajax etc) in it and was giving me the run time error.

Is the buildSessionFactory() Configuration method deprecated in Hibernate

In Hibernate 4.2.2

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class Test {
    public static void main(String[] args) throws Exception
{
    Configuration configuration = new Configuration()
            .configure();

    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
            configuration.getProperties()).buildServiceRegistry();

    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    Session session = sessionFactory.openSession();

    Transaction transaction = session.beginTransaction();

    Users users = new Users();

    ... ...

    session.save(users);

    transaction.commit();

    session.close();

    sessionFactory.close();

    }
}

SQL Server Case Statement when IS NULL

You can use IIF (I think from SQL Server 2012)

SELECT IIF(B.[STAT] IS NULL, C.[EVENT DATE]+10, '-') AS [DATE]

htmlentities() vs. htmlspecialchars()

You should use htmlspecialchars($strText, ENT_QUOTES) when you just want your string to be XML and HTML safe:

For example, encode

  • & to &
  • " to "
  • < to &lt;
  • > to &gt;
  • ' to &#039;

However, if you also have additional characters that are Unicode or uncommon symbols in your text then you should use htmlentities() to ensure they show up properly in your HTML page.

Notes:

  • ' will only be encoded by htmlspecialchars() to &#039; if the ENT_QUOTES option is passed in. &#039; is safer to use then &apos; since older versions of Internet Explorer do not support the &apos; entity.
  • Technically, > does not need to be encoded as per the XML specification, but it is usually encoded too for consistency with the requirement of < being encoded.

C# 4.0: Convert pdf to byte[] and vice versa

using (FileStream fs = new FileStream("sample.pdf", FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[fs.Length];
                int numBytesToRead = (int)fs.Length;
                int numBytesRead = 0;
                while (numBytesToRead > 0)
                {
                    // Read may return anything from 0 to numBytesToRead.
                    int n = fs.Read(bytes, numBytesRead, numBytesToRead);

                    // Break when the end of the file is reached.
                    if (n == 0)
                    {
                        break;
                    }

                    numBytesRead += n;
                    numBytesToRead -= n;
                }
                numBytesToRead = bytes.Length;
}

Checking if an input field is required using jQuery

You don't need jQuery to do this. Here's an ES2015 solution:

// Get all input fields
const inputs = document.querySelectorAll('#register input');

// Get only the required ones
const requiredFields = Array.from(inputs).filter(input => input.required);

// Do your stuff with the required fields
requiredFields.forEach(field => /* do what you want */);

Or you could just use the :required selector:

Array.from(document.querySelectorAll('#register input:required'))
    .forEach(field => /* do what you want */);

Send JavaScript variable to PHP variable

It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.

In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue" to then end of the URL you are opening. :

http://www.somesite.com/send.php?variableName=someValue

or

http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue

This way, from PHP you can access this value as:

$phpVariableName = $_POST["variableName"];

for forms using POST method or:

$phpVariableName = $_GET["variableName"];

for forms using GET method or the append to url method I've mentioned above (querystring).

Converting String To Float in C#

Your thread's locale is set to one in which the decimal mark is "," instead of ".".

Try using this:

float.Parse("41.00027357629127", CultureInfo.InvariantCulture.NumberFormat);

Note, however, that a float cannot hold that many digits of precision. You would have to use double or Decimal to do so.

jQuery event handlers always execute in order they were bound - any way around this?

Here's a solution for jQuery 1.4.x (unfortunately, the accepted answer didn't work for jquery 1.4.1)

$.fn.bindFirst = function(name, fn) {
    // bind as you normally would
    // don't want to miss out on any jQuery magic
    this.bind(name, fn);

    // Thanks to a comment by @Martin, adding support for
    // namespaced events too.
    var handlers = this.data('events')[name.split('.')[0]];
    // take out the handler we just inserted from the end
    var copy = {1: null};

    var last = 0, lastValue = null;
    $.each(handlers, function(name, value) {
        //console.log(name + ": " + value);
        var isNumber = !isNaN(name);
        if(isNumber) {last = name; lastValue = value;};

        var key = isNumber ? (parseInt(name) + 1) : name;
        copy[key] = value;
    });
    copy[1] = lastValue;
    this.data('events')[name.split('.')[0]] = copy;
};

How to center the elements in ConstraintLayout

You can center a view as a percentage of the screen size.

This example uses 50% of width and height:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#FF0000"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHeight_percent=".5"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_percent=".5"></LinearLayout>

</android.support.constraint.ConstraintLayout>

This was done using ConstraintLayout version 1.1.3. Don't forget to add it to your dependencies in the gradle, and increase the version if there is a new version out there:

dependencies {
...
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}

enter image description here

Oracle insert if not exists statement

insert into OPT (email, campaign_id) 
select '[email protected]',100
from dual
where not exists(select * 
                 from OPT 
                 where (email ='[email protected]' and campaign_id =100));

How do I convert an interval into a number of hours with postgres?

Probably the easiest way is:

SELECT EXTRACT(epoch FROM my_interval)/3600

shorthand If Statements: C#

Use the ternary operator

direction == 1 ? dosomething () : dosomethingelse ();

Are the days of passing const std::string & as a parameter over?

Are the days of passing const std::string & as a parameter over?

No. Many people take this advice (including Dave Abrahams) beyond the domain it applies to, and simplify it to apply to all std::string parameters -- Always passing std::string by value is not a "best practice" for any and all arbitrary parameters and applications because the optimizations these talks/articles focus on apply only to a restricted set of cases.

If you're returning a value, mutating the parameter, or taking the value, then passing by value could save expensive copying and offer syntactical convenience.

As ever, passing by const reference saves much copying when you don't need a copy.

Now to the specific example:

However inval is still quite a lot larger than the size of a reference (which is usually implemented as a pointer). This is because a std::string has various components including a pointer into the heap and a member char[] for short string optimization. So it seems to me that passing by reference is still a good idea. Can anyone explain why Herb might have said this?

If stack size is a concern (and assuming this is not inlined/optimized), return_val + inval > return_val -- IOW, peak stack usage can be reduced by passing by value here (note: oversimplification of ABIs). Meanwhile, passing by const reference can disable the optimizations. The primary reason here is not to avoid stack growth, but to ensure the optimization can be performed where it is applicable.

The days of passing by const reference aren't over -- the rules just more complicated than they once were. If performance is important, you'll be wise to consider how you pass these types, based on the details you use in your implementations.

Update Row if it Exists Else Insert Logic with Entity Framework

Insert else update both

public void InsertUpdateData()
{
//Here TestEntities is the class which is given from "Save entity connection setting in web.config"
TestEntities context = new TestEntities();

var query = from data in context.Employee
            orderby data.name
            select data;

foreach (Employee details in query)
{
    if (details.id == 1)
    {
        //Assign the new values to name whose id is 1
        details.name = "Sanjay";
        details. Surname="Desai";
        details.address=" Desiwadi";
    }
    else if(query==null)
    {
        details.name="Sharad";
        details.surname=" Chougale ";
        details.address=" Gargoti";
    }
}

//Save the changes back to database.
context.SaveChanges();
}

Extracting text OpenCV

Here is an alternative approach that I used to detect the text blocks:

  1. Converted the image to grayscale
  2. Applied threshold (simple binary threshold, with a handpicked value of 150 as the threshold value)
  3. Applied dilation to thicken lines in image, leading to more compact objects and less white space fragments. Used a high value for number of iterations, so dilation is very heavy (13 iterations, also handpicked for optimal results).
  4. Identified contours of objects in resulted image using opencv findContours function.
  5. Drew a bounding box (rectangle) circumscribing each contoured object - each of them frames a block of text.
  6. Optionally discarded areas that are unlikely to be the object you are searching for (e.g. text blocks) given their size, as the algorithm above can also find intersecting or nested objects (like the entire top area for the first card) some of which could be uninteresting for your purposes.

Below is the code written in python with pyopencv, it should easy to port to C++.

import cv2

image = cv2.imread("card.png")
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # grayscale
_,thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY_INV) # threshold
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
dilated = cv2.dilate(thresh,kernel,iterations = 13) # dilate
_, contours, hierarchy = cv2.findContours(dilated,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) # get contours

# for each contour found, draw a rectangle around it on original image
for contour in contours:
    # get rectangle bounding contour
    [x,y,w,h] = cv2.boundingRect(contour)

    # discard areas that are too large
    if h>300 and w>300:
        continue

    # discard areas that are too small
    if h<40 or w<40:
        continue

    # draw rectangle around contour on original image
    cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,255),2)

# write original image with added contours to disk  
cv2.imwrite("contoured.jpg", image) 

The original image is the first image in your post.

After preprocessing (grayscale, threshold and dilate - so after step 3) the image looked like this:

Dilated image

Below is the resulted image ("contoured.jpg" in the last line); the final bounding boxes for the objects in the image look like this:

enter image description here

You can see the text block on the left is detected as a separate block, delimited from its surroundings.

Using the same script with the same parameters (except for thresholding type that was changed for the second image like described below), here are the results for the other 2 cards:

enter image description here

enter image description here

Tuning the parameters

The parameters (threshold value, dilation parameters) were optimized for this image and this task (finding text blocks) and can be adjusted, if needed, for other cards images or other types of objects to be found.

For thresholding (step 2), I used a black threshold. For images where text is lighter than the background, such as the second image in your post, a white threshold should be used, so replace thesholding type with cv2.THRESH_BINARY). For the second image I also used a slightly higher value for the threshold (180). Varying the parameters for the threshold value and the number of iterations for dilation will result in different degrees of sensitivity in delimiting objects in the image.

Finding other object types:

For example, decreasing the dilation to 5 iterations in the first image gives us a more fine delimitation of objects in the image, roughly finding all words in the image (rather than text blocks):

enter image description here

Knowing the rough size of a word, here I discarded areas that were too small (below 20 pixels width or height) or too large (above 100 pixels width or height) to ignore objects that are unlikely to be words, to get the results in the above image.

svn cleanup: sqlite: database disk image is malformed

Maybe, could be a solution:

  1. right mouse click over project
  2. team -> disconnect
  3. Select: Also delete ...

Now, re-connect again:

  1. right mouse click over project
  2. team -> Share project
  3. select your repositorie: mine SVN ( other case: git, etc)
  4. select your repositorie folder

Note:

On my case, I did a backup of my files. ( safe ur back :P )

Edit:

I am talking about SVN plugin on Eclipse :)

LIKE operator in LINQ

In native LINQ you may use combination of Contains/StartsWith/EndsWith or RegExp.

In LINQ2SQL use method SqlMethods.Like()

    from i in db.myTable
    where SqlMethods.Like(i.field, "tra%ata")
    select i

add Assembly: System.Data.Linq (in System.Data.Linq.dll) to use this feature.

How to convert decimal to hexadecimal in JavaScript

Constrained/padded to a set number of characters:

function decimalToHex(decimal, chars) {
    return (decimal + Math.pow(16, chars)).toString(16).slice(-chars).toUpperCase();
}

Difference between the Apache HTTP Server and Apache Tomcat?

Well, Apache is HTTP webserver, where as Tomcat is also webserver for Servlets and JSP. Moreover Apache is preferred over Apache Tomcat in real time

How to include css files in Vue 2

As you can see, the import command did work but is showing errors because it tried to locate the resources in vendor.css and couldn't find them

You should also upload your project structure and ensure that there aren't any path issues. Also, you could include the css file in the index.html or the Component template and webpack loader would extract it when built

How can I add reflection to a C++ application?

There are two kinds of reflection swimming around.

  1. Inspection by iterating over members of a type, enumerating its methods and so on.

    This is not possible with C++.
  2. Inspection by checking whether a class-type (class, struct, union) has a method or nested type, is derived from another particular type.

    This kind of thing is possible with C++ using template-tricks. Use boost::type_traits for many things (like checking whether a type is integral). For checking for the existance of a member function, use Is it possible to write a template to check for a function's existence? . For checking whether a certain nested type exists, use plain SFINAE .

If you are rather looking for ways to accomplish 1), like looking how many methods a class has, or like getting the string representation of a class id, then i'm afraid there is no Standard C++ way of doing this. You have to use either

  • A Meta Compiler like the Qt Meta Object Compiler which translates your code adding additional meta informations.
  • A Framework constisting of macros that allow you to add the required meta-informations. You would need to tell the framework all methods, the class-names, base-classes and everything it needs.

C++ is made with speed in mind. If you want high-level inspection, like C# or Java has, then I'm afraid i have to tell you there is no way without some effort.

Is there a method for String conversion to Title Case?

Apache Commons StringUtils.capitalize() or Commons Text WordUtils.capitalize()

e.g: WordUtils.capitalize("i am FINE") = "I Am FINE" from WordUtils doc

sql primary key and index

primary keys are automatically indexed

you can create additional indices using the pk depending on your usage

  • index zip_code, id may be helpful if you often select by zip_code and id

Using BigDecimal to work with currencies

Use BigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP) when you want to round up to the 2 decimal points for cents. Be aware of rounding off error when you do calculations though. You need to be consistent when you will be doing the rounding of money value. Either do the rounding right at the end just once after all calculations are done, or apply rounding to each value before doing any calculations. Which one to use would depend on your business requirement, but generally, I think doing rounding right at the end seems to make a better sense to me.

Use a String when you construct BigDecimal for money value. If you use double, it will have a trailing floating point values at the end. This is due to computer architecture regarding how double/float values are represented in binary format.

Disable/turn off inherited CSS3 transitions

Another way to remove all transitions is with the unset keyword:

a.tags {
    transition: unset;
}

In the case of transition, unset is equivalent to initial, since transition is not an inherited property:

a.tags {
    transition: initial;
}

A reader who knows about unset and initial can tell that these solutions are correct immediately, without having to think about the specific syntax of transition.

Accessing Google Spreadsheets with C# using Google Data API

http://code.google.com/apis/gdata/articles/dotnet_client_lib.html

This should get you started. I haven't played with it lately but I downloaded a very old version a while back and it seemed pretty solid. This one is updated to Visual Studio 2008 as well so check out the docs!

Split string, convert ToList<int>() in one line

You can use new C# 6.0 Language Features:

  • replace delegate (s) => { return Convert.ToInt32(s); } with corresponding method group Convert.ToInt32
  • replace redundant constructor call: new Converter<string, int>(Convert.ToInt32) with: Convert.ToInt32

The result will be:

var intList = new List<int>(Array.ConvertAll(sNumbers.Split(','), Convert.ToInt32));

How to concatenate two strings in SQL Server 2005

so if you have a table with a row like:

firstname lastname
Bill      smith

you can do something like

select firstname + ' ' + lastname from thetable

and you will get "Bill Smith"

How do you keep parents of floated elements from collapsing?

Another possible solution which I think is more semantically correct is to change the floated inner elements to be 'display: inline'. This example and what I was working on when I came across this page both use floated divs in much exactly the same way that a span would be used. Instead of using divs, switch to span, or if you are using another element which is by default 'display: block' instead of 'display: inline' then change it to be 'display: inline'. I believe this is the 100% semantically correct solution.

Solution 1, floating the parent, is essentially to change the entire document to be floated.

Solution 2, setting an explicit height, is like drawing a box and saying I want to put a picture here, i.e. use this if you are doing an img tag.

Solution 3, adding a spacer to clear float, is like adding an extra line below your content and will mess with surrounding elements too. If you use this approach you probably want to set the div to be height: 0px.

Solution 4, overflow: auto, is acknowledging that you don't know how to lay out the document and you are admitting that you don't know what to do.

CSS: center element within a <div> element

text-align:center; on the parent div Should do the trick

Read .doc file with python

You can use python-docx2txt library to read text from Microsoft Word documents. It is an improvement over python-docx library as it can, in addition, extract text from links, headers and footers. It can even extract images.

You can install it by running: pip install docx2txt.

Let's download and read the first Microsoft document on here:

import docx2txt
my_text = docx2txt.process("test.docx")
print(my_text)

Here is a screenshot of the Terminal output the above code:

enter image description here

EDIT:

This does NOT work for .doc files. The only reason I am keep this answer is that it seems there are people who find it useful for .docx files.

How to remove symbols from a string with Python?

Sometimes it takes longer to figure out the regex than to just write it out in python:

import string
s = "how much for the maple syrup? $20.99? That's ricidulous!!!"
for char in string.punctuation:
    s = s.replace(char, ' ')

If you need other characters you can change it to use a white-list or extend your black-list.

Sample white-list:

whitelist = string.letters + string.digits + ' '
new_s = ''
for char in s:
    if char in whitelist:
        new_s += char
    else:
        new_s += ' '

Sample white-list using a generator-expression:

whitelist = string.letters + string.digits + ' '
new_s = ''.join(c for c in s if c in whitelist)

Detecting when user scrolls to bottom of div with jQuery

Guys this is the solution to the zoom issue, it works with all zoom levels, in case you need it:

if ( Math.abs(elem.offset().top) + elem.height() + elem.offset().top >= elem.outerHeight() ) {
                    console.log("bottom");
                    // We're at the bottom!
                }
            });
        }

How do I set a Windows scheduled task to run in the background?

As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.


It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.

enter image description here

enter image description here

enter image description here

Python: How to get stdout after running os.system?

I had to use os.system, since subprocess was giving me a memory error for larger tasks. Reference for this problem here. So, in order to get the output of the os.system command I used this workaround:

import os

batcmd = 'dir'
result_code = os.system(batcmd + ' > output.txt')
if os.path.exists('output.txt'):
    fp = open('output.txt', "r")
    output = fp.read()
    fp.close()
    os.remove('output.txt')
    print(output)

npm install errors with Error: ENOENT, chmod

Tried nearly everything then finally this:

Simply remove node_modules then run 'npm install' again

Subprocess changing directory

just use os.chdir
Example:

>>> import os
>>> import subprocess
>>> # Lets Just Say WE want To List The User Folders
>>> os.chdir("/home/")
>>> subprocess.run("ls")
user1 user2 user3 user4

JavaScript: filter() for Objects

I use this when I need it:

const filterObject = (obj, condition) => {
    const filteredObj = {};
    Object.keys(obj).map(key => {
      if (condition(key)) {
        dataFiltered[key] = obj[key];
      }
    });
  return filteredObj;
}

Why are Python lambdas useful?

The two-line summary:

  1. Closures: Very useful. Learn them, use them, love them.
  2. Python's lambda keyword: unnecessary, occasionally useful. If you find yourself doing anything remotely complex with it, put it away and define a real function.

Relative frequencies / proportions with dplyr

Here is a general function implementing Henrik's solution on dplyr 0.7.1.

freq_table <- function(x, 
                       group_var, 
                       prop_var) {
  group_var <- enquo(group_var)
  prop_var  <- enquo(prop_var)
  x %>% 
    group_by(!!group_var, !!prop_var) %>% 
    summarise(n = n()) %>% 
    mutate(freq = n /sum(n)) %>% 
    ungroup
}

Add to python path mac os x

Mathew's answer works for the terminal python shell, but it didn't work for IDLE shell in my case because many versions of python existed before I replaced them all with Python2.7.7. How I solved the problem with IDLE.

  1. In terminal, cd /Applications/Python\ 2.7/IDLE.app/Contents/Resources/
  2. then sudo nano idlemain.py, enter password if required.
  3. after os.chdir(os.path.expanduser('~/Documents')) this line, I added sys.path.append("/Users/admin/Downloads....") NOTE: replace contents of the quotes with the directory where python module to be added
  4. to save the change, ctrl+x and enter Now open idle and try to import the python module, no error for me!!!

How to open every file in a folder

You can actually just use os module to do both:

  1. list all files in a folder
  2. sort files by file type, file name etc.

Here's a simple example:

import os #os module imported here
location = os.getcwd() # get present working directory location here
counter = 0 #keep a count of all files found
csvfiles = [] #list to store all csv files found at location
filebeginwithhello = [] # list to keep all files that begin with 'hello'
otherfiles = [] #list to keep any other file that do not match the criteria

for file in os.listdir(location):
    try:
        if file.endswith(".csv"):
            print "csv file found:\t", file
            csvfiles.append(str(file))
            counter = counter+1

        elif file.startswith("hello") and file.endswith(".csv"): #because some files may start with hello and also be a csv file
            print "csv file found:\t", file
            csvfiles.append(str(file))
            counter = counter+1

        elif file.startswith("hello"):
            print "hello files found: \t", file
            filebeginwithhello.append(file)
            counter = counter+1

        else:
            otherfiles.append(file)
            counter = counter+1
    except Exception as e:
        raise e
        print "No files found here!"

print "Total files found:\t", counter

Now you have not only listed all the files in a folder but also have them (optionally) sorted by starting name, file type and others. Just now iterate over each list and do your stuff.

"Expected an indented block" error?

I also experienced that for example:

This code doesnt work and get the intended block error.

class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()

def __unicode__(self):
return self.title

However, when i press tab before typing return self.title statement, the code works.

class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()

def __unicode__(self):
    return self.title

Hope, this will help others.

How do you change library location in R?

I've used this successfully inside R script:

library("reshape2",lib.loc="/path/to/R-packages/")

useful if for whatever reason libraries are in more than one place.

Could not find a version that satisfies the requirement tensorflow

I installed it successfully by pip install https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.8.0-py3-none-any.whl

Passing data between view controllers

I am currently contributing to an open source solution to this problem through a project called MCViewFactory, which may be found here:

Manticore iOS View Factory

The idea is imitate Android's intent paradigm, using a global factory to manage which view you are looking at and using "intents" to switch and pass data between views. All the documentation is on the GitHub page, but here are some highlights:

You setup all your views in .XIB files and register them in the app delegate, while initializing the factory.

// Register activities

MCViewFactory *factory = [MCViewFactory sharedFactory];

// The following two lines are optional.
[factory registerView:@"YourSectionViewController"];

Now, in your view controller (VC), anytime you want to move to a new VC and pass data, you create a new intent and add data to its dictionary (savedInstanceState). Then, just set the current intent of factory:

MCIntent* intent = [MCIntent intentWithSectionName:@"YourSectionViewController"];
[intent setAnimationStyle:UIViewAnimationOptionTransitionFlipFromLeft];
[[intent savedInstanceState] setObject:@"someValue" forKey:@"yourKey"];
[[intent savedInstanceState] setObject:@"anotherValue" forKey:@"anotherKey"];
// ...
[[MCViewModel sharedModel] setCurrentSection:intent];

All of your views that conform to this need to be subclasses of MCViewController, which allow you to override the new onResume: method, allowing you access to the data you've passed in.

-(void)onResume:(MCIntent *)intent {
    NSObject* someValue = [intent.savedInstanceState objectForKey:@"yourKey"];
    NSObject* anotherValue = [intent.savedInstanceState objectForKey:@"anotherKey"];

    // ...

    // Ensure the following line is called, especially for MCSectionViewController
    [super onResume:intent];
}

isPrime Function for Python Language

Every code you write should be efficient.For a beginner like you the easiest way is to check the divisibility of the number 'n' from 2 to (n-1). This takes a lot of time when you consider very big numbers. The square root method helps us make the code faster by less number of comparisons. Read about complexities in Design and Analysis of Algorithms.

Change one value based on another value in pandas

This question might still be visited often enough that it's worth offering an addendum to Mr Kassies' answer. The dict built-in class can be sub-classed so that a default is returned for 'missing' keys. This mechanism works well for pandas. But see below.

In this way it's possible to avoid key errors.

>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> class SurnameMap(dict):
...     def __missing__(self, key):
...         return ''
...     
>>> surnamemap = SurnameMap()
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap[x])
>>> df
    ID  Surname
0  101  Mohanty
1  201         
2  301    Drake
3  401         

The same thing can be done more simply in the following way. The use of the 'default' argument for the get method of a dict object makes it unnecessary to subclass a dict.

>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> surnamemap = {}
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap.get(x, ''))
>>> df
    ID  Surname
0  101  Mohanty
1  201         
2  301    Drake
3  401         

How can I correctly format currency using jquery?

Expanding upon Melu's answer you can do this to functionalize the code and handle negative amounts.

Sample Output:
$5.23
-$5.23

function formatCurrency(total) {
    var neg = false;
    if(total < 0) {
        neg = true;
        total = Math.abs(total);
    }
    return (neg ? "-$" : '$') + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
}

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

Normally this error occurs when you invoke java by supplying the wrong arguments/options. In this case it should be the version option.

java -version

So to double check you can always do java -help, and see if the option exists. In this case, there is no option such as v.

How to use PHP's password_hash to hash and verify passwords

Using password_hash is the recommended way to store passwords. Don't separate them to DB and files.

Let's say we have the following input:

$password = $_POST['password'];

You first hash the password by doing this:

$hashed_password = password_hash($password, PASSWORD_DEFAULT);

Then see the output:

var_dump($hashed_password);

As you can see it's hashed. (I assume you did those steps).

Now you store this hashed password in your database, ensuring your password column is large enough to hold the hashed value (at least 60 characters or longer). When a user asks to log them in, you check the password input with this hash value in the database, by doing this:

// Query the database for username and password
// ...

if(password_verify($password, $hashed_password)) {
    // If the password inputs matched the hashed password in the database
    // Do something, you know... log them in.
} 

// Else, Redirect them back to the login page.

Official Reference

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

I had the same problem when I was trying to move the android studio to another Drive as it was taking a lot of space in my C(Windows drive) Drive, Here's what fixed my problem:-

  1. Copy the C:\Users\ #YourUserName\ .android folder to another drive,
  2. Go to start environment variable make a new variable named ANDROID_SDK_HOME and add the path of the new location like mine is F:\Android AVD( don't add .android to it )
  3. Then add ANDROID_SDK_HOME to the existing Path variable.
  4. Open android studio, go to configure --> AVD manager and you'll see that you've successfully moved to a new location.

How do I block comment in Jupyter notebook?

After searching for a while I have found a solution to comment on an AZERTY mac. The shortcut is Ctrl +/= key

How to scale a BufferedImage

If you do not mind using an external library, Thumbnailator can perform scaling of BufferedImages.

Thumbnailator will take care of handling the Java 2D processing (such as using Graphics2D and setting appropriate rendering hints) so that a simple fluent API call can be used to resize images:

BufferedImage image = Thumbnails.of(originalImage).scale(2.0).asBufferedImage();

Although Thumbnailator, as its name implies, is geared toward shrinking images, it will do a decent job enlarging images as well, using bilinear interpolation in its default resizer implementation.


Disclaimer: I am the maintainer of the Thumbnailator library.

The default XML namespace of the project must be the MSBuild XML namespace

If getting this error trying to build .Net Core 2.0 app on VSTS then ensure your build definition is using the Hosted VS2017 Agent queue.

RESTful URL design for search

I use two approaches to implement searches.

1) Simplest case, to query associated elements, and for navigation.

    /cars?q.garage.id.eq=1

This means, query cars that have garage ID equal to 1.

It is also possible to create more complex searches:

    /cars?q.garage.street.eq=FirstStreet&q.color.ne=red&offset=300&max=100

Cars in all garages in FirstStreet that are not red (3rd page, 100 elements per page).

2) Complex queries are considered as regular resources that are created and can be recovered.

    POST /searches  => Create
    GET  /searches/1  => Recover search
    GET  /searches/1?offset=300&max=100  => pagination in search

The POST body for search creation is as follows:

    {  
       "$class":"test.Car",
       "$q":{
          "$eq" : { "color" : "red" },
          "garage" : {
             "$ne" : { "street" : "FirstStreet" }
          }
       }
    }

It is based in Grails (criteria DSL): http://grails.org/doc/2.4.3/ref/Domain%20Classes/createCriteria.html

Max length UITextField

If you want to overwrite the last letter:

let maxLength = 10

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if range.location > maxLength - 1 {
        textField.text?.removeLast()
    }

    return true
}

The identity used to sign the executable is no longer valid

These were the reasons I had this error:

The App ID didn't have my iOS Developer Certificate checked (I'm a member of an Enterprise program) and I had 2 provisioning profiles with the same App ID in my Mac. I deleted one.

Hopefully this helps someone.

Get environment value in controller

It's a better idea to put your configuration variables in a configuration file.

In your case, I would suggest putting your variables in config/mail.php like:

'imap_hostname' => env('IMAP_HOSTNAME_TEST', 'imap.gmail.com')

And refer to them by

config('mail.imap_hostname')

It first tries to get the configuration variable value in the .env file and if it couldn't find the variable value in the .env file, it will get the variable value from file config/mail.php.

Correct format specifier for double in printf

%Lf (note the capital L) is the format specifier for long doubles.

For plain doubles, either %e, %E, %f, %g or %G will do.

What is the Windows equivalent of the diff command?

Another alternative is to download and install git from here. Then, add the path to Git\bin\ to your PATH variable. This will give you not only diff, but also many other linux commands that you can use from the windows command line.

You can set the PATH variable by right clicking on Computer and selecting Properties. Then you can click on Advanced System Settings on the left side of the screen. In the pop up, click Environment Variables and then either add or update the PATH variable in your user variables with Git\bin\

Git diff documentation

Differences between strong and weak in Objective-C

A dummy answer :-

I think explanation is given in above answer, so i am just gonna tell you where to use STRONG and where to use WEAK :

Use of Weak :- 1. Delegates 2. Outlets 3. Subviews 4. Controls, etc.

Use of Strong :- Remaining everywhere which is not included in WEAK.

Git fetch remote branch

git fetch --all & git checkout <branch name>

Is there a 'foreach' function in Python 3?

This does the foreach in python 3

test = [0,1,2,3,4,5,6,7,8,"test"]

for fetch in test:
    print(fetch)

How to find the width of a div using vanilla JavaScript?

The correct way of getting computed style is waiting till page is rendered. It can be done in the following manner. Pay attention to timeout on getting auto values.

function getStyleInfo() {
    setTimeout(function() {
        const style = window.getComputedStyle(document.getElementById('__root__'));
        if (style.height == 'auto') {
            getStyleInfo();
        }
        // IF we got here we can do actual business logic staff
        console.log(style.height, style.width);
    }, 100);
};

window.onload=function() { getStyleInfo(); };

If you use just

window.onload=function() {
    var computedStyle = window.getComputedStyle(document.getElementById('__root__'));
}

you can get auto values for width and height because browsers does not render till full load is performed.

Shell script to capture Process ID and kill it if exist

A lot of *NIX systems also have either or both pkill(1) and killall(1) which, allows you to kill processes by name. Using them, you can avoid the whole parsing ps problem.

check if "it's a number" function in Oracle

Function for mobile number of length 10 digits and starting from 9,8,7 using regexp

create or replace FUNCTION VALIDATE_MOBILE_NUMBER
(   
   "MOBILE_NUMBER" IN varchar2
)
RETURN varchar2
IS
  v_result varchar2(10);

BEGIN
    CASE
    WHEN length(MOBILE_NUMBER) = 10 
    AND MOBILE_NUMBER IS NOT NULL
    AND REGEXP_LIKE(MOBILE_NUMBER, '^[0-9]+$')
    AND MOBILE_NUMBER Like '9%' OR MOBILE_NUMBER Like '8%' OR MOBILE_NUMBER Like '7%'
    then 
    v_result := 'valid';
    RETURN v_result;
      else 
      v_result := 'invalid';
       RETURN v_result;
       end case;
    END;

Printing pointers in C

You have used:

char s[] = "asd";

Here s actually points to the bytes "asd". The address of s, would also point to this location.

If you used:

char *s = "asd";

the value of s and &s would be different, as s would actually be a pointer to the bytes "asd".

You used:

char s[] = "asd";
char **p = &s;

Here s points to the bytes "asd". p is a pointer to a pointer to characters, and has been set to a the address of characters. In other words you have too many indirections in p. If you used char *s = "asd", you could use this additional indirection.

How to parse JSON without JSON.NET library?

You can use the classes found in the System.Json Namespace which were added in .NET 4.5. You need to add a reference to the System.Runtime.Serialization assembly

The JsonValue.Parse() Method parses JSON text and returns a JsonValue:

JsonValue value = JsonValue.Parse(@"{ ""name"":""Prince Charming"", ...");

If you pass a string with a JSON object, you should be able to cast the value to a JsonObject:

using System.Json;


JsonObject result = value as JsonObject;

Console.WriteLine("Name .... {0}", (string)result["name"]);
Console.WriteLine("Artist .. {0}", (string)result["artist"]);
Console.WriteLine("Genre ... {0}", (string)result["genre"]);
Console.WriteLine("Album ... {0}", (string)result["album"]);

The classes are quite similar to those found in the System.Xml.Linq Namespace.

Number of elements in a javascript object

AFAIK, there is no way to do this reliably, unless you switch to an array. Which honestly, doesn't seem strange - it's seems pretty straight forward to me that arrays are countable, and objects aren't.

Probably the closest you'll get is something like this

// Monkey patching on purpose to make a point
Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this ) i++;
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 3

But this creates problems, or at least questions. All user-created properties are counted, including the _length function itself! And while in this simple example you could avoid it by just using a normal function, that doesn't mean you can stop other scripts from doing this. so what do you do? Ignore function properties?

Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this )
  {
      if ( 'function' == typeof this[p] ) continue;
      i++;
  }
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 2

In the end, I think you should probably ditch the idea of making your objects countable and figure out another way to do whatever it is you're doing.

How does HttpContext.Current.User.Identity.Name know which usernames exist?

For windows authentication

select your project.

Press F4

Disable "Anonymous Authentication" and enable "Windows Authentication"

enter image description here

Add 2 hours to current time in MySQL?

The DATE_ADD() function will do the trick. (You can also use the ADDTIME() function if you're running at least v4.1.1.)

For your query, this would be:

SELECT * 
FROM courses 
WHERE DATE_ADD(now(), INTERVAL 2 HOUR) > start_time

Or,

SELECT * 
FROM courses 
WHERE ADDTIME(now(), '02:00:00') > start_time

IndexError: list index out of range and python

In Python, indexing starts at 0. Therefore, if you have a list with 53 items, list[52] will be the last item in the list.

Error in Swift class: Property not initialized at super.init call

Sorry for ugly formatting. Just put a question character after declaration and everything will be ok. A question tells the compiler that the value is optional.

class Square: Shape {
    var sideLength: Double?   // <=== like this ..

    init(sideLength:Double, name:String) {
        super.init(name:name) // Error here
        self.sideLength = sideLength
        numberOfSides = 4
    }
    func area () -> Double {
        return sideLength * sideLength
    }
}

Edit1:

There is a better way to skip this error. According to jmaschad's comment there is no reason to use optional in your case cause optionals are not comfortable in use and You always have to check if optional is not nil before accessing it. So all you have to do is to initialize member after declaration:

class Square: Shape {
    var sideLength: Double=Double()   

    init(sideLength:Double, name:String) {
        super.init(name:name)
        self.sideLength = sideLength
        numberOfSides = 4
    }
    func area () -> Double {
        return sideLength * sideLength
    }
}

Edit2:

After two minuses got on this answer I found even better way. If you want class member to be initialized in your constructor you must assign initial value to it inside contructor and before super.init() call. Like this:

class Square: Shape {
    var sideLength: Double  

    init(sideLength:Double, name:String) {
        self.sideLength = sideLength   // <= before super.init call..
        super.init(name:name)
        numberOfSides = 4
    }
    func area () -> Double {
        return sideLength * sideLength
    }
}

Good luck in learning Swift.

Undefined symbols for architecture x86_64 on Xcode 6.1

Same error when I copied/pasted a class and forgot to rename it in .m file.

GROUP BY + CASE statement

Aliases can be used only if they were introduced in the preceding step. So aliases in the SELECT clause can be used in the ORDER BY but not the GROUP BY clause.

Reference: Microsoft T-SQL Documentation for further reading.

FROM
ON
JOIN
WHERE
GROUP BY
WITH CUBE or WITH ROLLUP
HAVING
SELECT
DISTINCT
ORDER BY
TOP

Hope this helps.

error: ORA-65096: invalid common user or role name in oracle

I just installed oracle11g

ORA-65096: invalid common user or role name in oracle

No, you have installed Oracle 12c. That error could only be on 12c, and cannot be on 11g.

Always check your database version up to 4 decimal places:

SELECT banner FROM v$version WHERE ROWNUM = 1;

Oracle 12c multitenant container database has:

  • a root container(CDB)
  • and/or zero, one or many pluggable databases(PDB).

You must have created the database as a container database. While, you are trying to create user in the container, i.e. CDB$ROOT, however, you should create the user in the PLUGGABLE database.

You are not supposed to create application-related objects in the container, the container holds the metadata for the pluggable databases. You should use the pluggable database for you general database operations. Else, do not create it as container, and not use multi-tenancy. However, 12cR2 onward you cannot create a non-container database anyway.

And most probably, the sample schemas might have been already installed, you just need to unlock them in the pluggable database.

For example, if you created pluggable database as pdborcl:

sqlplus SYS/password@PDBORCL AS SYSDBA

SQL> ALTER USER scott ACCOUNT UNLOCK IDENTIFIED BY tiger;

sqlplus scott/tiger@pdborcl

SQL> show user;
USER is "SCOTT"

To show the PDBs and connect to a pluggable database from root container:

SQL> show con_name

CON_NAME
------------------------------
CDB$ROOT

SQL> show pdbs

    CON_ID CON_NAME                       OPEN MODE  RESTRICTED
---------- ------------------------------ ---------- ----------
         2 PDB$SEED                       READ ONLY  NO
         3 ORCLPDB                        READ WRITE NO

SQL> alter session set container = ORCLPDB;

Session altered.

SQL> show con_name;

CON_NAME
------------------------------
ORCLPDB

I suggest read, Oracle 12c Post Installation Mandatory Steps


Note: Answers suggesting to use the _ORACLE_SCRIPT hidden parameter to set to true is dangerous in a production system and might also invalidate your support contract. Beware, without consulting Oracle support DO NOT use hidden parameters.

How to give credentials in a batch script that copies files to a network location?

You can also map the share to a local drive as follows:

net use X: "\\servername\share" /user:morgan password

Jackson and generic type reference

'JavaType' works !! I was trying to unmarshall (deserialize) a List in json String to ArrayList java Objects and was struggling to find a solution since days.
Below is the code that finally gave me solution. Code:

JsonMarshallerUnmarshaller<T> {
    T targetClass;

    public ArrayList<T> unmarshal(String jsonString) {
        ObjectMapper mapper = new ObjectMapper();

        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
        mapper.getDeserializationConfig()
            .withAnnotationIntrospector(introspector);

        mapper.getSerializationConfig()
            .withAnnotationIntrospector(introspector);
        JavaType type = mapper.getTypeFactory().
            constructCollectionType(
                ArrayList.class, 
                targetclass.getClass());

        try {
            Class c1 = this.targetclass.getClass();
            Class c2 = this.targetclass1.getClass();
            ArrayList<T> temp = (ArrayList<T>) 
                mapper.readValue(jsonString,  type);
            return temp ;
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null ;
    }  
}

How to change css property using javascript

You can use style property for this. For example, if you want to change border -

document.elm.style.border = "3px solid #FF0000";

similarly for color -

 document.getElementById("p2").style.color="blue";

Best thing is you define a class and do this -

document.getElementById("p2").className = "classname";

(Cross Browser artifacts must be considered accordingly).

Display UIViewController as Popup in iPhone

Modal Popups in Interface Builder (Storyboards)

Step 1

On the ViewController you want as your modal popup, make the background color of the root UIView clear. Set Clear Color on root view Tip: Do not use the root UIView as your popup. Add a new UIView that is smaller to be your popup.

Step 2

Create a Segue to the ViewController that has your popup. Select "Present Modally". Segue

Two Methods To Create Popup From Here

Method One - Using the Segue

Select the Segue and change Presentation to "Over Current Context": Over Current Context

Method Two - Using the View Controller

Select the ViewController Scene that is your popup. In Attributes Inspector, under View Controller section, set Presentation to "Over Current Context": ViewController

Either method will work. That should do it!

Finished Product

How to change the background-color of jumbrotron?

In the HTML file itself, modify the background-color of the jumbotron using the style attribute:
<div class="jumbotron" style="background-color:#CFD8DC;"></div>

What is the difference between a port and a socket?

A socket is a communication endpoint. A socket is not directly related to the TCP/IP protocol family, it can be used with any protocol your system supports. The C socket API expects you to first get a blank socket object from the system that you can then either bind to a local socket address (to directly retrieve incoming traffic for connection-less protocols or to accept incoming connection requests for connection-oriented protocols) or that you can connect to a remote socket address (for either kind of protocol). You can even do both if you want to control both, the local socket address a socket is bound to and the remote socket address a socket is connected to. For connection-less protocols connecting a socket is even optional but if you don't do that, you'll have to also pass the destination address with every packet you want to send over the socket as how else would the socket know where to send this data to? Advantage is that you can use a single socket to send packets to different socket addresses. Once you have your socket configured and maybe even connected, consider it to be a bi-directional communication pipe. You can use it to pass data to some destination and some destination can use it to pass data back to you. What you write to a socket is send out and what has been received is available for reading.

Ports on the other hand are something that only certain protocols of the TCP/IP protocol stack have. TCP and UDP packets have ports. A port is just a simple number. The combination of source port and destination port identify a communication channel between two hosts. E.g. you may have a server that shall be both, a simple HTTP server and a simple FTP server. If now a packet arrives for the address of that server, how would it know if that is a packet for the HTTP or the FTP server? Well, it will know so as the HTTP server will run on port 80 and the FTP server on port 21, so if the packet arrives with a destination port 80, it is for the HTTP server and not for the FTP server. Also the packet has a source port since without such a source port, a server could only have one connection to one IP address at a time. The source port makes it possible for a server to distinguish otherwise identical connections: they all have the same destination port, e.g. port 80, the same destination IP (the IP of the server), and the same source IP, as they all come from the same client, but as they have a different source ports, the server can distinguish them from each other. And when the server sends back replies, it will do so to the port the request came from, that way the client can also distinguish different replies it receives from the same server.

How to define a two-dimensional array?

A rewrite for easy reading:

# 2D array/ matrix

# 5 rows, 5 cols
rows_count = 5
cols_count = 5

# create
#     creation looks reverse
#     create an array of "cols_count" cols, for each of the "rows_count" rows
#        all elements are initialized to 0
two_d_array = [[0 for j in range(cols_count)] for i in range(rows_count)]

# index is from 0 to 4
#     for both rows & cols
#     since 5 rows, 5 cols

# use
two_d_array[0][0] = 1
print two_d_array[0][0]  # prints 1   # 1st row, 1st col (top-left element of matrix)

two_d_array[1][0] = 2
print two_d_array[1][0]  # prints 2   # 2nd row, 1st col

two_d_array[1][4] = 3
print two_d_array[1][4]  # prints 3   # 2nd row, last col

two_d_array[4][4] = 4
print two_d_array[4][4]  # prints 4   # last row, last col (right, bottom element of matrix)

jquery: animate scrollLeft

You'll want something like this:


$("#next").click(function(){
      var currentElement = currentElement.next();
      $('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
      return false;
   }); 
I believe this should work, it's adopted from a scrollTop function.

JavaScript variable assignments from tuples

This is not intended to be actually used in real life, just an interesting exercise. See Why is using the JavaScript eval function a bad idea? for details.

This is the closest you can get without resorting to vendor-specific extensions:

myArray = [1,2,3];
eval(set('a,b,c = myArray'));

Helper function:

function set(code) {
    var vars=code.split('=')[0].trim().split(',');
    var array=code.split('=')[1].trim();
    return 'var '+vars.map(function(x,i){return x+'='+array+'['+i+']'}).join(',');
}

Proof that it works in arbitrary scope:

(function(){
    myArray = [4,5,6];
    eval(set('x,y,z = myArray'));
    console.log(y);  // prints 5
})()

eval is not supported in Safari.

Capture iframe load complete event

Step 1: Add iframe in template.

<iframe id="uvIFrame" src="www.google.com"></iframe>

Step 2: Add load listener in Controller.

document.querySelector('iframe#uvIFrame').addEventListener('load', function () {
  $scope.loading = false;
  $scope.$apply();
});

How to create an empty array in PHP with predefined size?

You can't predefine a size of an array in php. A good way to acheive your goal is the following:

// Create a new array.
$array = array(); 

// Add an item while $i < yourWantedItemQuantity
for ($i = 0; $i < $number_of_items; $i++)
{
    array_push($array, $some_data);
    //or $array[] = $some_data; for single items.
}

Note that it is way faster to use array_fill() to fill an Array :

$array = array_fill(0,$number_of_items, $some_data);

If you want to verify if a value has been set at an index, you should use the following: array_key_exists("key", $array) or isset($array["key"])

See array_key_exists , isset and array_fill

What is the inclusive range of float and double in Java?

Binary floating-point numbers have interesting precision characteristics, since the value is stored as a binary integer raised to a binary power. When dealing with sub-integer values (that is, values between 0 and 1), negative powers of two "round off" very differently than negative powers of ten.

For example, the number 0.1 can be represented by 1 x 10-1, but there is no combination of base-2 exponent and mantissa that can precisely represent 0.1 -- the closest you get is 0.10000000000000001.

So if you have an application where you are working with values like 0.1 or 0.01 a great deal, but where small (less than 0.000000000000001%) errors cannot be tolerated, then binary floating-point numbers are not for you.

Conversely, if powers of ten are not "special" to your application (powers of ten are important in currency calculations, but not in, say, most applications of physics), then you are actually better off using binary floating-point, since it's usually at least an order of magnitude faster, and it is much more memory efficient.

The article from the Python documentation on floating point issues and limitations does an excellent job of explaining this issue in an easy to understand form. Wikipedia also has a good article on floating point that explains the math behind the representation.

self referential struct definition?

All previous answers are great , i just thought to give an insight on why a structure can't contain an instance of its own type (not a reference).

its very important to note that structures are 'value' types i.e they contain the actual value, so when you declare a structure the compiler has to decide how much memory to allocate to an instance of it, so it goes through all its members and adds up their memory to figure out the over all memory of the struct, but if the compiler found an instance of the same struct inside then this is a paradox (i.e in order to know how much memory struct A takes you have to decide how much memory struct A takes !).

But reference types are different, if a struct 'A' contains a 'reference' to an instance of its own type, although we don't know yet how much memory is allocated to it, we know how much memory is allocated to a memory address (i.e the reference).

HTH

Send attachments with PHP Mail()?

HTML Code:

<form enctype="multipart/form-data" method="POST" action=""> 
    <label>Your Name <input type="text" name="sender_name" /> </label> 
    <label>Your Email <input type="email" name="sender_email" /> </label> 
    <label>Your Contact Number <input type="tel" name="contactnumber" /> </label>
    <label>Subject <input type="text" name="subject" /> </label> 
    <label>Message <textarea name="description"></textarea> </label> 
    <label>Attachment <input type="file" name="attachment" /></label> 
    <label><input type="submit" name="button" value="Submit" /></label> 
</form> 

PHP Code:

<?php
if($_POST['button']){
{
    //Server Variables
    $server_name = "Your Name";
    $server_mail = "[email protected]";

    //Name Attributes of HTML FORM
    $sender_email = "sender_email";
    $sender_name = "sender_name";
    $contact = "contactnumber";
    $mail_subject = "subject";
    $input_file = "attachment";
    $message = "description";

    //Fetching HTML Values
    $sender_name = $_POST[$sender_name];
    $sender_mail = $_POST[$sender_email];
    $message = $_POST[$message];
    $contact= $_POST[$contact];
    $mail_subject = $_POST[$mail_subject];

    //Checking if File is uploaded
    if(isset($_FILES[$input_file])) 
    { 
        //Main Content
        $main_subject = "Subject seen on server's mail";
        $main_body = "Hello $server_name,<br><br> 
        $sender_name ,contacted you through your website and the details are as below: <br><br> 
        Name : $sender_name <br> 
        Contact Number : $contact <br> 
        Email : $sender_mail <br> 
        Subject : $mail_subject <br> 
        Message : $message.";

        //Reply Content
        $reply_subject = "Subject seen on sender's mail";
        $reply_body = "Hello $sender_name,<br> 
        \t Thank you for filling the contact form. We will revert back to you shortly.<br><br>
        This is an auto generated mail sent from our Mail Server.<br>
        Please do not reply to this mail.<br>
        Regards<br>
        $server_name";

//#############################DO NOT CHANGE ANYTHING BELOW THIS LINE#############################
        $filename= $_FILES[$input_file]['name'];
        $file = chunk_split(base64_encode(file_get_contents($_FILES[$input_file]['tmp_name'])));
        $uid = md5(uniqid(time()));
        //Sending mail to Server
        $retval = mail($server_mail, $main_subject, "--$uid\r\nContent-type:text/html; charset=iso-8859-1\r\nContent-Transfer-Encoding: 7bit\r\n\r\n $main_body \r\n\r\n--$uid\r\nContent-Type: application/octet-stream; name=\"$filename\"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\"$filename\"\r\n\r\n$file\r\n\r\n--$uid--", "From: $sender_name <$sender_mail>\r\nReply-To: $sender_mail\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$uid\"\r\n\r\n");
        //Sending mail to Sender
        $retval = mail($sender_mail, $reply_subject, $reply_body , "From: $server_name<$server_mail>\r\nMIME-Version: 1.0\r\nContent-type: text/html\r\n");
//#############################DO NOT CHANGE ANYTHING ABOVE THIS LINE#############################

        //Output
        if ($retval == true) {
            echo "Message sent successfully...";
            echo "<script>window.location.replace('index.html');</script>";
        } else {
            echo "Error<br>";
            echo "Message could not be sent...Try again later";
            echo "<script>window.location.replace('index.html');</script>";
        }
    }else{
        echo "Error<br>";
        echo "File Not Found";
    }
}else{
    echo "Error<br>";
    echo "Unauthorised Access";
}

how to install tensorflow on anaconda python 3.6

Please refer this link :

  • Go to https://www.anaconda.com/products/individual and click the “Download” -button
  • Download the Python 3.7 64-Bit (x86) Installer
  • Run the downloaded bash script (.sh) file to begin the installation. See here for more details.
  • -When prompted with the question “Do you wish the installer to prepend the Anaconda<2 or 3> install location to PATH in your /home//.bashrc ?”, answer “Yes”. If you enter “No”, you must manually add the path to Anaconda or conda will not work.

Select Windows or linked base command, In my case I have used Linux :

Create a new Anaconda virtual environment Open a new Terminal window

Type the following command: The above will create a new virtual environment with name tensorflow

conda create -n tensorflow pip python=3.8

 conda activate tensorflow

enter image description here

enter image description here

jQuery: Adding two attributes via the .attr(); method

Multiple Attribute

var tag = "tag name";
createNode(tag, target, attribute);

createNode: function(tag, target, attribute){
    var tag = jQuery("<" + tag + ">");
    jQuery.each(attribute, function(i,v){
        tag.attr(v);
    });
    target.append(tag);
    tag.appendTo(target);
}
var attribute = [
    {"data-level": "3"},
];

How do I clone a github project to run locally?

git clone git://github.com/ryanb/railscasts-episodes.git

Assembly Language - How to do Modulo?

An easy way to see what a modulus operator looks like on various architectures is to use the Godbolt Compiler Explorer.

https://godbolt.org/z/64zKGr

SPA best practices for authentication and session management

This question has been addressed, in a slightly different form, at length, here:

RESTful Authentication

But this addresses it from the server-side. Let's look at this from the client-side. Before we do that, though, there's an important prelude:

Javascript Crypto is Hopeless

Matasano's article on this is famous, but the lessons contained therein are pretty important:

https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/

To summarize:

  • A man-in-the-middle attack can trivially replace your crypto code with <script> function hash_algorithm(password){ lol_nope_send_it_to_me_instead(password); }</script>
  • A man-in-the-middle attack is trivial against a page that serves any resource over a non-SSL connection.
  • Once you have SSL, you're using real crypto anyways.

And to add a corollary of my own:

  • A successful XSS attack can result in an attacker executing code on your client's browser, even if you're using SSL - so even if you've got every hatch battened down, your browser crypto can still fail if your attacker finds a way to execute any javascript code on someone else's browser.

This renders a lot of RESTful authentication schemes impossible or silly if you're intending to use a JavaScript client. Let's look!

HTTP Basic Auth

First and foremost, HTTP Basic Auth. The simplest of schemes: simply pass a name and password with every request.

This, of course, absolutely requires SSL, because you're passing a Base64 (reversibly) encoded name and password with every request. Anybody listening on the line could extract username and password trivially. Most of the "Basic Auth is insecure" arguments come from a place of "Basic Auth over HTTP" which is an awful idea.

The browser provides baked-in HTTP Basic Auth support, but it is ugly as sin and you probably shouldn't use it for your app. The alternative, though, is to stash username and password in JavaScript.

This is the most RESTful solution. The server requires no knowledge of state whatsoever and authenticates every individual interaction with the user. Some REST enthusiasts (mostly strawmen) insist that maintaining any sort of state is heresy and will froth at the mouth if you think of any other authentication method. There are theoretical benefits to this sort of standards-compliance - it's supported by Apache out of the box - you could store your objects as files in folders protected by .htaccess files if your heart desired!

The problem? You are caching on the client-side a username and password. This gives evil.ru a better crack at it - even the most basic of XSS vulnerabilities could result in the client beaming his username and password to an evil server. You could try to alleviate this risk by hashing and salting the password, but remember: JavaScript Crypto is Hopeless. You could alleviate this risk by leaving it up to the Browser's Basic Auth support, but.. ugly as sin, as mentioned earlier.

HTTP Digest Auth

Is Digest authentication possible with jQuery?

A more "secure" auth, this is a request/response hash challenge. Except JavaScript Crypto is Hopeless, so it only works over SSL and you still have to cache the username and password on the client side, making it more complicated than HTTP Basic Auth but no more secure.

Query Authentication with Additional Signature Parameters.

Another more "secure" auth, where you encrypt your parameters with nonce and timing data (to protect against repeat and timing attacks) and send the. One of the best examples of this is the OAuth 1.0 protocol, which is, as far as I know, a pretty stonking way to implement authentication on a REST server.

http://tools.ietf.org/html/rfc5849

Oh, but there aren't any OAuth 1.0 clients for JavaScript. Why?

JavaScript Crypto is Hopeless, remember. JavaScript can't participate in OAuth 1.0 without SSL, and you still have to store the client's username and password locally - which puts this in the same category as Digest Auth - it's more complicated than HTTP Basic Auth but it's no more secure.

Token

The user sends a username and password, and in exchange gets a token that can be used to authenticate requests.

This is marginally more secure than HTTP Basic Auth, because as soon as the username/password transaction is complete you can discard the sensitive data. It's also less RESTful, as tokens constitute "state" and make the server implementation more complicated.

SSL Still

The rub though, is that you still have to send that initial username and password to get a token. Sensitive information still touches your compromisable JavaScript.

To protect your user's credentials, you still need to keep attackers out of your JavaScript, and you still need to send a username and password over the wire. SSL Required.

Token Expiry

It's common to enforce token policies like "hey, when this token has been around too long, discard it and make the user authenticate again." or "I'm pretty sure that the only IP address allowed to use this token is XXX.XXX.XXX.XXX". Many of these policies are pretty good ideas.

Firesheeping

However, using a token Without SSL is still vulnerable to an attack called 'sidejacking': http://codebutler.github.io/firesheep/

The attacker doesn't get your user's credentials, but they can still pretend to be your user, which can be pretty bad.

tl;dr: Sending unencrypted tokens over the wire means that attackers can easily nab those tokens and pretend to be your user. FireSheep is a program that makes this very easy.

A Separate, More Secure Zone

The larger the application that you're running, the harder it is to absolutely ensure that they won't be able to inject some code that changes how you process sensitive data. Do you absolutely trust your CDN? Your advertisers? Your own code base?

Common for credit card details and less common for username and password - some implementers keep 'sensitive data entry' on a separate page from the rest of their application, a page that can be tightly controlled and locked down as best as possible, preferably one that is difficult to phish users with.

Cookie (just means Token)

It is possible (and common) to put the authentication token in a cookie. This doesn't change any of the properties of auth with the token, it's more of a convenience thing. All of the previous arguments still apply.

Session (still just means Token)

Session Auth is just Token authentication, but with a few differences that make it seem like a slightly different thing:

  • Users start with an unauthenticated token.
  • The backend maintains a 'state' object that is tied to a user's token.
  • The token is provided in a cookie.
  • The application environment abstracts the details away from you.

Aside from that, though, it's no different from Token Auth, really.

This wanders even further from a RESTful implementation - with state objects you're going further and further down the path of plain ol' RPC on a stateful server.

OAuth 2.0

OAuth 2.0 looks at the problem of "How does Software A give Software B access to User X's data without Software B having access to User X's login credentials."

The implementation is very much just a standard way for a user to get a token, and then for a third party service to go "yep, this user and this token match, and you can get some of their data from us now."

Fundamentally, though, OAuth 2.0 is just a token protocol. It exhibits the same properties as other token protocols - you still need SSL to protect those tokens - it just changes up how those tokens are generated.

There are two ways that OAuth 2.0 can help you:

  • Providing Authentication/Information to Others
  • Getting Authentication/Information from Others

But when it comes down to it, you're just... using tokens.

Back to your question

So, the question that you're asking is "should I store my token in a cookie and have my environment's automatic session management take care of the details, or should I store my token in Javascript and handle those details myself?"

And the answer is: do whatever makes you happy.

The thing about automatic session management, though, is that there's a lot of magic happening behind the scenes for you. Often it's nicer to be in control of those details yourself.

I am 21 so SSL is yes

The other answer is: Use https for everything or brigands will steal your users' passwords and tokens.

How to add text at the end of each line in Vim?

ex mode is easiest:

:%s/$/,

: - enter command mode
% - for every line
s/ - substitute
$ - the end of the line
/ - and change it to
, - a comma

Backup a single table with its data from a database in sql server 2008

There are many ways you can take back of table.

  1. BCP (BULK COPY PROGRAM)
  2. Generate Table Script with data
  3. Make a copy of table using SELECT INTO, example here
  4. SAVE Table Data Directly in a Flat file
  5. Export Data using SSIS to any destination

Syntax for async arrow function

Immediately Invoked Async Arrow Function:

(async () => {
    console.log(await asyncFunction());
})();

Immediately Invoked Async Function Expression:

(async function () {
    console.log(await asyncFunction());
})();

Exact time measurement for performance testing

As others said, Stopwatch should be the right tool for this. There can be few improvements made to it though, see this thread specifically: Benchmarking small code samples in C#, can this implementation be improved?.

I have seen some useful tips by Thomas Maierhofer here

Basically his code looks like:

//prevent the JIT Compiler from optimizing Fkt calls away
long seed = Environment.TickCount;

//use the second Core/Processor for the test
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2);

//prevent "Normal" Processes from interrupting Threads
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;

//prevent "Normal" Threads from interrupting this thread
Thread.CurrentThread.Priority = ThreadPriority.Highest;

//warm up
method();

var stopwatch = new Stopwatch()
for (int i = 0; i < repetitions; i++)
{
    stopwatch.Reset();
    stopwatch.Start();
    for (int j = 0; j < iterations; j++)
        method();
    stopwatch.Stop();
    print stopwatch.Elapsed.TotalMilliseconds;
}

Another approach is to rely on Process.TotalProcessTime to measure how long the CPU has been kept busy running the very code/process, as shown here This can reflect more real scenario since no other process affects the measurement. It does something like:

 var start = Process.GetCurrentProcess().TotalProcessorTime;
 method();
 var stop = Process.GetCurrentProcess().TotalProcessorTime;
 print (end - begin).TotalMilliseconds;

A naked, detailed implementation of the samething can be found here.

I wrote a helper class to perform both in an easy to use manner:

public class Clock
{
    interface IStopwatch
    {
        bool IsRunning { get; }
        TimeSpan Elapsed { get; }

        void Start();
        void Stop();
        void Reset();
    }



    class TimeWatch : IStopwatch
    {
        Stopwatch stopwatch = new Stopwatch();

        public TimeSpan Elapsed
        {
            get { return stopwatch.Elapsed; }
        }

        public bool IsRunning
        {
            get { return stopwatch.IsRunning; }
        }



        public TimeWatch()
        {
            if (!Stopwatch.IsHighResolution)
                throw new NotSupportedException("Your hardware doesn't support high resolution counter");

            //prevent the JIT Compiler from optimizing Fkt calls away
            long seed = Environment.TickCount;

            //use the second Core/Processor for the test
            Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2);

            //prevent "Normal" Processes from interrupting Threads
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;

            //prevent "Normal" Threads from interrupting this thread
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
        }



        public void Start()
        {
            stopwatch.Start();
        }

        public void Stop()
        {
            stopwatch.Stop();
        }

        public void Reset()
        {
            stopwatch.Reset();
        }
    }



    class CpuWatch : IStopwatch
    {
        TimeSpan startTime;
        TimeSpan endTime;
        bool isRunning;



        public TimeSpan Elapsed
        {
            get
            {
                if (IsRunning)
                    throw new NotImplementedException("Getting elapsed span while watch is running is not implemented");

                return endTime - startTime;
            }
        }

        public bool IsRunning
        {
            get { return isRunning; }
        }



        public void Start()
        {
            startTime = Process.GetCurrentProcess().TotalProcessorTime;
            isRunning = true;
        }

        public void Stop()
        {
            endTime = Process.GetCurrentProcess().TotalProcessorTime;
            isRunning = false;
        }

        public void Reset()
        {
            startTime = TimeSpan.Zero;
            endTime = TimeSpan.Zero;
        }
    }



    public static void BenchmarkTime(Action action, int iterations = 10000)
    {
        Benchmark<TimeWatch>(action, iterations);
    }

    static void Benchmark<T>(Action action, int iterations) where T : IStopwatch, new()
    {
        //clean Garbage
        GC.Collect();

        //wait for the finalizer queue to empty
        GC.WaitForPendingFinalizers();

        //clean Garbage
        GC.Collect();

        //warm up
        action();

        var stopwatch = new T();
        var timings = new double[5];
        for (int i = 0; i < timings.Length; i++)
        {
            stopwatch.Reset();
            stopwatch.Start();
            for (int j = 0; j < iterations; j++)
                action();
            stopwatch.Stop();
            timings[i] = stopwatch.Elapsed.TotalMilliseconds;
            print timings[i];
        }
        print "normalized mean: " + timings.NormalizedMean().ToString();
    }

    public static void BenchmarkCpu(Action action, int iterations = 10000)
    {
        Benchmark<CpuWatch>(action, iterations);
    }
}

Just call

Clock.BenchmarkTime(() =>
{
    //code

}, 10000000);

or

Clock.BenchmarkCpu(() =>
{
    //code

}, 10000000);

The last part of the Clock is the tricky part. If you want to display the final timing, its up to you to choose what sort of timing you want. I wrote an extension method NormalizedMean which gives you the mean of the read timings discarding the noise. I mean I calculate the the deviation of each timing from the actual mean, and then I discard the values which was farer (only the slower ones) from the mean of deviation (called absolute deviation; note that its not the often heard standard deviation), and finally return the mean of remaining values. This means, for instance, if timed values are { 1, 2, 3, 2, 100 } (in ms or whatever), it discards 100, and returns the mean of { 1, 2, 3, 2 } which is 2. Or if timings are { 240, 220, 200, 220, 220, 270 }, it discards 270, and returns the mean of { 240, 220, 200, 220, 220 } which is 220.

public static double NormalizedMean(this ICollection<double> values)
{
    if (values.Count == 0)
        return double.NaN;

    var deviations = values.Deviations().ToArray();
    var meanDeviation = deviations.Sum(t => Math.Abs(t.Item2)) / values.Count;
    return deviations.Where(t => t.Item2 > 0 || Math.Abs(t.Item2) <= meanDeviation).Average(t => t.Item1);
}

public static IEnumerable<Tuple<double, double>> Deviations(this ICollection<double> values)
{
    if (values.Count == 0)
        yield break;

    var avg = values.Average();
    foreach (var d in values)
        yield return Tuple.Create(d, avg - d);
}

Python: Split a list into sub-lists based on index ranges

list1=['x','y','z','a','b','c','d','e','f','g']
find=raw_input("Enter string to be found")
l=list1.index(find)
list1a=[:l]
list1b=[l:]

Using set_facts and with_items together in Ansible

I was hunting around for an answer to this question. I found this helpful. The pattern wasn't apparent in the documentation for with_items.

https://github.com/ansible/ansible/issues/39389

- hosts: localhost
  connection: local
  gather_facts: no

  tasks:
    - name: set_fact
      set_fact:
        foo: "{{ foo }} + [ '{{ item }}' ]"
      with_items:
        - "one"
        - "two"
        - "three"
      vars:
        foo: []

    - name: Print the var
      debug:
        var: foo

How to determine a user's IP address in node

In your request object there is a property called connection, which is a net.Socket object. The net.Socket object has a property remoteAddress, therefore you should be able to get the IP with this call:

request.connection.remoteAddress

See documentation for http and net

EDIT

As @juand points out in the comments, the correct method to get the remote IP, if the server is behind a proxy, is request.headers['x-forwarded-for']

How to use HTTP GET in PowerShell?

Downloading Wget is not necessary; the .NET Framework has web client classes built in.

$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

There are only 3 joins:

  • A) Cross Join = Cartesian (E.g: Table A, Table B)
  • B) Inner Join = JOIN (E.g: Table A Join/Inner Join Table B)
  • C) Outer join:

       There are three type of outer join
       1)  Left Outer Join     = Left Join
       2)  Right Outer Join    = Right Join
       3)  Full Outer Join     = Full Join    
    

Hope it'd help.

HRESULT: 0x800A03EC on Worksheet.range

Seems like this i s a pretty generic error for "something went wrong" with the operation you attempted. I have observed that will also occur if you have a formula error and are assigning that formula into a cell. E.g. "=fubar()"

How to implement a lock in JavaScript

Locks are a concept required in a multi-threaded system. Even with worker threads, messages are sent by value between workers so that locking is unnecessary.

I suspect you need to just set a semaphore (flagging system) between your buttons.

Good ways to sort a queryset? - Django

Here's a way that allows for ties for the cut-off score.

author_count = Author.objects.count()
cut_off_score = Author.objects.order_by('-score').values_list('score')[min(30, author_count)]
top_authors = Author.objects.filter(score__gte=cut_off_score).order_by('last_name')

You may get more than 30 authors in top_authors this way and the min(30,author_count) is there incase you have fewer than 30 authors.

How do you implement a re-try-catch?

You can use https://github.com/bnsd55/RetryCatch

Example:

RetryCatch retryCatchSyncRunnable = new RetryCatch();
        retryCatchSyncRunnable
                // For infinite retry times, just remove this row
                .retryCount(3)
                // For retrying on all exceptions, just remove this row
                .retryOn(ArithmeticException.class, IndexOutOfBoundsException.class)
                .onSuccess(() -> System.out.println("Success, There is no result because this is a runnable."))
                .onRetry((retryCount, e) -> System.out.println("Retry count: " + retryCount + ", Exception message: " + e.getMessage()))
                .onFailure(e -> System.out.println("Failure: Exception message: " + e.getMessage()))
                .run(new ExampleRunnable());

Instead of new ExampleRunnable() you can pass your own anonymous function.

How do I select between the 1st day of the current month and current day in MySQL?

select * from table_name 
where `date` between curdate() - dayofmonth(curdate()) + 1
                 and curdate()

SQLFiddle example

"git pull" or "git merge" between master and development branches

This workflow works best for me:

git checkout -b develop

...make some changes...

...notice master has been updated...

...commit changes to develop...

git checkout master
git pull

...bring those changes back into develop...

git checkout develop
git rebase master

...make some more changes...

...commit them to develop...

...merge them into master...

git checkout master
git pull
git merge develop

No log4j2 configuration file found. Using default configuration: logging only errors to the console

Stuffs I check to verify logging,

1) Check that there're no older log4j versions.

mvn dependency:tree | grep log ## ./gradlew dependencies | grep log
[INFO] +- com.prayagupd:log-service:jar:1.0:compile
[INFO] +- org.apache.logging.log4j:log4j-api:jar:2.6.2:compile
[INFO] +- org.apache.logging.log4j:log4j-core:jar:2.6.2:compile
[INFO] |  \- commons-logging:commons-logging:jar:1.1.1:compile

2) make sure I'm setting log4j2.json properly, which is done with -Dlog4j.configurationFile=???

val logConfig: PropertiesConfiguration = new PropertiesConfiguration("application.properties")
System.setProperty("log4j.configurationFile", logConfig.getString("log4j.config.file"))

println("log4j.configurationFile :: " + System.getProperty("log4j.configurationFile"))

or

Configurator.initialize(null, logConfig.getString("log4j.config.file"));

Also if auto detection is happening make sure the file name is log4j2.* not log4j.*

3) Another check is for parser for log4j2.json. Thanks log4j team for not providing parser within the API.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.0</version>
</dependency>

This might throw an exception if can not find the json parser

[Fatal Error] log4j2.json:1:1: Content is not allowed in prolog.

Getting the WordPress Post ID of current post

Try using this:

$id = get_the_ID();

How to validate numeric values which may contain dots or commas?

In order to represent a single digit in the form of a regular expression you can use either:

[0-9] or \d

In order to specify how many times the number appears you would add

[0-9]*: the star means there are zero or more digits

[0-9]{2}: {N} means N digits

[0-9]{0,2}: {N,M} N digits or M digits

[0-9]{0-9}: {N-M} N digits to M digits. Note: M can be left blank for an infinite representation

Lets say I want to represent a number between 1 and 99 I would express it as such:

[0-9]{1-2} or [0-9]{1,2} or \d{1-2} or \d{1,2}

Or lets say we were working with binary display, displaying a byte size, we would want our digits to be between 0 and 1 and length of a byte size, 8, so we would represent it as follows:

[0-1]{8} representation of a binary byte

Then if you want to add a , or a . symbol you would use:

\, or \. or you can use [.] or [,]

You can also state a selection between possible values as such

[.,] means either a dot or a comma symbol

And you just need to concatenate the pieces together, so in the case where you want to represent a 1 or 2 digit number followed by either a comma or a period and followed by two more digits you would express it as follows: >

[0-9]{1,2}[.,]\d{1-2}

Also note that regular expression strings inside C++ strings must be double-back-slashed so every \ becomes \\

Add error bars to show standard deviation on a plot in R

A solution with ggplot2 :

qplot(x,y)+geom_errorbar(aes(x=x, ymin=y-sd, ymax=y+sd), width=0.25)

enter image description here

Pressing Ctrl + A in Selenium WebDriver

By using the Robot class in Java:

import java.awt.Robot;
import java.awt.event.KeyEvent;

public class Test1
{
    public static void main(String[] args) throws Exception
    {
        WebDriver d1 = new FirefoxDriver();
        d1.navigate().to("https://www.youtube.com/");
        Thread.sleep(3000);
        Robot rb = new Robot();
        rb.keyPress(KeyEvent.VK_TAB);
        rb.keyRelease(KeyEvent.VK_TAB);
        rb.keyPress(KeyEvent.VK_TAB);
        rb.keyRelease(KeyEvent.VK_TAB);

        // Perform [Ctrl+A] Operation - it works
        rb.keyPress(KeyEvent.VK_CONTROL);
        rb.keyPress(KeyEvent.VK_A);

        // It needs to release key after pressing
        rb.keyRelease(KeyEvent.VK_A);
        rb.keyRelease(KeyEvent.VK_CONTROL);
        Thread.sleep(3000);
    }
}

Div table-cell vertical align not working

An element styled as follows will be aligned vertically to middle:

.content{
     position:relative;
     -webkit-transform: translateY(-50%);
     -ms-transform: translateY(-50%);
     transform: translateY(-50%);
     top:50%;
}

However, the parent element must have a fixed height. See this fiddle: https://jsfiddle.net/15d0qfdg/12/

Are members of a C++ struct initialized to 0 by default?

With POD you can also write

Snapshot s = {};

You shouldn't use memset in C++, memset has the drawback that if there is a non-POD in the struct it will destroy it.

or like this:

struct init
{
  template <typename T>
  operator T * ()
  {
    return new T();
  }
};

Snapshot* s = init();

Serialize an object to XML

Here is a good tutorial on how to do this

You should basically use System.Xml.Serialization.XmlSerializer class to do this.

How can I define colors as variables in CSS?

Yeeeaaahhh.... you can now use var() function in CSS.....

The good news is you can change it using JavaScript access, which will change globally as well...

But how to declare them...

It's quite simple:

For example, you wanna assign a #ff0000 to a var(), just simply assign it in :root, also pay attention to --:

:root {
    --red: #ff0000; 
}

html, body {
    background-color: var(--red); 
}

The good things are the browser support is not bad, also don't need to be compiled to be used in the browser like LESS or SASS...

browser support

Also, here is a simple JavaScript script, which changes the red value to blue:

const rootEl = document.querySelector(':root');
root.style.setProperty('--red', 'blue');

Pythonic way to combine FOR loop and IF statement

As per The Zen of Python (if you are wondering whether your code is "Pythonic", that's the place to go):

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Flat is better than nested.
  • Readability counts.

The Pythonic way of getting the sorted intersection of two sets is:

>>> sorted(set(a).intersection(xyz))
[0, 4, 6, 7, 9]

Or those elements that are xyz but not in a:

>>> sorted(set(xyz).difference(a))
[12, 242]

But for a more complicated loop you may want to flatten it by iterating over a well-named generator expression and/or calling out to a well-named function. Trying to fit everything on one line is rarely "Pythonic".


Update following additional comments on your question and the accepted answer

I'm not sure what you are trying to do with enumerate, but if a is a dictionary, you probably want to use the keys, like this:

>>> a = {
...     2: 'Turtle Doves',
...     3: 'French Hens',
...     4: 'Colly Birds',
...     5: 'Gold Rings',
...     6: 'Geese-a-Laying',
...     7: 'Swans-a-Swimming',
...     8: 'Maids-a-Milking',
...     9: 'Ladies Dancing',
...     0: 'Camel Books',
... }
>>>
>>> xyz = [0, 12, 4, 6, 242, 7, 9]
>>>
>>> known_things = sorted(set(a.iterkeys()).intersection(xyz))
>>> unknown_things = sorted(set(xyz).difference(a.iterkeys()))
>>>
>>> for thing in known_things:
...     print 'I know about', a[thing]
...
I know about Camel Books
I know about Colly Birds
I know about Geese-a-Laying
I know about Swans-a-Swimming
I know about Ladies Dancing
>>> print '...but...'
...but...
>>>
>>> for thing in unknown_things:
...     print "I don't know what happened on the {0}th day of Christmas".format(thing)
...
I don't know what happened on the 12th day of Christmas
I don't know what happened on the 242th day of Christmas

How to get day of the month?

The following method would help you in finding day of any specified date :

public static int getDayOfMonth(Date aDate) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(aDate);
    return cal.get(Calendar.DAY_OF_MONTH);
}

Read lines from a file into a Bash array

Your first attempt was close. Here is the simplistic approach using your idea.

file="somefileondisk"
lines=`cat $file`
for line in $lines; do
        echo "$line"
done

Best way to Format a Double value to 2 Decimal places

An alternative is to use String.format:

double[] arr = { 23.59004,
    35.7,
    3.0,
    9
};

for ( double dub : arr ) {
  System.out.println( String.format( "%.2f", dub ) );
}

output:

23.59
35.70
3.00
9.00

You could also use System.out.format (same method signature), or create a java.util.Formatter which works in the same way.

Difference between SelectedItem, SelectedValue and SelectedValuePath

SelectedItem is an object. SelectedValue and SelectedValuePath are strings.

for example using the ListBox:

if you say give me listbox1.SelectedValue it will return the text of the currently selected item.

string value = listbox1.SelectedValue;

if you say give me listbox1.SelectedItem it will give you the entire object.

ListItem item = listbox1.SelectedItem;
string value = item.value;

How to catch exception output from Python subprocess.check_output()?

This did the trick for me. It captures all the stdout output from the subprocess(For python 3.8):

from subprocess import check_output, STDOUT
cmd = "Your Command goes here"
try:
    cmd_stdout = check_output(cmd, stderr=STDOUT, shell=True).decode()
except Exception as e:
    print(e.output.decode()) # print out the stdout messages up to the exception
    print(e) # To print out the exception message

Fastest way to reset every value of std::vector<int> to 0

How about the assign member function?

some_vector.assign(some_vector.size(), 0);

Updating a dataframe column in spark

While you cannot modify a column as such, you may operate on a column and return a new DataFrame reflecting that change. For that you'd first create a UserDefinedFunction implementing the operation to apply and then selectively apply that function to the targeted column only. In Python:

from pyspark.sql.functions import UserDefinedFunction
from pyspark.sql.types import StringType

name = 'target_column'
udf = UserDefinedFunction(lambda x: 'new_value', StringType())
new_df = old_df.select(*[udf(column).alias(name) if column == name else column for column in old_df.columns])

new_df now has the same schema as old_df (assuming that old_df.target_column was of type StringType as well) but all values in column target_column will be new_value.

Can I run multiple versions of Google Chrome on the same machine? (Mac or Windows)

A small virtual machine maybe?

Try VirtualBox a freeware program to install virtual machines (a lot of work for what you want to do, but it'll work)

Getting the folder name from a path

It's also important to note that while getting a list of directory names in a loop, the DirectoryInfo class gets initialized once thus allowing only first-time call. In order to bypass this limitation, ensure you use variables within your loop to store any individual directory's name.

For example, this sample code loops through a list of directories within any parent directory while adding each found directory-name inside a List of string type:

[C#]

string[] parentDirectory = Directory.GetDirectories("/yourpath");
List<string> directories = new List<string>();

foreach (var directory in parentDirectory)
{
    // Notice I've created a DirectoryInfo variable.
    DirectoryInfo dirInfo = new DirectoryInfo(directory);

    // And likewise a name variable for storing the name.
    // If this is not added, only the first directory will
    // be captured in the loop; the rest won't.
    string name = dirInfo.Name;

    // Finally we add the directory name to our defined List.
    directories.Add(name);
}

[VB.NET]

Dim parentDirectory() As String = Directory.GetDirectories("/yourpath")
Dim directories As New List(Of String)()

For Each directory In parentDirectory

    ' Notice I've created a DirectoryInfo variable.
    Dim dirInfo As New DirectoryInfo(directory)

    ' And likewise a name variable for storing the name.
    ' If this is not added, only the first directory will
    ' be captured in the loop; the rest won't.
    Dim name As String = dirInfo.Name

    ' Finally we add the directory name to our defined List.
    directories.Add(name)

Next directory

Determine the line of code that causes a segmentation fault?

Lucas's answer about core dumps is good. In my .cshrc I have:

alias core 'ls -lt core; echo where | gdb -core=core -silent; echo "\n"'

to display the backtrace by entering 'core'. And the date stamp, to ensure I am looking at the right file :(.

Added: If there is a stack corruption bug, then the backtrace applied to the core dump is often garbage. In this case, running the program within gdb can give better results, as per the accepted answer (assuming the fault is easily reproducible). And also beware of multiple processes dumping core simultaneously; some OS's add the PID to the name of the core file.

What is the purpose of flush() in Java streams?

For performance issue, first data is to be written into Buffer. When buffer get full then data is written to output (File,console etc.). When buffer is partially filled and you want to send it to output(file,console) then you need to call flush() method manually in order to write partially filled buffer to output(file,console).

How do I convert an integer to string as part of a PostgreSQL query?

You could do this:

SELECT * FROM table WHERE cast(YOUR_INTEGER_VALUE as varchar) = 'string of numbers'

HTML / CSS table with GRIDLINES

<table border="1"></table>

should do the trick.

C# switch statement limitations - why?

The first reason that comes to mind is historical:

Since most C, C++, and Java programmers are not accustomed to having such freedoms, they do not demand them.

Another, more valid, reason is that the language complexity would increase:

First of all, should the objects be compared with .Equals() or with the == operator? Both are valid in some cases. Should we introduce new syntax to do this? Should we allow the programmer to introduce their own comparison method?

In addition, allowing to switch on objects would break underlying assumptions about the switch statement. There are two rules governing the switch statement that the compiler would not be able to enforce if objects were allowed to be switched on (see the C# version 3.0 language specification, §8.7.2):

  • That the values of switch labels are constant
  • That the values of switch labels are distinct (so that only one switch block can be selected for a given switch-expression)

Consider this code example in the hypothetical case that non-constant case values were allowed:

void DoIt()
{
    String foo = "bar";
    Switch(foo, foo);
}

void Switch(String val1, String val2)
{
    switch ("bar")
    {
        // The compiler will not know that val1 and val2 are not distinct
        case val1:
            // Is this case block selected?
            break;
        case val2:
            // Or this one?
            break;
        case "bar":
            // Or perhaps this one?
            break;
    }
}

What will the code do? What if the case statements are reordered? Indeed, one of the reasons why C# made switch fall-through illegal is that the switch statements could be arbitrarily rearranged.

These rules are in place for a reason - so that the programmer can, by looking at one case block, know for certain the precise condition under which the block is entered. When the aforementioned switch statement grows into 100 lines or more (and it will), such knowledge is invaluable.

How to present UIAlertController when not in a view controller?

I use this code with some little personal variations in my AppDelegate class

-(UIViewController*)presentingRootViewController
{
    UIViewController *vc = self.window.rootViewController;
    if ([vc isKindOfClass:[UINavigationController class]] ||
        [vc isKindOfClass:[UITabBarController class]])
    {
        // filter nav controller
        vc = [AppDelegate findChildThatIsNotNavController:vc];
        // filter tab controller
        if ([vc isKindOfClass:[UITabBarController class]]) {
            UITabBarController *tbc = ((UITabBarController*)vc);
            if ([tbc viewControllers].count > 0) {
                vc = [tbc viewControllers][tbc.selectedIndex];
                // filter nav controller again
                vc = [AppDelegate findChildThatIsNotNavController:vc];
            }
        }
    }
    return vc;
}
/**
 *   Private helper
 */
+(UIViewController*)findChildThatIsNotNavController:(UIViewController*)vc
{
    if ([vc isKindOfClass:[UINavigationController class]]) {
        if (((UINavigationController *)vc).viewControllers.count > 0) {
            vc = [((UINavigationController *)vc).viewControllers objectAtIndex:0];
        }
    }
    return vc;
}

How do I get the current date in Cocoa

You need to do something along the lines of the following:

NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now];
NSLog(@"%d", [components hour]);

And so on.

Type.GetType("namespace.a.b.ClassName") returns null

This solution above seems to be the best to me, but it didn't work for me, so I did it as follows:

AssemblyName assemblyName = AssemblyName.GetAssemblyName(HttpContext.Current.Server.MapPath("~\\Bin\\AnotherAssembly.dll"));
string typeAssemblyQualifiedName = string.Join(", ", "MyNamespace.MyType", assemblyName.FullName);

Type myType = Type.GetType(typeAssemblyQualifiedName);

The precondition is that you know the path of the assembly. In my case I know it because this is an assembly built from another internal project and its included in our project's bin folder.

In case it matters I am using Visual Studio 2013, my target .NET is 4.0. This is an ASP.NET project, so I am getting absolute path via HttpContext. However, absolute path is not a requirement as it seems from MSDN on AssemblyQualifiedNames

HTML5 Canvas background image

Make sure that in case your image is not in the dom, and you get it from local directory or server, you should wait for the image to load and just after that to draw it on the canvas.

something like that:

function drawBgImg() {
    let bgImg = new Image();
    bgImg.src = '/images/1.jpg';
    bgImg.onload = () => {
        gCtx.drawImage(bgImg, 0, 0, gElCanvas.width, gElCanvas.height);
    }
}

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

I belive you need to add itemprop to the og:image meta tag, have the image size set to 256x256 and also it would not harm to add the site_name, type and updated_time properties either :)

<meta property="og:site_name" content="San Roque 2014 Pollos">
<meta property="og:title" content="San Roque 2014 Pollos" />
<meta property="og:description" content="Programa de fiestas" />
<meta property="og:image" itemprop="image" content="http://pollosweb.wesped.es/programa_pollos/play.png">
<meta property="og:type" content="website" />
<meta property="og:updated_time" content="1440432930" />

You can see these meta tags in action on for example Google Maps.
After you have changed your meta tags, you might need to wait a while for possible caches to update.

You can debug/verify Open Graph meta tags from the Facebook Debugger
If you can see all your tags there, then the sites/apps where your tags are not showing properly might have different requirements for Open Graph tags.

EDIT:
If you are going to specify an image by a HTTP-Secure link, you need to use og:image:secure_url instead of og:image.

EDIT2:
You also need to specify og:type as it is one of the four base required parameters.
<meta property="og:type" content="website" /> should get you in the right direction.

How to find the nearest parent of a Git branch?

Here is a PowerShell implementation of Mark Reed's solution:

git show-branch -a | where-object { $_.Contains('*') -eq $true} | Where-object {$_.Contains($branchName) -ne $true } | select -first 1 | % {$_ -replace('.*\[(.*)\].*','$1')} | % { $_ -replace('[\^~].*','') }

CSS div element - how to show horizontal scroll bars only?

you can also make it overflow: auto and give a maximum fixed height and width that way, when the text or whatever is in there, overflows it'll show only the required scrollbar

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

The FailedPreconditionError comes because the session is trying to read a variable that hasn"t been initialized.

As of Tensorflow version 1.11.0, you need to take this :

init_op = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init_op)

Getting A File's Mime Type In Java

Unfortunately,

mimeType = file.toURL().openConnection().getContentType();

does not work, since this use of URL leaves a file locked, so that, for example, it is undeletable.

However, you have this:

mimeType= URLConnection.guessContentTypeFromName(file.getName());

and also the following, which has the advantage of going beyond mere use of file extension, and takes a peek at content

InputStream is = new BufferedInputStream(new FileInputStream(file));
mimeType = URLConnection.guessContentTypeFromStream(is);
 //...close stream

However, as suggested by the comment above, the built-in table of mime-types is quite limited, not including, for example, MSWord and PDF. So, if you want to generalize, you'll need to go beyond the built-in libraries, using, e.g., Mime-Util (which is a great library, using both file extension and content).

Getting Database connection in pure JPA setup

Hibernate 4 / 5:

Session session = entityManager.unwrap(Session.class);
session.doWork(connection -> doSomeStuffWith(connection));

How do I alias commands in git?

Follwing are the 4 git shortcuts or aliases youc an use to save time.

Open the commandline and type these below 4 commands and use the shortcuts after.

git config --global alias.co checkout  
git config --global alias.ci commit    
git config --global alias.st status    
git config --global alias.br branch  

Now test them!

$ git co              # use git co instead of git checkout
$ git ci              # use git ci instead of git commit
$ git st              # use git st instead of git status
$ git br              # use git br instead of git branch

Copy a file in a sane, safe and efficient way

I'm not quite sure what a "good way" of copying a file is, but assuming "good" means "fast", I could broaden the subject a little.

Current operating systems have long been optimized to deal with run of the mill file copy. No clever bit of code will beat that. It is possible that some variant of your copy techniques will prove faster in some test scenario, but they most likely would fare worse in other cases.

Typically, the sendfile function probably returns before the write has been committed, thus giving the impression of being faster than the rest. I haven't read the code, but it is most certainly because it allocates its own dedicated buffer, trading memory for time. And the reason why it won't work for files bigger than 2Gb.

As long as you're dealing with a small number of files, everything occurs inside various buffers (the C++ runtime's first if you use iostream, the OS internal ones, apparently a file-sized extra buffer in the case of sendfile). Actual storage media is only accessed once enough data has been moved around to be worth the trouble of spinning a hard disk.

I suppose you could slightly improve performances in specific cases. Off the top of my head:

  • If you're copying a huge file on the same disk, using a buffer bigger than the OS's might improve things a bit (but we're probably talking about gigabytes here).
  • If you want to copy the same file on two different physical destinations you will probably be faster opening the three files at once than calling two copy_file sequentially (though you'll hardly notice the difference as long as the file fits in the OS cache)
  • If you're dealing with lots of tiny files on an HDD you might want to read them in batches to minimize seeking time (though the OS already caches directory entries to avoid seeking like crazy and tiny files will likely reduce disk bandwidth dramatically anyway).

But all that is outside the scope of a general purpose file copy function.

So in my arguably seasoned programmer's opinion, a C++ file copy should just use the C++17 file_copy dedicated function, unless more is known about the context where the file copy occurs and some clever strategies can be devised to outsmart the OS.

How to convert char to integer in C?

The standard function atoi() will likely do what you want.

A simple example using "atoi":

#include <unistd.h>

int main(int argc, char *argv[])
{
    int useconds = atoi(argv[1]); 
    usleep(useconds);
}

source of historical stock data

A former project of mine was going to use freely downloadable data from EODData.

Where's javax.servlet?

A bit more detail to Joachim Sauer's answer:

On Ubuntu at least, the metapackage tomcat6 depends on metapackage tomcat6-common (and others), which depends on metapackage libtomcat6-java, which depends on package libservlet2.5-java (and others). It contains, among others, the files /usr/share/java/servlet-api-2.5.jar and /usr/share/java/jsp-api-2.1.jar, which are the servlet and JSP libraries you need. So if you've installed Tomcat 6 through apt-get or the Ubuntu Software Centre, you already have the libraries; all that's left is to get Tomcat to use them in your project.

Place libraries /usr/share/java/servlet-api-2.5.jar and /usr/share/java/jsp-api-2.1.jar on the class path like this:

  • For all projects, by configuring Eclipse by selecting Window -> Preferences -> Java -> Installed JREs, then selecting the JRE you're using, pressing Edit, then pressing Add External JARs, and then by selecting the files from the locations given above.

  • For just one project, by right-clicking on the project in the Project Explorer pane, then selecting Properties -> Java Build Path, and then pressing Add External JARs, and then by selecting the files from the locations given above.

Further note 1: These are the correct versions of those libraries for use with Tomcat 6; for the other Tomcat versions, see the table on page http://tomcat.apache.org/whichversion.html, though I would suppose each Tomcat version includes the versions of these libraries that are appropriate for it.

Further note 2: Package libservlet2.5-java's description (dpkg-query -s libservlet2.5-java) says: 'Apache Tomcat implements the Java Servlet and the JavaServer Pages (JSP) specifications from Sun Microsystems, and provides a "pure Java" HTTP web server environment for Java code to run. This package contains the Java Servlet and JSP library.'

UTF-8 byte[] to String

String has a constructor that takes byte[] and charsetname as parameters :)

How to add property to a class dynamically?

You don't need to use a property for that. Just override __setattr__ to make them read only.

class C(object):
    def __init__(self, keys, values):
        for (key, value) in zip(keys, values):
            self.__dict__[key] = value

    def __setattr__(self, name, value):
        raise Exception("It is read only!")

Tada.

>>> c = C('abc', [1,2,3])
>>> c.a
1
>>> c.b
2
>>> c.c
3
>>> c.d
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'd'
>>> c.d = 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in __setattr__
Exception: It is read only!
>>> c.a = 'blah'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in __setattr__
Exception: It is read only!

How do I make a transparent border with CSS?

Yep, you can use border: 1px solid transparent

Another solution is to use outline on hover (and set the border to 0) which doesn't affect the document flow:

li{
    display:inline-block;
    padding:5px;
    border:0;
}
li:hover{
    outline:1px solid #FC0;
}

NB. You can only set the outline as a sharthand property, not for individual sides. It's only meant to be used for debugging but it works nicely.

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

So.. I had noticed in event viewer that this crash corresponded to a "System.IO.FileNotFoundException" error.

So I fired ProcMon and noticed that one of the program dlls was failing to load vcruntime140. So I simply installed vs15 redist and it worked.

How to check which locks are held on a table

You can find current locks on your table by following query.

USE yourdatabase;
GO

SELECT * FROM sys.dm_tran_locks
  WHERE resource_database_id = DB_ID()
  AND resource_associated_entity_id = OBJECT_ID(N'dbo.yourtablename');

See sys.dm_tran_locks

If multiple instances of the same request_owner_type exist, the request_owner_id column is used to distinguish each instance. For distributed transactions, the request_owner_type and the request_owner_guid columns will show the different entity information.

For example, Session S1 owns a shared lock on Table1; and transaction T1, which is running under session S1, also owns a shared lock on Table1. In this case, the resource_description column that is returned by sys.dm_tran_locks will show two instances of the same resource. The request_owner_type column will show one instance as a session and the other as a transaction. Also, the resource_owner_id column will have different values.

Re-ordering columns in pandas dataframe based on column name

Tweet's answer can be passed to BrenBarn's answer above with

data.reindex_axis(sorted(data.columns, key=lambda x: float(x[1:])), axis=1)

So for your example, say:

vals = randint(low=16, high=80, size=25).reshape(5,5)
cols = ['Q1.3', 'Q6.1', 'Q1.2', 'Q9.1', 'Q10.2']
data = DataFrame(vals, columns = cols)

You get:

data

    Q1.3    Q6.1    Q1.2    Q9.1    Q10.2
0   73      29      63      51      72
1   61      29      32      68      57
2   36      49      76      18      37
3   63      61      51      30      31
4   36      66      71      24      77

Then do:

data.reindex_axis(sorted(data.columns, key=lambda x: float(x[1:])), axis=1)

resulting in:

data


     Q1.2    Q1.3    Q6.1    Q9.1    Q10.2
0    2       0       1       3       4
1    7       5       6       8       9
2    2       0       1       3       4
3    2       0       1       3       4
4    2       0       1       3       4

C++: Rounding up to the nearest multiple of a number

Here is a super simple solution to show the concept of elegance. It's basically for grid snaps.

(pseudo code)

nearestPos = Math.Ceil( numberToRound / multiple ) * multiple;

Failed to load ApplicationContext for JUnit test of Spring controller

As mentioned in duscusion: WEB-INF is not really a part of class path. If you use a common template such as maven, use src/main/resources or src/test/resources to place the app-context.xml into. Then you can use 'classpath:'.

Place your config file into src/main/resources/app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:app-context.xml")
public class PersonControllerTest {
...
}

or you can make yout test context with different configuration of beans.

Place your config file into src/test/resources/test-app-context.xml and use code

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test-app-context.xml")
public class PersonControllerTest {
...
}

How to get the month name in C#?

If you just want to use MonthName then reference Microsoft.VisualBasic and it's in Microsoft.VisualBasic.DateAndTime

//eg. Get January
String monthName = Microsoft.VisualBasic.DateAndTime.MonthName(1);

Sending emails in Node.js?

Check out emailjs

After wasting lots of time on trying to make nodemailer work with large attachments, found emailjs and happy ever since.

It supports sending files by using normal File objects, and not huge Buffers as nodemailer requires. Means that you can link it to, f.e., formidable to pass the attachments from an html form to the mailer. It also supports queueing..

All in all, no idea why nodejitsu ppl chose nodemailer to base their version on, emailjs is just much more advanced.

Dynamically load a function from a DLL

In addition to the already posted answer, I thought I should share a handy trick I use to load all the DLL functions into the program through function pointers, without writing a separate GetProcAddress call for each and every function. I also like to call the functions directly as attempted in the OP.

Start by defining a generic function pointer type:

typedef int (__stdcall* func_ptr_t)();

What types that are used aren't really important. Now create an array of that type, which corresponds to the amount of functions you have in the DLL:

func_ptr_t func_ptr [DLL_FUNCTIONS_N];

In this array we can store the actual function pointers that point into the DLL memory space.

Next problem is that GetProcAddress expects the function names as strings. So create a similar array consisting of the function names in the DLL:

const char* DLL_FUNCTION_NAMES [DLL_FUNCTIONS_N] = 
{
  "dll_add",
  "dll_subtract",
  "dll_do_stuff",
  ...
};

Now we can easily call GetProcAddress() in a loop and store each function inside that array:

for(int i=0; i<DLL_FUNCTIONS_N; i++)
{
  func_ptr[i] = GetProcAddress(hinst_mydll, DLL_FUNCTION_NAMES[i]);

  if(func_ptr[i] == NULL)
  {
    // error handling, most likely you have to terminate the program here
  }
}

If the loop was successful, the only problem we have now is calling the functions. The function pointer typedef from earlier isn't helpful, because each function will have its own signature. This can be solved by creating a struct with all the function types:

typedef struct
{
  int  (__stdcall* dll_add_ptr)(int, int);
  int  (__stdcall* dll_subtract_ptr)(int, int);
  void (__stdcall* dll_do_stuff_ptr)(something);
  ...
} functions_struct;

And finally, to connect these to the array from before, create a union:

typedef union
{
  functions_struct  by_type;
  func_ptr_t        func_ptr [DLL_FUNCTIONS_N];
} functions_union;

Now you can load all the functions from the DLL with the convenient loop, but call them through the by_type union member.

But of course, it is a bit burdensome to type out something like

functions.by_type.dll_add_ptr(1, 1); whenever you want to call a function.

As it turns out, this is the reason why I added the "ptr" postfix to the names: I wanted to keep them different from the actual function names. We can now smooth out the icky struct syntax and get the desired names, by using some macros:

#define dll_add (functions.by_type.dll_add_ptr)
#define dll_subtract (functions.by_type.dll_subtract_ptr)
#define dll_do_stuff (functions.by_type.dll_do_stuff_ptr)

And voilà, you can now use the function names, with the correct type and parameters, as if they were statically linked to your project:

int result = dll_add(1, 1);

Disclaimer: Strictly speaking, conversions between different function pointers are not defined by the C standard and not safe. So formally, what I'm doing here is undefined behavior. However, in the Windows world, function pointers are always of the same size no matter their type and the conversions between them are predictable on any version of Windows I've used.

Also, there might in theory be padding inserted in the union/struct, which would cause everything to fail. However, pointers happen to be of the same size as the alignment requirement in Windows. A static_assert to ensure that the struct/union has no padding might be in order still.

PHP CURL Enable Linux

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

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

Django set field value after a form is initialized

Another way to do this, if you have already initialised a form (with or without data), and you need to add further data before displaying it:

form = Form(request.POST.form)
form.data['Email'] = GetEmailString()

How to fix "could not find a base address that matches schema http"... in WCF

If it is hosted in IIS, there is no need to specify a base address, it will be the address of the virtual directory.

How do I get a UTC Timestamp in JavaScript?

Using day.js

In browser:

_x000D_
_x000D_
dayjs.extend(dayjs_plugin_utc)
console.log(dayjs.utc().unix())
_x000D_
<script src="https://cdn.jsdelivr.net/npm/dayjs@latest/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@latest/plugin/utc.js"></script>
_x000D_
_x000D_
_x000D_

In node.js:

import dayjs from 'dayjs'
dayjs.extend(require('dayjs/plugin/utc'))
console.log(dayjs.utc().unix())

You get a UTC unix timestamp without milliseconds.

Versioning SQL Server database

This is one of the "hard problems" surrounding development. As far as I know there are no perfect solutions.

If you only need to store the database structure and not the data you can export the database as SQL queries. (in Enterprise Manager: Right click on database -> Generate SQL script. I recommend setting the "create one file per object" on the options tab) You can then commit these text files to svn and make use of svn's diff and logging functions.

I have this tied together with a Batch script that takes a couple parameters and sets up the database. I also added some additional queries that enter default data like user types and the admin user. (If you want more info on this, post something and I can put the script somewhere accessible)

If you need to keep all of the data as well, I recommend keeping a back up of the database and using Redgate (http://www.red-gate.com/) products to do the comparisons. They don't come cheap, but they are worth every penny.

Select All Rows Using Entity Framework

You can use:

ptx.[tablename].Select( o => true)

Apply multiple functions to multiple groupby columns

Pandas >= 0.25.0, named aggregations

Since pandas version 0.25.0 or higher, we are moving away from the dictionary based aggregation and renaming, and moving towards named aggregations which accepts a tuple. Now we can simultaneously aggregate + rename to a more informative column name:

Example:

df = pd.DataFrame(np.random.rand(4,4), columns=list('abcd'))
df['group'] = [0, 0, 1, 1]

          a         b         c         d  group
0  0.521279  0.914988  0.054057  0.125668      0
1  0.426058  0.828890  0.784093  0.446211      0
2  0.363136  0.843751  0.184967  0.467351      1
3  0.241012  0.470053  0.358018  0.525032      1

Apply GroupBy.agg with named aggregation:

df.groupby('group').agg(
             a_sum=('a', 'sum'),
             a_mean=('a', 'mean'),
             b_mean=('b', 'mean'),
             c_sum=('c', 'sum'),
             d_range=('d', lambda x: x.max() - x.min())
)

          a_sum    a_mean    b_mean     c_sum   d_range
group                                                  
0      0.947337  0.473668  0.871939  0.838150  0.320543
1      0.604149  0.302074  0.656902  0.542985  0.057681

ALTER COLUMN in sqlite

SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table. But you can alter table column datatype or other property by the following steps.

  1. BEGIN TRANSACTION;
  2. CREATE TEMPORARY TABLE t1_backup(a,b);
  3. INSERT INTO t1_backup SELECT a,b FROM t1;
  4. DROP TABLE t1;
  5. CREATE TABLE t1(a,b);
  6. INSERT INTO t1 SELECT a,b FROM t1_backup;
  7. DROP TABLE t1_backup;
  8. COMMIT

For more detail you can refer the link.

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

For me the cause of the issue was that the format of username was incorrect. It was earlierly specified as "mydomain\user". I removed the domain part and the error was gone.

PS I was using ServerBind authentication.

jQuery.inArray(), how to use it right?

Just no one use $ instead of jQuery:

if ($.inArray(nearest.node.name, array)>=0){
   console.log("is in array");
}else{
   console.log("is not in array");
}

How do I append to a table in Lua

You are looking for the insert function, found in the table section of the main library.

foo = {}
table.insert(foo, "bar")
table.insert(foo, "baz")

font size in html code

Try this:

<html>
  <table>
    <tr>
      <td style="padding-left: 5px;
                 padding-bottom: 3px;">
        <strong style="font-size: 35px;">Datum:</strong><br />
        November 2010 
      </td>
    </tr>
  </table>
</html>

Notice that I also included the table-tag, which you seem to have forgotten. This has to be included if you want this to appear as a table.

Adding three months to a date in PHP

Add nth Days, months and years

$n = 2;
for ($i = 0; $i <= $n; $i++){
    $d = strtotime("$i days");
    $x = strtotime("$i month");
    $y = strtotime("$i year");
    echo "Dates : ".$dates = date('d M Y', "+$d days");
    echo "<br>";
    echo "Months : ".$months = date('M Y', "+$x months");
    echo '<br>';
    echo "Years : ".$years = date('Y', "+$y years");
    echo '<br>';
}

Finding diff between current and last version

Difference between last but one commit and last commit (plus current state, if any):

git diff HEAD~

or even (easier to type)

git diff @~

where @ is the synonim for HEAD of current branch and ~ means "give me the parent of mentioned revision".

Could not open input file: artisan

I checked out an existing Laravel project, which did not have this script. Even a find / -name 'artisan' produced no results. The solution turned out to be simple, if a bit weird:

curl -L 'https://raw.githubusercontent.com/laravel/laravel/v4.2.11/artisan' > artisan

You probably want to choose a tagged version that matches your installed version of Laravel.

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

I put together a script based on the good answers here & in other posts

You can set title timeout & even sleep to schedule it for latter & \n for new line

also you get back the key press into a variable (%pop.key%).

Here is my code

Node JS Error: ENOENT

if your tmp folder is relative to the directory where your code is running remove the / in front of /tmp.

So you just have tmp/test.jpg in your code. This worked for me in a similar situation.

Background color of text in SVG

Answer by Robert Longson (@RobertLongson) with modifications:

<svg width="100%" height="100%">
  <defs>
    <filter x="0" y="0" width="1" height="1" id="solid">
      <feFlood flood-color="yellow"/>
      <feComposite in="SourceGraphic" operator="xor"/>
    </filter>
  </defs>
  <text filter="url(#solid)" x="20" y="50" font-size="50"> solid background </text>
  <text x="20" y="50" font-size="50">solid background</text>
</svg>

and we have no bluring and no heavy "getBBox" :) Padding is provided by white spaces in text-element with filter. It's worked for me

How do I hide the PHP explode delimiter from submitted form results?

<select name="FakeName" id="Fake-ID" aria-required="true" required>  <?php $options=nl2br(file_get_contents("employees.txt")); $options=explode("<br />",$options);  foreach ($options as $item_array) { echo "<option value='".$item_array"'>".$item_array"</option>";  } ?> </select> 

Is it possible to use pip to install a package from a private GitHub repository?

It also works with Bitbucket:

pip install git+ssh://[email protected]/username/projectname.git

Pip will use your SSH keys in this case.

Standard concise way to copy a file in Java?

As toolkit mentions above, Apache Commons IO is the way to go, specifically FileUtils.copyFile(); it handles all the heavy lifting for you.

And as a postscript, note that recent versions of FileUtils (such as the 2.0.1 release) have added the use of NIO for copying files; NIO can significantly increase file-copying performance, in a large part because the NIO routines defer copying directly to the OS/filesystem rather than handle it by reading and writing bytes through the Java layer. So if you're looking for performance, it might be worth checking that you are using a recent version of FileUtils.

(SC) DeleteService FAILED 1072

For some buggy reason both Event Viewer and/or Services.msc won't do a proper refresh when you tell them to!

Close them and restart, and the service would have been deleted anyway.

How to uncheck a checkbox in pure JavaScript?

<html>
    <body>
        <input id="mycheck" type="checkbox">
    </body>

    <script language="javascript">
        var=check;
        document.getElementById("mycheck");
        check.checked="false";
    </script>
</html>

Squaring all elements in a list

import numpy as np
a = [2 ,3, 4]
np.square(a)

Show special characters in Unix while using 'less' Command

In the same spirit as https://stackoverflow.com/a/6943976/7154924:

cat -A

-A, --show-all
       equivalent to -vET
-v, --show-nonprinting
       use ^ and M- notation, except for LFD and TAB
-E, --show-ends
       display $ at end of each line
-T, --show-tabs
       display TAB characters as ^I

Alternatively, or at the same time, you can pipe to tr to substitute arbitrary characters to the desired ones for display, before piping to a pager like less if desired.

$(document).click() not working correctly on iPhone. jquery

try this, applies only to iPhone and iPod so you're not making everything turn blue on chrome or firefox mobile;

/iP/i.test(navigator.userAgent) && $('*').css('cursor', 'pointer');

basically, on iOS, things aren't "clickable" by default -- they're "touchable" (pfffff) so you make them "clickable" by giving them a pointer cursor. makes total sense, right??

jQuery find element by data attribute value

Use Attribute Equals Selector

$('.slide-link[data-slide="0"]').addClass('active');

Fiddle Demo

.find()

it works down the tree

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

How to launch Windows Scheduler by command-line?

I'm also running XP SP2, and this works perfectly (from the command line...):

start control schedtasks

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/jsp-api-6.0.16.jar
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/servlet-api-6.0.16.jar

You should not have any server-specific libraries in the /WEB-INF/lib. Leave them in the appserver's own library. It would only lead to collisions in the classpath. Get rid of all appserver-specific libraries in /WEB-INF/lib (and also in JRE/lib and JRE/lib/ext if you have placed any of them there).

A common cause that the appserver-specific libraries are included in the webapp's library is that starters think that it is the right way to fix compilation errors of among others the javax.servlet classes not being resolveable. Putting them in webapp's library is the wrong solution. You should reference them in the classpath during compilation, i.e. javac -cp /path/to/server/lib/servlet.jar and so on, or if you're using an IDE, you should integrate the server in the IDE and associate the web project with the server. The IDE will then automatically take server-specific libraries in the classpath (buildpath) of the webapp project.

How to fix div on scroll

(function($) {
  var triggers = [];
  $.fn.floatingFixed = function(options) {
    options = $.extend({}, $.floatingFixed.defaults, options);
    var r = $(this).each(function() {
      var $this = $(this), pos = $this.position();
      pos.position = $this.css("position");
      $this.data("floatingFixedOrig", pos);
      $this.data("floatingFixedOptions", options);
      triggers.push($this);
    });
    windowScroll();
    return r;
  };

  $.floatingFixed = $.fn.floatingFixed;
  $.floatingFixed.defaults = {
    padding: 0
  };

  var $window = $(window);
  var windowScroll = function() {
    if(triggers.length === 0) { return; }
    var scrollY = $window.scrollTop();
    for(var i = 0; i < triggers.length; i++) {
      var t = triggers[i], opt = t.data("floatingFixedOptions");
      if(!t.data("isFloating")) {
        var off = t.offset();
        t.data("floatingFixedTop", off.top);
        t.data("floatingFixedLeft", off.left);
      }
      var top = top = t.data("floatingFixedTop");
      if(top < scrollY + opt.padding && !t.data("isFloating")) {
        t.css({position: 'fixed', top: opt.padding, left: t.data("floatingFixedLeft"), width: t.width() }).data("isFloating", true);
      } else if(top >= scrollY + opt.padding && t.data("isFloating")) {
        var pos = t.data("floatingFixedOrig");
        t.css(pos).data("isFloating", false);
      }
    }
  };

  $window.scroll(windowScroll).resize(windowScroll);
})(jQuery);

and then make any div as floating fixed by calling

$('#id of the div').floatingFixed();

source: https://github.com/cheald/floatingFixed

grep for special characters in Unix

You could try removing any alphanumeric characters and space. And then use -n will give you the line number. Try following:

grep -vn "^[a-zA-Z0-9 ]*$" application.log

Delete all rows in a table based on another table

I often do things like the following made-up example. (This example is from Informix SE running on Linux.)

The point of of this example is to delete all real estate exemption/abatement transaction records -- because the abatement application has a bug -- based on information in the real_estate table.

In this case last_update != nullmeans the account is not closed, and res_exempt != 'p' means the accounts are not personal property (commercial equipment/furnishings).

delete from trans 
where   yr = '16'
and     tran_date = '01/22/2016'
and     acct_type = 'r'
and     tran_type = 'a'
and     bill_no in
(select acct_no from real_estate where last_update is not null
 and res_exempt != 'p');

I like this method, because the filtering criteria -- at least for me -- is easier to read while creating the query, and to understand many months from now when I'm looking at it and wondering what I was thinking.