Programs & Examples On #Class table inheritance

Class Table Inheritance is one of several techniques for designing SQL tables in situations where subclasses that extend classes would apply if SQL had a mechanism for inheritance, which it doesn't.

How can you represent inheritance in a database?

@Bill Karwin describes three inheritance models in his SQL Antipatterns book, when proposing solutions to the SQL Entity-Attribute-Value antipattern. This is a brief overview:

Single Table Inheritance (aka Table Per Hierarchy Inheritance):

Using a single table as in your first option is probably the simplest design. As you mentioned, many attributes that are subtype-specific will have to be given a NULL value on rows where these attributes do not apply. With this model, you would have one policies table, which would look something like this:

+------+---------------------+----------+----------------+------------------+
| id   | date_issued         | type     | vehicle_reg_no | property_address |
+------+---------------------+----------+----------------+------------------+
|    1 | 2010-08-20 12:00:00 | MOTOR    | 01-A-04004     | NULL             |
|    2 | 2010-08-20 13:00:00 | MOTOR    | 02-B-01010     | NULL             |
|    3 | 2010-08-20 14:00:00 | PROPERTY | NULL           | Oxford Street    |
|    4 | 2010-08-20 15:00:00 | MOTOR    | 03-C-02020     | NULL             |
+------+---------------------+----------+----------------+------------------+

\------ COMMON FIELDS -------/          \----- SUBTYPE SPECIFIC FIELDS -----/

Keeping the design simple is a plus, but the main problems with this approach are the following:

  • When it comes to adding new subtypes, you would have to alter the table to accommodate the attributes that describe these new objects. This can quickly become problematic when you have many subtypes, or if you plan to add subtypes on a regular basis.

  • The database will not be able to enforce which attributes apply and which don't, since there is no metadata to define which attributes belong to which subtypes.

  • You also cannot enforce NOT NULL on attributes of a subtype that should be mandatory. You would have to handle this in your application, which in general is not ideal.

Concrete Table Inheritance:

Another approach to tackle inheritance is to create a new table for each subtype, repeating all the common attributes in each table. For example:

--// Table: policies_motor
+------+---------------------+----------------+
| id   | date_issued         | vehicle_reg_no |
+------+---------------------+----------------+
|    1 | 2010-08-20 12:00:00 | 01-A-04004     |
|    2 | 2010-08-20 13:00:00 | 02-B-01010     |
|    3 | 2010-08-20 15:00:00 | 03-C-02020     |
+------+---------------------+----------------+
                          
--// Table: policies_property    
+------+---------------------+------------------+
| id   | date_issued         | property_address |
+------+---------------------+------------------+
|    1 | 2010-08-20 14:00:00 | Oxford Street    |   
+------+---------------------+------------------+

This design will basically solve the problems identified for the single table method:

  • Mandatory attributes can now be enforced with NOT NULL.

  • Adding a new subtype requires adding a new table instead of adding columns to an existing one.

  • There is also no risk that an inappropriate attribute is set for a particular subtype, such as the vehicle_reg_no field for a property policy.

  • There is no need for the type attribute as in the single table method. The type is now defined by the metadata: the table name.

However this model also comes with a few disadvantages:

  • The common attributes are mixed with the subtype specific attributes, and there is no easy way to identify them. The database will not know either.

  • When defining the tables, you would have to repeat the common attributes for each subtype table. That's definitely not DRY.

  • Searching for all the policies regardless of the subtype becomes difficult, and would require a bunch of UNIONs.

This is how you would have to query all the policies regardless of the type:

SELECT     date_issued, other_common_fields, 'MOTOR' AS type
FROM       policies_motor
UNION ALL
SELECT     date_issued, other_common_fields, 'PROPERTY' AS type
FROM       policies_property;

Note how adding new subtypes would require the above query to be modified with an additional UNION ALL for each subtype. This can easily lead to bugs in your application if this operation is forgotten.

Class Table Inheritance (aka Table Per Type Inheritance):

This is the solution that @David mentions in the other answer. You create a single table for your base class, which includes all the common attributes. Then you would create specific tables for each subtype, whose primary key also serves as a foreign key to the base table. Example:

CREATE TABLE policies (
   policy_id          int,
   date_issued        datetime,

   -- // other common attributes ...
);

CREATE TABLE policy_motor (
    policy_id         int,
    vehicle_reg_no    varchar(20),

   -- // other attributes specific to motor insurance ...

   FOREIGN KEY (policy_id) REFERENCES policies (policy_id)
);

CREATE TABLE policy_property (
    policy_id         int,
    property_address  varchar(20),

   -- // other attributes specific to property insurance ...

   FOREIGN KEY (policy_id) REFERENCES policies (policy_id)
);

This solution solves the problems identified in the other two designs:

  • Mandatory attributes can be enforced with NOT NULL.

  • Adding a new subtype requires adding a new table instead of adding columns to an existing one.

  • No risk that an inappropriate attribute is set for a particular subtype.

  • No need for the type attribute.

  • Now the common attributes are not mixed with the subtype specific attributes anymore.

  • We can stay DRY, finally. There is no need to repeat the common attributes for each subtype table when creating the tables.

  • Managing an auto incrementing id for the policies becomes easier, because this can be handled by the base table, instead of each subtype table generating them independently.

  • Searching for all the policies regardless of the subtype now becomes very easy: No UNIONs needed - just a SELECT * FROM policies.

I consider the class table approach as the most suitable in most situations.


The names of these three models come from Martin Fowler's book Patterns of Enterprise Application Architecture.

CSS text-align not working

Change the rule on your <a> element from:

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

to

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

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

jsFiddle example

Find and replace specific text characters across a document with JS

Use split and join method

$("#idBut").click(function() {
    $("body").children().each(function() {
        $(this).html($(this).html().split('@').join("$"));
    });
});

here is solution

How to get thread id from a thread pool?

Using Thread.currentThread():

private class MyTask implements Runnable {
    public void run() {
        long threadId = Thread.currentThread().getId();
        logger.debug("Thread # " + threadId + " is doing this task");
    }
}

How to clear the Entry widget after a button is pressed in Tkinter?

if none of the above is working you can use this->

idAssignedToEntryWidget.delete(first = 0, last = UpperLimitAssignedToEntryWidget)

for e.g. ->

id assigned is = en then

en.delete(first =0, last =100)

Does java.util.List.isEmpty() check if the list itself is null?

No java.util.List.isEmpty() doesn't check if a list is null.

If you are using Spring framework you can use the CollectionUtils class to check if a list is empty or not. It also takes care of the null references. Following is the code snippet from Spring framework's CollectionUtils class.

public static boolean isEmpty(Collection<?> collection) {
    return (collection == null || collection.isEmpty());
}

Even if you are not using Spring, you can go on and tweak this code to add in your AppUtil class.

Disable Chrome strict MIME type checking

In my case, I turned off X-Content-Type-Options on nginx then works fine. But make sure this declines your security level a little. Would be a temporally fix.

# Not work
add_header X-Content-Type-Options nosniff;
# OK (comment out)
#add_header X-Content-Type-Options nosniff;

It'll be the same for apache.

<IfModule mod_headers.c>
  #Header set X-Content-Type-Options nosniff
</IfModule>

How to create a new file in unix?

The command is lowercase: touch filename.

Keep in mind that touch will only create a new file if it does not exist! Here's some docs for good measure: http://unixhelp.ed.ac.uk/CGI/man-cgi?touch

If you always want an empty file, one way to do so would be to use:

echo "" > filename

PHP if not statements

I think this is the best and easiest way to do it:

if (!(isset($action) && ($action == "add" || $action == "delete")))

How do I trim() a string in angularjs?

If you need only display the trimmed value then I'd suggest against manipulating the original string and using a filter instead.

app.filter('trim', function () {
    return function(value) {
        if(!angular.isString(value)) {
            return value;
        }  
        return value.replace(/^\s+|\s+$/g, ''); // you could use .trim, but it's not going to work in IE<9
    };
});

And then

<span>{{ foo | trim }}</span>

Find a string within a cell using VBA

I simplified your code to isolate the test for "%" being in the cell. Once you get that to work, you can add in the rest of your code.

Try this:

Option Explicit


Sub DoIHavePercentSymbol()
   Dim rng As Range

   Set rng = ActiveCell

   Do While rng.Value <> Empty
        If InStr(rng.Value, "%") = 0 Then
            MsgBox "I know nothing about percentages!"
            Set rng = rng.Offset(1)
            rng.Select
        Else
            MsgBox "I contain a % symbol!"
            Set rng = rng.Offset(1)
            rng.Select
        End If
   Loop

End Sub

InStr will return the number of times your search text appears in the string. I changed your if test to check for no matches first.

The message boxes and the .Selects are there simply for you to see what is happening while you are stepping through the code. Take them out once you get it working.

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

[Quick Answer]

After try to solve this problem in my workspace I found a solution.

This error is because there are a problem with Metro using some combinations of NPM and Node version.

You have 2 alternatives:

  • Alternative 1: Try to update or downgrade npm and node version.
  • Alternative 2: Go to this file: \node_modules\metro-config\src\defaults\blacklist.js and change this code:

    var sharedBlacklist = [
      /node_modules[/\\]react[/\\]dist[/\\].*/,
      /website\/node_modules\/.*/,
      /heapCapture\/bundle\.js/,
      /.*\/__tests__\/.*/
    ];
    

    and change to this:

    var sharedBlacklist = [
      /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
      /website\/node_modules\/.*/,
      /heapCapture\/bundle\.js/,
      /.*\/__tests__\/.*/
    ];
    

    Please note that if you run an npm install or a yarn install you need to change the code again.

Where is the itoa function in Linux?

The replacement with snprintf is NOT complete!

It covers only bases: 2, 8, 10, 16, whereas itoa works for bases between 2 and 36.

Since I was searching a replacement for base 32, I guess I'll have to code my own!

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

Also In VS 2015 Community Edition

go to Debug->Options or Tools->Options

and check Debugging->General->Suppress JIT optimization on module load (Managed only)

How to find MAC address of an Android device programmatically

Recent update from Developer.Android.com

Don't work with MAC addresses MAC addresses are globally unique, not user-resettable, and survive factory resets. For these reasons, it's generally not recommended to use MAC address for any form of user identification. Devices running Android 10 (API level 29) and higher report randomized MAC addresses to all apps that aren't device owner apps.

Between Android 6.0 (API level 23) and Android 9 (API level 28), local device MAC addresses, such as Wi-Fi and Bluetooth, aren't available via third-party APIs. The WifiInfo.getMacAddress() method and the BluetoothAdapter.getDefaultAdapter().getAddress() method both return 02:00:00:00:00:00.

Additionally, between Android 6.0 and Android 9, you must hold the following permissions to access MAC addresses of nearby external devices available via Bluetooth and Wi-Fi scans:

Method/Property Permissions Required

ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION

Source: https://developer.android.com/training/articles/user-data-ids.html#version_specific_details_identifiers_in_m

How to uncommit my last commit in Git

Just a note - if you're using ZSH and see the error

zsh: no matches found: HEAD^

You need to escape the ^

git reset --soft HEAD\^

How do include paths work in Visual Studio?

To use Windows SDK successfully you need not only make include files available to your projects but also library files and executables (tools). To set all these directories you should use WinSDK Configuration Tool.

pip not working in Python Installation in Windows 10

instead of typing in "python". try using "py". for ex:

py -m pip install    packagename
py -m pip --install  packagename
py -m pip --upgrade  packagename
py -m pip upgrade    packagename

note: this should be done in the command prompt "cmd" and not in python idle. also FYI pip is installed with python 3.6 automatically.

How to fix corrupted git repository?

In my case, I was creating the repository from source code already in my pc and that error appeared. I deleted the .git folder and did everything again and it worked :)

How to detect pressing Enter on keyboard using jQuery?

$(document).keydown(function (event) {
      //proper indentiation of keycode and which to be equal to 13.
    if ( (event.keyCode || event.which) === 13) {
        // Cancel the default action, if needed
        event.preventDefault();
        //call function, trigger events and everything tou want to dd . ex : Trigger the button element with a click
        $("#btnsearch").trigger('click');
    }
});

How do I change the title of the "back" button on a Navigation Bar

Here's another way to do it.

In your parent view controller, implement the following method:

- (void) setBackBarButtonItemTitle:(NSString *)newTitle {
  self.navigationItem.backBarButtonItem.title = newTitle;
}

In your child view controller, when you want to change the title, this will work:

NSArray *viewControllerArray = [self.navigationController viewControllers];
int parentViewControllerIndex = [viewControllerArray count] - 2;
[[viewControllerArray objectAtIndex:parentViewControllerIndex] setBackBarButtonItemTitle:@"New Title"];

I was never able to get the parentViewController property to work:

[(ParentViewController *)(self.navigationController.parentViewController) setBackBarButtonItemTitle:@"New Title"];

I don't know if that's a bug or I'm not using it properly. But grabbing the second-to-last view controller in the viewControllers array points to the parent view controller, and I can call parent methods correctly with that reference.

Convert string to variable name in JavaScript

let me make it more clear

function changeStringToVariable(variable, value){
window[variable]=value
}
changeStringToVariable("name", "john doe");
console.log(name);
//this outputs: john doe
let file="newFile";
changeStringToVariable(file, "text file");
console.log(newFile);
//this outputs: text file

How are VST Plugins made?

I know this is 3 years old, but for everyone reading this now: Don't stick to VST, AU or any vendor's format. Steinberg has stopped supporting VST2, and people are in trouble porting their code to newer formats, because it's too tied to VST2.

These tutorials cover creating plugins that run on Win/Mac, 32/64, all plugin formats from the same code base.

How should you diagnose the error SEHException - External component has thrown an exception

Just another information... Had that problem today on a Windows 2012 R2 x64 TS system where the application was started from a unc/network path. The issue occured for one application for all terminal server users. Executing the application locally worked without problems. After a reboot it started working again - the SEHException's thrown had been Constructor init and TargetInvocationException

TypeScript - Append HTML to container element in Angular 2

With the new angular class Renderer2

constructor(private renderer:Renderer2) {}

  @ViewChild('one', { static: false }) d1: ElementRef;

  ngAfterViewInit() {
    const d2 = this.renderer.createElement('div');
    const text = this.renderer.createText('two');
    this.renderer.appendChild(d2, text);
    this.renderer.appendChild(this.d1.nativeElement, d2);
  }

Where do I find some good examples for DDD?

The difficulty with DDD samples is that they're often very domain specific and the technical implementation of the resulting system doesn't always show the design decisions and transitions that were made in modelling the domain, which is really at the core of DDD. DDD is much more about the process than it is the code. (as some say, the best DDD sample is the book itself!)

That said, a well commented sample app should at least reveal some of these decisions and give you some direction in terms of matching up your domain model with the technical patterns used to implement it.

You haven't specified which language you're using, but I'll give you a few in a few different languages:

DDDSample - a Java sample that reflects the examples Eric Evans talks about in his book. This is well commented and shows a number of different methods of solving various problems with separate bounded contexts (ie, the presentation layer). It's being actively worked on, so check it regularly for updates.

dddps - Tim McCarthy's sample C# app for his book, .NET Domain-Driven Design with C#

S#arp Architecture - a pragmatic C# example, not as "pure" a DDD approach perhaps due to its lack of a real domain problem, but still a nice clean approach.

With all of these sample apps, it's probably best to check out the latest trunk versions from SVN/whatever to really get an idea of the thinking and technology patterns as they should be updated regularly.

Python Web Crawlers and "getting" html source code

The first thing you need to do is read the HTTP spec which will explain what you can expect to receive over the wire. The data returned inside the content will be the "rendered" web page, not the source. The source could be a JSP, a servlet, a CGI script, in short, just about anything, and you have no access to that. You only get the HTML that the server sent you. In the case of a static HTML page, then yes, you will be seeing the "source". But for anything else you see the generated HTML, not the source.

When you say modify the page and return the modified page what do you mean?

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

Just a supplement here.

The following question is that what if I want more subplots in the figure?

As mentioned in the Doc, we can use fig = plt.subplots(nrows=2, ncols=2) to set a group of subplots with grid(2,2) in one figure object.

Then as we know, the fig, ax = plt.subplots() returns a tuple, let's try fig, ax1, ax2, ax3, ax4 = plt.subplots(nrows=2, ncols=2) firstly.

ValueError: not enough values to unpack (expected 4, got 2)

It raises a error, but no worry, because we now see that plt.subplots() actually returns a tuple with two elements. The 1st one must be a figure object, and the other one should be a group of subplots objects.

So let's try this again:

fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)

and check the type:

type(fig) #<class 'matplotlib.figure.Figure'>
type(ax1) #<class 'matplotlib.axes._subplots.AxesSubplot'>

Of course, if you use parameters as (nrows=1, ncols=4), then the format should be:

fig, [ax1, ax2, ax3, ax4] = plt.subplots(nrows=1, ncols=4)

So just remember to keep the construction of the list as the same as the subplots grid we set in the figure.

Hope this would be helpful for you.

PHP Warning Permission denied (13) on session_start()

I have had this issue before, you need more than the standard 755 or 644 permission to store the $_SESSION information. You need to be able to write to that file as that is how it remembers.

How to update/modify an XML file in python?

The quick and easy way, which you definitely should not do (see below), is to read the whole file into a list of strings using readlines(). I write this in case the quick and easy solution is what you're looking for.

Just open the file using open(), then call the readlines() method. What you'll get is a list of all the strings in the file. Now, you can easily add strings before the last element (just add to the list one element before the last). Finally, you can write these back to the file using writelines().

An example might help:

my_file = open(filename, "r")
lines_of_file = my_file.readlines()
lines_of_file.insert(-1, "This line is added one before the last line")
my_file.writelines(lines_of_file)

The reason you shouldn't be doing this is because, unless you are doing something very quick n' dirty, you should be using an XML parser. This is a library that allows you to work with XML intelligently, using concepts like DOM, trees, and nodes. This is not only the proper way to work with XML, it is also the standard way, making your code both more portable, and easier for other programmers to understand.

Tim's answer mentioned checking out xml.dom.minidom for this purpose, which I think would be a great idea.

Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'

Use FromResult Method

public async Task<string> GetString()
{
   System.Threading.Thread.Sleep(5000);
   return await Task.FromResult("Hello");
}

Android List View Drag and Drop sort

I have been working on this for some time now. Tough to get right, and I don't claim I do, but I'm happy with it so far. My code and several demos can be found at

Its use is very similar to the TouchInterceptor (on which the code is based), although significant implementation changes have been made.

DragSortListView has smooth and predictable scrolling while dragging and shuffling items. Item shuffles are much more consistent with the position of the dragging/floating item. Heterogeneous-height list items are supported. Drag-scrolling is customizable (I demonstrate rapid drag scrolling through a long list---not that an application comes to mind). Headers/Footers are respected. etc.?? Take a look.

Select first empty cell in column F starting from row 1. (without using offset )

I think a Do Until-loop is cleaner, shorter and more appropriate here:

Public Sub SelectFirstBlankCell(col As String)
    Dim Column_Index as Integer
    Dim Row_Counter as 

    Column_Index = Range(col & 1).Column
    Row_Counter = 1

    Do Until IsEmpty(Cells(Row_Counter, 1))
        Row_Counter = Row_Counter + 1
    Loop

    Cells(Row_Counter, Column_Index).Select

Perfect 100% width of parent container for a Bootstrap input?

If you're using C# ASP.NET MVC's default template you may find that site.css overrides some of Bootstraps styles. If you want to use Bootstrap, as I did, having M$ override this (without your knowledge) can be a source of great frustration! Feel free to remove any of the unwanted styles...

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

Is floating point math broken?

Floating point rounding error. From What Every Computer Scientist Should Know About Floating-Point Arithmetic:

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation.

Find duplicate lines in a file and count how many time each line was duplicated?

To find and count duplicate lines in multiple files, you can try the following command:

sort <files> | uniq -c | sort -nr

or:

cat <files> | sort | uniq -c | sort -nr

SELECT only rows that contain only alphanumeric characters in MySQL

Try this:

REGEXP '^[a-z0-9]+$'

As regexp is not case sensitive except for binary fields.

Getting rid of all the rounded corners in Twitter Bootstrap

If you are using Bootstrap version < 3...

With sass/scss

$baseBorderRadius: 0;

With less

@baseBorderRadius: 0;

You will need to set this variable before importing the bootstrap. This will affect all wells and navbars.

Update

If you are using Bootstrap 3 baseBorderRadius should be border-radius-base

How generate unique Integers based on GUIDs

Here is the simplest way:

Guid guid = Guid.NewGuid();
Random random = new Random();
int i = random.Next();

You'll notice that guid is not actually used here, mainly because there would be no point in using it. Microsoft's GUID algorithm does not use the computer's MAC address any more - GUID's are actually generated using a pseudo-random generator (based on time values), so if you want a random integer it makes more sense to use the Random class for this.

Update: actually, using a GUID to generate an int would probably be worse than just using Random ("worse" in the sense that this would be more likely to generate collisions). This is because not all 128 bits in a GUID are random. Ideally, you would want to exclude the non-varying bits from a hashing function, although it would be a lot easier to just generate a random number, as I think I mentioned before. :)

How to hide a div with jQuery?

$('#myDiv').hide() will hide the div...

Getting GET "?" variable in laravel

This is the best practice. This way you will get the variables from GET method as well as POST method

    public function index(Request $request) {
            $data=$request->all();
            dd($data);
    }
//OR if you want few of them then
    public function index(Request $request) {
            $data=$request->only('id','name','etc');
            dd($data);
    }
//OR if you want all except few then
    public function index(Request $request) {
            $data=$request->except('__token');
            dd($data);
    }

How to pass arguments to a Button command in Tkinter?

The best thing to do is use lambda as follows:

button = Tk.Button(master=frame, text='press', command=lambda: action(someNumber))

Turning off auto indent when pasting text into vim

The fastest way I’m aware of to quickly go to paste-insert mode for a one-shot paste is tpope’s unimpaired, which features yo and yO, presumably mnemonics for “you open”. They’re only documented in his vimdoc, as:

A toggle has not been provided for 'paste' because the typical use case of wrapping of a solitary insertion is so wasteful: You toggle twice, but you only paste once (YOPO). Instead, press yo or yO to invoke o or O with 'paste' already set. Leaving insert mode sets 'nopaste' automatically.

Get first row of dataframe in Python Pandas based on criteria

For the point that 'returns the value as soon as you find the first row/record that meets the requirements and NOT iterating other rows', the following code would work:

def pd_iter_func(df):
    for row in df.itertuples():
        # Define your criteria here
        if row.A > 4 and row.B > 3:
            return row

It is more efficient than Boolean Indexing when it comes to a large dataframe.

To make the function above more applicable, one can implements lambda functions:

def pd_iter_func(df: DataFrame, criteria: Callable[[NamedTuple], bool]) -> Optional[NamedTuple]:
    for row in df.itertuples():
        if criteria(row):
            return row

pd_iter_func(df, lambda row: row.A > 4 and row.B > 3)

As mentioned in the answer to the 'mirror' question, pandas.Series.idxmax would also be a nice choice.

def pd_idxmax_func(df, mask):
    return df.loc[mask.idxmax()]

pd_idxmax_func(df, (df.A > 4) & (df.B > 3))

git - pulling from specific branch

This worked perfectly for me, although fetching all branches could be a bit too much:

git init
git remote add origin https://github.com/Vitosh/VBA_personal.git
git fetch --all
git checkout develop

enter image description here

How to dynamically set bootstrap-datepicker's date value?

That really works.

Simple,

Easy to understand,

Single method to set and update plugin which worked for me.

$(".datepicker").datepicker("update", new Date());

Other ways to update

$('.datepicker').data({date: '2015-01-01'});
$('.datepicker').datepicker('update');

Dont forget to call update manually.

How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?

If you're using Entity Framework < v6.0, then use EntityFunctions.TruncateTime If you're using Entity Framework >= v6.0, then use DbFunctions.TruncateTime

Use either (based on your EF version) around any DateTime class property you want to use inside your Linq query

Example

var list = db.Cars.Where(c=> DbFunctions.TruncateTime(c.CreatedDate) 
                                       >= DbFunctions.TruncateTime(DateTime.UtcNow));

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

A more appropriate approach is to specify a Locale region as a parameter in the constructor. The example below uses a US Locale region. Date formatting is locale-sensitive and uses the Locale to tailor information relative to the customs and conventions of the user's region Locale (Java Platform SE 7)

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss", Locale.US).format(new Date());

How to test if JSON object is empty in Java

A JSON notation {} represents an empty object, meaning an object without members. This is not the same as null. Neither it is string as you are trying to compare it with string "{}". I don't know which json library are you using, but try to look for method something like:

isEmptyObject() 

Page vs Window in WPF?

Page Control can be contained in Window Control but vice versa is not possible

You can use Page control within the Window control using NavigationWindow and Frame controls. Window is the root control that must be used to hold/host other controls (e.g. Button) as container. Page is a control which can be hosted in other container controls like NavigationWindow or Frame. Page control has its own goal to serve like other controls (e.g. Button). Page is to create browser like applications. So if you host Page in NavigationWindow, you will get the navigation implementation built-in. Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer).

WPF provides support for browser style navigation inside standalone application using Page class. User can create multiple pages, navigate between those pages along with data.There are multiple ways available to Navigate through one page to another page.

git ignore vim temporary files

Vim temporary files end with ~ so you can add to the file .gitignore the line

*~

Vim also creates swap files that have the swp and swo extensions. to remove those use the lines:

*.swp
*.swo

This will ignore all the vim temporary files in a single project

If you want to do it globally, you can create a .gitignore file in your home (you can give it other name or location), and use the following command:

git config --global core.excludesfile ~/.gitignore

Then you just need to add the files you want to ignore to that file

How can I split a shell command over multiple lines when using an IF statement?

For Windows/WSL/Cygwin etc users:

Make sure that your line endings are standard Unix line feeds, i.e. \n (LF) only.

Using Windows line endings \r\n (CRLF) line endings will break the command line break.


This is because having \ at the end of a line with Windows line ending translates to \ \r \n.
As Mark correctly explains above:

The line-continuation will fail if you have whitespace after the backslash and before the newline.

This includes not just space () or tabs (\t) but also the carriage return (\r).

Change output format for MySQL command line results to CSV

As a partial answer: mysql -N -B -e "select people, places from things"

-N tells it not to print column headers. -B is "batch mode", and uses tabs to separate fields.

If tab separated values won't suffice, see this Stackoverflow Q&A.

Two decimal places using printf( )

Try using a format like %d.%02d

int iAmount = 10050;
printf("The number with fake decimal point is %d.%02d", iAmount/100, iAmount%100);

Another approach is to type cast it to double before printing it using %f like this:

printf("The number with fake decimal point is %0.2f", (double)(iAmount)/100);

My 2 cents :)

Bash script processing limited number of commands in parallel

See parallel. Its syntax is similar to xargs, but it runs the commands in parallel.

How to efficiently build a tree from a flat structure?

The accepted answer looks way too complex to me so I am adding a Ruby and NodeJS versions of it

Suppose that flat nodes list have the following structure:

nodes = [
  { id: 7, parent_id: 1 },
  ...
] # ruby

nodes = [
  { id: 7, parentId: 1 },
  ...
] # nodeJS

The functions which will turn the flat list structure above into a tree look the following way

for Ruby:

def to_tree(nodes)

  nodes.each do |node|

    parent = nodes.find { |another| another[:id] == node[:parent_id] }
    next unless parent

    node[:parent] = parent
    parent[:children] ||= []
    parent[:children] << node

  end

  nodes.select { |node| node[:parent].nil? }

end

for NodeJS:

const toTree = (nodes) => {

  nodes.forEach((node) => {

    const parent = nodes.find((another) => another.id == node.parentId)
    if(parent == null) return;

    node.parent = parent;
    parent.children = parent.children || [];
    parent.children = parent.children.concat(node);

  });

  return nodes.filter((node) => node.parent == null)

};

What to do about Eclipse's "No repository found containing: ..." error messages?

Updating from Kepler SR1 to Kepler SR2 solved this for me. I've just installed over the existing installation, so none of my settings were harmed.

Win8.1, 64bit

SSIS cannot convert because a potential loss of data

For me just removed the OLE DB source from SSIS and added again. Worked!

Git push rejected after feature branch rebase

My way of avoiding the force push is to create a new branch and continuing work on that new branch and after some stability, remove the old branch that was rebased:

  • Rebasing the checked out branch locally
  • Branching from the rebased branch to a new branch
  • Pushing that branch as a new branch to remote. and deleting the old branch on remote

import android packages cannot be resolved

I just had the same problem after accepting a Java update--scores of build errors and android import not recognized. On checking the build path in Project=>Properties, I found that the check box for Android 4.3 had somehow gotten cleared. Checking it resolved all the import errors without my even having to restart the IDE or run a project clean.

Replace last occurrence of a string in a string

You can use this function:

function str_lreplace($search, $replace, $subject)
{
    $pos = strrpos($subject, $search);

    if($pos !== false)
    {
        $subject = substr_replace($subject, $replace, $pos, strlen($search));
    }

    return $subject;
}

Create a directory if it does not exist and then create the files in that directory as well

Java 8+ version:

Files.createDirectories(Paths.get("/Your/Path/Here"));

The Files.createDirectories() creates a new directory and parent directories that do not exist. This method does not throw an exception if the directory already exists.

How to run SQL in shell script

You can use a heredoc. e.g. from a prompt:

$ sqlplus -s username/password@oracle_instance <<EOF
set feed off
set pages 0
select count(*) from table;
exit
EOF

so sqlplus will consume everything up to the EOF marker as stdin.

How does Trello access the user's clipboard?

With the help of raincoat's code on GitHub, I managed to get a running version accessing the clipboard with plain JavaScript.

function TrelloClipboard() {
    var me = this;

    var utils = {
        nodeName: function (node, name) {
            return !!(node.nodeName.toLowerCase() === name)
        }
    }
    var textareaId = 'simulate-trello-clipboard',
        containerId = textareaId + '-container',
        container, textarea

    var createTextarea = function () {
        container = document.querySelector('#' + containerId)
        if (!container) {
            container = document.createElement('div')
            container.id = containerId
            container.setAttribute('style', [, 'position: fixed;', 'left: 0px;', 'top: 0px;', 'width: 0px;', 'height: 0px;', 'z-index: 100;', 'opacity: 0;'].join(''))
            document.body.appendChild(container)
        }
        container.style.display = 'block'
        textarea = document.createElement('textarea')
        textarea.setAttribute('style', [, 'width: 1px;', 'height: 1px;', 'padding: 0px;'].join(''))
        textarea.id = textareaId
        container.innerHTML = ''
        container.appendChild(textarea)

        textarea.appendChild(document.createTextNode(me.value))
        textarea.focus()
        textarea.select()
    }

    var keyDownMonitor = function (e) {
        var code = e.keyCode || e.which;
        if (!(e.ctrlKey || e.metaKey)) {
            return
        }
        var target = e.target
        if (utils.nodeName(target, 'textarea') || utils.nodeName(target, 'input')) {
            return
        }
        if (window.getSelection && window.getSelection() && window.getSelection().toString()) {
            return
        }
        if (document.selection && document.selection.createRange().text) {
            return
        }
        setTimeout(createTextarea, 0)
    }

    var keyUpMonitor = function (e) {
        var code = e.keyCode || e.which;
        if (e.target.id !== textareaId || code !== 67) {
            return
        }
        container.style.display = 'none'
    }

    document.addEventListener('keydown', keyDownMonitor)
    document.addEventListener('keyup', keyUpMonitor)
}

TrelloClipboard.prototype.setValue = function (value) {
    this.value = value;
}

var clip = new TrelloClipboard();
clip.setValue("test");

See a working example: http://jsfiddle.net/AGEf7/

How to replace DOM element in place using Javascript?

Example for replacing LI elements

function (element) {
    let li = element.parentElement;
    let ul = li.parentNode;   
    if (li.nextSibling.nodeName === 'LI') {
        let li_replaced = ul.replaceChild(li, li.nextSibling);
        ul.insertBefore(li_replaced, li);
    }
}

Update query PHP MySQL

You have to have single quotes around any VARCHAR content in your queries. So your update query should be:

mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = $id");

Also, it is bad form to update your database directly with the content from a POST. You should sanitize your incoming data with the mysql_real_escape_string function.

How do I remove trailing whitespace using a regular expression?

Try just removing trailing spaces and tabs:

[ \t]+$

How to add composite primary key to table

The ALTER TABLE statement presented by Chris should work, but first you need to declare the columns NOT NULL. All parts of a primary key need to be NOT NULL.

How to get the IP address of the server on which my C# application is running on?

For getting the current public IP address, all you need to do is create an ASPX page with the following line on the page load event:

Response.Write(HttpContext.Current.Request.UserHostAddress.ToString());

How to change working directory in Jupyter Notebook?

  1. list all magic command %lsmagic
  2. show current directory %pwd

Python CSV error: line contains NULL byte

Instead of csv reader I use read file and split function for string:

lines = open(input_file,'rb') 

for line_all in lines:

    line=line_all.replace('\x00', '').split(";")

How do I convert an integer to binary in JavaScript?

we can also calculate the binary for positive or negative numbers as below:

_x000D_
_x000D_
function toBinary(n){
    let binary = "";
    if (n < 0) {
      n = n >>> 0;
    }
    while(Math.ceil(n/2) > 0){
        binary = n%2 + binary;
        n = Math.floor(n/2);
    }
    return binary;
}

console.log(toBinary(7));
console.log(toBinary(-7));
_x000D_
_x000D_
_x000D_

How to escape regular expression special characters using javascript?

Use the backslash to escape a character. For example:

/\\d/

This will match \d instead of a numeric character

Change a Django form field to a hidden field

If you want the field to always be hidden, use the following:

class MyForm(forms.Form):
    hidden_input = forms.CharField(widget=forms.HiddenInput(), initial="value")

If you want the field to be conditionally hidden, you can do the following:

form = MyForm()
if condition:
    form.fields["field_name"].widget = forms.HiddenInput()
    form.fields["field_name"].initial = "value"

How to I say Is Not Null in VBA

Use Not IsNull(Fields!W_O_Count.Value)

How to sort a list of strings?

list.sort()

It really is that simple :)

Where should I put the log4j.properties file?

If you put log4j.properties inside src, you don't need to use the statement -

PropertyConfigurator.configure("log4j.properties");

It will be taken automatically as the properties file is in the classpath.

How to set .net Framework 4.5 version in IIS 7 application pool

There is no 4.5 application pool. You can use any 4.5 application in 4.0 app pool. The .NET 4.5 is "just" an in-place-update not a major new version.

Java: is there a map function?

This is another functional lib with which you may use map: http://code.google.com/p/totallylazy/

sequence(1, 2).map(toString); // lazily returns "1", "2"

Updating address bar with new URL without hash or reloading the page

Update to Davids answer to even detect browsers that do not support pushstate:

if (history.pushState) {
  window.history.pushState("object or string", "Title", "/new-url");
} else {
  document.location.href = "/new-url";
}

Android WebView not loading URL

Add Permission Internet permission in manifest.

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

This code it working

  public class WebActivity extends Activity {
  WebView wv;

 String url="http://www.teluguoneradio.com/rssHostDescr.php?hostId=147";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web);
    wv=(WebView)findViewById(R.id.webUrl_WEB);



WebSettings webSettings = wv.getSettings();
    wv.getSettings().setLoadWithOverviewMode(true);
    wv.getSettings().setUseWideViewPort(true);
    wv.getSettings().setBuiltInZoomControls(true);
    wv.getSettings().setPluginState(PluginState.ON);


    wv.setWebViewClient(new myWebClient());

    wv.loadUrl(url);
}




public class myWebClient extends WebViewClient {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub

        view.loadUrl(url);
        return true;

    }
}

Passing array in GET for a REST call

Collections are a resource so /appointments is fine as the resource.

Collections also typically offer filters via the querystring which is essentially what users=id1,id2... is.

So,

/appointments?users=id1,id2 

is fine as a filtered RESTful resource.

JavaScript ternary operator example with functions

I would also like to add something from me.

Other possible syntax to call functions with the ternary operator, would be:

(condition ? fn1 : fn2)();

It can be handy if you have to pass the same list of parameters to both functions, so you have to write them only once.

(condition ? fn1 : fn2)(arg1, arg2, arg3, arg4, arg5);

You can use the ternary operator even with member function names, which I personally like very much to save space:

$('.some-element')[showThisElement ? 'addClass' : 'removeClass']('visible');

or

$('.some-element')[(showThisElement ? 'add' : 'remove') + 'Class']('visible');

Another example:

var addToEnd = true; //or false
var list = [1,2,3,4];
list[addToEnd ? 'push' : 'unshift'](5);

How can I split a text into sentences?

The Natural Language Toolkit (nltk.org) has what you need. This group posting indicates this does it:

import nltk.data

tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
fp = open("test.txt")
data = fp.read()
print '\n-----\n'.join(tokenizer.tokenize(data))

(I haven't tried it!)

Permanently hide Navigation Bar in an activity

Start by hiding in OnResume() of the activity then also keep hiding as shown below:

decorView.setOnSystemUiVisibilityChangeListener
                (new View.OnSystemUiVisibilityChangeListener() {
                    @Override
                    public void onSystemUiVisibilityChange(int visibility) {
                        // Note that system bars will only be "visible" if none of the
                        // LOW_PROFILE, HIDE_NAVIGATION, or FULLSCREEN flags are set.
                        if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                            //visible
                            hideSystemUI();
                        } 
                    }
                    }
                });`

    public void hideSystemUI() {
        // Set the IMMERSIVE flag.
        // Set the content to appear under the system bars so that the content
        // doesn't resize when the system bars hide and show.
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                        | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                        | View.SYSTEM_UI_FLAG_IMMERSIVE);
    }

How do I use a pipe to redirect the output of one command to the input of another?

Not sure if you are coding these programs, but this is a simple example of how you'd do it.

program1.c

#include <stdio.h>
int main (int argc, char * argv[] ) {
    printf("%s", argv[1]); 
    return 0;
}

rgx.cpp

#include <cstdio>
#include <regex>
#include <iostream>
using namespace std;
int main (int argc, char * argv[] ) {
    char input[200];
    fgets(input,200,stdin);
    string s(input)
    smatch m;
    string reg_exp(argv[1]);
    regex e(reg_exp);
    while (regex_search (s,m,e)) {
      for (auto x:m) cout << x << " ";
      cout << endl;
      s = m.suffix().str();
    }
    return 0;
}

Compile both then run program1.exe "this subject has a submarine as a subsequence" | rgx.exe "\b(sub)([^ ]*)"

The | operator simply redirects the output of program1's printf operation from the stdout stream to the stdin stream whereby it's sitting there waiting for rgx.exe to pick up.

What's the difference between jquery.js and jquery.min.js?

In easy language, both versions are absolutely the same. Only difference is:

  • min.js is for websites (online)

  • .js is for developers, guys who needs to read, learn about or/and understand jquery codes, for ie plugin development (offline, local work).

Static link of shared library function in gcc

Yeah, I know this is an 8 year-old question, but I was told that it was possible to statically link against a shared-object library and this was literally the top hit when I searched for more information about it.

To actually demonstrate that statically linking a shared-object library is not possible with ld (gcc's linker) -- as opposed to just a bunch of people insisting that it's not possible -- use the following gcc command:

gcc -o executablename objectname.o -Wl,-Bstatic -l:libnamespec.so

(Of course you'll have to compile objectname.o from sourcename.c, and you should probably make up your own shared-object library as well. If you do, use -Wl,--library-path,. so that ld can find your library in the local directory.)

The actual error you receive is:

/usr/bin/ld: attempted static link of dynamic object `libnamespec.so'
collect2: error: ld returned 1 exit status

Hope that helps.

Python check if website exists

It's better to check that status code is < 400, like it was done here. Here is what do status codes mean (taken from wikipedia):

  • 1xx - informational
  • 2xx - success
  • 3xx - redirection
  • 4xx - client error
  • 5xx - server error

If you want to check if page exists and don't want to download the whole page, you should use Head Request:

import httplib2
h = httplib2.Http()
resp = h.request("http://www.google.com", 'HEAD')
assert int(resp[0]['status']) < 400

taken from this answer.

If you want to download the whole page, just make a normal request and check the status code. Example using requests:

import requests

response = requests.get('http://google.com')
assert response.status_code < 400

See also similar topics:

Hope that helps.

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

I created my AppIcon catalog manually and had all the correct icons in it, but my project was not using it as the icon catalog. On the project's General tab (where you can set the project name and version number), there was an entry for App Icons Source, but no way to select the catalog I created. I had to click the button to create a new catalog, then delete that new catalog, and then the button changed to a menu where I could select the existing catalog.

custom facebook share button

Given that we are in a php code context and the variable $url contains the link the user wants to share, you can try this to use a custom image :

<a class="facebook-share-button" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($url); ?>" target="_blank"><img src="/img/facebook-share-button.png" /></a>

or this for just plain text :

<a class="facebook-share-button" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($url); ?>" target="_blank">share</a>

You can also style the link purely with css.

The html code :

<a class="facebook-share-button" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo urlencode($url); ?>" target="_blank"></a>

The css code :

.facebook-share-button {
    background-image: url("/img/facebook-share-button.png");
    display: inline-block;
    height: 32px;
    width: 32px;
}

.facebook-share-button:active,
.facebook-share-button:focus,
.facebook-share-button:hover {
    background-image: url("/img/facebook-share-button-hover.png");
}

Converting HTML to Excel?

Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.

How do I REALLY reset the Visual Studio window layout?

I tried most of the suggestions, and none of them worked. I didn't get a chance to try /resetuserdata. Finally I reinstalled the plugin and uninstalled it again, and the windows went away.

Extracting specific columns in numpy array

One more thing you should pay attention to when selecting columns from N-D array using a list like this:

data[:,:,[1,9]]

If you are removing a dimension (by selecting only one row, for example), the resulting array will be (for some reason) permuted. So:

print data.shape            # gives [10,20,30]
selection = data[1,:,[1,9]]
print selection.shape       # gives [2,20] instead of [20,2]!!

Is there a regular expression to detect a valid regular expression?

No, if you are strictly speaking about regular expressions and not including some regular expression implementations that are actually context free grammars.

There is one limitation of regular expressions which makes it impossible to write a regex that matches all and only regexes. You cannot match implementations such as braces which are paired. Regexes use many such constructs, let's take [] as an example. Whenever there is an [ there must be a matching ], which is simple enough for a regex "\[.*\]".

What makes it impossible for regexes is that they can be nested. How can you write a regex that matches nested brackets? The answer is you can't without an infinitely long regex. You can match any number of nested parenthesis through brute force but you can't ever match an arbitrarily long set of nested brackets.

This capability is often referred to as counting, because you're counting the depth of the nesting. A regex by definition does not have the capability to count.


I ended up writing "Regular Expression Limitations" about this.

installing urllib in Python3.6

yu have to install the correct version for your computer 32 or 63 bits thats all

How to generate gcc debug symbol outside the build target?

You need to use objcopy to separate the debug information:

objcopy --only-keep-debug "${tostripfile}" "${debugdir}/${debugfile}"
strip --strip-debug --strip-unneeded "${tostripfile}"
objcopy --add-gnu-debuglink="${debugdir}/${debugfile}" "${tostripfile}"

I use the bash script below to separate the debug information into files with a .debug extension in a .debug directory. This way I can tar the libraries and executables in one tar file and the .debug directories in another. If I want to add the debug info later on I simply extract the debug tar file and voila I have symbolic debug information.

This is the bash script:

#!/bin/bash

scriptdir=`dirname ${0}`
scriptdir=`(cd ${scriptdir}; pwd)`
scriptname=`basename ${0}`

set -e

function errorexit()
{
  errorcode=${1}
  shift
  echo $@
  exit ${errorcode}
}

function usage()
{
  echo "USAGE ${scriptname} <tostrip>"
}

tostripdir=`dirname "$1"`
tostripfile=`basename "$1"`


if [ -z ${tostripfile} ] ; then
  usage
  errorexit 0 "tostrip must be specified"
fi

cd "${tostripdir}"

debugdir=.debug
debugfile="${tostripfile}.debug"

if [ ! -d "${debugdir}" ] ; then
  echo "creating dir ${tostripdir}/${debugdir}"
  mkdir -p "${debugdir}"
fi
echo "stripping ${tostripfile}, putting debug info into ${debugfile}"
objcopy --only-keep-debug "${tostripfile}" "${debugdir}/${debugfile}"
strip --strip-debug --strip-unneeded "${tostripfile}"
objcopy --add-gnu-debuglink="${debugdir}/${debugfile}" "${tostripfile}"
chmod -x "${debugdir}/${debugfile}"

How to install mod_ssl for Apache httpd?

Are any other LoadModule commands referencing modules in the /usr/lib/httpd/modules folder? If so, you should be fine just adding LoadModule ssl_module /usr/lib/httpd/modules/mod_ssl.so to your conf file.

Otherwise, you'll want to copy the mod_ssl.so file to whatever directory the other modules are being loaded from and reference it there.

How do I import a specific version of a package using go get?

Glide is a really elegant package management for Go especially if you come from Node's npm or Rust's cargo.

It behaves closely to Godep's new vendor feature in 1.6 but is way more easier. Your dependencies and versions are "locked" inside your projectdir/vendor directory without relying on GOPATH.

Install with brew (OS X)

$ brew install glide

Init the glide.yaml file (akin to package.json). This also grabs the existing imported packages in your project from GOPATH and copy then to the project's vendor/ directory.

$ glide init

Get new packages

$ glide get vcs/namespace/package

Update and lock the packages' versions. This creates glide.lock file in your project directory to lock the versions.

$ glide up

I tried glide and been happily using it for my current project.

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

    echo " Enter any values to sorting: "
read n
i=0;
t=0;
echo " Enter the n value: "
for(( i=0;i<n;i++ ))
do
read s[$i]
done
for(( i=0;i<n;i++ ))
do
for(( j=i+1;j<n;j++ ))
do
if [ ${s[$i]} -gt ${s[$j]} ]
then
t=${s[$i]}
s[$i]=${s[$j]}
s[$j]=$t
fi
done
done
for(( i=0;i<n;i++ ))
do
echo " ${s[$i]}  "
done

Best radio-button implementation for IOS

The following simple way to create radio button in your iOS app follow two steps.

Step1- Put this code in your in viewDidLoad or any other desired method

 [_mrRadio setSelected:YES];
        [_mrRadio setTag:1];
        [_msRadio setTag:1];
        [_mrRadio setBackgroundImage:[UIImage imageNamed:@"radiodselect_white.png"] forState:UIControlStateNormal];
        [_mrRadio setBackgroundImage:[UIImage imageNamed:@"radioselect_white.png"] forState:UIControlStateSelected];
        [_mrRadio addTarget:self action:@selector(radioButtonSelected:) forControlEvents:UIControlEventTouchUpInside];

        [_msRadio setBackgroundImage:[UIImage imageNamed:@"radiodselect_white.png"] forState:UIControlStateNormal];
        [_msRadio setBackgroundImage:[UIImage imageNamed:@"radioselect_white.png"] forState:UIControlStateSelected];
        [_msRadio addTarget:self action:@selector(radioButtonSelected:) forControlEvents:UIControlEventTouchUpInside];

Step2- Put following IBAction method in your class

-(void)radioButtonSelected:(id)sender
{
    switch ([sender tag ]) {
        case 1:
            if ([_mrRadio isSelected]==YES) {
              //  [_mrRadio setSelected:NO];
               // [_msRadio setSelected:YES];
               genderType = @"1";
            }
            else
            {
                [_mrRadio setSelected:YES];
                [_msRadio setSelected:NO];
                genderType = @"1";
            }
            break;
        case 2:
            if ([_msRadio isSelected]==YES) {
               // [_msRadio setSelected:NO];
               // [_mrRadio setSelected:YES];
                genderType = @"2";
            }
            else
            {
                [_msRadio setSelected:YES];
                [_mrRadio setSelected:NO];
                 genderType = @"2";
            }
            break;
        default:
            break;
    }
}

If file exists then delete the file

You're close, you just need to delete the file before trying to over-write it.

dim infolder: set infolder = fso.GetFolder(IN_PATH)
dim file: for each file in infolder.Files

    dim name: name = file.name
    dim parts: parts = split(name, ".")

    if UBound(parts) = 2 then

       ' file name like a.c.pdf    

        dim newname: newname = parts(0) & "." & parts(2)
        dim newpath: newpath = fso.BuildPath(OUT_PATH, newname)

        ' warning:
        ' if we have source files C:\IN_PATH\ABC.01.PDF, C:\IN_PATH\ABC.02.PDF, ...
        ' only one of them will be saved as D:\OUT_PATH\ABC.PDF

        if fso.FileExists(newpath) then
            fso.DeleteFile newpath
        end if

        file.Move newpath

    end if

next

How do you make an anchor link non-clickable or disabled?

Just remove the href attribute from the anchor tag.

How to write a basic swap function in Java

You can easily write one yourself.

given:

int array[]={1,2};

you do:

int temp=array[0];
array[0]=array[1];
array[1]=temp;

And you're done. 3 lines of code.

Java, How to specify absolute value and square roots

Try using Math.abs:

variableAbs = Math.abs(variable);

For square root use:

variableSqRt = Math.sqrt(variable);

How do I find an array item with TypeScript? (a modern, easier way)

If you need some es6 improvements not supported by Typescript, you can target es6 in your tsconfig and use Babel to convert your files in es5.

How to convert xml into array in php?

Converting an XML string ($buffer) into a simplified array ignoring attributes and grouping child-elements with the same names:

function XML2Array(SimpleXMLElement $parent)
{
    $array = array();

    foreach ($parent as $name => $element) {
        ($node = & $array[$name])
            && (1 === count($node) ? $node = array($node) : 1)
            && $node = & $node[];

        $node = $element->count() ? XML2Array($element) : trim($element);
    }

    return $array;
}

$xml   = simplexml_load_string($buffer);
$array = XML2Array($xml);
$array = array($xml->getName() => $array);

Result:

Array
(
    [aaaa] => Array
        (
            [bbb] => Array
                (
                    [cccc] => Array
                        (
                            [dddd] => 
                            [eeee] => 
                        )

                )

        )

)

If you also want to have the attributes, they are available via JSON encoding/decoding of SimpleXMLElement. This is often the most easy quick'n'dirty solution:

$xml   = simplexml_load_string($buffer);
$array = json_decode(json_encode((array) $xml), true);
$array = array($xml->getName() => $array);

Result:

Array
(
    [aaaa] => Array
        (
            [@attributes] => Array
                (
                    [Version] => 1.0
                )

            [bbb] => Array
                (
                    [cccc] => Array
                        (
                            [dddd] => Array
                                (
                                    [@attributes] => Array
                                        (
                                            [Id] => id:pass
                                        )

                                )

                            [eeee] => Array
                                (
                                    [@attributes] => Array
                                        (
                                            [name] => hearaman
                                            [age] => 24
                                        )

                                )

                        )

                )

        )

)

Take note that all these methods only work in the namespace of the XML document.

How do I iterate over the words of a string?

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>

int main() {
    using namespace std;
   int n=8;
    string sentence = "10 20 30 40 5 6 7 8";
    istringstream iss(sentence);

  vector<string> tokens;
copy(istream_iterator<string>(iss),
     istream_iterator<string>(),
     back_inserter(tokens));

     for(int i=0;i<n;i++){
        cout<<tokens.at(i);
     }


}

how to check if a file is a directory or regular file in python?

os.path.isfile("bob.txt") # Does bob.txt exist?  Is it a file, or a directory?
os.path.isdir("bob")

Use Ant for running program with command line arguments

If you do not want to handle separate properties for each possible argument, I suggest you'd use:

<arg line="${args}"/>

You can check if the property is not set using a specific target with an unless attribute and inside do:

<input message="Type the desired command line arguments:" addProperty="args"/>

Putting it all together gives:

<target name="run" depends="compile, input-runargs" description="run the project">
  <!-- You can use exec here, depending on your needs -->
  <java classname="Main">
    <arg line="${args}"/>
  </java>
</target>
<target name="input-runargs" unless="args" description="prompts for command line arguments if necessary">
  <input addProperty="args" message="Type the desired command line arguments:"/>
</target>

You can use it as follows:

ant
ant run
ant run -Dargs='--help'

The first two commands will prompt for the command-line arguments, whereas the latter won't.

Which variable size to use (db, dw, dd) with x86 assembly?

The full list is:

DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)

See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html

They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):

    db      0x55                ; just the byte 0x55
    db      0x55,0x56,0x57      ; three bytes in succession
    db      'a',0x55            ; character constants are OK
    db      'hello',13,10,'$'   ; so are string constants
    dw      0x1234              ; 0x34 0x12
    dw      'A'                 ; 0x41 0x00 (it's just a number)
    dw      'AB'                ; 0x41 0x42 (character constant)
    dw      'ABC'               ; 0x41 0x42 0x43 0x00 (string)
    dd      0x12345678          ; 0x78 0x56 0x34 0x12
    dq      0x1122334455667788  ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    ddq     0x112233445566778899aabbccddeeff00
    ; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
    ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    do      0x112233445566778899aabbccddeeff00 ; same as previous
    dd      1.234567e20         ; floating-point constant
    dq      1.234567e20         ; double-precision float
    dt      1.234567e20         ; extended-precision float

DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.

Return array from function

At a minimum, change this:

function BlockID() {
    var IDs = new Array();
        images['s'] = "Images/Block_01.png";
        images['g'] = "Images/Block_02.png";
        images['C'] = "Images/Block_03.png";
        images['d'] = "Images/Block_04.png";
    return IDs;
}

To this:

function BlockID() {
    var IDs = new Object();
        IDs['s'] = "Images/Block_01.png";
        IDs['g'] = "Images/Block_02.png";
        IDs['C'] = "Images/Block_03.png";
        IDs['d'] = "Images/Block_04.png";
    return IDs;
}

There are a couple fixes to point out. First, images is not defined in your original function, so assigning property values to it will throw an error. We correct that by changing images to IDs. Second, you want to return an Object, not an Array. An object can be assigned property values akin to an associative array or hash -- an array cannot. So we change the declaration of var IDs = new Array(); to var IDs = new Object();.

After those changes your code will run fine, but it can be simplified further. You can use shorthand notation (i.e., object literal property value shorthand) to create the object and return it immediately:

function BlockID() {
    return {
            "s":"Images/Block_01.png"
            ,"g":"Images/Block_02.png"
            ,"C":"Images/Block_03.png"
            ,"d":"Images/Block_04.png"
    };
}

Is there a format code shortcut for Visual Studio?

Select all text in the document and press Ctrl + E + D.

C#: what is the easiest way to subtract time?

Hi if you are going to subtract only Integer value from DateTime then you have to write code like this

DateTime.Now.AddHours(-2)

Here I am subtracting 2 hours from the current date and time

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

Above two answers are correct but didn't work for me.

  1. I kept on seeing blank like below for docker container lsenter image description here
  2. then I tried, docker container ls -a and after that it showed all the process previously exited and running.
  3. Then docker stop <container id> or docker container stop <container id> didn't work
  4. then I tried docker rm -f <container id> and it worked.
  5. Now at this I tried docker container ls -a and this process wasn't present.

Test process.env with Jest

Another option is to add it to the jest.config.js file after the module.exports definition:

process.env = Object.assign(process.env, {
  VAR_NAME: 'varValue',
  VAR_NAME_2: 'varValue2'
});

This way it's not necessary to define the environment variables in each .spec file and they can be adjusted globally.

Embedding DLLs in a compiled executable

I use the csc.exe compiler called from a .vbs script.

In your xyz.cs script, add the following lines after the directives (my example is for the Renci SSH):

using System;
using Renci;//FOR THE SSH
using System.Net;//FOR THE ADDRESS TRANSLATION
using System.Reflection;//FOR THE Assembly

//+ref>"C:\Program Files (x86)\Microsoft\ILMerge\Renci.SshNet.dll"
//+res>"C:\Program Files (x86)\Microsoft\ILMerge\Renci.SshNet.dll"
//+ico>"C:\Program Files (x86)\Microsoft CAPICOM 2.1.0.2 SDK\Samples\c_sharp\xmldsig\resources\Traffic.ico"

The ref, res and ico tags will be picked up by the .vbs script below to form the csc command.

Then add the assembly resolver caller in the Main:

public static void Main(string[] args)
{
    AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
    .

...and add the resolver itself somewhere in the class:

    static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    {
        String resourceName = new AssemblyName(args.Name).Name + ".dll";

        using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
        {
            Byte[] assemblyData = new Byte[stream.Length];
            stream.Read(assemblyData, 0, assemblyData.Length);
            return Assembly.Load(assemblyData);
        }

    }

I name the vbs script to match the .cs filename (e.g. ssh.vbs looks for ssh.cs); this makes running the script numerous times a lot easier, but if you aren't an idiot like me then a generic script could pick up the target .cs file from a drag-and-drop:

    Dim name_,oShell,fso
    Set oShell = CreateObject("Shell.Application")
    Set fso = CreateObject("Scripting.fileSystemObject")

    'TAKE THE VBS SCRIPT NAME AS THE TARGET FILE NAME
    '################################################
    name_ = Split(wscript.ScriptName, ".")(0)

    'GET THE EXTERNAL DLL's AND ICON NAMES FROM THE .CS FILE
    '#######################################################
    Const OPEN_FILE_FOR_READING = 1
    Set objInputFile = fso.OpenTextFile(name_ & ".cs", 1)

    'READ EVERYTHING INTO AN ARRAY
    '#############################
    inputData = Split(objInputFile.ReadAll, vbNewline)

    For each strData In inputData

        if left(strData,7)="//+ref>" then 
            csc_references = csc_references & " /reference:" &         trim(replace(strData,"//+ref>","")) & " "
        end if

        if left(strData,7)="//+res>" then 
            csc_resources = csc_resources & " /resource:" & trim(replace(strData,"//+res>","")) & " "
        end if

        if left(strData,7)="//+ico>" then 
            csc_icon = " /win32icon:" & trim(replace(strData,"//+ico>","")) & " "
        end if
    Next

    objInputFile.Close


    'COMPILE THE FILE
    '################
    oShell.ShellExecute "c:\windows\microsoft.net\framework\v3.5\csc.exe", "/warn:1 /target:exe " & csc_references & csc_resources & csc_icon & " " & name_ & ".cs", "", "runas", 2


    WScript.Quit(0)

String replacement in Objective-C

It also posible string replacement with stringByReplacingCharactersInRange:withString:

for (int i = 0; i < card.length - 4; i++) {

    if (![[card substringWithRange:NSMakeRange(i, 1)] isEqual:@" "]) {

        NSRange range = NSMakeRange(i, 1);
        card = [card stringByReplacingCharactersInRange:range withString:@"*"];

    }

} //out: **** **** **** 1234

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

I faced this error becouse I sent the Query string with wrong format

http://localhost:56110/user/updateuserinfo?Id=55?Name=Basheer&Phone=(111)%20111-1111
------------------------------------------^----(^)-----------^---...
--------------------------------------------must be &

so make sure your Query String or passed parameter in the right format

How to exclude rows that don't join with another table?

Another solution is:

SELECT * FROM TABLE1 WHERE id NOT IN (SELECT id FROM TABLE2)

Simple (I think) Horizontal Line in WPF?

How about add this to your xaml:

<Separator/>

Creating composite primary key in SQL Server

If you use management studio, simply select the wardNo, BHTNo, testID columns and click on the key mark in the toolbar.

enter image description here

Command for this is,

ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest 
PRIMARY KEY (wardNo, BHTNo, TestID)

Maven plugin not using Eclipse's proxy settings

Eclipse by default does not know about your external Maven installation and uses the embedded one. Therefore in order for Eclipse to use your global settings you need to set it in menu Settings ? Maven ? Installations.

apache server reached MaxClients setting, consider raising the MaxClients setting

Here's an approach that could resolve your problem, and if not would help with troubleshooting.

  1. Create a second Apache virtual server identical to the current one

  2. Send all "normal" user traffic to the original virtual server

  3. Send special or long-running traffic to the new virtual server

Special or long-running traffic could be report-generation, maintenance ops or anything else you don't expect to complete in <<1 second. This can happen serving APIs, not just web pages.

If your resource utilization is low but you still exceed MaxClients, the most likely answer is you have new connections arriving faster than they can be serviced. Putting any slow operations on a second virtual server will help prove if this is the case. Use the Apache access logs to quantify the effect.

How to make a HTTP PUT request?

How to use PUT method using WebRequest.

    //JsonResultModel class
    public class JsonResultModel
    {
       public string ErrorMessage { get; set; }
       public bool IsSuccess { get; set; }
       public string Results { get; set; }
    }
    // HTTP_PUT Function
    public static JsonResultModel HTTP_PUT(string Url, string Data)
    {
        JsonResultModel model = new JsonResultModel();
        string Out = String.Empty;
        string Error = String.Empty;
        System.Net.WebRequest req = System.Net.WebRequest.Create(Url);

        try
        {
            req.Method = "PUT";
            req.Timeout = 100000;
            req.ContentType = "application/json";
            byte[] sentData = Encoding.UTF8.GetBytes(Data);
            req.ContentLength = sentData.Length;

            using (System.IO.Stream sendStream = req.GetRequestStream())
            {
                sendStream.Write(sentData, 0, sentData.Length);
                sendStream.Close();

            }

            System.Net.WebResponse res = req.GetResponse();
            System.IO.Stream ReceiveStream = res.GetResponseStream();
            using (System.IO.StreamReader sr = new 
            System.IO.StreamReader(ReceiveStream, Encoding.UTF8))
            {

                Char[] read = new Char[256];
                int count = sr.Read(read, 0, 256);

                while (count > 0)
                {
                    String str = new String(read, 0, count);
                    Out += str;
                    count = sr.Read(read, 0, 256);
                }
            }
        }
        catch (ArgumentException ex)
        {
            Error = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
        }
        catch (WebException ex)
        {
            Error = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
        }
        catch (Exception ex)
        {
            Error = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);
        }

        model.Results = Out;
        model.ErrorMessage = Error;
        if (!string.IsNullOrWhiteSpace(Out))
        {
            model.IsSuccess = true;
        }
        return model;
    }

WPF Label Foreground Color

I checked your XAML, it works fine - e.g. both labels have a gray foreground.
My guess is that you have some style which is affecting the way it looks...

Try moving your XAML to a brand-new window and see for yourself... Then, check if you have any themes or styles (in the Window.Resources for instance) which might be affecting the labels...

Swift add icon/image in UITextField

Try adding emailField.leftViewMode = UITextFieldViewMode.Always

(Default leftViewMode is Never)

Updated Answer for Swift 4

emailField.leftViewMode = UITextFieldViewMode.always

emailField.leftViewMode = .always

Batch file to copy directories recursively

You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:

@echo off
call :treeProcess
goto :eof

:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
copy *.* C:\dest\dir
for /D %%d in (*) do (
    cd %%d
    call :treeProcess
    cd ..
)
exit /b

Windows Batch File Looping Through Directories to Process Files?

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

if x is numeric, then add scale_x_continuous(); if x is character/factor, then add scale_x_discrete(). This might solve your problem.

Run PHP function on html button click

It depends on what function you want to run. If you need something done on server side, like querying a database or setting something in the session or anything that can not be done on client side, you need AJAX, else you can do it on client-side with JavaScript. Don't make the server work when you can do what you need to do on client side.

jQuery provides an easy way to do ajax : http://api.jquery.com/jQuery.ajax/

How to hide scrollbar in Firefox?

Try using this:

overflow-y: -moz-hidden-unscrollable;

Should have subtitle controller already set Mediaplayer error Android

Also you can only set mediaPlayer.reset() and in onDestroy set it to release.

display: inline-block extra margin

Can you post a link to the HTML in question?

Ultimately you should be able to do:

div {
    margin:0;
    padding: 0;
}

to remove the spacing. Is this just in one particular browser or all of them?

CSV in Python adding an extra carriage return, on Windows

You can introduce the lineterminator='\n' parameter in the csv writer command.

import csv
delimiter='\t'
with open('tmp.csv', '+w', encoding='utf-8') as stream:
    writer = csv.writer(stream, delimiter=delimiter, quoting=csv.QUOTE_NONE, quotechar='',  lineterminator='\n')
    writer.writerow(['A1' , 'B1', 'C1'])
    writer.writerow(['A2' , 'B2', 'C2'])
    writer.writerow(['A3' , 'B3', 'C3'])

Putting a simple if-then-else statement on one line

count = 0 if count == N else N+1

- the ternary operator. Although I'd say your solution is more readable than this.

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

In windows environment just check the PATH environment variable if Oracle JRE runtime refreshed the path and put himself at the very beginning of the path. In this case even if the JAVA_HOME AND JRE_HOME points to the correct JDK, the JRE will have precedence. And this case IntelliJ will not start Tomcat instance with the mentioned error message.

Pandas merge two dataframes with different columns

I think in this case concat is what you want:

In [12]:

pd.concat([df,df1], axis=0, ignore_index=True)
Out[12]:
   attr_1  attr_2  attr_3  id  quantity
0       0       1     NaN   1        20
1       1       1     NaN   2        23
2       1       1     NaN   3        19
3       0       0     NaN   4        19
4       1     NaN       0   5         8
5       0     NaN       1   6        13
6       1     NaN       1   7        20
7       1     NaN       1   8        25

by passing axis=0 here you are stacking the df's on top of each other which I believe is what you want then producing NaN value where they are absent from their respective dfs.

Clear contents of cells in VBA using column reference

As Gary's Student mentioned, you would need to remove the dot before Cells to make the code work as you originally wrote it. I can't be sure, since you only included the one line of code, but the error you got when you deleted the dots might have something to do with how you defined your variables.

I ran your line of code with the variables defined as integers and it worked:

Sub TestClearLastColumn()

    Dim LastColData As Long
        Set LastColData = Range("A1").End(xlToRight).Column

    Dim LastRowData As Long
        Set LastRowData = Range("A1").End(xlDown).Row

    Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).ClearContents

End Sub

I don't think a With statement is appropriate to the line of code you shared, but if you were to use one, the With would be at the start of the line that defines the object you are manipulating. Here is your code rewritten using an unnecessary With statement:

With Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData))
    .ClearContents
End With

With statements are designed to save you from retyping code and to make your coding easier to read. It becomes useful and appropriate if you do more than one thing with an object. For example, if you wanted to also turn the column red and add a thick black border, you might use a With statement like this:

With Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData))
    .ClearContents
    .Interior.Color = vbRed
    .BorderAround Color:=vbBlack, Weight:=xlThick
End With

Otherwise you would have to declare the range for each action or property, like this:

    Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).ClearContents
    Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).Interior.Color = vbRed
    Worksheets("Sheet1").Range(Cells(2, LastColData), Cells(LastRowData, LastColData)).BorderAround Color:=vbBlack, Weight:=xlThick

I hope this gives you a sense for why Gary's Student believed the compiler might be expecting a With (even though it was inappropriate) and how and when a With can be useful in your code.

gdb: how to print the current line or find the current line number?

Command where or frame can be used. where command will give more info with the function name

Evaluate if list is empty JSTL

empty is an operator:

The empty operator is a prefix operation that can be used to determine whether a value is null or empty.

<c:if test="${empty myObject.featuresList}">

Cannot perform runtime binding on a null reference, But it is NOT a null reference

You must define states not equal to null..

@if (ViewBag.States!= null)
{
    @foreach (KeyValuePair<int, string> de in ViewBag.States)
    {
        value="@de.Key">@de.Value 
    }
}                                

How to know what the 'errno' means?

You can use strerror() to get a human-readable string for the error number. This is the same string printed by perror() but it's useful if you're formatting the error message for something other than standard error output.

For example:

#include <errno.h>
#include <string.h>

/* ... */

if(read(fd, buf, 1)==-1) {
    printf("Oh dear, something went wrong with read()! %s\n", strerror(errno));
}

Linux also supports the explicitly-threadsafe variant strerror_r().

Reading a text file and splitting it into single words in python

As supplementary, if you are reading a vvvvery large file, and you don't want read all of the content into memory at once, you might consider using a buffer, then return each word by yield:

def read_words(inputfile):
    with open(inputfile, 'r') as f:
        while True:
            buf = f.read(10240)
            if not buf:
                break

            # make sure we end on a space (word boundary)
            while not str.isspace(buf[-1]):
                ch = f.read(1)
                if not ch:
                    break
                buf += ch

            words = buf.split()
            for word in words:
                yield word
        yield '' #handle the scene that the file is empty

if __name__ == "__main__":
    for word in read_words('./very_large_file.txt'):
        process(word)

Password masking console application

(My) nuget package to do this, based on the top answer:

install-package PanoramicData.ConsoleExtensions

Usage:

using PanoramicData.ConsoleExtensions;

...

Console.Write("Password: ");
var password = ConsolePlus.ReadPassword();
Console.WriteLine();

Project URL: https://github.com/panoramicdata/PanoramicData.ConsoleExtensions

Pull requests welcome.

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

ERROR Android emulator gets killed

Go to SDK Manager and see if there are any updates on the emulator & build tools that need to be updated.

Code line wrapping - how to handle long lines

Uses Guava's static factory methods for Maps and is only 105 characters long.

private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper = Maps.newHashMap();

Updating a JSON object using Javascript

JSON is the JavaScript Object Notation. There is no such thing as a JSON object. JSON is just a way of representing a JavaScript object in text.

So what you're after is a way of updating a in in-memory JavaScript object. qiao's answer shows how to do that simply enough.

Saving a high resolution image in R

A simpler way is

ggplot(data=df, aes(x=xvar, y=yvar)) + 
geom_point()

ggsave(path = path, width = width, height = height, device='tiff', dpi=700)

Facebook Graph API : get larger pictures in one request

you do not need to pull 'picture' attribute though. there is much more convenient way, the only thing you need is userid, see example below;

https://graph.facebook.com/user_id/picture?type=large

p.s. type defines the size you want

plz keep in mind that using token with basic permissions, /me/friends will return list of friends only with id+name attributes

Check if inputs form are empty jQuery

Define a helper function like this

function checkWhitespace(inputString){

    let stringArray = inputString.split(' ');

    let output = true;

    for (let el of stringArray){
        if (el!=''){
            output=false;
        }
    }

    return output;
}

Then check your input field value by passing through as an argument. If function returns true, that means value is only white space.

As an example

let inputValue = $('#firstName').val();
if(checkWhitespace(inputValue)) {
  // Show Warnings or return warnings
}else {
  // // Block of code-probably store input value into database
}

How to reverse an animation on mouse out after hover

Using transform in combination with transition works flawlessly for me:

.ani-grow {
    -webkit-transition: all 0.5s ease; 
    -moz-transition: all 0.5s ease; 
    -o-transition: all 0.5s ease; 
    -ms-transition: all 0.5s ease; 
    transition: all 0.5s ease; 
}
.ani-grow:hover {
    transform: scale(1.01);
}

How to serialize Joda DateTime with Jackson JSON processor?

It seems that for Jackson 1.9.12 there is no such possibility by default, because of:

public final static class DateTimeSerializer
    extends JodaSerializer<DateTime>
{
    public DateTimeSerializer() { super(DateTime.class); }

    @Override
    public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException
    {
        if (provider.isEnabled(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS)) {
            jgen.writeNumber(value.getMillis());
        } else {
            jgen.writeString(value.toString());
        }
    }

    @Override
    public JsonNode getSchema(SerializerProvider provider, java.lang.reflect.Type typeHint)
    {
        return createSchemaNode(provider.isEnabled(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS)
                ? "number" : "string", true);
    }
}

This class serializes data using toString() method of Joda DateTime.

Approach proposed by Rusty Kuntz works perfect for my case.

What is unexpected T_VARIABLE in PHP?

In my case it was an issue of the PHP version.

The .phar file I was using was not compatible with PHP 5.3.9. Switching interpreter to PHP 7 did fix it.

Format datetime in asp.net mvc 4

Thanks Darin, For me, to be able to post to the create method, It only worked after I modified the BindModel code to :

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
    var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

    if (!string.IsNullOrEmpty(displayFormat) && value != null)
    {
        DateTime date;
        displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
        // use the format specified in the DisplayFormat attribute to parse the date
         if (DateTime.TryParse(value.AttemptedValue, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out date))
        {
            return date;
        }
        else
        {
            bindingContext.ModelState.AddModelError(
                bindingContext.ModelName,
                string.Format("{0} is an invalid date format", value.AttemptedValue)
            );
        }
    }

    return base.BindModel(controllerContext, bindingContext);
}

Hope this could help someone else...

Is it possible to decompile an Android .apk file?

I may also add, that nowadays it is possible to decompile Android application online, no software needed!

Here are 2 options for you:

Why can't I use switch statement on a String?

If you have a place in your code where you can switch on a String, then it may be better to refactor the String to be an enumeration of the possible values, which you can switch on. Of course, you limit the potential values of Strings you can have to those in the enumeration, which may or may not be desired.

Of course your enumeration could have an entry for 'other', and a fromString(String) method, then you could have

ValueEnum enumval = ValueEnum.fromString(myString);
switch (enumval) {
   case MILK: lap(); break;
   case WATER: sip(); break;
   case BEER: quaff(); break;
   case OTHER: 
   default: dance(); break;
}

How can I declare a Boolean parameter in SQL statement?

SQL Server recognizes 'TRUE' and 'FALSE' as bit values. So, use a bit data type!

declare @var bit
set @var = 'true'
print @var

That returns 1.

Check if a string matches a regex in Bash script

I would use expr match instead of =~:

expr match "$date" "[0-9]\{8\}" >/dev/null && echo yes

This is better than the currently accepted answer of using =~ because =~ will also match empty strings, which IMHO it shouldn't. Suppose badvar is not defined, then [[ "1234" =~ "$badvar" ]]; echo $? gives (incorrectly) 0, while expr match "1234" "$badvar" >/dev/null ; echo $? gives correct result 1.

We have to use >/dev/null to hide expr match's output value, which is the number of characters matched or 0 if no match found. Note its output value is different from its exit status. The exit status is 0 if there's a match found, or 1 otherwise.

Generally, the syntax for expr is:

expr match "$string" "$lead"

Or:

expr "$string" : "$lead"

where $lead is a regular expression. Its exit status will be true (0) if lead matches the leading slice of string (Is there a name for this?). For example expr match "abcdefghi" "abc"exits true, but expr match "abcdefghi" "bcd" exits false. (Credit to @Carlo Wood for pointing out this.

How to print current date on python3?

I always use this code, which print the year to second in a tuple

import datetime

now = datetime.datetime.now()

time_now = (now.year, now.month, now.day, now.hour, now.minute, now.second)

print(time_now)

How to check if an element does NOT have a specific class?

There are more complex scenarios where this doesn't work. What if you want to select an element with class A that doesn't contain elements with class B. You end up needing something more like:

If parent element does not contain certain child element; jQuery

How to make a DIV not wrap?

overflow: hidden should give you the correct behavior. My guess is that RTL is messed up because you have float: left on the encapsulated divs.

Beside that bug, you got the right behavior.

Get the key corresponding to the minimum value within a dictionary

For the case where you have multiple minimal keys and want to keep it simple

def minimums(some_dict):
    positions = [] # output variable
    min_value = float("inf")
    for k, v in some_dict.items():
        if v == min_value:
            positions.append(k)
        if v < min_value:
            min_value = v
            positions = [] # output variable
            positions.append(k)

    return positions

minimums({'a':1, 'b':2, 'c':-1, 'd':0, 'e':-1})

['e', 'c']

List of installed gems?

From within your debugger type $LOAD_PATH to get a list of your gems. If you don't have a debugger, install pry:

gem install pry
pry
Pry(main)> $LOAD_PATH

This will output an array of your installed gems.

JavaScript string newline character?

Get a line separator for the current browser:

function getLineSeparator() {
  var textarea = document.createElement("textarea");
  textarea.value = "\n"; 
  return textarea.value;
}

String length in bytes in JavaScript

Actually, I figured out what's wrong. For the code to work the page <head> should have this tag:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Or, as suggested in comments, if server sends HTTP Content-Encoding header, it should work as well.

Then results from different browsers are consistent.

Here is an example:

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
  <title>mini string length test</title>
</head>
<body>

<script type="text/javascript">
document.write('<div style="font-size:100px">' 
    + (unescape(encodeURIComponent("???! Naïve?")).length) + '</div>'
  );
</script>
</body>
</html>

Note: I suspect that specifying any (accurate) encoding would fix the encoding problem. It is just a coincidence that I need UTF-8.

How do I create directory if it doesn't exist to create a file?

As @hitec said, you have to be sure that you have the right permissions, if you do, you can use this line to ensure the existence of the directory:

Directory.CreateDirectory(Path.GetDirectoryName(filePath))

How to disable RecyclerView scrolling?

At activity's onCreate method, you can simply do:

recyclerView.stopScroll()

and it stops scrolling.

How to get data from database in javascript based on the value passed to the function

'SELECT * FROM Employ where number = ' + parseInt(val, 10) + ';'

For example, if val is "10" then this will end up building the string:

"SELECT * FROM Employ where number = 10;"

PHP validation/regex for URL

Use the filter_var() function to validate whether a string is URL or not:

var_dump(filter_var('example.com', FILTER_VALIDATE_URL));

It is bad practice to use regular expressions when not necessary.

EDIT: Be careful, this solution is not unicode-safe and not XSS-safe. If you need a complex validation, maybe it's better to look somewhere else.

PHP - print all properties of an object

try using Pretty Dump it works great for me

Show datalist labels but submit the actual value

The solution I use is the following:

<input list="answers" id="answer">
<datalist id="answers">
  <option data-value="42" value="The answer">
</datalist>

Then access the value to be sent to the server using JavaScript like this:

var shownVal = document.getElementById("answer").value;
var value2send = document.querySelector("#answers option[value='"+shownVal+"']").dataset.value;


Hope it helps.

Why do you need to put #!/bin/bash at the beginning of a script file?

It is called a shebang. It consists of a number sign and an exclamation point character (#!), followed by the full path to the interpreter such as /bin/bash. All scripts under UNIX and Linux execute using the interpreter specified on a first line.

R barplot Y-axis scale too short

Simplest solution seems to be specifying the ylim range. Here is some code to do this automatically (left default, right - adjusted):

# default y-axis
barplot(dat, beside=TRUE)

# automatically adjusted y-axis
barplot(dat, beside=TRUE, ylim=range(pretty(c(0, dat))))

img

The trick is to use pretty() which returns a list of interval breaks covering all values of the provided data. It guarantees that the maximum returned value is 1) a round number 2) greater than maximum value in the data.

In the example 0 was also added pretty(c(0, dat)) which makes sure that axis starts from 0.

What’s the best way to get an HTTP response code from a URL?

In future, for those that use python3 and later, here's another code to find response code.

import urllib.request

def getResponseCode(url):
    conn = urllib.request.urlopen(url)
    return conn.getcode()

Java LinkedHashMap get first or last entry

        import java.util.Arrays;
        import java.util.LinkedHashMap;
        import java.util.List;
        import java.util.Map;

        public class Scratch {
           public static void main(String[] args) {

              // Plain java version

              Map<String, List<Integer>> linked = new LinkedHashMap<>();
              linked.put("a", Arrays.asList(1, 2, 3));
              linked.put("aa", Arrays.asList(1, 2, 3, 4));
              linked.put("b", Arrays.asList(1, 2, 3, 4, 5));
              linked.put("bb", Arrays.asList(1, 2, 3, 4, 5, 6));

              System.out.println("linked = " + linked);

              String firstKey = getFirstKey(linked);
              System.out.println("firstKey = " + firstKey);
              List<Integer> firstEntry = linked.get(firstKey);
              System.out.println("firstEntry = " + firstEntry);

              String lastKey = getLastKey(linked);
              System.out.println("lastKey = " + lastKey);
              List<Integer> lastEntry = linked.get(lastKey);
              System.out.println("lastEntry = " + lastEntry);



           }

           private static String getLastKey(Map<String, List<Integer>> linked) {
              int index = 0;
              for (String key : linked.keySet()) {
             index++;
             if (index == linked.size()) {
                return key;
             }
              }
              return null;
           }

           private static String getFirstKey(Map<String, List<Integer>> linked) {
              for (String key : linked.keySet()) {
             return key;
              }
              return null;
           }
        }

ValidateAntiForgeryToken purpose, explanation and example

In ASP.Net Core anti forgery token is automatically added to forms, so you don't need to add @Html.AntiForgeryToken() if you use razor form element or if you use IHtmlHelper.BeginForm and if the form's method isn't GET.

It will generate input element for your form similar to this:

<input name="__RequestVerificationToken" type="hidden" 
       value="CfDJ8HSQ_cdnkvBPo-jales205VCq9ISkg9BilG0VXAiNm3Fl5Lyu_JGpQDA4_CLNvty28w43AL8zjeR86fNALdsR3queTfAogif9ut-Zd-fwo8SAYuT0wmZ5eZUYClvpLfYm4LLIVy6VllbD54UxJ8W6FA">

And when user submits form this token is verified on server side if validation is enabled.

[ValidateAntiForgeryToken] attribute can be used against actions. Requests made to actions that have this filter applied are blocked unless the request includes a valid antiforgery token.

[AutoValidateAntiforgeryToken] attribute can be used against controllers. This attribute works identically to the ValidateAntiForgeryToken attribute, except that it doesn't require tokens for requests made using the following HTTP methods: GET HEAD OPTIONS TRACE

Additional information: docs.microsoft.com/aspnet/core/security/anti-request-forgery

iOS for VirtualBox

You could try qemu, which is what the Android emulator uses. I believe it actually emulates the ARM hardware.

jQuery how to find an element based on a data-attribute value?

$("ul").find("li[data-slide='" + current + "']");

I hope this may work better

thanks

li:before{ content: "¦"; } How to Encode this Special Character as a Bullit in an Email Stationery?

Lea's converter is no longer available. I just used this converter

Steps:

  1. Enter the Unicode decimal version such as 8226 in the tool's green input field.
  2. Press Dec code points
  3. See the result in the box Unicode U+hex notation (eg U+2022)
  4. Use it in your CSS. Eg content: '\2022'

ps. I have no connection with the web site.

Can HTML be embedded inside PHP "if" statement?

<?php if ($my_name == 'aboutme') { ?>
    HTML_GOES_HERE
<?php } ?>

GitLab git user password

To add yet another reason to the list ... in my case I found this problem was being caused by an SELinux permissions problem on the server. This is worth checking if your server is running Fedora / CentOS / Red Hat. To test this scenario you can run:

Client: ssh -vT git@<gitlab-server> -- asks for password
Server: sudo setenforce 0
Client: ssh -vT git@<gitlab-server> -- succeeds
Server: sudo setenforce 1

In my case the gitlab/git user's authorized_keys file had the wrong SELinux file context, and the ssh service was being denied permission to read it. I fixed this on the server side as follows:

sudo semanage fcontext -a -t ssh_home_t /gitlab/.ssh/
sudo semanage fcontext -a -t ssh_home_t /gitlab/.ssh/authorized_keys
sudo restorecon -F -Rv /gitlab/.ssh/

And I was then able to git clone on the client side as expected.

What does the "assert" keyword do?

If the condition isn't satisfied, an AssertionError will be thrown.

Assertions have to be enabled, though; otherwise the assert expression does nothing. See:

http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html#enable-disable

No restricted globals

For me I had issues with history and location... As the accepted answer using window before history and location (i.e) window.history and window.location solved mine

How to escape single quotes within single quoted strings

I just use shell codes.. e.g. \x27 or \\x22 as applicable. No hassle, ever really.

Promise.all().then() resolve?

Today NodeJS supports new async/await syntax. This is an easy syntax and makes the life much easier

async function process(promises) { // must be an async function
    let x = await Promise.all(promises);  // now x will be an array
    x = x.map( tmp => tmp * 10);              // proccessing the data.
}

const promises = [
   new Promise(resolve => setTimeout(resolve, 0, 1)),
   new Promise(resolve => setTimeout(resolve, 0, 2))
];

process(promises)

Learn more:

Selenium C# WebDriver: Wait until element is present

This is the reusable function to wait for an element present in the DOM using an explicit wait.

public void WaitForElement(IWebElement element, int timeout = 2)
{
    WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromMinutes(timeout));
    wait.IgnoreExceptionTypes(typeof(NoSuchElementException));
    wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException));
    wait.Until<bool>(driver =>
    {
        try
        {
            return element.Displayed;
        }
        catch (Exception)
        {
            return false;
        }
    });
}

Cloning an Object in Node.js

None of the answers satisfied me, several don't work or are just shallow clones, answers from @clint-harris and using JSON.parse/stringify are good but quite slow. I found a module that does deep cloning fast: https://github.com/AlexeyKupershtokh/node-v8-clone

When is it acceptable to call GC.Collect?

Have a look at this article by Rico Mariani. He gives two rules when to call GC.Collect (rule 1 is: "Don't"):

When to call GC.Collect()

WPF: Grid with column/row margin/padding?

You could write your own GridWithMargin class, inherited from Grid, and override the ArrangeOverride method to apply the margins

Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm­­.dll, please install or use the JRE or JDK that contains these missing components.

Follow these steps:

Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)

After that, go to C:/Program files/java/jre7/bin

Here, create an folder called Server

Now go into the C:/Program files/java/jre7/bin/client folder

Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server folder

React-Native: Module AppRegistry is not a registered callable module

Hopefully this can save someone a headache. I got this error after upgrading my react-native version. Confusingly it only appeared on the android side of things.

My file structure includes an index.ios.js and an index.android.js. Both contain the code:

AppRegistry.registerComponent('App', () => App);

What I had to do was, in android/app/src/main/java/com/{projectName}/MainApplication.java, change index to index.android:

@Override
protected String getJSMainModuleName() {
    return "index.android"; // was "index"
}

Then in app/build/build.gradle, change the entryFile from index.js to index.android.js

project.ext.react = [
    entryFile: "index.android.js" // was index.js"
]

Formatting a double to two decimal places

Well, depending on your needs you can choose any of the following. Out put is written against each method

You can choose the one you need

This will round

decimal d = 2.5789m;
Console.WriteLine(d.ToString("#.##")); // 2.58

This will ensure that 2 decimal places are written.

d = 2.5m;
Console.WriteLine(d.ToString("F")); //2.50

if you want to write commas you can use this

d=23545789.5432m;
Console.WriteLine(d.ToString("n2")); //23,545,789.54

if you want to return the rounded of decimal value you can do this

d = 2.578m;
d = decimal.Round(d, 2, MidpointRounding.AwayFromZero); //2.58

jQuery delete all table rows except first

This should work:

$(document).ready(function() {
   $("someTableSelector").find("tr:gt(0)").remove();
});

Pipe subprocess standard output to a variable

With a = subprocess.Popen("cdrecord --help",stdout = subprocess.PIPE) , you need to either use a list or use shell=True;

Either of these will work. The former is preferable.

a = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE)

a = subprocess.Popen('cdrecord --help', shell=True, stdout=subprocess.PIPE)

Also, instead of using Popen.stdout.read/Popen.stderr.read, you should use .communicate() (refer to the subprocess documentation for why).

proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()

How to create relationships in MySQL

CREATE TABLE accounts(
    account_id INT NOT NULL AUTO_INCREMENT,
    customer_id INT( 4 ) NOT NULL ,
    account_type ENUM( 'savings', 'credit' ) NOT NULL,
    balance FLOAT( 9 ) NOT NULL,
    PRIMARY KEY ( account_id )
)

and

CREATE TABLE customers(
    customer_id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(20) NOT NULL,
    address VARCHAR(20) NOT NULL,
    city VARCHAR(20) NOT NULL,
    state VARCHAR(20) NOT NULL,
)

How do I create a 'relationship' between the two tables? I want each account to be 'assigned' one customer_id (to indicate who owns it).

You have to ask yourself is this a 1 to 1 relationship or a 1 out of many relationship. That is, does every account have a customer and every customer have an account. Or will there be customers without accounts. Your question implies the latter.

If you want to have a strict 1 to 1 relationship, just merge the two tables.

CREATE TABLE customers(
    customer_id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(20) NOT NULL,
    address VARCHAR(20) NOT NULL,
    city VARCHAR(20) NOT NULL,
    state VARCHAR(20) NOT NULL,
    account_type ENUM( 'savings', 'credit' ) NOT NULL,
    balance FLOAT( 9 ) NOT NULL,
)

In the other case, the correct way to create a relationship between two tables is to create a relationship table.

CREATE TABLE customersaccounts(
    customer_id INT NOT NULL,
    account_id INT NOT NULL,
    PRIMARY KEY (customer_id, account_id)
    FOREIGN KEY customer_id references customers (customer_id) on delete cascade,
    FOREIGN KEY account_id  references accounts  (account_id) on delete cascade
}

Then if you have a customer_id and want the account info, you join on customersaccounts and accounts:

SELECT a.*
    FROM customersaccounts ca
        INNER JOIN accounts a ca.account_id=a.account_id
            AND ca.customer_id=mycustomerid;

Because of indexing this will be blindingly quick.

You could also create a VIEW which gives you the effect of the combined customersaccounts table while keeping them separate

CREATE VIEW customeraccounts AS 
    SELECT a.*, c.* FROM customersaccounts ca
        INNER JOIN accounts a ON ca.account_id=a.account_id
        INNER JOIN customers c ON ca.customer_id=c.customer_id;

MySql Query Replace NULL with Empty String in Select

SELECT COALESCE(prereq, '') FROM test

Coalesce will return the first non-null argument passed to it from left to right. If all arguemnts are null, it'll return null, but we're forcing an empty string there, so no null values will be returned.

Also note that the COALESCE operator is supported in standard SQL. This is not the case of IFNULL. So it is a good practice to get use the former. Additionally, bear in mind that COALESCE supports more than 2 parameters and it will iterate over them until a non-null coincidence is found.

Using await outside of an async function

There is always this of course:

(async () => {
    await ...

    // all of the script.... 

})();
// nothing else

This makes a quick function with async where you can use await. It saves you the need to make an async function which is great! //credits Silve2611

INNER JOIN vs INNER JOIN (SELECT . FROM)

Seems to be identical just in case that SQL server will not try to read data which is not required for the query, the optimizer is clever enough

It can have sense when join on complex query (i.e which have joings, groupings etc itself) then, yes, it is better to specify required fields.

But there is one more point. If the query is simple there is no difference but EVERY extra action even which is supposed to improve performance makes optimizer works harder and optimizer can fail to get the best plan in time and will run not optimal query. So extras select can be a such action which can even decrease performance

How to create a database from shell command?

You mean while the mysql environment?

create database testdb;

Or directly from command line:

mysql -u root -e "create database testdb";