Programs & Examples On #Invalidoperationexception

The exception that is thrown when a method call is invalid for the object's current state.

nullable object must have a value

Assign the members directly without the .Value part:

DateTimeExtended(DateTimeExtended myNewDT)
{
   this.MyDateTime = myNewDT.MyDateTime;
   this.otherdata = myNewDT.otherdata;
}

Windows Application has stopped working :: Event Name CLR20r3

This is just because the application is built in non unicode language fonts and you are running the system on unicode fonts. change your default non unicode fonts to arabic by going in regional settings advanced tab in control panel. That will solve your problem.

ASP.NET MVC: No parameterless constructor defined for this object

This can also be caused if your Model is using a SelectList, as this has no parameterless constructor:

public class MyViewModel
{
    public SelectList Contacts { get;set; }
}

You'll need to refactor your model to do it a different way if this is the cause. So using an IEnumerable<Contact> and writing an extension method that creates the drop down list with the different property definitions:

public class MyViewModel
{
    public Contact SelectedContact { get;set; }
    public IEnumerable<Contact> Contacts { get;set; }
}

public static MvcHtmlString DropDownListForContacts(this HtmlHelper helper, IEnumerable<Contact> contacts, string name, Contact selectedContact)
{
    // Create a List<SelectListItem>, populate it, return DropDownList(..)
}

Or you can use the @Mark and @krilovich approach, just need replace SelectList to IEnumerable, it's works with MultiSelectList too.

 public class MyViewModel
    {
        public Contact SelectedContact { get;set; }
        public IEnumerable<SelectListItem> Contacts { get;set; }
    }

What is the definition of "interface" in object oriented programming

An interface separates out operations on a class from the implementation within. Thus, some implementations may provide for many interfaces.

People would usually describe it as a "contract" for what must be available in the methods of the class.

It is absolutely not a blueprint, since that would also determine implementation. A full class definition could be said to be a blueprint.

How to create timer in angular2

Found a npm package that makes this easy with RxJS as a service.

https://www.npmjs.com/package/ng2-simple-timer

You can 'subscribe' to an existing timer so you don't create a bazillion timers if you're using it many times in the same component.

Linq to Entities - SQL "IN" clause

This should suffice your purpose. It compares two collections and checks if one collection has the values matching those in the other collection

fea_Features.Where(s => selectedFeatures.Contains(s.feaId))

How can I dynamically set the position of view in Android?

I would recommend using setTranslationX and setTranslationY. I'm only just getting started on this myself, but these seem to be the safest and preferred way of moving a view. I guess it depends a lot on what exactly you're trying to do, but this is working well for me for 2D animation.

How to convert DataTable to class Object?

Is it very expensive to do this by json convert? But at least you have a 2 line solution and its generic. It does not matter eather if your datatable contains more or less fields than the object class:

Dim sSql = $"SELECT '{jobID}' AS ConfigNo, 'MainSettings' AS ParamName, VarNm AS ParamFieldName, 1 AS ParamSetId, Val1 AS ParamValue FROM StrSVar WHERE NmSp = '{sAppName} Params {jobID}'"
            Dim dtParameters As DataTable = DBLib.GetDatabaseData(sSql)

            Dim paramListObject As New List(Of ParameterListModel)()

            If (Not dtParameters Is Nothing And dtParameters.Rows.Count > 0) Then
                Dim json = Newtonsoft.Json.JsonConvert.SerializeObject(dtParameters).ToString()

                paramListObject = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of ParameterListModel))(json)
            End If

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

Sort a List of Object in VB.NET

To sort by a property in the object, you have to specify a comparer or a method to get that property.

Using the List.Sort method:

theList.Sort(Function(x, y) x.age.CompareTo(y.age))

Using the OrderBy extension method:

theList = theList.OrderBy(Function(x) x.age).ToList()

Scrolling a div with jQuery

There's a plug-in for this if you don't want to write a bare-bones implementation yourself. It's called "scrollTo" (link). It allows you to perform programmed scrolling to certain points, or use values like -= 10px for continuous scrolling.

ScrollTo jQuery Plug-in

How To Create Table with Identity Column

[id] [int] IDENTITY(1,1) NOT NULL,

of course since you're creating the table in SQL Server Management Studio you could use the table designer to set the Identity Specification.

enter image description here

What is the best way to calculate a checksum for a file that is on my machine?

for sure the certutil is the best approach but there's a chance to hit windows xp/2003 machine without certutil command.There makecab command can be used which has its own hash algorithm - here the fileinf.bat which will output some info about the file including the checksum.

BeanFactory vs ApplicationContext

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

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

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

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

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

public class LazyLoadingXmlApplicationContext extends ClassPathXmlApplicationContext {

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

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

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

}

How to install MySQLdb package? (ImportError: No module named setuptools)

This was sort of tricky for me too, I did the following which worked pretty well.

  • Download the appropriate Python .egg for setuptools (ie, for Python 2.6, you can get it here. Grab the correct one from the PyPI site here.)
  • chmod the egg to be executable: chmod a+x [egg] (ie, for Python 2.6, chmod a+x setuptools-0.6c9-py2.6.egg)
  • Run ./[egg] (ie, for Python 2.6, ./setuptools-0.6c9-py2.6.egg)

Not sure if you'll need to use sudo if you're just installing it for you current user. You'd definitely need it to install it for all users.

Data truncation: Data too long for column 'logo' at row 1

You are trying to insert data that is larger than allowed for the column logo.

Use following data types as per your need

TINYBLOB   :     maximum length of 255 bytes  
BLOB       :     maximum length of 65,535 bytes  
MEDIUMBLOB :     maximum length of 16,777,215 bytes  
LONGBLOB   :     maximum length of 4,294,967,295 bytes  

Use LONGBLOB to avoid this exception.

Python how to plot graph sine wave

import math
import turtle

ws = turtle.Screen()
ws.bgcolor("lightblue")
fred = turtle.Turtle()
for angle in range(360):
    y = math.sin(math.radians(angle))
    fred.goto(angle, y * 80)

ws.exitonclick()

Right way to reverse a pandas DataFrame?

This works:

    for i,r in data[::-1].iterrows():
        print(r['Odd'], r['Even'])

Is it possible to modify a string of char in C?

The memory for a & b is not allocated by you. The compiler is free to choose a read-only memory location to store the characters. So if you try to change it may result in seg fault. So I suggest you to create a character array yourself. Something like: char a[10]; strcpy(a, "Hello");

How to get the first day of the current week and month?

java.time

The java.time framework in Java 8 and later supplants the old java.util.Date/.Calendar classes. The old classes have proven to be troublesome, confusing, and flawed. Avoid them.

The java.time framework is inspired by the highly-successful Joda-Time library, defined by JSR 310, extended by the ThreeTen-Extra project, and explained in the Tutorial.

Instant

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

The java.time framework has a resolution of nanoseconds, or 9 digits of a fractional second. Milliseconds is only 3 digits of a fractional second. Because millisecond resolution is common, java.time includes a handy factory method.

long millisecondsSinceEpoch = 1446959825213L;
Instant instant = Instant.ofEpochMilli ( millisecondsSinceEpoch );

millisecondsSinceEpoch: 1446959825213 is instant: 2015-11-08T05:17:05.213Z

ZonedDateTime

To consider current week and current month, we need to apply a particular time zone.

ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );

In zoneId: America/Montreal that is: 2015-11-08T00:17:05.213-05:00[America/Montreal]

Half-Open

In date-time work, we commonly use the Half-Open approach to defining a span of time. The beginning is inclusive while the ending in exclusive. Rather than try to determine the last split-second of the end of the week (or month), we get the first moment of the following week (or month). So a week runs from the first moment of Monday and goes up to but not including the first moment of the following Monday.

Let's the first day of the week, and last. The java.time framework includes a tool for that, the with method and the ChronoField enum.

By default, java.time uses the ISO 8601 standard. So Monday is the first day of the week (1) and Sunday is last (7).

ZonedDateTime firstOfWeek = zdt.with ( ChronoField.DAY_OF_WEEK , 1 ); // ISO 8601, Monday is first day of week.
ZonedDateTime firstOfNextWeek = firstOfWeek.plusWeeks ( 1 );

That week runs from: 2015-11-02T00:17:05.213-05:00[America/Montreal] to 2015-11-09T00:17:05.213-05:00[America/Montreal]

Oops! Look at the time-of-day on those values. We want the first moment of the day. The first moment of the day is not always 00:00:00.000 because of Daylight Saving Time (DST) or other anomalies. So we should let java.time make the adjustment on our behalf. To do that, we must go through the LocalDate class.

ZonedDateTime firstOfWeek = zdt.with ( ChronoField.DAY_OF_WEEK , 1 ); // ISO 8601, Monday is first day of week.
firstOfWeek = firstOfWeek.toLocalDate ().atStartOfDay ( zoneId );
ZonedDateTime firstOfNextWeek = firstOfWeek.plusWeeks ( 1 );

That week runs from: 2015-11-02T00:00-05:00[America/Montreal] to 2015-11-09T00:00-05:00[America/Montreal]

And same for the month.

ZonedDateTime firstOfMonth = zdt.with ( ChronoField.DAY_OF_MONTH , 1 );
firstOfMonth = firstOfMonth.toLocalDate ().atStartOfDay ( zoneId );
ZonedDateTime firstOfNextMonth = firstOfMonth.plusMonths ( 1 );

That month runs from: 2015-11-01T00:00-04:00[America/Montreal] to 2015-12-01T00:00-05:00[America/Montreal]

YearMonth

Another way to see if a pair of moments are in the same month is to check for the same YearMonth value.

For example, assuming thisZdt and thatZdt are both ZonedDateTime objects:

boolean inSameMonth = YearMonth.from( thisZdt ).equals( YearMonth.from( thatZdt ) ) ;

Milliseconds

I strongly recommend against doing your date-time work in milliseconds-from-epoch. That is indeed the way date-time classes tend to work internally, but we have the classes for a reason. Handling a count-from-epoch is clumsy as the values are not intelligible by humans so debugging and logging is difficult and error-prone. And, as we've already seen, different resolutions may be in play; old Java classes and Joda-Time library use milliseconds, while databases like Postgres use microseconds, and now java.time uses nanoseconds.

Would you handle text as bits, or do you let classes such as String, StringBuffer, and StringBuilder handle such details?

But if you insist, from a ZonedDateTime get an Instant, and from that get a milliseconds-count-from-epoch. But keep in mind this call can mean loss of data. Any microseconds or nanoseconds that you might have in your ZonedDateTime/Instant will be truncated (lost).

long millis = firstOfWeek.toInstant().toEpochMilli();  // Possible data loss.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Difference between Encapsulation and Abstraction

A very practical example is.

let's just say I want to encrypt my password.

  • I don't want to know the details, I just call encryptionImpl.encrypt(password) and it returns an encrypted password.

    public interface Encryption{ public String encrypt(String password); }

    This is called abstraction. It just shows what should be done.

  • Now let us assume We have Two types of Encryption Md5 and RSA which implement Encryption from a third-party encryption jar.

    Then those Encryption classes have their own way of implementing encryption which protects their implementation from outsiders

    This is called Encapsulation. Hides how it should be done.

Remember:what should be done vs how it should be done.

Hiding complications vs Protecting implementations

Looping through all the properties of object php

Sometimes, you need to list the variables of an object and not for debugging purposes. The right way to do it is using get_object_vars($object). It returns an array that has all the class variables and their value. You can then loop through them in a foreach loop. If used within the object itself, simply do get_object_vars($this)

Resize a large bitmap file to scaled output file on Android

When i have large bitmaps and i want to decode them resized i use the following

BitmapFactory.Options options = new BitmapFactory.Options();
InputStream is = null;
is = new FileInputStream(path_to_file);
BitmapFactory.decodeStream(is,null,options);
is.close();
is = new FileInputStream(path_to_file);
// here w and h are the desired width and height
options.inSampleSize = Math.max(options.outWidth/w, options.outHeight/h);
// bitmap is the resized bitmap
Bitmap bitmap = BitmapFactory.decodeStream(is,null,options);

How to pass arguments and redirect stdin from a file to program run in gdb?

You can do this:

gdb --args path/to/executable -every -arg you can=think < of

The magic bit being --args.

Just type run in the gdb command console to start debugging.

How do you copy the contents of an array to a std::vector in C++ without looping?

Assuming you know how big the item in the vector are:

std::vector<int> myArray;
myArray.resize (item_count, 0);
memcpy (&myArray.front(), source, item_count * sizeof(int));

http://www.cppreference.com/wiki/stl/vector/start

R solve:system is exactly singular

Using solve with a single parameter is a request to invert a matrix. The error message is telling you that your matrix is singular and cannot be inverted.

Get all photos from Instagram which have a specific hashtag with PHP

Since Nov 17, 2015 you have to authenticate users to make any (even such as "get some pictures who have specific hashtag") requests. See the Instagram Platform Changelog:

Apps created on or after Nov 17, 2015: All API endpoints require a valid access_token. Apps created before Nov 17, 2015: Unaffected by new API behavior until June 1, 2016.

this makes now all answers given here before June 1, 2016 no longer useful.

What should I do if the current ASP.NET session is null?

The following statement is not entirely accurate:

"So if you are calling other functionality, including static classes, from your page, you should be fine"

I am calling a static method that references the session through HttpContext.Current.Session and it is null. However, I am calling the method via a webservice method through ajax using jQuery.

As I found out here you can fix the problem with a simple attribute on the method, or use the web service session object:

There’s a trick though, in order to access the session state within a web method, you must enable the session state management like so:

[WebMethod(EnableSession = true)]

By specifying the EnableSession value, you will now have a managed session to play with. If you don’t specify this value, you will get a null Session object, and more than likely run into null reference exceptions whilst trying to access the session object.

Thanks to Matthew Cosier for the solution.

Just thought I'd add my two cents.

Ed

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

NSDictionary   *dict = [NSDictionary dictionaryWithObject: @"String" forKey: @"Test"];
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionary];

[anotherDict setObject: dict forKey: "sub-dictionary-key"];
[anotherDict setObject: @"Another String" forKey: @"another test"];

NSLog(@"Dictionary: %@, Mutable Dictionary: %@", dict, anotherDict);

// now we can save these to a file
NSString   *savePath = [@"~/Documents/Saved.data" stringByExpandingTildeInPath];
[anotherDict writeToFile: savePath atomically: YES];

//and restore them
NSMutableDictionary  *restored = [NSDictionary dictionaryWithContentsOfFile: savePath];

Check if a row exists using old mysql_* API

Use mysql_num_rows(), to check if rows are available or not

$result = mysql_query("SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName' LIMIT 1");
$num_rows = mysql_num_rows($result);

if ($num_rows > 0) {
  // do something
}
else {
  // do something else
}

DateTime group by date and hour

In my case... with MySQL:

SELECT ... GROUP BY TIMESTAMPADD(HOUR, HOUR(columName), DATE(columName))

Removing App ID from Developer Connection

As @AlexanderN pointed out, you can now delete App IDs.

  1. In your Member Center go to the Certificates, Identifiers & Profiles section.
  2. Go to Identifiers folder.
  3. Select the App ID you want to delete and click Settings
  4. Scroll down and click Delete.

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

create procedure <procedure_name>(p_cur out sys_refcursor) as begin open p_cur for select * from <table_name> end;

multiple axis in matplotlib with different scales

Bootstrapping something fast to chart multiple y-axes sharing an x-axis using @joe-kington's answer: enter image description here

# d = Pandas Dataframe, 
# ys = [ [cols in the same y], [cols in the same y], [cols in the same y], .. ] 
def chart(d,ys):

    from itertools import cycle
    fig, ax = plt.subplots()

    axes = [ax]
    for y in ys[1:]:
        # Twin the x-axis twice to make independent y-axes.
        axes.append(ax.twinx())

    extra_ys =  len(axes[2:])

    # Make some space on the right side for the extra y-axes.
    if extra_ys>0:
        temp = 0.85
        if extra_ys<=2:
            temp = 0.75
        elif extra_ys<=4:
            temp = 0.6
        if extra_ys>5:
            print 'you are being ridiculous'
        fig.subplots_adjust(right=temp)
        right_additive = (0.98-temp)/float(extra_ys)
    # Move the last y-axis spine over to the right by x% of the width of the axes
    i = 1.
    for ax in axes[2:]:
        ax.spines['right'].set_position(('axes', 1.+right_additive*i))
        ax.set_frame_on(True)
        ax.patch.set_visible(False)
        ax.yaxis.set_major_formatter(matplotlib.ticker.OldScalarFormatter())
        i +=1.
    # To make the border of the right-most axis visible, we need to turn the frame
    # on. This hides the other plots, however, so we need to turn its fill off.

    cols = []
    lines = []
    line_styles = cycle(['-','-','-', '--', '-.', ':', '.', ',', 'o', 'v', '^', '<', '>',
               '1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_'])
    colors = cycle(matplotlib.rcParams['axes.color_cycle'])
    for ax,y in zip(axes,ys):
        ls=line_styles.next()
        if len(y)==1:
            col = y[0]
            cols.append(col)
            color = colors.next()
            lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
            ax.set_ylabel(col,color=color)
            #ax.tick_params(axis='y', colors=color)
            ax.spines['right'].set_color(color)
        else:
            for col in y:
                color = colors.next()
                lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
                cols.append(col)
            ax.set_ylabel(', '.join(y))
            #ax.tick_params(axis='y')
    axes[0].set_xlabel(d.index.name)
    lns = lines[0]
    for l in lines[1:]:
        lns +=l
    labs = [l.get_label() for l in lns]
    axes[0].legend(lns, labs, loc=0)

    plt.show()

Java random number with given length

For the follow-up question, you can get a number between 36^5 and 36^6 and convert it in base 36

UPDATED:

using this code

http://javaconfessions.com/2008/09/convert-between-base-10-and-base-62-in_28.html

It's written BaseConverterUtil.toBase36(60466176+r.nextInt(2116316160))

but in your use case, it can be optimized by using a StringBuilder and having the number in the reverse order ie 71 should be converted in Z1 instead of 1Z

EDITED:

How to include libraries in Visual Studio 2012?

In code level also, you could add your lib to the project using the compiler directives #pragma.

example:

#pragma comment( lib, "yourLibrary.lib" )

AngularJS HTTP post to PHP and undefined

It's an old question but it worth to mention that in Angular 1.4 $httpParamSerializer is added and when using $http.post, if we use $httpParamSerializer(params) to pass the parameters, everything works like a regular post request and no JSON deserializing is needed on server side.

https://docs.angularjs.org/api/ng/service/$httpParamSerializer

jQuery: count number of rows in a table

I found this to work really well if you want to count rows without counting the th and any rows from tables inside of tables:

var rowCount = $("#tableData > tbody").children().length;

LINQ Contains Case Insensitive

StringComparison.InvariantCultureIgnoreCase just do the job for me:

.Where(fi => fi.DESCRIPTION.Contains(description, StringComparison.InvariantCultureIgnoreCase));

Find Number of CPUs and Cores per CPU using Command Prompt

If you want to find how many processors (or CPUs) a machine has the same way %NUMBER_OF_PROCESSORS% shows you the number of cores, save the following script in a batch file, for example, GetNumberOfCores.cmd:

@echo off
for /f "tokens=*" %%f in ('wmic cpu get NumberOfCores /value ^| find "="') do set %%f

And then execute like this:

GetNumberOfCores.cmd

echo %NumberOfCores%

The script will set a environment variable named %NumberOfCores% and it will contain the number of processors.

Trying to start a service on boot on Android

Along with

<action android:name="android.intent.action.BOOT_COMPLETED" />  

also use,

<action android:name="android.intent.action.QUICKBOOT_POWERON" />

HTC devices dont seem to catch BOOT_COMPLETED

Installing packages in Sublime Text 2

This recently worked for me. You just need to add to your packages, so that the package manager would be aware of the packages:

  1. Add the Sublime Text 2 Repository to your Synaptic Package Manager:

    sudo add-apt-repository ppa:webupd8team/sublime-text-2
    
  2. Update

    sudo apt-get update
    
  3. Install Sublime Text:

    sudo apt-get install sublime-text
    

How do I search for files in Visual Studio Code?

Other answers don't mention this command is named workbench.action.quickOpen.

You can use this to search the Keyboard Shortcuts menu located in Preferences.

On MacOS the default keybinding is cmd ? + P.

(Coming from Sublime Text, I always change this to cmd ? + T)

How to use select/option/NgFor on an array of objects in Angular2

I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:

<select [(ngModel)]="simpleValue"> // value is a string or number
    <option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>

If you want to match on the actual object, I'd do it like this:

<select [(ngModel)]="objValue"> // value is an object
    <option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>

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

To get the number of days the easiest way would be:

SELECT EXTRACT(DAY FROM NOW() - '2014-08-02 08:10:56');

As far as I know it would return the same as:

SELECT (EXTRACT(epoch FROM (SELECT (NOW() - '2014-08-02 08:10:56')))/86400)::int;

Maven Modules + Building a Single Specific Module

You say you "really just want B", but this is false. You want B, but you also want an updated A if there have been any changes to it ("active development").

So, sometimes you want to work with A, B, and C. For this case you have aggregator project P. For the case where you want to work with A and B (but do not want C), you should create aggregator project Q.

Edit 2016: The above information was perhaps relevant in 2009. As of 2016, I highly recommend ignoring this in most cases, and simply using the -am or -pl command-line flags as described in the accepted answer. If you're using a version of maven from before v2.1, change that first :)

Getting first value from map in C++

A map will not keep insertion order. Use *(myMap.begin()) to get the value of the first pair (the one with the smallest key when ordered).

You could also do myMap.begin()->first to get the key and myMap.begin()->second to get the value.

How can I tell which button was clicked in a PHP form submit?

With an HTML form like:

<input type="submit" name="btnSubmit" value="Save Changes" />
<input type="submit" name="btnDelete" value="Delete" />

The PHP code to use would look like:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Something posted

    if (isset($_POST['btnDelete'])) {
        // btnDelete
    } else {
        // Assume btnSubmit
    }
}

You should always assume or default to the first submit button to appear in the form HTML source code. In practice, the various browsers reliably send the name/value of a submit button with the post data when:

  1. The user literally clicks the submit button with the mouse or pointing device
  2. Or there is focus on the submit button (they tabbed to it), and then the Enter key is pressed.

Other ways to submit a form exist, and some browsers/versions decide not to send the name/value of any submit buttons in some of these situations. For example, many users submit forms by pressing the Enter key when the cursor/focus is on a text field. Forms can also be submitted via JavaScript, as well as some more obscure methods.

It's important to pay attention to this detail, otherwise you can really frustrate your users when they submit a form, yet "nothing happens" and their data is lost, because your code failed to detect a form submission, because you did not anticipate the fact that the name/value of a submit button may not be sent with the post data.

Also, the above advice should be used for forms with a single submit button too because you should always assume a default submit button.

I'm aware that the Internet is filled with tons of form-handler tutorials, and almost of all them do nothing more than check for the name and value of a submit button. But, they're just plain wrong!

Convert Mat to Array/Vector in OpenCV

Can be done in two lines :)

Mat to array

uchar * arr = image.isContinuous()? image.data: image.clone().data;
uint length = image.total()*image.channels();

Mat to vector

cv::Mat flat = image.reshape(1, image.total()*image.channels());
std::vector<uchar> vec = image.isContinuous()? flat : flat.clone();

Both work for any general cv::Mat.

Explanation with a working example

    cv::Mat image;
    image = cv::imread(argv[1], cv::IMREAD_UNCHANGED);   // Read the file
    cv::namedWindow("cvmat", cv::WINDOW_AUTOSIZE );// Create a window for display.
    cv::imshow("cvmat", image );                   // Show our image inside it.

    // flatten the mat.
    uint totalElements = image.total()*image.channels(); // Note: image.total() == rows*cols.
    cv::Mat flat = image.reshape(1, totalElements); // 1xN mat of 1 channel, O(1) operation
    if(!image.isContinuous()) {
        flat = flat.clone(); // O(N),
    }
    // flat.data is your array pointer
    auto * ptr = flat.data; // usually, its uchar*
    // You have your array, its length is flat.total() [rows=1, cols=totalElements]
    // Converting to vector
    std::vector<uchar> vec(flat.data, flat.data + flat.total());
    // Testing by reconstruction of cvMat
    cv::Mat restored = cv::Mat(image.rows, image.cols, image.type(), ptr); // OR vec.data() instead of ptr
    cv::namedWindow("reconstructed", cv::WINDOW_AUTOSIZE);
    cv::imshow("reconstructed", restored);

    cv::waitKey(0);     

Extended explanation:

Mat is stored as a contiguous block of memory, if created using one of its constructors or when copied to another Mat using clone() or similar methods. To convert to an array or vector we need the address of its first block and array/vector length.

Pointer to internal memory block

Mat::data is a public uchar pointer to its memory.
But this memory may not be contiguous. As explained in other answers, we can check if mat.data is pointing to contiguous memory or not using mat.isContinous(). Unless you need extreme efficiency, you can obtain a continuous version of the mat using mat.clone() in O(N) time. (N = number of elements from all channels). However, when dealing images read by cv::imread() we will rarely ever encounter a non-continous mat.

Length of array/vector

Q: Should be row*cols*channels right?
A: Not always. It can be rows*cols*x*y*channels.
Q: Should be equal to mat.total()?
A: True for single channel mat. But not for multi-channel mat
Length of the array/vector is slightly tricky because of poor documentation of OpenCV. We have Mat::size public member which stores only the dimensions of single Mat without channels. For RGB image, Mat.size = [rows, cols] and not [rows, cols, channels]. Mat.total() returns total elements in a single channel of the mat which is equal to product of values in mat.size. For RGB image, total() = rows*cols. Thus, for any general Mat, length of continuous memory block would be mat.total()*mat.channels().

Reconstructing Mat from array/vector

Apart from array/vector we also need the original Mat's mat.size [array like] and mat.type() [int]. Then using one of the constructors that take data's pointer, we can obtain original Mat. The optional step argument is not required because our data pointer points to continuous memory. I used this method to pass Mat as Uint8Array between nodejs and C++. This avoided writing C++ bindings for cv::Mat with node-addon-api.

References:

Apply style to cells of first row

Use tr:first-child to take the first tr:

.category_table tr:first-child td {
    vertical-align: top;
}

If you have nested tables, and you don't want to apply styles to the inner rows, add some child selectors so only the top-level tds in the first top-level tr get the styles:

.category_table > tbody > tr:first-child > td {
    vertical-align: top;
}

Tomcat 8 Maven Plugin for Java 8

Plugin run Tomcat 7.0.47:

mvn org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:run

 ...
 INFO: Starting Servlet Engine: Apache Tomcat/7.0.47

This is sample to run plugin with Tomcat 8 and Java 8: Cargo embedded tomcat: custom context.xml

How to convert OutputStream to InputStream?

An OutputStream is one where you write data to. If some module exposes an OutputStream, the expectation is that there is something reading at the other end.

Something that exposes an InputStream, on the other hand, is indicating that you will need to listen to this stream, and there will be data that you can read.

So it is possible to connect an InputStream to an OutputStream

InputStream----read---> intermediateBytes[n] ----write----> OutputStream

As someone metioned, this is what the copy() method from IOUtils lets you do. It does not make sense to go the other way... hopefully this makes some sense

UPDATE:

Of course the more I think of this, the more I can see how this actually would be a requirement. I know some of the comments mentioned Piped input/ouput streams, but there is another possibility.

If the output stream that is exposed is a ByteArrayOutputStream, then you can always get the full contents by calling the toByteArray() method. Then you can create an input stream wrapper by using the ByteArrayInputStream sub-class. These two are pseudo-streams, they both basically just wrap an array of bytes. Using the streams this way, therefore, is technically possible, but to me it is still very strange...

CSS center content inside div

You just need

.parent-div { text-align: center }

Can Console.Clear be used to only clear a line instead of whole console?

"ClearCurrentConsoleLine", "ClearLine" and the rest of the above functions should use Console.BufferWidth instead of Console.WindowWidth (you can see why when you try to make the window smaller). The window size of the console currently depends of its buffer and cannot be wider than it. Example (thanks goes to Dan Cornilescu):

public static void ClearLastLine()
{
    Console.SetCursorPosition(0, Console.CursorTop - 1);
    Console.Write(new string(' ', Console.BufferWidth));
    Console.SetCursorPosition(0, Console.CursorTop - 1);
}

Java String import

import java.lang.String;

This is an unnecessary import. java.lang classes are always implicitly imported. This means that you do not have to import them manually (explicitly).

iOS - Build fails with CocoaPods cannot find header files

The wiki gives an advice on how to solve this problem:

If Xcode can’t find the headers of the dependencies:

Check if the pod header files are correctly symlinked in Pods/Headers and you are not overriding the HEADER_SEARCH_PATHS (see #1). If Xcode still can’t find them, as a last resort you can prepend your imports, e.g. #import "Pods/SSZipArchive.h".

PHPExcel auto size column width

In case somebody was looking for this.

The resolution below also works on PHPSpreadsheet, their new version of PHPExcel.

// assuming $spreadsheet is instance of PhpOffice\PhpSpreadsheet\Spreadsheet
// assuming $worksheet = $spreadsheet->getActiveSheet();
foreach(range('A',$worksheet->getHighestColumn()) as $column) {
    $spreadsheet->getColumnDimension($column)->setAutoSize(true);
}

Note: getHighestColumn() can be replaced with getHighestDataColumn() or the last actual column.

What these methods do:

getHighestColumn($row = null) - Get highest worksheet column.

getHighestDataColumn($row = null) - Get highest worksheet column that contains data.

getHighestRow($column = null) - Get highest worksheet row

getHighestDataRow($column = null) - Get highest worksheet row that contains data.

pip3: command not found

Writing the whole path/directory eg. (for windows) C:\Programs\Python\Python36-32\Scripts\pip3.exe install mypackage. This worked well for me when I had trouble with pip.

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

Just a quick comment: sometimes Maven does not copy the jstl-.jar to the WEB-INF folder even if the pom.xml has the entry for it.

I had to manually copy the JSTL jar to /WEB-INF/lib on the file system. That resolved the problem. The issue may be related to Maven war packaging plugin.

Why does ASP.NET webforms need the Runat="Server" attribute?

I've always believed it was there more for the understanding that you can mix ASP.NET tags and HTML Tags, and HTML Tags have the option of either being runat="server" or not. It doesn't hurt anything to leave the tag in, and it causes a compiler error to take it out. The more things you imply about web language, the less easy it is for a budding programmer to come in and learn it. That's as good a reason as any to be verbose about tag attributes.

This conversation was had on Mike Schinkel's Blog between himself and Talbot Crowell of Microsoft National Services. The relevant information is below (first paragraph paraphrased due to grammatical errors in source):

[...] but the importance of <runat="server"> is more for consistency and extensibility.

If the developer has to mark some tags (viz. <asp: />) for the ASP.NET Engine to ignore, then there's also the potential issue of namespace collisions among tags and future enhancements. By requiring the <runat="server"> attribute, this is negated.

It continues:

If <runat=client> was required for all client-side tags, the parser would need to parse all tags and strip out the <runat=client> part.

He continues:

Currently, If my guess is correct, the parser simply ignores all text (tags or no tags) unless it is a tag with the runat=server attribute or a “<%” prefix or ssi “<!– #include(...) Also, since ASP.NET is designed to allow separation of the web designers (foo.aspx) from the web developers (foo.aspx.vb), the web designers can use their own web designer tools to place HTML and client-side JavaScript without having to know about ASP.NET specific tags or attributes.

Constructor overload in TypeScript

We can simulate constructor overload using guards

interface IUser {
  name: string;
  lastName: string;
}

interface IUserRaw {
  UserName: string;
  UserLastName: string;
}

function isUserRaw(user): user is IUserRaw {
  return !!(user.UserName && user.UserLastName);
}

class User {
  name: string;
  lastName: string;

  constructor(data: IUser | IUserRaw) {
    if (isUserRaw(data)) {
      this.name = data.UserName;
      this.lastName = data.UserLastName;
    } else {
      this.name = data.name;
      this.lastName = data.lastName;
    }
  }
}

const user  = new User({ name: "Jhon", lastName: "Doe" })
const user2 = new User({ UserName: "Jhon", UserLastName: "Doe" })

Uploading Images to Server android

use below code it helps you....

        BitmapFactory.Options options = new BitmapFactory.Options();

        options.inSampleSize = 4;
        options.inPurgeable = true;
        Bitmap bm = BitmapFactory.decodeFile("your path of image",options);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        bm.compress(Bitmap.CompressFormat.JPEG,40,baos); 


        // bitmap object

        byteImage_photo = baos.toByteArray();

                    //generate base64 string of image

                   String encodedImage =Base64.encodeToString(byteImage_photo,Base64.DEFAULT);

  //send this encoded string to server

encrypt and decrypt md5

Hashes can not be decrypted check this out.

If you want to encrypt-decrypt, use a two way encryption function of your database like - AES_ENCRYPT (in MySQL).

But I'll suggest CRYPT_BLOWFISH algorithm for storing password. Read this- http://php.net/manual/en/function.crypt.php and http://us2.php.net/manual/en/function.password-hash.php

For Blowfish by crypt() function -

crypt('String', '$2a$07$twentytwocharactersalt$');

password_hash will be introduced in PHP 5.5.

$options = [
    'cost' => 7,
    'salt' => 'BCryptRequires22Chrcts',
];
password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);

Once you have stored the password, you can then check if the user has entered correct password by hashing it again and comparing it with the stored value.

Why doesn't JavaScript support multithreading?

Traditionally, JS was intended for short, quick-running pieces of code. If you had major calculations going on, you did it on a server - the idea of a JS+HTML app that ran in your browser for long periods of time doing non-trivial things was absurd.

Of course, now we have that. But, it'll take a bit for browsers to catch up - most of them have been designed around a single-threaded model, and changing that is not easy. Google Gears side-steps a lot of potential problems by requiring that background execution is isolated - no changing the DOM (since that's not thread-safe), no accessing objects created by the main thread (ditto). While restrictive, this will likely be the most practical design for the near future, both because it simplifies the design of the browser, and because it reduces the risk involved in allowing inexperienced JS coders mess around with threads...

@marcio:

Why is that a reason not to implement multi-threading in Javascript? Programmers can do whatever they want with the tools they have.

So then, let's not give them tools that are so easy to misuse that every other website i open ends up crashing my browser. A naive implementation of this would bring you straight into the territory that caused MS so many headaches during IE7 development: add-on authors played fast and loose with the threading model, resulting in hidden bugs that became evident when object lifecycles changed on the primary thread. BAD. If you're writing multi-threaded ActiveX add-ons for IE, i guess it comes with the territory; doesn't mean it needs to go any further than that.

ViewDidAppear is not called when opening app from background

Swift 3.0 ++ version

In your viewDidLoad, register at notification center to listen to this opened from background action

NotificationCenter.default.addObserver(self, selector:#selector(doSomething), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
        

Then add this function and perform needed action

func doSomething(){
    //...
}

Finally add this function to clean up the notification observer when your view controller is destroyed.

deinit {
    NotificationCenter.default.removeObserver(self)
}

How do I check to see if my array includes an object?

If you want to check if an object is within in array by checking an attribute on the object, you can use any? and pass a block that evaluates to true or false:

unless @suggested_horses.any? {|h| h.id == horse.id }
  @suggested_horses << horse
end

MySQL Multiple Where Clause

SELECT a.image_id 
FROM list a
INNER JOIN list b
   ON a.image_id = b.image_id
   AND b.style_id = 25
   AND b.style_value = 'big'
INNER JOIN list c
   ON a.image_id = c.image_id
   AND c.style_id = 27
   AND c.style_value = 'round'
WHERE a.style_id = 24 
   AND a.style_value = 'red'

Usage of $broadcast(), $emit() And $on() in AngularJS

$emit

It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $emit was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.

$broadcast

It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $broadcast was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.

$on

It listen on events of a given type. It can catch the event dispatched by $broadcast and $emit.


Visual demo:

Demo working code, visually showing scope tree (parent/child relationship):
http://plnkr.co/edit/am6IDw?p=preview

Demonstrates the method calls:

  $scope.$on('eventEmitedName', function(event, data) ...
  $scope.broadcastEvent
  $scope.emitEvent

Loop through columns and add string lengths as new columns

With dplyr and stringr you can use mutate_all:

> df %>% mutate_all(funs(length = str_length(.)))

     col1     col2 col1_length col2_length
1     abc adf qqwe           3           8
2    abcd        d           4           1
3       a        e           1           1
4 abcdefg        f           7           1

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

You can get the full path of the selected file to upload only by IE11 and MS Edge.

var fullPath = Request.Form.Files["myFile"].FileName;

How to import a module given its name as string?

If you want it in your locals:

>>> mod = 'sys'
>>> locals()['my_module'] = __import__(mod)
>>> my_module.version
'2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]'

same would work with globals()

@Transactional(propagation=Propagation.REQUIRED)

To understand the various transactional settings and behaviours adopted for Transaction management, such as REQUIRED, ISOLATION etc. you'll have to understand the basics of transaction management itself.

Read Trasaction management for more on explanation.

What is a good regular expression to match a URL?

I was trying to put together some JavaScript to validate a domain name (ex. google.com) and if it validates enable a submit button. I thought that I would share my code for those who are looking to accomplish something similar. It expects a domain without any http:// or www. value. The script uses a stripped down regular expression from above for domain matching, which isn't strict about fake TLD.

http://jsfiddle.net/nMVDS/1/

$(function () {
  $('#whitelist_add').keyup(function () {
    if ($(this).val() == '') { //Check to see if there is any text entered
        //If there is no text within the input, disable the button
        $('.whitelistCheck').attr('disabled', 'disabled');
    } else {
        // Domain name regular expression
        var regex = new RegExp("^([0-9A-Za-z-\\.@:%_\+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");
        if (regex.test($(this).val())) {
            // Domain looks OK
            //alert("Successful match");
            $('.whitelistCheck').removeAttr('disabled');
        } else {
            // Domain is NOT OK
            //alert("No match");
            $('.whitelistCheck').attr('disabled', 'disabled');
        }
    }
  });
});

HTML FORM:

<form action="domain_management.php" method="get">
    <input type="text" name="whitelist_add" id="whitelist_add" placeholder="domain.com">
    <button type="submit" class="btn btn-success whitelistCheck" disabled='disabled'>Add to Whitelist</button>
</form>

Command CompileSwift failed with a nonzero exit code in Xcode 10

For me, the error message said I had too many simulator files open to build Swift. When I quit the simulator and built again, everything worked.

No connection could be made because the target machine actively refused it?

I've received this error from referencing services located on a WCFHost from my web tier. What worked for me may not apply to everyone, but I'm leaving this answer for those whom it may. The port number for my WCFHost was randomly updated by IIS, I simply had to update the end routes to the svc references in my web config. Problem solved.

How do I tell if a variable has a numeric value in Perl?

A slightly more robust regex can be found in Regexp::Common.

It sounds like you want to know if Perl thinks a variable is numeric. Here's a function that traps that warning:

sub is_number{
  my $n = shift;
  my $ret = 1;
  $SIG{"__WARN__"} = sub {$ret = 0};
  eval { my $x = $n + 1 };
  return $ret
}

Another option is to turn off the warning locally:

{
  no warnings "numeric"; # Ignore "isn't numeric" warning
  ...                    # Use a variable that might not be numeric
}

Note that non-numeric variables will be silently converted to 0, which is probably what you wanted anyway.

Difference between webdriver.get() and webdriver.navigate()

Not sure it applies here also but in the case of protractor when using navigate().to(...) the history is being kept but when using get() it is lost.

One of my test was failing because I was using get() 2 times in a row and then doing a navigate().back(). Because the history was lost, when going back it went to the about page and an error was thrown:

Error: Error while waiting for Protractor to sync with the page: {}

Disable and later enable all table indexes in Oracle

If you are using non-parallel direct path loads then consider and benchmark not dropping the indexes at all, particularly if the indexes only cover a minority of the columns. Oracle has a mechanism for efficient maintenance of indexes on direct path loads.

Otherwise, I'd also advise making the indexes unusable instead of dropping them. Less chance of accidentally not recreating an index.

How to set bootstrap navbar active class with Angular JS?

You can actually use angular-ui-utils' ui-route directive:

<a ui-route ng-href="/">Home</a>
<a ui-route ng-href="/about">About</a>
<a ui-route ng-href="/contact">Contact</a>

or:

Header Controller

/**
 * Header controller
 */
angular.module('myApp')
  .controller('HeaderCtrl', function ($scope) {
    $scope.menuItems = [
      {
        name: 'Home',
        url:  '/',
        title: 'Go to homepage.'
      },
      {
        name:   'About',
        url:    '/about',
        title:  'Learn about the project.'
      },
      {
        name:   'Contact',
        url:    '/contact',
        title:  'Contact us.'
      }
    ];
  });

Index page

<!-- index.html: -->
<div class="header" ng-controller="HeaderCtrl">
  <ul class="nav navbar-nav navbar-right">
    <li ui-route="{{menuItem.url}}" ng-class="{active: $uiRoute}"
      ng-repeat="menuItem in menuItems">
      <a ng-href="#{{menuItem.url}}" title="{{menuItem.title}}">
        {{menuItem.name}}
      </a>
    </li>
  </ul>
</div>

If you're using ui-utils, you may also be interested in ui-router for managing partial/nested views.

Hide the browse button on a input type=file

_x000D_
_x000D_
        .dropZoneOverlay, .FileUpload {_x000D_
            width: 283px;_x000D_
            height: 71px;_x000D_
        }_x000D_
_x000D_
        .dropZoneOverlay {_x000D_
            border: dotted 1px;_x000D_
            font-family: cursive;_x000D_
            color: #7066fb;_x000D_
            position: absolute;_x000D_
            top: 0px;_x000D_
            text-align: center;_x000D_
        }_x000D_
_x000D_
        .FileUpload {_x000D_
            opacity: 0;_x000D_
            position: relative;_x000D_
            z-index: 1;_x000D_
        }
_x000D_
        <div class="dropZoneContainer">_x000D_
            <input type="file" id="drop_zone" class="FileUpload" accept=".jpg,.png,.gif" onchange="handleFileSelect(this) " />_x000D_
            <div class="dropZoneOverlay">Drag and drop your image <br />or<br />Click to add</div>_x000D_
        </div>
_x000D_
_x000D_
_x000D_

I find a good way of achieving this at Remove browse button from input=file.

The rationale behind this solution is that it creates a transparent input=file control and creates an layer visible to the user below the file control. The z-index of the input=file will be higher than the layer.

With this, it appears that the layer is the file control itself. But actually when you clicks on it, the input=file is the one clicked and the dialog for choosing file will appear.

How to clear the cache of nginx?

You can also bypass/re-cache on a file by file basis using

proxy_cache_bypass $http_secret_header;

and as a bonus you can return this header to see if you got it from the cache (will return 'HIT') or from the content server (will return 'BYPASS').

add_header X-Cache-Status $upstream_cache_status;

to expire/refresh the cached file, use curl or any rest client to make a request to the cached page.

curl http://abcdomain.com/mypage.html -s -I -H "secret-header:true"

this will return a fresh copy of the item and it will also replace what's in cache.

What column type/length should I use for storing a Bcrypt hashed password in a Database?

The modular crypt format for bcrypt consists of

  • $2$, $2a$ or $2y$ identifying the hashing algorithm and format
  • a two digit value denoting the cost parameter, followed by $
  • a 53 characters long base-64-encoded value (they use the alphabet ., /, 09, AZ, az that is different to the standard Base 64 Encoding alphabet) consisting of:
    • 22 characters of salt (effectively only 128 bits of the 132 decoded bits)
    • 31 characters of encrypted output (effectively only 184 bits of the 186 decoded bits)

Thus the total length is 59 or 60 bytes respectively.

As you use the 2a format, you’ll need 60 bytes. And thus for MySQL I’ll recommend to use the CHAR(60) BINARYor BINARY(60) (see The _bin and binary Collations for information about the difference).

CHAR is not binary safe and equality does not depend solely on the byte value but on the actual collation; in the worst case A is treated as equal to a. See The _bin and binary Collations for more information.

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

  • Ensure the fields named in the table adapter query match those in the query you have defined. The DAL does not seem to like mismatches. This will typically happen to your sprocs and queries after you add a new field to a table.

  • If you have changed the length of a varchar field in the database and the XML contained in the XSS file has not picked it up, find the field name and attribute definition in the XML and change it manually.

  • Remove primary keys from select lists in table adapters if they are not related to the data being returned.

  • Run your query in SQL Management Studio and ensure there are not duplicate records being returned. Duplicate records can generate duplicate primary keys which will cause this error.

  • SQL unions can spell trouble. I modified one table adapter by adding a ‘please select an employee’ record preceding the others. For the other fields I provided dummy data including, for example, strings of length one. The DAL inferred the schema from that initial record. Records following with strings of length 12 failed.

Makefile, header dependencies

As I posted here gcc can create dependencies and compile at the same time:

DEPS := $(OBJS:.o=.d)

-include $(DEPS)

%.o: %.c
    $(CC) $(CFLAGS) -MM -MF $(patsubst %.o,%.d,$@) -o $@ $<

The '-MF' parameter specifies a file to store the dependencies in.

The dash at the start of '-include' tells Make to continue when the .d file doesn't exist (e.g. on first compilation).

Note there seems to be a bug in gcc regarding the -o option. If you set the object filename to say obj/_file__c.o then the generated file.d will still contain file.o, not obj/_file__c.o.

Virtualbox shared folder permissions

Add yourself to the vboxsf group within the guest VM.

Solution 1

Run sudo adduser $USER vboxsf from terminal.
(On Suse it's sudo usermod --append --groups vboxsf $USER)

To take effect you should log out and then log in, or you may need to reboot.

Solution 2

Edit the file /etc/group (you will need root privileges). Look for the line vboxsf:x:999 and add at the end :yourusername -- use this solution if you don't have sudo.

To take effect you should log out and then log in, or you may need to reboot.

Convert string to JSON Object

only with js

   JSON.parse(jsonObj);

reference

Background color not showing in print preview

Your CSS must be like this:

@media print {
   body {
      -webkit-print-color-adjust: exact;
   }
}

.vendorListHeading th {
   background-color: #1a4567 !important;
   color: white !important;   
}

IOException: read failed, socket might closed - Bluetooth on Android 4.3

I had the same symptoms as described here. I could connect once to a bluetooth printer but subsequent connects failed with "socket closed" no matter what I did.

I found it a bit strange that the workarounds described here would be necessary. After going through my code I found that I had forgot to close the socket's InputStream and OutputSteram and not terminated the ConnectedThreads properly.

The ConnectedThread I use is the same as in the example here:

http://developer.android.com/guide/topics/connectivity/bluetooth.html

Note that ConnectThread and ConnectedThread are two different classes.

Whatever class that starts the ConnectedThread must call interrupt() and cancel() on the thread. I added mmInStream.close() and mmOutStream.close() in the ConnectedTread.cancel() method.

After closing the threads/streams/sockets properly I could create new sockets without any problem.

Subset data.frame by date

The first thing you should do with date variables is confirm that R reads it as a Date. To do this, for the variable (i.e. vector/column) called Date, in the data frame called EPL2011_12, input

class(EPL2011_12$Date)

The output should read [1] "Date". If it doesn't, you should format it as a date by inputting

EPL2011_12$Date <- as.Date(EPL2011_12$Date, "%d-%m-%y")

Note that the hyphens in the date format ("%d-%m-%y") above can also be slashes ("%d/%m/%y"). Confirm that R sees it as a Date. If it doesn't, try a different formatting command

EPL2011_12$Date <- format(EPL2011_12$Date, format="%d/%m/%y")

Once you have it in Date format, you can use the subset command, or you can use brackets

WhateverYouWant <- EPL2011_12[EPL2011_12$Date > as.Date("2014-12-15"),]

SQL Server 2008 Row Insert and Update timestamps

As an alternative to using a trigger, you might like to consider creating a stored procedure to handle the INSERTs that takes most of the columns as arguments and gets the CURRENT_TIMESTAMP which it includes in the final INSERT to the database. You could do the same for the CREATE. You may also be able to set things up so that users cannot execute INSERT and CREATE statements other than via the stored procedures.

I have to admit that I haven't actually done this myself so I'm not at all sure of the details.

Rails has_many with alias name

You could also use alias_attribute if you still want to be able to refer to them as tasks as well:

class User < ActiveRecord::Base
  alias_attribute :jobs, :tasks

  has_many :tasks
end

try/catch with InputMismatchException creates infinite loop

To complement the AmitD answer:

Just copy/pasted your program and had this output:

Error!
Enter first num: 
.... infinite times ....

As you can see, the instruction:

n1 = input.nextInt();

Is continuously throwing the Exception when your double number is entered, and that's because your stream is not cleared. To fix it, follow the AmitD answer.

How to copy a char array in C?

I recommend to use memcpy() for copying data. Also if we assign a buffer to another as array2 = array1 , both array have same memory and any change in the arrary1 deflects in array2 too. But we use memcpy, both buffer have different array. I recommend memcpy() because strcpy and related function do not copy NULL character.

Java : Accessing a class within a package, which is the better way?

No, it doesn't save you memory.

Also note that you don't have to import Math at all. Everything in java.lang is imported automatically.

A better example would be something like an ArrayList

import java.util.ArrayList;
....
ArrayList<String> i = new ArrayList<String>();

Note I'm importing the ArrayList specifically. I could have done

import java.util.*; 

But you generally want to avoid large wildcard imports to avoid the problem of collisions between packages.

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

window.onload vs document.onload

In Chrome, window.onload is different from <body onload="">, whereas they are the same in both Firefox(version 35.0) and IE (version 11).

You could explore that by the following snippet:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <!--import css here-->
        <!--import js scripts here-->

        <script language="javascript">

            function bodyOnloadHandler() {
                console.log("body onload");
            }

            window.onload = function(e) {
                console.log("window loaded");
            };
        </script>
    </head>

    <body onload="bodyOnloadHandler()">

        Page contents go here.

    </body>
</html>

And you will see both "window loaded"(which comes firstly) and "body onload" in Chrome console. However, you will see just "body onload" in Firefox and IE. If you run "window.onload.toString()" in the consoles of IE & FF, you will see:

"function onload(event) { bodyOnloadHandler() }"

which means that the assignment "window.onload = function(e)..." is overwritten.

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

Nothing easier than that man. Try this one:

<?xml version="1.0" encoding="iso-8859-1"?>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css" type="text/css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script>
    <style>
        .loading { background: url(/img/spinner.gif) center no-repeat !important}
    </style>
</head>
<body>
    <a class="ajax" href="http://www.google.com">
      Open as dialog
    </a>

    <script type="text/javascript">
    $(function (){
        $('a.ajax').click(function() {
            var url = this.href;
            // show a spinner or something via css
            var dialog = $('<div style="display:none" class="loading"></div>').appendTo('body');
            // open the dialog
            dialog.dialog({
                // add a close listener to prevent adding multiple divs to the document
                close: function(event, ui) {
                    // remove div with all data and events
                    dialog.remove();
                },
                modal: true
            });
            // load remote content
            dialog.load(
                url, 
                {}, // omit this param object to issue a GET request instead a POST request, otherwise you may provide post parameters within the object
                function (responseText, textStatus, XMLHttpRequest) {
                    // remove the loading class
                    dialog.removeClass('loading');
                }
            );
            //prevent the browser to follow the link
            return false;
        });
    });
    </script>
</body>
</html>

Note that you can't load remote from local, so you'll have to upload this to a server or whatever. Also note that you can't load from foreign domains, so you should replace href of the link to a document hosted on the same domain (and here's the workaround).

Cheers

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

I just had this problem

  1. Having multiple user using the same repo caused the problem
  2. Logout evey other user using the repo

Hope this helps

Regular expression for decimal number

In .NET, I recommend to dynamically build the regular expression with the decimal separator of the current cultural context:

using System.Globalization;

...

NumberFormatInfo nfi = NumberFormatInfo.CurrentInfo;
Regex re = new Regex("^(?\\d+(" 
                   + Regex.Escape(nfi.CurrencyDecimalSeparator) 
                   + "\\d{1,2}))$");

You might want to pimp the regexp by allowing 1000er separators the same way as the decimal separator.

Cannot read property 'push' of undefined when combining arrays

You get the error because order[1] is undefined.

That error message means that somewhere in your code, an attempt is being made to access a property with some name (here it's "push"), but instead of an object, the base for the reference is actually undefined. Thus, to find the problem, you'd look for code that refers to that property name ("push"), and see what's to the left of it. In this case, the code is

if(parseInt(a[i].daysleft) > 0){ order[1].push(a[i]); }

which means that the code expects order[1] to be an array. It is, however, not an array; it's undefined, so you get the error. Why is it undefined? Well, your code doesn't do anything to make it anything else, based on what's in your question.

Now, if you just want to place a[i] in a particular property of the object, then there's no need to call .push() at all:

var order = [], stack = [];
for(var i=0;i<a.length;i++){
    if(parseInt(a[i].daysleft) == 0){ order[0] = a[i]; }
    if(parseInt(a[i].daysleft) > 0){ order[1] = a[i]; }
    if(parseInt(a[i].daysleft) < 0){ order[2] = a[i]; }
}

C# string reference type?

If we have to answer the question: String is a reference type and it behaves as a reference. We pass a parameter that holds a reference to, not the actual string. The problem is in the function:

public static void TestI(string test)
{
    test = "after passing";
}

The parameter test holds a reference to the string but it is a copy. We have two variables pointing to the string. And because any operations with strings actually create a new object, we make our local copy to point to the new string. But the original test variable is not changed.

The suggested solutions to put ref in the function declaration and in the invocation work because we will not pass the value of the test variable but will pass just a reference to it. Thus any changes inside the function will reflect the original variable.

I want to repeat at the end: String is a reference type but since its immutable the line test = "after passing"; actually creates a new object and our copy of the variable test is changed to point to the new string.

What does an exclamation mark before a cell reference mean?

When entered as the reference of a Named range, it refers to range on the sheet the named range is used on.

For example, create a named range MyName refering to =SUM(!B1:!K1)

Place a formula on Sheet1 =MyName. This will sum Sheet1!B1:K1

Now place the same formula (=MyName) on Sheet2. That formula will sum Sheet2!B1:K1

Note: (as pnuts commented) this and the regular SheetName!B1:K1 format are relative, so reference different cells as the =MyName formula is entered into different cells.

AngularJS ngClass conditional

Using ng-class inside ng-repeat

<table>
    <tbody>
            <tr ng-repeat="task in todos"
                ng-class="{'warning': task.status == 'Hold' , 'success': task.status == 'Completed',
              'active': task.status == 'Started', 'danger': task.status == 'Pending' } ">
                <td>{{$index + 1}}</td>
                <td>{{task.name}}</td>
                <td>{{task.date|date:'yyyy-MM-dd'}}</td>
                <td>{{task.status}}</td>
            </tr>
    </tbody>
</table>

For each status in task.status a different class is used for the row.

How to asynchronously call a method in Java

There is also nice library for Async-Await created by EA: https://github.com/electronicarts/ea-async

From their Readme:

With EA Async

import static com.ea.async.Async.await;
import static java.util.concurrent.CompletableFuture.completedFuture;

public class Store
{
    public CompletableFuture<Boolean> buyItem(String itemTypeId, int cost)
    {
        if(!await(bank.decrement(cost))) {
            return completedFuture(false);
        }
        await(inventory.giveItem(itemTypeId));
        return completedFuture(true);
    }
}

Without EA Async

import static java.util.concurrent.CompletableFuture.completedFuture;

public class Store
{
    public CompletableFuture<Boolean> buyItem(String itemTypeId, int cost)
    {
        return bank.decrement(cost)
            .thenCompose(result -> {
                if(!result) {
                    return completedFuture(false);
                }
                return inventory.giveItem(itemTypeId).thenApply(res -> true);
            });
    }
}

Python readlines() usage and efficient practice for reading

The short version is: The efficient way to use readlines() is to not use it. Ever.


I read some doc notes on readlines(), where people has claimed that this readlines() reads whole file content into memory and hence generally consumes more memory compared to readline() or read().

The documentation for readlines() explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list full of strings out of those lines.

But the documentation for read() likewise guarantees that it reads the whole file into memory, and builds a string, so that doesn't help.


On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.


You can work around this in three ways:

  1. Write a loop around readlines(sizehint), read(size), or readline().
  2. Just use the file as a lazy iterator without calling any of these.
  3. mmap the file, which allows you to treat it as a giant string without first reading it in.

For example, this has to read all of foo at once:

with open('foo') as f:
    lines = f.readlines()
    for line in lines:
        pass

But this only reads about 8K at a time:

with open('foo') as f:
    while True:
        lines = f.readlines(8192)
        if not lines:
            break
        for line in lines:
            pass

And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.

with open('foo') as f:
    while True:
        line = f.readline()
        if not line:
            break
        pass

And this will do the exact same thing as the previous:

with open('foo') as f:
    for line in f:
        pass

Meanwhile:

but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?

Python doesn't make any such guarantees about garbage collection.

The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.

However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.

On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.

Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of mallocs to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).


Putting it all together, here's how I'd write your program:

for filename in os.listdir(input_dir):
    with open(filename, 'rb') as f:
        if filename.endswith(".gz"):
            f = gzip.open(fileobj=f)
        words = (line.split(delimiter) for line in f)
        ... my logic ...  

Or, maybe:

for filename in os.listdir(input_dir):
    if filename.endswith(".gz"):
        f = gzip.open(filename, 'rb')
    else:
        f = open(filename, 'rb')
    with contextlib.closing(f):
        words = (line.split(delimiter) for line in f)
        ... my logic ...

How to send email from Terminal?

For SMTP hosts and Gmail I like to use Swaks -> https://easyengine.io/tutorials/mail/swaks-smtp-test-tool/

On a Mac:

  1. brew install swaks
  2. swaks --to [email protected] --server smtp.example.com

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

Try using the following query which will create Respective table in same or other DB ("DataBase").

SELECT * INTO DataBase.dbo.BackUpTable FROM SourceDataBase.dbo.SourceTable

How do I list all tables in all databases in SQL Server in a single result set?

Link to a stored-procedure-less approach that Bart Gawrych posted on Dataedo site

I was asking myself, 'Do we really have to use a stored procedure here?' and I found this helpful post. (The state=0 was added to fix issues with offline databases per feedback from users of the linked page.)

declare @sql nvarchar(max);

select @sql = 
    (select ' UNION ALL
        SELECT ' +  + quotename(name,'''') + ' as database_name,
               s.name COLLATE DATABASE_DEFAULT
                    AS schema_name,
               t.name COLLATE DATABASE_DEFAULT as table_name 
               FROM '+ quotename(name) + '.sys.tables t
               JOIN '+ quotename(name) + '.sys.schemas s
                    on s.schema_id = t.schema_id'
    from sys.databases 
    where state=0
    order by [name] for xml path(''), type).value('.', 'nvarchar(max)');

set @sql = stuff(@sql, 1, 12, '') + ' order by database_name, 
                                               schema_name,
                                               table_name';

execute (@sql);

Failed linking file resources

Look at the error you are getting:

C:\Projects\TimeTable\app\src\main\res\layout-land\activity_main.xml Error:error: resource android:attr/colorSwitchThumbNormal is private.

It means that in your activity_main.xml you are referencing the color "android:colorSwitchThumbNormal", but inside the 'android' namespace that resource is private. What you probably meant to do is try to reference that color from the support version of this attribute, so without the "android:" prefix.

<item name="android:colorSwitchThumbNormal">@color/myColor</item>

Replace with:

<item name="colorSwitchThumbNormal">@color/second</item>

Set colspan dynamically with jquery

I've also found that if you had display:none, then programmatically changed it to be visible, you might also have to set

$tr.css({display:'table-row'});

rather than display:inline or display:block otherwise the cell might only show as taking up 1 cell, no matter how large you have the colspan set to.

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
Out[80]:
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
Out[81]:
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
Out[82]:
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

Can you change a path without reloading the controller in AngularJS?

Answers above, including the GitHub one, had some issues for my scenario and also back button or direct url change from browser was reloading the controller, which I did not like. I finally went with the following approach:

1. Define a property in route definitions, called 'noReload' for those routes where you don't want the controller to reload on route change.

.when('/:param1/:param2?/:param3?', {
    templateUrl: 'home.html',
    controller: 'HomeController',
    controllerAs: 'vm',
    noReload: true
})

2. In the run function of your module, put the logic that checks for those routes. It will prevent reload only if noReload is true and previous route controller is the same.

fooRun.$inject = ['$rootScope', '$route', '$routeParams'];

function fooRun($rootScope, $route, $routeParams) {
    $rootScope.$on('$routeChangeStart', function (event, nextRoute, lastRoute) {
        if (lastRoute && nextRoute.noReload 
         && lastRoute.controller === nextRoute.controller) {
            var un = $rootScope.$on('$locationChangeSuccess', function () {
                un();
                // Broadcast routeUpdate if params changed. Also update
                // $routeParams accordingly
                if (!angular.equals($route.current.params, lastRoute.params)) {
                    lastRoute.params = nextRoute.params;
                    angular.copy(lastRoute.params, $routeParams);
                    $rootScope.$broadcast('$routeUpdate', lastRoute);
                }
                // Prevent reload of controller by setting current
                // route to the previous one.
                $route.current = lastRoute;
            });
        }
    });
}

3. Finally, in the controller, listen to $routeUpdate event so you can do whatever you need to do when route parameters change.

HomeController.$inject = ['$scope', '$routeParams'];

function HomeController($scope, $routeParams) {
    //(...)

    $scope.$on("$routeUpdate", function handler(route) {
        // Do whatever you need to do with new $routeParams
        // You can also access the route from the parameter passed
        // to the event
    });

    //(...)
}

Keep in mind that with this approach, you don't change things in the controller and then update the path accordingly. It's the other way around. You first change the path, then listen to $routeUpdate event to change things in the controller when route parameters change.

This keeps things simple and consistent as you can use the same logic both when you simply change path (but without expensive $http requests if you like) and when you completely reload the browser.

Installing Python 3 on RHEL

You can download a source RPMs and binary RPMs for RHEL6 / CentOS6 from here

This is a backport from the newest Fedora development source rpm to RHEL6 / CentOS6

Copy Data from a table in one Database to another separate database

INSERT INTO DB1.dbo.TempTable
SELECT * FROM DB2.dbo.TempTable

If we use this query it will return Primary key error.... So better to choose which columns need to be moved, like

INSERT INTO db1.dbo.TempTable // (List of columns here)
SELECT (Same list of columns here)
FROM db2.dbo.TempTable

Git push error: "origin does not appear to be a git repository"

Most likely the remote repository doesn't exist or you have added the wrong one.

You have to first remove the origin and re-add it:

git remote remove origin
git remote add origin https://github.com/username/repository

How to delete specific characters from a string in Ruby?

Here is an even shorter way of achieving this:

1) using Negative character class pattern matching

irb(main)> "((String1))"[/[^()]+/]
=> "String1"

^ - Matches anything NOT in the character class. Inside the charachter class, we have ( and )

Or with global substitution "AKA: gsub" like others have mentioned.

irb(main)> "((String1))".gsub(/[)(]/, '')
=> "String1"

Export P7b file with all the certificate chain into CER file

-print_certs is the option you want to use to list all of the certificates in the p7b file, you may need to specify the format of the p7b file you are reading.

You can then redirect the output to a new file to build the concatenated list of certificates.

Open the file in a text editor, you will either see Base64 (PEM) or binary data (DER).

openssl pkcs7 -inform DER -outform PEM -in certificate.p7b -print_certs > certificate_bundle.cer

http://www.openssl.org/docs/apps/pkcs7.html

Oracle query to fetch column names

  1. SELECT * FROM <SCHEMA_NAME.TABLE_NAME> WHERE ROWNUM = 0; --> Note that, this is Query Result, a ResultSet. This is exportable to other formats. And, you can export the Query Result to Text format. Export looks like below when I did SELECT * FROM SATURN.SPRIDEN WHERE ROWNUM = 0; :

    "SPRTELE_PIDM" "SPRTELE_SEQNO" "SPRTELE_TELE_CODE" "SPRTELE_ACTIVITY_DATE" "SPRTELE_PHONE_AREA" "SPRTELE_PHONE_NUMBER" "SPRTELE_PHONE_EXT" "SPRTELE_STATUS_IND" "SPRTELE_ATYP_CODE" "SPRTELE_ADDR_SEQNO" "SPRTELE_PRIMARY_IND" "SPRTELE_UNLIST_IND" "SPRTELE_COMMENT" "SPRTELE_INTL_ACCESS" "SPRTELE_DATA_ORIGIN" "SPRTELE_USER_ID" "SPRTELE_CTRY_CODE_PHONE" "SPRTELE_SURROGATE_ID" "SPRTELE_VERSION" "SPRTELE_VPDI_CODE"

  2. DESCRIBE <TABLE_NAME> --> Note: This is script output.

Script not served by static file handler on IIS7.5

I stumbled upon this question when I ran into the same issue. The root cause of my issue was an incorrectly-configured app pool. It was set for 2.0 inadvertently, when it needed to be set to 4.0. The answer at the following link helped me uncover this issue: http://forums.iis.net/t/1160143.aspx

Can't find how to use HttpContent

Just leaving the way using Microsoft.AspNet.WebApi.Client here.

Example:

var client = HttpClientFactory.Create();
var result = await client.PostAsync<ExampleClass>("http://www.sample.com/write", new ExampleClass(), new JsonMediaTypeFormatter());

jQuery Datepicker onchange event issue

Manual says:

apply.daterangepicker: Triggered when the apply button is clicked, or when a predefined range is clicked

So:

$('#daterange').daterangepicker({
  locale: { cancelLabel: 'Clear' }  
});

$('#daterange').on('apply.daterangepicker', function() {
  alert('worked!');
});

Works for me.

SQL statement to get column type

USE [YourDatabaseName]
GO

SELECT column_name 'Column Name',
data_type 'Data Type'
FROM information_schema.columns
WHERE table_name = 'YourTableName'
GO

This will return the values Column Name, showing you the names of the columns, and the Data Types of those columns (ints, varchars, etc).

How to change workspace and build record Root Directory on Jenkins?

You can modify the path on the config.xml file in the default directory

<projectNamingStrategy class="jenkins.model.ProjectNamingStrategy$DefaultProjectNamingStrategy"/>
<workspaceDir>D:/Workspace/${ITEM_FULL_NAME}</workspaceDir>
<buildsDir>D:/Logs/${ITEM_ROOTDIR}/Build</buildsDir>

Swift presentViewController

You can use below code :

var vc = self.storyboard?.instantiateViewControllerWithIdentifier("YourViewController") as! YourViewController;
            vc.mode_Player = 1
            self.presentViewController(vc, animated: true, completion: nil)

How to write a comment in a Razor view?

This comment syntax should work for you:

@* enter comments here *@

Android Studio: Can't start Git

The path for your git is invalid. Copy the path from File -> Settings -> Version Control -> Git and search that folder and you can see the path to your Git is not valid. Reset the path with correct location and test it. The error should be gone.

Using an image caption in Markdown Jekyll

There are two semantically correct solutions to this question:

  1. Using a plugin
  2. Creating a custom include

1. Using a plugin

I've tried a couple of plugins doing this and my favourite is jekyll-figure.

1.1. Install jekyll-figure

One way to install jekyll-figure is to add gem "jekyll-figure" to your Gemfile in your plugins group.

Then run bundle install from your terminal window.

1.2. Use jekyll-figure

Simply wrap your markdown in {% figure %} and {% endfigure %} tags.

You caption goes in the opening {% figure %} tag, and you can even style it with markdown!

Example:

{% figure caption:"Le logo de **Jekyll** et son clin d'oeil à Robert Louis Stevenson" %}
    ![Le logo de Jekyll](/assets/images/2018-08-07-jekyll-logo.png)
{% endfigure %}

1.3. Style it

Now that your images and captions are semantically correct, you can apply CSS as you wish to:

  • figure (for both image and caption)
  • figure img (for image only)
  • figcaption (for caption only)

2. Creating a custom include

You'll need to create an image.html file in your _includes folder, and include it using Liquid in Markdown.

2.1. Create _includes/image.html

Create the image.html document in your _includes folder :

<!-- _includes/image.html -->
<figure>
    {% if include.url %}
    <a href="{{ include.url }}">
    {% endif %}
    <img
        {% if include.srcabs %}
            src="{{ include.srcabs }}"
        {% else %}
            src="{{ site.baseurl }}/assets/images/{{ include.src }}"
        {% endif %}
    alt="{{ include.alt }}">
    {% if include.url %}
    </a>
    {% endif %}
    {% if include.caption %}
        <figcaption>{{ include.caption }}</figcaption>
    {% endif %}
</figure>

2.2. In Markdown, include an image using Liquid

An image in /assets/images with a caption:

This is [Jekyll](https://jekyllrb.com)'s logo :

{% include image.html
    src="jekyll-logo.png" <!-- image filename (placed in /assets/images) -->
    alt="Jekyll's logo" <!-- alt text -->
    caption="This is Jekyll's logo, featuring Dr. Jekyll's serum!" <!-- Caption -->
%}

An (external) image using an absolute URL: (change src="" to srcabs="")

This is [Jekyll](https://jekyllrb.com)'s logo :

{% include image.html
    srcabs="https://jekyllrb.com/img/logo-2x.png" <!-- absolute URL to image file -->
    alt="Jekyll's logo" <!-- alt text -->
    caption="This is Jekyll's logo, featuring Dr. Jekyll's serum!" <!-- Caption -->
%}

A clickable image: (add url="" argument)

This is [Jekyll](https://jekyllrb.com)'s logo :

{% include image.html
    src="https://jekyllrb.com/img/logo-2x.png" <!-- absolute URL to image file -->
    url="https://jekyllrb.com" <!-- destination url -->
    alt="Jekyll's logo" <!-- alt text -->
    caption="This is Jekyll's logo, featuring Dr. Jekyll's serum!" <!-- Caption -->
%}

An image without a caption:

This is [Jekyll](https://jekyllrb.com)'s logo :

{% include image.html
    src="https://jekyllrb.com/img/logo-2x.png" <!-- absolute URL to image file -->
    alt="Jekyll's logo" <!-- alt text -->
%}

2.3. Style it

Now that your images and captions are semantically correct, you can apply CSS as you wish to:

  • figure (for both image and caption)
  • figure img (for image only)
  • figcaption (for caption only)

Storing Python dictionaries

If save to a JSON file, the best and easiest way of doing this is:

import json
with open("file.json", "wb") as f:
    f.write(json.dumps(dict).encode("utf-8"))

remove space between paragraph and unordered list

p, ul{
     padding:0; 
     margin:0;
}

If that's not what your looking for you'll have to be more specific

How to execute an external program from within Node.js?

The simplest way is:

const { exec } = require("child_process")
exec('yourApp').unref()

unref is necessary to end your process without waiting for "yourApp"

Here are the exec docs

HTTP Status 404 - The requested resource (/) is not available

If you are new in JSP/Tomcat don't modify tomcat's xml files.

I assume you have already deployed web application. But to be sure, try these steps: - right click on your web application - select Run As / Run on Server, choose your Tomcat 7

These steps will deploy and run in the browser your application. Another idea to check if your Tomcat works correctly is to find path where tomcat exists (in eclipse plugin), and copy some working WAR file to webapps (not to wtpwebapps), and then try to run the app.

How to prevent column break within an element?

As of October 2014, break-inside still seems to be buggy in Firefox and IE 10-11. However, adding overflow: hidden to the element, along with the break-inside: avoid, seems to make it work in Firefox and IE 10-11. I am currently using:

overflow: hidden; /* Fix for firefox and IE 10-11  */
-webkit-column-break-inside: avoid; /* Chrome, Safari, Opera */
page-break-inside: avoid; /* Firefox */
break-inside: avoid; /* IE 10+ */
break-inside: avoid-column;

Is it possible to get the current spark context settings in PySpark?

Suppose I want to increase the driver memory in runtime using Spark Session:

s2 = SparkSession.builder.config("spark.driver.memory", "29g").getOrCreate()

Now I want to view the updated settings:

s2.conf.get("spark.driver.memory")

To get all the settings, you can make use of spark.sparkContext._conf.getAll()

UPDATED SETTINGS

Hope this helps

Alternative Windows shells, besides CMD.EXE?

Try Clink. It's awesome, especially if you are used to bash keybindings and features.

(As already pointed out - there is a similar question: Is there a better Windows Console Window?)

Group by with union mysql select query

This may be what your after:

SELECT Count(Owner_ID), Name
FROM (
    SELECT M.Owner_ID, O.Name, T.Type
    FROM Transport As T, Owner As O, Motorbike As M
    WHERE T.Type = 'Motorbike'
    AND O.Owner_ID = M.Owner_ID
    AND T.Type_ID = M.Motorbike_ID

    UNION ALL

    SELECT C.Owner_ID, O.Name, T.Type
    FROM Transport As T, Owner As O, Car As C
    WHERE T.Type = 'Car'
    AND O.Owner_ID = C.Owner_ID
    AND T.Type_ID = C.Car_ID
)
GROUP BY Owner_ID

change directory in batch file using variable

The set statement doesn't treat spaces the way you expect; your variable is really named Pathname[space] and is equal to [space]C:\Program Files.

Remove the spaces from both sides of the = sign, and put the value in double quotes:

set Pathname="C:\Program Files"

Also, if your command prompt is not open to C:\, then using cd alone can't change drives.

Use

cd /d %Pathname%

or

pushd %Pathname%

instead.

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

If there is other content not being shown inside the outer-div (the green box), why not have that content wrapped inside another div, let's call it "content". Have overflow hidden on this new inner-div, but keep overflow visible on the green box.

The only catch is that you will then have to mess around to make sure that the content div doesn't interfere with the positioning of the red box, but it sounds like you should be able to fix that with little headache.

<div id="1" background: #efe; padding: 5px; width: 125px">
    <div id="content" style="overflow: hidden;">
    </div>
    <div id="2" style="position: relative; background: #fee; padding: 2px; width: 100px; height: 100px">
        <div id="3" style="position: absolute; top: 10px; background: #eef; padding: 2px; width: 75px; height: 150px"/>
    </div>
</div>

How to get the date and time values in a C program?

To expand on the answer by Ori Osherov

You can use the WinAPI to get the date and time, this method is specific to Windows, but if you are targeting Windows only, or are already using the WinAPI then this is definitly a possibility1:

You can get both the time and date by using the SYSTEMTIME struct. You also need to call one of two functions (either GetLocalTime() or GetSystemTime()) to fill out the struct.

GetLocalTime() will give you the time and date specific to your time zone.

GetSystemTime() will give you the time and date in UTC.

The SYSTEMTIME struct has the following members:

wYear, wMonth, wDayOfWeek, wDay, wHour, wMinute, wSecond and wMilliseconds

You then need to just access the struct in the regular way


Actual example code:

#include <windows.h> // use to define SYSTEMTIME , GetLocalTime() and GetSystemTime()
#include <stdio.h> // For printf() (could otherwise use WinAPI equivalent)

int main(void) { // Or any other WinAPI entry point (e.g. WinMain/wmain)

    SYSTEMTIME t; // Declare SYSTEMTIME struct

    GetLocalTime(&t); // Fill out the struct so that it can be used

    // Use GetSystemTime(&t) to get UTC time 

    printf("Year: %d, Month: %d, Day: %d, Hour: %d, Minute:%d, Second: %d, Millisecond: %d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds); // Return year, month, day, hour, minute, second and millisecond in that order

    return 0;
}

(Coded for simplicity and clarity, see the original answer for a better formatted method)

The output will be something like this:

Year: 2018, Month: 11, Day: 24, Hour: 12, Minute:28, Second: 1, Millisecond: 572

Useful References:

All the WinAPI documentation (most already listed above):

An extremely good beginners tutorial on this subject by Zetcode:

Simple operations with datetime on Codeproject:


1: As mentioned in the comments in Ori Osherov's answer ("Given that OP started with date +%F, they're almost certainly not using Windows. – melpomene Sep 9 at 22:17") the OP is not using Windows, however since this question has no platform specific tag (nor does it mention anywhere that the answer should be for that particular system), and is one of the top results when Googling "get time in c" both answers belong here, some users searching for an answer to this question may be on Windows and therefore will be useful to them.

insert/delete/update trigger in SQL server

I use that for all status (update, insert and delete)

CREATE TRIGGER trg_Insert_Test
ON [dbo].[MyTable]
AFTER UPDATE, INSERT, DELETE 
AS
BEGIN
SET NOCOUNT ON;

DECLARE @Activity  NVARCHAR (50)

-- update
IF EXISTS (SELECT * FROM inserted) AND EXISTS (SELECT * FROM deleted)
BEGIN
    SET @Activity = 'UPDATE'
END

-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted)
BEGIN
    SET @Activity = 'INSERT'
END

-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS(SELECT * FROM inserted)
BEGIN
    SET @Activity = 'DELETE'
END



-- delete temp table
IF OBJECT_ID('tempdb..#tmpTbl') IS NOT NULL DROP TABLE #tmpTbl

-- get last 1 row
SELECT * INTO #tmpTbl FROM (SELECT TOP 1 * FROM (SELECT * FROM inserted
                                                 UNION 
                                                 SELECT * FROM deleted
                                                 ) AS A ORDER BY A.Date DESC
                            ) AS T


-- try catch
BEGIN TRY 

    INSERT INTO MyTable  (
           [Code]
          ,[Name]
           .....
          ,[Activity])
    SELECT [Code]
          ,[Name]
          ,@Activity 
    FROM #tmpTbl

END TRY BEGIN CATCH END CATCH


-- delete temp table
IF OBJECT_ID('tempdb..#tmpTbl') IS NOT NULL DROP TABLE #tmpTbl

SET NOCOUNT OFF;
END

Found 'OR 1=1/* sql injection in my newsletter database

Its better if you use validation code to the users input for making it restricted to use symbols and part of code in your input form. If you embeed php in html code your php code have to become on the top to make sure that it is not ignored as comment if a hacker edit the page and add /* in your html code

modal View controllers - how to display and dismiss

Radu Simionescu - awesome work! and below Your solution for Swift lovers:

@IBAction func showSecondControlerAndCloseCurrentOne(sender: UIButton) {
    let secondViewController = storyboard?.instantiateViewControllerWithIdentifier("ConrollerStoryboardID") as UIViewControllerClass // change it as You need it
    var presentingVC = self.presentingViewController
    self.dismissViewControllerAnimated(false, completion: { () -> Void   in
        presentingVC!.presentViewController(secondViewController, animated: true, completion: nil)
    })
}

python xlrd unsupported format, or corrupt file.

I had the same issue. Those old files are formatted like a tab-delimited file. I've been able to open my problem files with read_table; ie df = pd.read_table('trouble_maker.xls').

SQL injection that gets around mysql_real_escape_string()

Consider the following query:

$iId = mysql_real_escape_string("1 OR 1=1");    
$sSql = "SELECT * FROM table WHERE id = $iId";

mysql_real_escape_string() will not protect you against this. The fact that you use single quotes (' ') around your variables inside your query is what protects you against this. The following is also an option:

$iId = (int)"1 OR 1=1";
$sSql = "SELECT * FROM table WHERE id = $iId";

Getting command-line password input in Python

Use getpass.getpass():

from getpass import getpass
password = getpass()

An optional prompt can be passed as parameter; the default is "Password: ".

Note that this function requires a proper terminal, so it can turn off echoing of typed characters – see “GetPassWarning: Can not control echo on the terminal” when running from IDLE for further details.

How do I declare and initialize an array in Java?

It's very easy to declare and initialize an array. For example, you want to save five integer elements which are 1, 2, 3, 4, and 5 in an array. You can do it in the following way:

a)

int[] a = new int[5];

or

b)

int[] a = {1, 2, 3, 4, 5};

so the basic pattern is for initialization and declaration by method a) is:

datatype[] arrayname = new datatype[requiredarraysize];

datatype should be in lower case.

So the basic pattern is for initialization and declaration by method a is:

If it's a string array:

String[] a = {"as", "asd", "ssd"};

If it's a character array:

char[] a = {'a', 's', 'w'};

For float double, the format of array will be same as integer.

For example:

double[] a = {1.2, 1.3, 12.3};

but when you declare and initialize the array by "method a" you will have to enter the values manually or by loop or something.

But when you do it by "method b" you will not have to enter the values manually.

jQuery datepicker set selected date, on the fly

Noted that for DatePicker by Keith Wood (http://keith-wood.name/datepickRef.html) the following works - note that the setting of the default date is last:

    $('#datepicker').datepick({
        minDate: 0,
        maxDate: '+145D',
        multiSelect: 7,
        renderer: $.datepick.themeRollerRenderer,
        ***defaultDate: new Date('1 January 2008')***
    });

How do I tell Maven to use the latest version of a dependency?

By the time this question was posed there were some kinks with version ranges in maven, but these have been resolved in newer versions of maven. This article captures very well how version ranges work and best practices to better understand how maven understands versions: https://docs.oracle.com/middleware/1212/core/MAVEN/maven_version.htm#MAVEN8855

Iterator Loop vs index loop

With a vector iterators do no offer any real advantage. The syntax is uglier, longer to type and harder to read.

Iterating over a vector using iterators is not faster and is not safer (actually if the vector is possibly resized during the iteration using iterators will put you in big troubles).

The idea of having a generic loop that works when you will change later the container type is also mostly nonsense in real cases. Unfortunately the dark side of a strictly typed language without serious typing inference (a bit better now with C++11, however) is that you need to say what is the type of everything at each step. If you change your mind later you will still need to go around and change everything. Moreover different containers have very different trade-offs and changing container type is not something that happens that often.

The only case in which iteration should be kept if possible generic is when writing template code, but that (I hope for you) is not the most frequent case.

The only problem present in your explicit index loop is that size returns an unsigned value (a design bug of C++) and comparison between signed and unsigned is dangerous and surprising, so better avoided. If you use a decent compiler with warnings enabled there should be a diagnostic on that.

Note that the solution is not to use an unsiged as the index, because arithmetic between unsigned values is also apparently illogical (it's modulo arithmetic, and x-1 may be bigger than x). You instead should cast the size to an integer before using it. It may make some sense to use unsigned sizes and indexes (paying a LOT of attention to every expression you write) only if you're working on a 16 bit C++ implementation (16 bit was the reason for having unsigned values in sizes).

As a typical mistake that unsigned size may introduce consider:

void drawPolyline(const std::vector<P2d>& points)
{
    for (int i=0; i<points.size()-1; i++)
        drawLine(points[i], points[i+1]);
}

Here the bug is present because if you pass an empty points vector the value points.size()-1 will be a huge positive number, making you looping into a segfault. A working solution could be

for (int i=1; i<points.size(); i++)
    drawLine(points[i - 1], points[i]);

but I personally prefer to always remove unsinged-ness with int(v.size()).

PS: If you really don't want to think by to yourself to the implications and simply want an expert to tell you then consider that a quite a few world recognized C++ experts agree and expressed opinions on that unsigned values are a bad idea except for bit manipulations.

Discovering the ugliness of using iterators in the case of iterating up to second-last is left as an exercise for the reader.

Check for file exists or not in sql server?

Try the following code to verify whether the file exist. You can create a user function and use it in your stored procedure. modify it as you need:

Set NOCOUNT ON

 DECLARE @Filename NVARCHAR(50)
 DECLARE @fileFullPath NVARCHAR(100)

 SELECT @Filename = N'LogiSetup.log'
 SELECT @fileFullPath = N'C:\LogiSetup.log'

create table #dir

(output varchar(2000))

 DECLARE @cmd NVARCHAR(100)
SELECT @cmd = 'dir ' + @fileFullPath     

insert into #dir    

exec master.dbo.xp_cmdshell @cmd

--Select * from #dir

-- This is risky, as the fle path itself might contain the filename
if exists (Select * from #dir where output like '%'+ @Filename +'%')

       begin    
              Print 'File found'    
              --Add code you want to run if file exists    
       end    
else    
       begin    
              Print 'No File Found'    
              --Add code you want to run if file does not exists    
       end

drop table #dir

How would I get everything before a : in a string Python

I have benchmarked these various technics under Python 3.7.0 (IPython).

TLDR

  • fastest (when the split symbol c is known): pre-compiled regex.
  • fastest (otherwise): s.partition(c)[0].
  • safe (i.e., when c may not be in s): partition, split.
  • unsafe: index, regex.

Code

import string, random, re

SYMBOLS = string.ascii_uppercase + string.digits
SIZE = 100

def create_test_set(string_length):
    for _ in range(SIZE):
        random_string = ''.join(random.choices(SYMBOLS, k=string_length))
        yield (random.choice(random_string), random_string)

for string_length in (2**4, 2**8, 2**16, 2**32):
    print("\nString length:", string_length)
    print("  regex (compiled):", end=" ")
    test_set_for_regex = ((re.compile("(.*?)" + c).match, s) for (c, s) in test_set)
    %timeit [re_match(s).group() for (re_match, s) in test_set_for_regex]
    test_set = list(create_test_set(16))
    print("  partition:       ", end=" ")
    %timeit [s.partition(c)[0] for (c, s) in test_set]
    print("  index:           ", end=" ")
    %timeit [s[:s.index(c)] for (c, s) in test_set]
    print("  split (limited): ", end=" ")
    %timeit [s.split(c, 1)[0] for (c, s) in test_set]
    print("  split:           ", end=" ")
    %timeit [s.split(c)[0] for (c, s) in test_set]
    print("  regex:           ", end=" ")
    %timeit [re.match("(.*?)" + c, s).group() for (c, s) in test_set]

Results

String length: 16
  regex (compiled): 156 ns ± 4.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        19.3 µs ± 430 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            26.1 µs ± 341 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  26.8 µs ± 1.26 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            26.3 µs ± 835 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            128 µs ± 4.02 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

String length: 256
  regex (compiled): 167 ns ± 2.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        20.9 µs ± 694 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  index:            28.6 µs ± 2.73 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  27.4 µs ± 979 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            31.5 µs ± 4.86 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            148 µs ± 7.05 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

String length: 65536
  regex (compiled): 173 ns ± 3.95 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        20.9 µs ± 613 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            27.7 µs ± 515 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  27.2 µs ± 796 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            26.5 µs ± 377 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            128 µs ± 1.5 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

String length: 4294967296
  regex (compiled): 165 ns ± 1.2 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
  partition:        19.9 µs ± 144 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  index:            27.7 µs ± 571 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split (limited):  26.1 µs ± 472 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  split:            28.1 µs ± 1.69 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
  regex:            137 µs ± 6.53 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

shell-script headers (#!/bin/sh vs #!/bin/csh)

The #! line tells the kernel (specifically, the implementation of the execve system call) that this program is written in an interpreted language; the absolute pathname that follows identifies the interpreter. Programs compiled to machine code begin with a different byte sequence -- on most modern Unixes, 7f 45 4c 46 (^?ELF) that identifies them as such.

You can put an absolute path to any program you want after the #!, as long as that program is not itself a #! script. The kernel rewrites an invocation of

./script arg1 arg2 arg3 ...

where ./script starts with, say, #! /usr/bin/perl, as if the command line had actually been

/usr/bin/perl ./script arg1 arg2 arg3

Or, as you have seen, you can use #! /bin/sh to write a script intended to be interpreted by sh.

The #! line is only processed if you directly invoke the script (./script on the command line); the file must also be executable (chmod +x script). If you do sh ./script the #! line is not necessary (and will be ignored if present), and the file does not have to be executable. The point of the feature is to allow you to directly invoke interpreted-language programs without having to know what language they are written in. (Do grep '^#!' /usr/bin/* -- you will discover that a great many stock programs are in fact using this feature.)

Here are some rules for using this feature:

  • The #! must be the very first two bytes in the file. In particular, the file must be in an ASCII-compatible encoding (e.g. UTF-8 will work, but UTF-16 won't) and must not start with a "byte order mark", or the kernel will not recognize it as a #! script.
  • The path after #! must be an absolute path (starts with /). It cannot contain space, tab, or newline characters.
  • It is good style, but not required, to put a space between the #! and the /. Do not put more than one space there.
  • You cannot put shell variables on the #! line, they will not be expanded.
  • You can put one command-line argument after the absolute path, separated from it by a single space. Like the absolute path, this argument cannot contain space, tab, or newline characters. Sometimes this is necessary to get things to work (#! /usr/bin/awk -f), sometimes it's just useful (#! /usr/bin/perl -Tw). Unfortunately, you cannot put two or more arguments after the absolute path.
  • Some people will tell you to use #! /usr/bin/env interpreter instead of #! /absolute/path/to/interpreter. This is almost always a mistake. It makes your program's behavior depend on the $PATH variable of the user who invokes the script. And not all systems have env in the first place.
  • Programs that need setuid or setgid privileges can't use #!; they have to be compiled to machine code. (If you don't know what setuid is, don't worry about this.)

Regarding csh, it relates to sh roughly as Nutrimat Advanced Tea Substitute does to tea. It has (or rather had; modern implementations of sh have caught up) a number of advantages over sh for interactive usage, but using it (or its descendant tcsh) for scripting is almost always a mistake. If you're new to shell scripting in general, I strongly recommend you ignore it and focus on sh. If you are using a csh relative as your login shell, switch to bash or zsh, so that the interactive command language will be the same as the scripting language you're learning.

How to add text inside the doughnut chart using Chart.js?

Here is cleaned up and combined example of above solutions - responsive (try to resize the window), supports animation self-aligning, supports tooltips

https://jsfiddle.net/cmyker/u6rr5moq/

_x000D_
_x000D_
Chart.types.Doughnut.extend({_x000D_
    name: "DoughnutTextInside",_x000D_
    showTooltip: function() {_x000D_
        this.chart.ctx.save();_x000D_
        Chart.types.Doughnut.prototype.showTooltip.apply(this, arguments);_x000D_
        this.chart.ctx.restore();_x000D_
    },_x000D_
    draw: function() {_x000D_
        Chart.types.Doughnut.prototype.draw.apply(this, arguments);_x000D_
_x000D_
        var width = this.chart.width,_x000D_
            height = this.chart.height;_x000D_
_x000D_
        var fontSize = (height / 114).toFixed(2);_x000D_
        this.chart.ctx.font = fontSize + "em Verdana";_x000D_
        this.chart.ctx.textBaseline = "middle";_x000D_
_x000D_
        var text = "82%",_x000D_
            textX = Math.round((width - this.chart.ctx.measureText(text).width) / 2),_x000D_
            textY = height / 2;_x000D_
_x000D_
        this.chart.ctx.fillText(text, textX, textY);_x000D_
    }_x000D_
});_x000D_
_x000D_
var data = [{_x000D_
    value: 30,_x000D_
    color: "#F7464A"_x000D_
}, {_x000D_
    value: 50,_x000D_
    color: "#E2EAE9"_x000D_
}, {_x000D_
    value: 100,_x000D_
    color: "#D4CCC5"_x000D_
}, {_x000D_
    value: 40,_x000D_
    color: "#949FB1"_x000D_
}, {_x000D_
    value: 120,_x000D_
    color: "#4D5360"_x000D_
}];_x000D_
_x000D_
var DoughnutTextInsideChart = new Chart($('#myChart')[0].getContext('2d')).DoughnutTextInside(data, {_x000D_
    responsive: true_x000D_
});
_x000D_
<html>_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>_x000D_
<body>_x000D_
    <canvas id="myChart"></canvas>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

UPDATE 17.06.16:

Same functionality but for chart.js version 2:

https://jsfiddle.net/cmyker/ooxdL2vj/

_x000D_
_x000D_
var data = {_x000D_
  labels: [_x000D_
    "Red",_x000D_
    "Blue",_x000D_
    "Yellow"_x000D_
  ],_x000D_
  datasets: [_x000D_
    {_x000D_
      data: [300, 50, 100],_x000D_
      backgroundColor: [_x000D_
        "#FF6384",_x000D_
        "#36A2EB",_x000D_
        "#FFCE56"_x000D_
      ],_x000D_
      hoverBackgroundColor: [_x000D_
        "#FF6384",_x000D_
        "#36A2EB",_x000D_
        "#FFCE56"_x000D_
      ]_x000D_
    }]_x000D_
};_x000D_
_x000D_
Chart.pluginService.register({_x000D_
  beforeDraw: function(chart) {_x000D_
    var width = chart.chart.width,_x000D_
        height = chart.chart.height,_x000D_
        ctx = chart.chart.ctx;_x000D_
_x000D_
    ctx.restore();_x000D_
    var fontSize = (height / 114).toFixed(2);_x000D_
    ctx.font = fontSize + "em sans-serif";_x000D_
    ctx.textBaseline = "middle";_x000D_
_x000D_
    var text = "75%",_x000D_
        textX = Math.round((width - ctx.measureText(text).width) / 2),_x000D_
        textY = height / 2;_x000D_
_x000D_
    ctx.fillText(text, textX, textY);_x000D_
    ctx.save();_x000D_
  }_x000D_
});_x000D_
_x000D_
var chart = new Chart(document.getElementById('myChart'), {_x000D_
  type: 'doughnut',_x000D_
  data: data,_x000D_
  options: {_x000D_
   responsive: true,_x000D_
    legend: {_x000D_
      display: false_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.js"></script>_x000D_
<canvas id="myChart"></canvas>
_x000D_
_x000D_
_x000D_

How to compile and run C in sublime text 3?

In Sublime Text 3....Try changing the above code to this, note the addition of "start".....

"variants" : [

    { "name": "Run",
      "cmd" : ["start", "${file_base_name}.exe"]
    } 

How to handle a single quote in Oracle SQL

I found the above answer giving an error with Oracle SQL, you also must use square brackets, below;

SQL> SELECT Q'[Paddy O'Reilly]' FROM DUAL;


Result: Paddy O'Reilly

jQuery: Setting select list 'selected' based on text, failing strangely

The following works for text entries both with and without spaces:

$("#mySelect1").find("option[text=" + text1 + "]").attr("selected", true);

Finding element's position relative to the document

You can get top and left without traversing DOM like this:

function getCoords(elem) { // crossbrowser version
    var box = elem.getBoundingClientRect();

    var body = document.body;
    var docEl = document.documentElement;

    var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
    var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;

    var clientTop = docEl.clientTop || body.clientTop || 0;
    var clientLeft = docEl.clientLeft || body.clientLeft || 0;

    var top  = box.top +  scrollTop - clientTop;
    var left = box.left + scrollLeft - clientLeft;

    return { top: Math.round(top), left: Math.round(left) };
}

What is SOA "in plain english"?

Let's assume you have four cooks. In SOA, you assume they hate each other, so you strive to let them have to talk to each other as little as possible.

How do you do that? Well, you will first define the roles and interface -- cook 1 will make salad, cook 2 will make soup, cook 3 will make the steak, etc.. Then you will place the dishes well organised on the table (so these are the interfaces) and say, "Everybody please place your creation into your assigned dishes. Don't care about anybody else.".

This way, the four cooks have to talk to each other as little as possible, which is very good in software development -- not necessarily because they hate each other, but for other reasons like physical location, efficiency in making decisions etc.

It also means you can recombine the dishes (services) as you like. For example, you might just use the dessert to service a cafe, or just take the soup and combine it with a bread you bought from another company to provide a cheaper menu, or let other restaurants use your salads to combine with their dishes, etc.

One of the most successful implementation of SOA was at Amazon. Because of their design, they could re-package their whole infrastructure and sell it as Amazon Web Service.

*This is only one aspect of SOA.

Show or hide element in React

I start with this statement from the React team:

In React, you can create distinct components that encapsulate behaviour you need. Then, you can render only some of them, depending on the state of your application.

Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them.

You basically need to show the component when the button gets clicked, you can do it two ways, using pure React or using CSS, using pure React way, you can do something like below code in your case, so in the first run, results are not showing as hideResults is true, but by clicking on the button, state gonna change and hideResults is false and the component get rendered again with the new value conditions, this is very common use of changing component view in React...

var Search = React.createClass({
  getInitialState: function() {
    return { hideResults: true };
  },

  handleClick: function() {
    this.setState({ hideResults: false });
  },

  render: function() {
    return (
      <div>
        <input type="submit" value="Search" onClick={this.handleClick} />
        { !this.state.hideResults && <Results /> }
      </div> );
  }

});

var Results = React.createClass({
  render: function() {
    return (
    <div id="results" className="search-results">
      Some Results
    </div>);
   }
});

ReactDOM.render(<Search />, document.body);

If you want to do further study in conditional rendering in React, have a look here.

Why does modulus division (%) only work with integers?

I can't really say for sure, but I'd guess it's mostly historical. Quite a few early C compilers didn't support floating point at all. It was added on later, and even then not as completely -- mostly the data type was added, and the most primitive operations supported in the language, but everything else left to the standard library.

How do I ignore a directory with SVN?

Bash oneliner for multiple ignores:

svn propset svn:ignore ".project"$'\n'".settings"$'\n'".buildpath" "yourpath"

JSON.parse vs. eval()

You are more vulnerable to attacks if using eval: JSON is a subset of Javascript and json.parse just parses JSON whereas eval would leave the door open to all JS expressions.

Dismissing a Presented View Controller

Quote from View Controller Programming Guide, "How View Controllers Present Other View Controllers".

Each view controller in a chain of presented view controllers has pointers to the other objects surrounding it in the chain. In other words, a presented view controller that presents another view controller has valid objects in both its presentingViewController and presentedViewController properties. You can use these relationships to trace through the chain of view controllers as needed. For example, if the user cancels the current operation, you can remove all objects in the chain by dismissing the first presented view controller. Dismissing a view controller dismisses not only that view controller but also any view controllers it presented.

So on one hand it makes for a nice balanced design, good de-coupling, etc... But on the other hand it's very practical, because you can quickly get back to a certain point in navigation.

Although, I personally would rather use unwinding segues than try to traverse backwards the presenting view controllers tree, which is what Apple talks about in this chapter where the quote is from.

Clear android application user data

The command pm clear com.android.browser requires root permission.
So, run su first.

Here is the sample code:

private static final String CHARSET_NAME = "UTF-8";
String cmd = "pm clear com.android.browser";

ProcessBuilder pb = new ProcessBuilder().redirectErrorStream(true).command("su");
Process p = pb.start();

// We must handle the result stream in another Thread first
StreamReader stdoutReader = new StreamReader(p.getInputStream(), CHARSET_NAME);
stdoutReader.start();

out = p.getOutputStream();
out.write((cmd + "\n").getBytes(CHARSET_NAME));
out.write(("exit" + "\n").getBytes(CHARSET_NAME));
out.flush();

p.waitFor();
String result = stdoutReader.getResult();

The class StreamReader:

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.CountDownLatch;

class StreamReader extends Thread {
    private InputStream is;
    private StringBuffer mBuffer;
    private String mCharset;
    private CountDownLatch mCountDownLatch;

    StreamReader(InputStream is, String charset) {
        this.is = is;
        mCharset = charset;
        mBuffer = new StringBuffer("");
        mCountDownLatch = new CountDownLatch(1);
    }

    String getResult() {
        try {
            mCountDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return mBuffer.toString();
    }

    @Override
    public void run() {
        InputStreamReader isr = null;
        try {
            isr = new InputStreamReader(is, mCharset);
            int c = -1;
            while ((c = isr.read()) != -1) {
                mBuffer.append((char) c);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (isr != null)
                    isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mCountDownLatch.countDown();
        }
    }
}

What is the difference between Subject and BehaviorSubject?

It might help you to understand.

import * as Rx from 'rxjs';

const subject1 = new Rx.Subject();
subject1.next(1);
subject1.subscribe(x => console.log(x)); // will print nothing -> because we subscribed after the emission and it does not hold the value.

const subject2 = new Rx.Subject();
subject2.subscribe(x => console.log(x)); // print 1 -> because the emission happend after the subscription.
subject2.next(1);

const behavSubject1 = new Rx.BehaviorSubject(1);
behavSubject1.next(2);
behavSubject1.subscribe(x => console.log(x)); // print 2 -> because it holds the value.

const behavSubject2 = new Rx.BehaviorSubject(1);
behavSubject2.subscribe(x => console.log('val:', x)); // print 1 -> default value
behavSubject2.next(2) // just because of next emission will print 2 

How to replace string in Groovy

You need to escape the backslash \:

println yourString.replace("\\", "/")

How to prevent XSS with HTML/PHP?

One of the most important steps is to sanitize any user input before it is processed and/or rendered back to the browser. PHP has some "filter" functions that can be used.

The form that XSS attacks usually have is to insert a link to some off-site javascript that contains malicious intent for the user. Read more about it here.

You'll also want to test your site - I can recommend the Firefox add-on XSS Me.

'Class' does not contain a definition for 'Method'

I just ran into this problem; the issue seems different from the other answers posted here, so I'll mention it in case it helps someone.

In my case, I have an internal base class defined in one assembly ("A"), an internal derived class defined in a second assembly ("B"), and a test assembly ("TEST"). I exposed internals defined in assembly "B" to "TEST" using InternalsVisibleToAttribute, but neglected to do so for assembly "A". This produced the error mentioned at top with no further indication of the problem; using InternalsVisibleToAttribute to expose assembly "A" to "TEST" resolved the issue.

Create a asmx web service in C# using visual studio 2013

  1. Create Empty ASP.NET Project enter image description here
  2. Add Web Service(asmx) to your project
    enter image description here

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

To clarify the problem with @@Identity:

For instance, if you insert a table and that table has triggers doing inserts, @@Identity will return the id from the insert in the trigger (a log_id or something), while scope_identity() will return the id from the insert in the original table.

So if you don't have any triggers, scope_identity() and @@identity will return the same value. If you have triggers, you need to think about what value you'd like.

How to disable a ts rule for a specific line?

@ts-expect-error

TS 3.9 introduces a new magic comment. @ts-expect-error will:

  • have same functionality as @ts-ignore
  • trigger an error, if actually no compiler error has been suppressed (= indicates useless flag)
if (false) {
  // @ts-expect-error: Let's ignore a single compiler error like this unreachable code 
  console.log("hello"); // compiles
}

// If @ts-expect-error didn't suppress anything at all, we now get a nice warning 
let flag = true;
// ...
if (flag) {
  // @ts-expect-error
  // ^~~~~~~~~~~~~~~^ error: "Unused '@ts-expect-error' directive.(2578)"
  console.log("hello"); 
}

Alternatives

@ts-ignore and @ts-expect-error can be used for all sorts of compiler errors. For type issues (like in OP), I recommend one of the following alternatives due to narrower error suppression scope:

? Use any type

// type assertion for single expression
delete ($ as any).summernote.options.keyMap.pc.TAB;

// new variable assignment for multiple usages
const $$: any = $
delete $$.summernote.options.keyMap.pc.TAB;
delete $$.summernote.options.keyMap.mac.TAB;

? Augment JQueryStatic interface

// ./global.d.ts
interface JQueryStatic {
  summernote: any;
}

// ./main.ts
delete $.summernote.options.keyMap.pc.TAB; // works

In other cases, shorthand module declarations or module augmentations for modules with no/extendable types are handy utilities. A viable strategy is also to keep not migrated code in .js and use --allowJs with checkJs: false.

How to change Tkinter Button state from disabled to normal?

This is what worked for me. I am not sure why the syntax is different, But it was extremely frustrating trying every combination of activate, inactive, deactivated, disabled, etc. In lower case upper case in quotes out of quotes in brackets out of brackets etc. Well, here's the winning combination for me, for some reason.. different than everyone else?

import tkinter

class App(object):
    def __init__(self):
        self.tree = None
        self._setup_widgets()

    def _setup_widgets(self):
        butts = tkinter.Button(text = "add line", state="disabled")
        butts.grid()

def main():  
    root = tkinter.Tk()
    app = App()
    root.mainloop()

if __name__ == "__main__":
    main()

Importing lodash into angular2 + typescript application

Maybe it is too strange, but none of the above helped me, first of all, because I had properly installed the lodash (also re-installed via above suggestions).

So long story short the issue was connected with using _.has method from lodash.

I fixed it by simply using JS in operator.

Lodash remove duplicates from array

Or simply Use union, for simple array.

_.union([1,2,3,3], [3,5])

// [1,2,3,5]

GroupBy pandas DataFrame and select most common value

The two top answers here suggest:

df.groupby(cols).agg(lambda x:x.value_counts().index[0])

or, preferably

df.groupby(cols).agg(pd.Series.mode)

However both of these fail in simple edge cases, as demonstrated here:

df = pd.DataFrame({
    'client_id':['A', 'A', 'A', 'A', 'B', 'B', 'B', 'C'],
    'date':['2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01'],
    'location':['NY', 'NY', 'LA', 'LA', 'DC', 'DC', 'LA', np.NaN]
})

The first:

df.groupby(['client_id', 'date']).agg(lambda x:x.value_counts().index[0])

yields IndexError (because of the empty Series returned by group C). The second:

df.groupby(['client_id', 'date']).agg(pd.Series.mode)

returns ValueError: Function does not reduce, since the first group returns a list of two (since there are two modes). (As documented here, if the first group returned a single mode this would work!)

Two possible solutions for this case are:

import scipy
x.groupby(['client_id', 'date']).agg(lambda x: scipy.stats.mode(x)[0])

And the solution given to me by cs95 in the comments here:

def foo(x): 
    m = pd.Series.mode(x); 
    return m.values[0] if not m.empty else np.nan
df.groupby(['client_id', 'date']).agg(foo)

However, all of these are slow and not suited for large datasets. A solution I ended up using which a) can deal with these cases and b) is much, much faster, is a lightly modified version of abw33's answer (which should be higher):

def get_mode_per_column(dataframe, group_cols, col):
    return (dataframe.fillna(-1)  # NaN placeholder to keep group 
            .groupby(group_cols + [col])
            .size()
            .to_frame('count')
            .reset_index()
            .sort_values('count', ascending=False)
            .drop_duplicates(subset=group_cols)
            .drop(columns=['count'])
            .sort_values(group_cols)
            .replace(-1, np.NaN))  # restore NaNs

group_cols = ['client_id', 'date']    
non_grp_cols = list(set(df).difference(group_cols))
output_df = get_mode_per_column(df, group_cols, non_grp_cols[0]).set_index(group_cols)
for col in non_grp_cols[1:]:
    output_df[col] = get_mode_per_column(df, group_cols, col)[col].values

Essentially, the method works on one col at a time and outputs a df, so instead of concat, which is intensive, you treat the first as a df, and then iteratively add the output array (values.flatten()) as a column in the df.

How do you format an unsigned long long int using printf?

Apparently no one has come up with a multi-platform* solution for over a decade since [the] year 2008, so I shall append mine . Plz upvote. (Joking. I don’t care.)

Solution: lltoa()

How to use:

#include <stdlib.h> /* lltoa() */
// ...
char dummy[255];
printf("Over 4 bytes: %s\n", lltoa(5555555555, dummy, 10));
printf("Another one: %s\n", lltoa(15555555555, dummy, 10));

OP’s example:

#include <stdio.h>
#include <stdlib.h> /* lltoa() */

int main() {
    unsigned long long int num = 285212672; // fits in 29 bits
    char dummy[255];
    int normalInt = 5;
    printf("My number is %d bytes wide and its value is %s. "
        "A normal number is %d.\n", 
        sizeof(num), lltoa(num, dummy, 10), normalInt);
    return 0;
}

Unlike the %lld print format string, this one works for me under 32-bit GCC on Windows.

*) Well, almost multi-platform. In MSVC, you apparently need _ui64toa() instead of lltoa().

Auto-increment on partial primary key with Entity Framework Core

First of all you should not merge the Fluent Api with the data annotation so I would suggest you to use one of the below:

make sure you have correclty set the keys

modelBuilder.Entity<Foo>()
            .HasKey(p => new { p.Name, p.Id });
modelBuilder.Entity<Foo>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

OR you can achieve it using data annotation as well

public class Foo
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key, Column(Order = 0)]
    public int Id { get; set; }

    [Key, Column(Order = 1)]
    public string Name{ get; set; }
}

Setting up Gradle for api 26 (Android)

Appears to be resolved by Android Studio 3.0 Canary 4 and Gradle 3.0.0-alpha4.

How to escape double quotes in JSON

Note that this most often occurs when the content has been "double encoded", meaning the encoding algorithm has accidentally been called twice.

The first call would encode the "text2" value:

FROM: Heute startet unsere Rundreise "Example text". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.

TO: Heute startet unsere Rundreise \"Example text\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.

A second encoding then converts it again, escaping the already escaped characters:

FROM: Heute startet unsere Rundreise \"Example text\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.

TO: Heute startet unsere Rundreise \\\"Example text\\\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.

So, if you are responsible for the implementation of the server here, check to make sure there aren't two steps trying to encode the same content.

ORA-01652 Unable to extend temp segment by in tablespace

I found the solution to this. There is a temporary tablespace called TEMP which is used internally by database for operations like distinct, joins,etc. Since my query(which has 4 joins) fetches almost 50 million records the TEMP tablespace does not have that much space to occupy all data. Hence the query fails even though my tablespace has free space.So, after increasing the size of TEMP tablespace the issue was resolved. Hope this helps someone with the same issue. Thanks :)

String.Replace(char, char) method in C#

string temp = mystring.Replace("\n", string.Empty).Replace("\r", string.Empty);

Obviously, this removes both '\n' and '\r' and is as simple as I know how to do it.

Aligning rotated xticklabels with their respective xticks

An easy, loop-free alternative is to use the horizontalalignment Text property as a keyword argument to xticks[1]. In the below, at the commented line, I've forced the xticks alignment to be "right".

n=5
x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Long ticklabel %i' % i for i in range(n)]
fig, ax = plt.subplots()
ax.plot(x,y, 'o-')

plt.xticks(
        [0,1,2,3,4],
        ["this label extends way past the figure's left boundary",
        "bad motorfinger", "green", "in the age of octopus diplomacy", "x"], 
        rotation=45,
        horizontalalignment="right")    # here
plt.show()

(yticks already aligns the right edge with the tick by default, but for xticks the default appears to be "center".)

[1] You find that described in the xticks documentation if you search for the phrase "Text properties".

Find the item with maximum occurrences in a list

In your question, you asked for the fastest way to do it. As has been demonstrated repeatedly, particularly with Python, intuition is not a reliable guide: you need to measure.

Here's a simple test of several different implementations:

import sys
from collections import Counter, defaultdict
from itertools import groupby
from operator import itemgetter
from timeit import timeit

L = [1,2,45,55,5,4,4,4,4,4,4,5456,56,6,7,67]

def max_occurrences_1a(seq=L):
    "dict iteritems"
    c = dict()
    for item in seq:
        c[item] = c.get(item, 0) + 1
    return max(c.iteritems(), key=itemgetter(1))

def max_occurrences_1b(seq=L):
    "dict items"
    c = dict()
    for item in seq:
        c[item] = c.get(item, 0) + 1
    return max(c.items(), key=itemgetter(1))

def max_occurrences_2(seq=L):
    "defaultdict iteritems"
    c = defaultdict(int)
    for item in seq:
        c[item] += 1
    return max(c.iteritems(), key=itemgetter(1))

def max_occurrences_3a(seq=L):
    "sort groupby generator expression"
    return max(((k, sum(1 for i in g)) for k, g in groupby(sorted(seq))), key=itemgetter(1))

def max_occurrences_3b(seq=L):
    "sort groupby list comprehension"
    return max([(k, sum(1 for i in g)) for k, g in groupby(sorted(seq))], key=itemgetter(1))

def max_occurrences_4(seq=L):
    "counter"
    return Counter(L).most_common(1)[0]

versions = [max_occurrences_1a, max_occurrences_1b, max_occurrences_2, max_occurrences_3a, max_occurrences_3b, max_occurrences_4]

print sys.version, "\n"

for vers in versions:
    print vers.__doc__, vers(), timeit(vers, number=20000)

The results on my machine:

2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] 

dict iteritems (4, 6) 0.202214956284
dict items (4, 6) 0.208412885666
defaultdict iteritems (4, 6) 0.221301078796
sort groupby generator expression (4, 6) 0.383440971375
sort groupby list comprehension (4, 6) 0.402786016464
counter (4, 6) 0.564319133759

So it appears that the Counter solution is not the fastest. And, in this case at least, groupby is faster. defaultdict is good but you pay a little bit for its convenience; it's slightly faster to use a regular dict with a get.

What happens if the list is much bigger? Adding L *= 10000 to the test above and reducing the repeat count to 200:

dict iteritems (4, 60000) 10.3451900482
dict items (4, 60000) 10.2988479137
defaultdict iteritems (4, 60000) 5.52838587761
sort groupby generator expression (4, 60000) 11.9538850784
sort groupby list comprehension (4, 60000) 12.1327362061
counter (4, 60000) 14.7495789528

Now defaultdict is the clear winner. So perhaps the cost of the 'get' method and the loss of the inplace add adds up (an examination of the generated code is left as an exercise).

But with the modified test data, the number of unique item values did not change so presumably dict and defaultdict have an advantage there over the other implementations. So what happens if we use the bigger list but substantially increase the number of unique items? Replacing the initialization of L with:

LL = [1,2,45,55,5,4,4,4,4,4,4,5456,56,6,7,67]
L = []
for i in xrange(1,10001):
    L.extend(l * i for l in LL)

dict iteritems (2520, 13) 17.9935798645
dict items (2520, 13) 21.8974409103
defaultdict iteritems (2520, 13) 16.8289561272
sort groupby generator expression (2520, 13) 33.853593111
sort groupby list comprehension (2520, 13) 36.1303369999
counter (2520, 13) 22.626899004

So now Counter is clearly faster than the groupby solutions but still slower than the iteritems versions of dict and defaultdict.

The point of these examples isn't to produce an optimal solution. The point is that there often isn't one optimal general solution. Plus there are other performance criteria. The memory requirements will differ substantially among the solutions and, as the size of the input goes up, memory requirements may become the overriding factor in algorithm selection.

Bottom line: it all depends and you need to measure.

SQL Server CTE and recursion example

    --DROP TABLE #Employee
    CREATE TABLE #Employee(EmpId BIGINT IDENTITY,EmpName VARCHAR(25),Designation VARCHAR(25),ManagerID BIGINT)

    INSERT INTO #Employee VALUES('M11M','Manager',NULL)
    INSERT INTO #Employee VALUES('P11P','Manager',NULL)

    INSERT INTO #Employee VALUES('AA','Clerk',1)
    INSERT INTO #Employee VALUES('AB','Assistant',1)
    INSERT INTO #Employee VALUES('ZC','Supervisor',2)
    INSERT INTO #Employee VALUES('ZD','Security',2)


    SELECT * FROM #Employee (NOLOCK)

    ;
    WITH Emp_CTE 
    AS
    (
        SELECT EmpId,EmpName,Designation, ManagerID
              ,CASE WHEN ManagerID IS NULL THEN EmpId ELSE ManagerID END ManagerID_N
        FROM #Employee  
    )
    select EmpId,EmpName,Designation, ManagerID
    FROM Emp_CTE
    order BY ManagerID_N, EmpId

CSS text-decoration underline color

(for fellow googlers, copied from duplicate question) This answer is outdated since text-decoration-color is now supported by most modern browsers.

You can do this via the following CSS rule as an example:

text-decoration-color:green


If this rule isn't supported by an older browser, you can use the following solution:

Setting your word with a border-bottom:

a:link {
  color: red;
  text-decoration: none;
  border-bottom: 1px solid blue;
}
a:hover {
 border-bottom-color: green;
}

How to select all and copy in vim?

In normal mode:

gg"+yG

In ex mode:

:%y+

Fix Access denied for user 'root'@'localhost' for phpMyAdmin

I use this URL to enter phpMyAdmin http://localhost:2145/phpmyadmin but get the following error:
"phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server"
my config.inc.php file is

$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['host'] = 'localhost:2145';
$cfg['Servers'][$i]['connect_type'] = 'cookie';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = true;
/* User used to manipulate with storage */
// $cfg['Servers'][$i]['controlhost'] = '';
// $cfg['Servers'][$i]['controlport'] = '';
$cfg['Servers'][$i]['controluser'] = '';
$cfg['Servers'][$i]['controlpass'] = '';

this change resolve the mistake for me

$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = true;

and then

sudo service mysql stop
/opt/lampp/lampp start

and problem solved

How to use zIndex in react-native

Use elevation instead of zIndex for android devices

elevatedElement: {
  zIndex: 3, // works on ios
  elevation: 3, // works on android
}

This worked fine for me!

How to declare string constants in JavaScript?

Starting ECMAScript 2015 (a.k.a ES6), you can use const

const constantString = 'Hello';

But not all browsers/servers support this yet. In order to support this, use a polyfill library like Babel.

Check if PHP session has already started

Prior to PHP 5.4 there is no reliable way of knowing other than setting a global flag.

Consider:

var_dump($_SESSION); // null
session_start();
var_dump($_SESSION); // array
session_destroy();
var_dump($_SESSION); // array, but session isn't active.

Or:

session_id(); // returns empty string
session_start();
session_id(); // returns session hash
session_destroy();
session_id(); // returns empty string, ok, but then
session_id('foo'); // tell php the session id to use
session_id(); // returns 'foo', but no session is active.

So, prior to PHP 5.4 you should set a global boolean.

Could not find a version that satisfies the requirement tensorflow

As of October 2020:

  • Tensorflow only supports the 64-bit version of Python

  • Tensorflow only supports Python 3.5 to 3.8

So, if you're using an out-of-range version of Python (older or newer) or a 32-bit version, then you'll need to use a different version.

Serialize Property as Xml Attribute in Element

Kind of, use the XmlAttribute instead of XmlElement, but it won't look like what you want. It will look like the following:

<SomeModel SomeStringElementName="testData"> 
</SomeModel> 

The only way I can think of to achieve what you want (natively) would be to have properties pointing to objects named SomeStringElementName and SomeInfoElementName where the class contained a single getter named "value". You could take this one step further and use DataContractSerializer so that the wrapper classes can be private. XmlSerializer won't read private properties.

// TODO: make the class generic so that an int or string can be used.
[Serializable]  
public class SerializationClass
{
    public SerializationClass(string value)
    {
        this.Value = value;
    }

    [XmlAttribute("value")]
    public string Value { get; }
}


[Serializable]                     
public class SomeModel                     
{                     
    [XmlIgnore]                     
    public string SomeString { get; set; }                     

    [XmlIgnore]                      
    public int SomeInfo { get; set; }  

    [XmlElement]
    public SerializationClass SomeStringElementName
    {
        get { return new SerializationClass(this.SomeString); }
    }               
}

Gradle: Could not determine java version from '11.0.2'

I was facing the same issue in Docker setup, while I was trying to install Gradle-2.4 with JDL 11.0.7. I have to install a later version to fix the issue.

Here is the Working Dockerfile

FROM openjdk:11.0.7-jdk
RUN apt-get update && apt-get install -y unzip
WORKDIR /gradle
RUN curl -L https://services.gradle.org/distributions/gradle-6.5.1-bin.zip -o gradle-6.5.1-bin.zip
RUN unzip gradle-6.5.1-bin.zip
ENV GRADLE_HOME=/gradle/gradle-6.5.1
ENV PATH=$PATH:$GRADLE_HOME/bin
RUN gradle --version

Docker error : no space left on device

If it's just a test installation of Docker (ie not production) and you don't care about doing a nuclear clean, you can:

clean all containers: docker ps -a | sed '1 d' | awk '{print $1}' | xargs -L1 docker rm

clean all images: docker images -a | sed '1 d' | awk '{print $3}' | xargs -L1 docker rmi -f

Again, I use this in my ec2 instances when developing Docker, not in any serious QA or Production path. The great thing is that if you have your Dockerfile(s), it's easy to rebuild and or docker pull.

How to use JavaScript to change the form action

Try this:

var frm = document.getElementById('search-theme-form') || null;
if(frm) {
   frm.action = 'whatever_you_need.ext' 
}

python encoding utf-8

Unfortunately, the string.encode() method is not always reliable. Check out this thread for more information: What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python

Setting background-image using jQuery CSS property

Don't forget that the jQuery css function allows objects to be passed which allows you to set multiple items at the same time. The answered code would then look like this:

$(this).css({'background-image':'url(' + imageUrl + ')'})

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

Also this issue occurres when the response contenttype is not application/json. In my case response contenttype was text/html and i faced this problem. I changed it to application/json then it worked.

Using % for host when creating a MySQL user

The percent symbol means: any host, including remote and local connections.

The localhost allows only local connections.

(so to start off, if you don't need remote connections to your database, you can get rid of the appuser@'%' user right away)

So, yes, they are overlapping, but...

...there is a reason for setting both types of accounts, this is explained in the mysql docs: http://dev.mysql.com/doc/refman/5.7/en/adding-users.html.

If you have an have an anonymous user on your localhost, which you can spot with:

select Host from mysql.user where User='' and Host='localhost';

and if you just create the user appuser@'%' (and you not the appuser@'localhost'), then when the appuser mysql user connects from the local host, the anonymous user account is used (it has precedence over your appuser@'%' user).

And the fix for this is (as one can guess) to create the appuser@'localhost' (which is more specific that the local host anonymous user and will be used if your appuser connects from the localhost).

jQuery - Detecting if a file has been selected in the file input

I'd suggest try the change event? test to see if it has a value if it does then you can continue with your code. jQuery has

.bind("change", function(){ ... });

Or

.change(function(){ ... }); 

which are equivalents.

http://api.jquery.com/change/

for a unique selector change your name attribute to id and then jQuery("#imafile") or a general jQuery('input[type="file"]') for all the file inputs

Reading Excel files from C#

Here's some code I wrote in C# using .NET 1.1 a few years ago. Not sure if this would be exactly what you need (and may not be my best code :)).

using System;
using System.Data;
using System.Data.OleDb;

namespace ExportExcelToAccess
{
    /// <summary>
    /// Summary description for ExcelHelper.
    /// </summary>
    public sealed class ExcelHelper
    {
        private const string CONNECTION_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<FILENAME>;Extended Properties=\"Excel 8.0;HDR=Yes;\";";

        public static DataTable GetDataTableFromExcelFile(string fullFileName, ref string sheetName)
        {
            OleDbConnection objConnection = new OleDbConnection();
            objConnection = new OleDbConnection(CONNECTION_STRING.Replace("<FILENAME>", fullFileName));
            DataSet dsImport = new DataSet();

            try
            {
                objConnection.Open();

                DataTable dtSchema = objConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                if( (null == dtSchema) || ( dtSchema.Rows.Count <= 0 ) )
                {
                    //raise exception if needed
                }

                if( (null != sheetName) && (0 != sheetName.Length))
                {
                    if( !CheckIfSheetNameExists(sheetName, dtSchema) )
                    {
                        //raise exception if needed
                    }
                }
                else
                {
                    //Reading the first sheet name from the Excel file.
                    sheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString();
                }

                new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", objConnection ).Fill(dsImport);
            }
            catch (Exception)
            {
                //raise exception if needed
            }
            finally
            {
                // Clean up.
                if(objConnection != null)
                {
                    objConnection.Close();
                    objConnection.Dispose();
                }
            }


            return dsImport.Tables[0];
            #region Commented code for importing data from CSV file.
            //              string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source=" + System.IO.Path.GetDirectoryName(fullFileName) +";" +"Extended Properties=\"Text;HDR=YES;FMT=Delimited\"";
            //
            //              System.Data.OleDb.OleDbConnection conText = new System.Data.OleDb.OleDbConnection(strConnectionString);
            //              new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(fullFileName).Replace(".", "#"), conText).Fill(dsImport);
            //              return dsImport.Tables[0];

            #endregion
        }

        /// <summary>
        /// This method checks if the user entered sheetName exists in the Schema Table
        /// </summary>
        /// <param name="sheetName">Sheet name to be verified</param>
        /// <param name="dtSchema">schema table </param>
        private static bool CheckIfSheetNameExists(string sheetName, DataTable dtSchema)
        {
            foreach(DataRow dataRow in dtSchema.Rows)
            {
                if( sheetName == dataRow["TABLE_NAME"].ToString() )
                {
                    return true;
                }   
            }
            return false;
        }
    }
}

segmentation fault : 11

Your array is occupying roughly 8 GB of memory (1,000 x 1,000,000 x sizeof(double) bytes). That might be a factor in your problem. It is a global variable rather than a stack variable, so you may be OK, but you're pushing limits here.

Writing that much data to a file is going to take a while.

You don't check that the file was opened successfully, which could be a source of trouble, too (if it did fail, a segmentation fault is very likely).

You really should introduce some named constants for 1,000 and 1,000,000; what do they represent?

You should also write a function to do the calculation; you could use an inline function in C99 or later (or C++). The repetition in the code is excruciating to behold.

You should also use C99 notation for main(), with the explicit return type (and preferably void for the argument list when you are not using argc or argv):

int main(void)

Out of idle curiosity, I took a copy of your code, changed all occurrences of 1000 to ROWS, all occurrences of 1000000 to COLS, and then created enum { ROWS = 1000, COLS = 10000 }; (thereby reducing the problem size by a factor of 100). I made a few minor changes so it would compile cleanly under my preferred set of compilation options (nothing serious: static in front of the functions, and the main array; file becomes a local to main; error check the fopen(), etc.).

I then created a second copy and created an inline function to do the repeated calculation, (and a second one to do subscript calculations). This means that the monstrous expression is only written out once — which is highly desirable as it ensure consistency.

#include <stdio.h>

#define   lambda   2.0
#define   g        1.0
#define   F0       1.0
#define   h        0.1
#define   e        0.00001

enum { ROWS = 1000, COLS = 10000 };

static double F[ROWS][COLS];

static void Inicio(double D[ROWS][COLS])
{
    for (int i = 399; i < 600; i++) // Magic numbers!!
        D[i][0] = F0;
}

enum { R = ROWS - 1 };

static inline int ko(int k, int n)
{
    int rv = k + n;
    if (rv >= R)
        rv -= R;
    else if (rv < 0)
        rv += R;
    return(rv);
}

static inline void calculate_value(int i, int k, double A[ROWS][COLS])
{
    int ks2 = ko(k, -2);
    int ks1 = ko(k, -1);
    int kp1 = ko(k, +1);
    int kp2 = ko(k, +2);

    A[k][i] = A[k][i-1]
            + e/(h*h*h*h) * g*g * (A[kp2][i-1] - 4.0*A[kp1][i-1] + 6.0*A[k][i-1] - 4.0*A[ks1][i-1] + A[ks2][i-1])
            + 2.0*g*e/(h*h) * (A[kp1][i-1] - 2*A[k][i-1] + A[ks1][i-1])
            + e * A[k][i-1] * (lambda - A[k][i-1] * A[k][i-1]);
}

static void Iteration(double A[ROWS][COLS])
{
    for (int i = 1; i < COLS; i++)
    {
        for (int k = 0; k < R; k++)
            calculate_value(i, k, A);
        A[999][i] = A[0][i];
    }
}

int main(void)
{
    FILE *file = fopen("P2.txt","wt");
    if (file == 0)
        return(1);
    Inicio(F);
    Iteration(F);
    for (int i = 0; i < COLS; i++)
    {
        for (int j = 0; j < ROWS; j++)
        {
            fprintf(file,"%lf \t %.4f \t %lf\n", 1.0*j/10.0, 1.0*i, F[j][i]);
        }
    }
    fclose(file);
    return(0);
}

This program writes to P2.txt instead of P1.txt. I ran both programs and compared the output files; the output was identical. When I ran the programs on a mostly idle machine (MacBook Pro, 2.3 GHz Intel Core i7, 16 GiB 1333 MHz RAM, Mac OS X 10.7.5, GCC 4.7.1), I got reasonably but not wholly consistent timing:

Original   Modified
6.334s      6.367s
6.241s      6.231s
6.315s     10.778s
6.378s      6.320s
6.388s      6.293s
6.285s      6.268s
6.387s     10.954s
6.377s      6.227s
8.888s      6.347s
6.304s      6.286s
6.258s     10.302s
6.975s      6.260s
6.663s      6.847s
6.359s      6.313s
6.344s      6.335s
7.762s      6.533s
6.310s      9.418s
8.972s      6.370s
6.383s      6.357s

However, almost all that time is spent on disk I/O. I reduced the disk I/O to just the very last row of data, so the outer I/O for loop became:

for (int i = COLS - 1; i < COLS; i++)

the timings were vastly reduced and very much more consistent:

Original    Modified
0.168s      0.165s
0.145s      0.165s
0.165s      0.166s
0.164s      0.163s
0.151s      0.151s
0.148s      0.153s
0.152s      0.171s
0.165s      0.165s
0.173s      0.176s
0.171s      0.165s
0.151s      0.169s

The simplification in the code from having the ghastly expression written out just once is very beneficial, it seems to me. I'd certainly far rather have to maintain that program than the original.