Programs & Examples On #Second level cache

Second-level-cache, as the name implies, is a layer of cache that lives between a "primary" cache and a data service/store (relational database, in most cases) to optimize read operations on the service/store. It is different from the primary cache in its lifespan (primary cache being limited to a request lifetime) and capabilities (persist to store, clustering, etc.).

Cannot use a leading ../ to exit above the top directory

In my case it turned out to be commented out HTML in a master page!

Who knew that commented out HTML such as this were actually interpreted by ASP.NET!

<!--
<link rel="icon" href="../../favicon.ico">
-->

How do I style radio buttons with images - laughing smiley for good, sad smiley for bad?

Faced with the same problem I created a simple jQuery plugin http://xypaul.github.io/radioimg.js/

It works using hidden radio buttons and labels containing images as shown below.

<input type="radio" style="display: none;" id="a" />
<label for="a">
   <img class="" />
</label>

PostgreSQL naming conventions

Regarding tables names, case, etc, the prevalent convention is:

  • SQL keywords: UPPER CASE
  • names (identifiers): lower_case_with_underscores

For example:

UPDATE my_table SET name = 5;

This is not written in stone, but the bit about identifiers in lower case is highly recommended, IMO. Postgresql treats identifiers case insensitively when not quoted (it actually folds them to lowercase internally), and case sensitively when quoted; many people are not aware of this idiosyncrasy. Using always lowercase you are safe. Anyway, it's acceptable to use camelCase or PascalCase (or UPPER_CASE), as long as you are consistent: either quote identifiers always or never (and this includes the schema creation!).

I am not aware of many more conventions or style guides. Surrogate keys are normally made from a sequence (usually with the serial macro), it would be convenient to stick to that naming for those sequences if you create them by hand (tablename_colname_seq).

See also some discussion here, here and (for general SQL) here, all with several related links.

Note: Postgresql 10 introduced identity columns as an SQL-compliant replacement for serial.

Convert Xml to DataTable

How To Read XML Data into a DataSet by Using Visual C# .NET contains some details. Basically, you can use the overloaded DataSet method ReadXml to get the data into a DataSet. Your XML data will be in the first DataTable there.

There is also a DataTable.ReadXml method.

boundingRectWithSize for NSAttributedString returning wrong size

I'd like to add my thoughts since I had exactly the same problem.

I was using UITextView since it had nicer text alignment (justify, which at the time was not available in UILabel), but in order to "simulate" non-interactive-non-scrollable UILabel, I'd switch off completely scrolling, bouncing, and user interaction.

Of course, problem was that text was dynamic, and while width would be fixed, height should be recalculated every time I'd set new text value.

boundingRectWithSize didn't work well for me at all, from what I could see, UITextView was adding some margin on top which boundingRectWithSize would not get into a count, hence, height retrieved from boundingRectWithSize was smaller than it should be.

Since text was not to be updated rapidly, it's just used for some information that may update every 2-3 seconds the most, I've decided following approach:

/* This f is nested in a custom UIView-inherited class that is built using xib file */
-(void) setTextAndAutoSize:(NSString*)text inTextView:(UITextView*)tv
{
    CGFloat msgWidth = tv.frame.size.width; // get target's width

    // Make "test" UITextView to calculate correct size
    UITextView *temp = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, msgWidth, 300)]; // we set some height, really doesn't matter, just put some value like this one.
    // Set all font and text related parameters to be exact as the ones in targeted text view
    [temp setFont:tv.font];
    [temp setTextAlignment:tv.textAlignment];
    [temp setTextColor:tv.textColor];
    [temp setText:text];

    // Ask for size that fits :P
    CGSize tv_size = [temp sizeThatFits:CGSizeMake(msgWidth, 300)];

    // kill this "test" UITextView, it's purpose is over
    [temp release];
    temp = nil;

    // apply calculated size. if calcualted width differs, I choose to ignore it anyway and use only height because I want to have width absolutely fixed to designed value
    tv.frame = CGRectMake(tv.frame.origin.x, tv.frame.origin.y, msgWidth, tv_size.height );
}

*Above code is not directly copied from my source, I had to adjust it / clear it from bunch of other stuff not needed for this article. Don't take it for copy-paste-and-it-will-work-code.

Obvious disadvantage is that it has alloc and release, for each call.

But, advantage is that you avoid depending on compatibility between how boundingRectWithSize draws text and calculates it's size and implementation of text drawing in UITextView (or UILabel which also you can use just replace UITextView with UILabel). Any "bugs" that Apple may have are this way avoided.

P.S. It would seem that you shouldn't need this "temp" UITextView and can just ask sizeThatFits directly from target, however that didn't work for me. Though logic would say it should work and alloc/release of temporary UITextView are not needed, it did not. But this solution worked flawlessly for any text I would set in.

jquery to validate phone number

jQuery.validator.methods.matches = function( value, element, params ) {
    var re = new RegExp(params);
    // window.console.log(re);
    // window.console.log(value);
    // window.console.log(re.test( value ));
    return this.optional( element ) || re.test( value );
}

rules: {
        input_telf: {
            required  : true,
            matches   : "^(\\d|\\s)+$",
            minlength : 10,
            maxlength : 20
        }
    }

How to change the size of the font of a JLabel to take the maximum size

JLabel label = new JLabel("Hello World");
label.setFont(new Font("Calibri", Font.BOLD, 20));

ORA-06508: PL/SQL: could not find program unit being called

I suspect you're only reporting the last error in a stack like this:

ORA-04068: existing state of packages has been discarded
ORA-04061: existing state of package body "schema.package" has been invalidated
ORA-04065: not executed, altered or dropped package body "schema.package"
ORA-06508: PL/SQL: could not find program unit being called: "schema.package"

If so, that's because your package is stateful:

The values of the variables, constants, and cursors that a package declares (in either its specification or body) comprise its package state. If a PL/SQL package declares at least one variable, constant, or cursor, then the package is stateful; otherwise, it is stateless.

When you recompile the state is lost:

If the body of an instantiated, stateful package is recompiled (either explicitly, with the "ALTER PACKAGE Statement", or implicitly), the next invocation of a subprogram in the package causes Oracle Database to discard the existing package state and raise the exception ORA-04068.

After PL/SQL raises the exception, a reference to the package causes Oracle Database to re-instantiate the package, which re-initializes it...

You can't avoid this if your package has state. I think it's fairly rare to really need a package to be stateful though, so you should revisit anything you have declared in the package, but outside a function or procedure, to see if it's really needed at that level. Since you're on 10g though, that includes constants, not just variables and cursors.

But the last paragraph from the quoted documentation means that the next time you reference the package in the same session, you won't get the error and it will work as normal (until you recompile again).

How to submit a form on enter when the textarea has focus?

<form id="myform">
    <input type="textbox" id="field"/>
    <input type="button" value="submit">
</form>

<script>
    $(function () {
        $("#field").keyup(function (event) {
            if (event.which === 13) {
                document.myform.submit();
            }
        }
    });
</script>

How to compare LocalDate instances Java 8

I believe this snippet will also be helpful in a situation where the dates comparison spans more than two entries.

static final int COMPARE_EARLIEST = 0;

static final int COMPARE_MOST_RECENT = 1;


public LocalDate getTargetDate(List<LocalDate> datesList, int comparatorType) { 
   LocalDate refDate = null;
   switch(comparatorType)
   {
       case COMPARE_EARLIEST:         
       //returns the most earliest of the date entries
          refDate = (LocalDate) datesList.stream().min(Comparator.comparing(item -> 
                      item.toDateTimeAtCurrentTime())).get();
          break;

       case COMPARE_MOST_RECENT:
          //returns the most recent of the date entries 
          refDate = (LocalDate) datesList.stream().max(Comparator.comparing(item -> 
                    item.toDateTimeAtCurrentTime())).get();
          break;
   }

   return refDate;
}

how to open a page in new tab on button click in asp.net?

Add_ supplier is name of the form

private void add_supplier_Load(object sender, EventArgs e)
{
    add_supplier childform = new add_supplier();
    childform.MdiParent = this;
    childform.Show();
}

SQL Greater than, Equal to AND Less Than

If start time is a datetime type then you can use something like

SELECT BookingId, StartTime
FROM Booking
WHERE StartTime >= '2012-03-08 00:00:00.000' 
AND StartTime <= '2012-03-08 01:00:00.000'

Obviously you would want to use your own values for the times but this should give you everything in that 1 hour period inclusive of both the upper and lower limit.

You can use the GETDATE() function to get todays current date.

Div Height in Percentage

It doesn't take the 50% of the whole page is because the "whole page" is only how tall your contents are. Change the enclosing html and body to 100% height and it will work.

html, body{
    height: 100%;
}
div{
    height: 50%;
}

http://jsfiddle.net/DerekL/5YukJ/1/

enter image description here

^ Your document is only 20px high. 50% of 20px is 10px, and it is not what you expected.

enter image description here

^ Now if you change the height of the document to the height of the whole page (150px), 50% of 150px is 75px, then it will work.

Get Last Part of URL PHP

1-liner

$end = preg_replace( '%^(.+)/%', '', $url );

// if( ! $end ) no match.

This simply removes everything before the last slash, including it.

React Checkbox not sending onChange

To get the checked state of your checkbox the path would be:

this.refs.complete.state.checked

The alternative is to get it from the event passed into the handleChange method:

event.target.checked

What does PermGen actually stand for?

Not really related match to the original question, but may be someone will find it useful. PermGen is indeed an area in memory where Java used to keep its classes. So, many of us have came across OOM in PermGen, if there were, for example a lot of classes.

Since Java 8, PermGen area has been replaced by MetaSpace area, which is more efficient and is unlimited by default (or more precisely - limited by amount of native memory, depending on 32 or 64 bit jvm and OS virtual memory availability) . However it is possible to tune it in some ways, by for example specifying a max limit for the area. You can find more useful information in this blog post.

Can't install nuget package because of "Failed to initialize the PowerShell host"

Download and Install Administrative Templates for Windows PowerShell

Next:  Powershell x86 from As Administrator

Run:   Get-ExecutionPolicy -List  , and see if you have RemoteSigned etc..

1. 5 different scopes  Set-ExecutionPolicy "RemoteSigned" -Scope Process -Confirm:$false

2. Machine and User Policy you have to set through the Group Policy Administration Template in 2 areas.

UPDATE - EDIT:

Set ALL of them to  "Undefined" and ONLY the LocalMachine to "Restricted" 

This is what fixed might after I had given my powershell more permissions not knowing that it would mess up visual studio 2013 and 2015

How do you convert a time.struct_time object into a datetime object?

This is not a direct answer to your question (which was answered pretty well already). However, having had times bite me on the fundament several times, I cannot stress enough that it would behoove you to look closely at what your time.struct_time object is providing, vs. what other time fields may have.

Assuming you have both a time.struct_time object, and some other date/time string, compare the two, and be sure you are not losing data and inadvertently creating a naive datetime object, when you can do otherwise.

For example, the excellent feedparser module will return a "published" field and may return a time.struct_time object in its "published_parsed" field:

time.struct_time(tm_year=2013, tm_mon=9, tm_mday=9, tm_hour=23, tm_min=57, tm_sec=42, tm_wday=0, tm_yday=252, tm_isdst=0)

Now note what you actually get with the "published" field.

Mon, 09 Sep 2013 19:57:42 -0400

By Stallman's Beard! Timezone information!

In this case, the lazy man might want to use the excellent dateutil module to keep the timezone information:

from dateutil import parser
dt = parser.parse(entry["published"])
print "published", entry["published"])
print "dt", dt
print "utcoffset", dt.utcoffset()
print "tzinfo", dt.tzinfo
print "dst", dt.dst()

which gives us:

published Mon, 09 Sep 2013 19:57:42 -0400
dt 2013-09-09 19:57:42-04:00
utcoffset -1 day, 20:00:00
tzinfo tzoffset(None, -14400)
dst 0:00:00

One could then use the timezone-aware datetime object to normalize all time to UTC or whatever you think is awesome.

Generating matplotlib graphs without a running X server

You need to use the matplotlib API directly rather than going through the pylab interface. There's a good example here:

http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html

How to assign colors to categorical variables in ggplot2 that have stable mapping?

Based on the very helpful answer by joran I was able to come up with this solution for a stable color scale for a boolean factor (TRUE, FALSE).

boolColors <- as.character(c("TRUE"="#5aae61", "FALSE"="#7b3294"))
boolScale <- scale_colour_manual(name="myboolean", values=boolColors)

ggplot(myDataFrame, aes(date, duration)) + 
  geom_point(aes(colour = myboolean)) +
  boolScale

Since ColorBrewer isn't very helpful with binary color scales, the two needed colors are defined manually.

Here myboolean is the name of the column in myDataFrame holding the TRUE/FALSE factor. date and duration are the column names to be mapped to the x and y axis of the plot in this example.

How to add a spinner icon to button when it's in the Loading state?

To make the solution by @flion look really great, you could adjust the center point for that icon so it doesn't wobble up and down. This looks right for me at a small font size:

.glyphicon-refresh.spinning {
  transform-origin: 48% 50%;
}

BadValue Invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are set correctly

Generating locales

Missing locales are generated with locale-gen:

locale-gen en_US.UTF-8

Alternatively a locale file can be created manually with localedef:[1]

localedef -i en_US -f UTF-8 en_US.UTF-8

Setting Locale Settings

The locale settings can be set (to en_US.UTF-8 in the example) as follows:

export LANGUAGE=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
locale-gen en_US.UTF-8
dpkg-reconfigure locales

The dpkg-reconfigure locales command will open a dialog under Debian for selecting the desired locale. This dialog will not appear under Ubuntu. The Configure Locales in Ubuntu article shows how to find the information regarding Ubuntu.

Could not find method android() for arguments

You are using the wrong build.gradle file.

In your top-level file you can't define an android block.

Just move this part inside the module/build.gradle file.

android {
    compileSdkVersion 17
    buildToolsVersion '23.0.0'
}
dependencies {
    compile files('app/libs/junit-4.12-JavaDoc.jar')
}
apply plugin: 'maven'

How to convert a data frame column to numeric type?

Considering there might exist char columns, this is based on @Abdou in Get column types of excel sheet automatically answer:

makenumcols<-function(df){
  df<-as.data.frame(df)
  df[] <- lapply(df, as.character)
  cond <- apply(df, 2, function(x) {
    x <- x[!is.na(x)]
    all(suppressWarnings(!is.na(as.numeric(x))))
  })
  numeric_cols <- names(df)[cond]
  df[,numeric_cols] <- sapply(df[,numeric_cols], as.numeric)
  return(df)
}
df<-makenumcols(df)

MySQL/SQL: Group by date only on a Datetime column

I found that I needed to group by the month and year so neither of the above worked for me. Instead I used date_format

SELECT date
FROM blog 
GROUP BY DATE_FORMAT(date, "%m-%y")
ORDER BY YEAR(date) DESC, MONTH(date) DESC 

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

One more useful command:
vmstat -s | grep memory
sample output on my machine is:

  2050060 K total memory
  1092992 K used memory
   743072 K active memory
   177084 K inactive memory
   957068 K free memory
   385388 K buffer memory

another useful command to get memory information is:
free
sample output is:

             total       used       free     shared    buffers     cached
Mem:       2050060    1093324     956736        108     385392     386812
-/+ buffers/cache:     321120    1728940
Swap:      2095100       2732    2092368

One observation here is that, the command free gives information about swap space also.
The following link may be useful for you:
http://www.linuxnix.com/find-ram-details-in-linuxunix/

Android check null or empty string in Android

This worked for me

EditText   etname = (EditText) findViewById(R.id.etname);
 if(etname.length() == 0){
                    etname.setError("Required field");
                }else{
                    Toast.makeText(getApplicationContext(),"Saved",Toast.LENGTH_LONG).show();
                }

or Use this for strings

String DEP_DATE;
if (DEP_DATE.equals("") || DEP_DATE.length() == 0 || DEP_DATE.isEmpty() || DEP_DATE == null){
}

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

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

What is the reason behind "non-static method cannot be referenced from a static context"?

The answers so far describe why, but here is a something else you might want to consider:

You can can call a method from an instantiable class by appending a method call to its constructor,

Object instance = new Constuctor().methodCall();

or

primitive name = new Constuctor().methodCall();

This is useful it you only wish to use a method of an instantiable class once within a single scope. If you are calling multiple methods from an instantiable class within a single scope, definitely create a referable instance.

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

This solution shows a list of applications in a ListView dialog that resembles the chooser:

screenshot

It is up to you to:

  1. obtain the list of relevant application packages
  2. given a package name, invoke the relevant intent

The adapter class:

import java.util.List;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class ChooserArrayAdapter extends ArrayAdapter<String> {
    PackageManager mPm;
    int mTextViewResourceId;
    List<String> mPackages;

    public ChooserArrayAdapter(Context context, int resource, int textViewResourceId, List<String> packages) {
        super(context, resource, textViewResourceId, packages);
        mPm = context.getPackageManager();
        mTextViewResourceId = textViewResourceId;
        mPackages = packages;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        String pkg = mPackages.get(position);
        View view = super.getView(position, convertView, parent);

        try {
            ApplicationInfo ai = mPm.getApplicationInfo(pkg, 0);

            CharSequence appName = mPm.getApplicationLabel(ai);
            Drawable appIcon = mPm.getApplicationIcon(pkg);

            TextView textView = (TextView) view.findViewById(mTextViewResourceId);
            textView.setText(appName);
            textView.setCompoundDrawablesWithIntrinsicBounds(appIcon, null, null, null);
            textView.setCompoundDrawablePadding((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12, getContext().getResources().getDisplayMetrics()));
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        return view;
    }

}

and its usage:

    void doXxxButton() {
        final List<String> packages = ...;
        if (packages.size() > 1) {
            ArrayAdapter<String> adapter = new ChooserArrayAdapter(MyActivity.this, android.R.layout.select_dialog_item, android.R.id.text1, packages);

            new AlertDialog.Builder(MyActivity.this)
            .setTitle(R.string.app_list_title)
            .setAdapter(adapter, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item ) {
                    invokeApplication(packages.get(item));
                }
            })
            .show();
        } else if (packages.size() == 1) {
            invokeApplication(packages.get(0));
        }
    }

    void invokeApplication(String packageName) {
        // given a package name, create an intent and fill it with data
        ...
        startActivityForResult(intent, rq);
    }

What is better, adjacency lists or adjacency matrices for graph problems in C++?

Okay, I've compiled the Time and Space complexities of basic operations on graphs.
The image below should be self-explanatory.
Notice how Adjacency Matrix is preferable when we expect the graph to be dense, and how Adjacency List is preferable when we expect the graph to be sparse.
I've made some assumptions. Ask me if a complexity (Time or Space) needs clarification. (For example, For a sparse graph, I've taken En to be a small constant, as I've assumed that addition of a new vertex will add only a few edges, because we expect the graph to remain sparse even after adding that vertex.)

Please tell me if there are any mistakes.

enter image description here

Is there an alternative sleep function in C to milliseconds?

#include <stdio.h>
#include <stdlib.h>
int main () {

puts("Program Will Sleep For 2 Seconds");

system("sleep 2");      // works for linux systems


return 0;
}

Avoid browser popup blockers

I didn't want to make the new page unless the callback returned successfully, so I did this to simulate the user click:

function submitAndRedirect {
  apiCall.then(({ redirect }) => {
      const a = document.createElement('a');
      a.href = redirect;
      a.target = '_blank';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
  });
}

Detecting scroll direction

While the accepted answer works, it is worth noting that this will fire at a high rate. This can cause performance issues for computationally expensive operations.

The recommendation from MDN is to throttle the events. Below is a modification of their sample, enhanced to detect scroll direction.

Modified from: https://developer.mozilla.org/en-US/docs/Web/API/Document/scroll_event

// ## function declaration
function scrollEventThrottle(fn) {
  let last_known_scroll_position = 0;
  let ticking = false;
  window.addEventListener("scroll", function () {
    let previous_known_scroll_position = last_known_scroll_position;
    last_known_scroll_position = window.scrollY;
    if (!ticking) {
      window.requestAnimationFrame(function () {
        fn(last_known_scroll_position, previous_known_scroll_position);
        ticking = false;
      });
      ticking = true;
    }
  });
}

// ## function instantiation
scrollEventThrottle((scrollPos, previousScrollPos) => {
    if (previousScrollPos > scrollPos) {
      console.log("going up");
    } else {
      console.log("going down");
    }
});

Route.get() requires callback functions but got a "object Undefined"

I got the same error. After debugging, I found that I misspelled the method name that I imported from the controller into the route file. Please check the method name.

Get Row Index on Asp.net Rowcommand event

If you have a built-in command of GridView like insert, update or delete, on row command you can use the following code to get the index:

int index = Convert.ToInt32(e.CommandArgument);

In a custom command, you can set the command argument to yourRow.RowIndex.ToString() and then get it back in the RowCommand event handler. Unless, of course, you need the command argument for another purpose.

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

Here are a couple of things that could be preventing you from connecting to your Linode instance:

  1. DNS problem: if the computer that you're using to connect to your remote server isn't resolving test.kameronderdehamer.nl properly then you won't be able to reach your host. Try to connect using the public IP address assigned to your Linode and see if it works (e.g. ssh [email protected]). If you can connect using the public IP but not using the hostname that would confirm that you're having some problem with domain name resolution.

  2. Network issues: there might be some network issues preventing you from establishing a connection to your server. For example, there may be a misconfigured router in the path between you and your host, or you may be experiencing packet loss. While this is not frequent, it has happenned to me several times with Linode and can be very annoying. It could be a good idea to check this just in case. You can have a look at Diagnosing network issues with MTR (from the Linode library).

using stored procedure in entity framework

After importing stored procedure, you can create object of stored procedure pass the parameter like function

using (var entity = new FunctionsContext())
{
   var DBdata = entity.GetFunctionByID(5).ToList<Functions>();
}

or you can also use SqlQuery

using (var entity = new FunctionsContext())
{
    var Parameter = new SqlParameter {
                     ParameterName = "FunctionId",
                     Value = 5
            };

    var DBdata = entity.Database.SqlQuery<Course>("exec GetFunctionByID @FunctionId ", Parameter).ToList<Functions>();
}

How to read single Excel cell value

The issue with reading single Excel Cell in .Net comes from the fact, that the empty cell is evaluated to a Null. Thus, one cannot use its .Value or .Value2 properties, because an error shows up.

To return an empty string, when the cell is Null the Convert.ToString(Cell) can be used in the following way:

Excel.Workbook wkb = Open(excel, filePath);
Excel.Worksheet wk = (Excel.Worksheet)excel.Worksheets.get_Item(1);

for (int i = 1; i < 5; i++)
{
    string a = Convert.ToString(wk.Cells[i, 1].Value2);
    Console.WriteLine(a);
}

Drawing an image from a data URL to a canvas

in javascript , using jquery for canvas id selection :

 var Canvas2 = $("#canvas2")[0];
        var Context2 = Canvas2.getContext("2d");
        var image = new Image();
        image.src = "images/eye.jpg";
        Context2.drawImage(image, 0, 0);

html5:

<canvas id="canvas2"></canvas>

VS 2017 Metadata file '.dll could not be found

In my case the issue was, I was referencing a project where I commented out all the .cs files.

For example ProjectApp references ProjectUtility. In ProjectUtility I only had 1 .cs file. I wasn't using it anymore so I commented out the whole file. In ProjectApp I wasn't calling any of the code from ProjectUtility, but I had using ProjectUtility; in one of the ProjectApp .cs files. The only error I got from the compiler was the CS0006 error.

I uncommented the .cs file in ProjectUtility and the error went away. So I'm not sure if having no code in a project causes the compiler to create an invalid assembly or not generate the DLL at all. The fix for me was to just remove the reference to ProjectUtility rather than commenting all the code.

In case you were wondering why I commented all the code from the referenced project instead of removing the reference, I did it because I was testing something and didn't want to modify the ProjectApp.csproj file.

How to change an application icon programmatically in Android?

Applying the suggestions mentioned, I've faced the issue of app getting killed whenever default icon gets changed to new icon. So have implemented the code with some tweaks. Step 1). In file AndroidManifest.xml, create for default activity with android:enabled="true" & other alias with android:enabled="false". Your will not contain but append those in with android:enabled="true".

       <activity
        android:name=".activities.SplashActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@style/SplashTheme">

    </activity>
    <!-- <activity-alias used to change app icon dynamically>   : default icon, set enabled true    -->
    <activity-alias
        android:label="@string/app_name"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:name=".SplashActivityAlias1" <!--put any random name started with dot-->
        android:enabled="true"
        android:targetActivity=".activities.SplashActivity"> <!--target activity class path will be same for all alias-->
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity-alias>
    <!-- <activity-alias used to change app icon dynamically>  : sale icon, set enabled false initially -->
    <activity-alias
        android:label="@string/app_name"
        android:icon="@drawable/ic_store_marker"
        android:roundIcon="@drawable/ic_store_marker"
        android:name=".SplashActivityAlias" <!--put any random name started with dot-->
        android:enabled="false"
        android:targetActivity=".activities.SplashActivity"> <!--target activity class path will be same for all alias-->
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity-alias>

Step 2). Make a method that will be used to disable 1st activity-alias that contains default icon & enable 2nd alias that contains icon need to be changed.

/**
 * method to change the app icon dynamically
 *
 * @param context
 * @param isNewIcon  : true if new icon need to be set; false to set default 
 * icon
 */

public static void changeAppIconDynamically(Context context, boolean isNewIcon) {
    PackageManager pm = context.getApplicationContext().getPackageManager();
    if (isNewIcon) {
        pm.setComponentEnabledSetting(
                new ComponentName(context,
                        "com.example.dummy.SplashActivityAlias1"), //com.example.dummy will be your package
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);

        pm.setComponentEnabledSetting(
                new ComponentName(context,
                        "com.example.dummy.SplashActivityAlias"),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
    } else {
        pm.setComponentEnabledSetting(
                new ComponentName(context,
                        "com.example.dummy.SplashActivityAlias1"),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

        pm.setComponentEnabledSetting(
                new ComponentName(context,
                        "com.example.dummy.SplashActivityAlias"),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }
}

Step 3). Now call this method depending on your requirement, say on button click or date specific or occasion specific conditions, simply like -

// Switch app icon to new icon
    GeneralUtils.changeAppIconDynamically(EditProfileActivity.this, true);
// Switch app icon to default icon
            GeneralUtils.changeAppIconDynamically(EditProfileActivity.this, false);

Hope this will help those who face the issue of app getting killed on icon change. Happy Coding :)

Capturing image from webcam in java?

Here is a similar question with some - yet unaccepted - answers. One of them mentions FMJ as a java alternative to JMF.

Difference between Pig and Hive? Why have both?

Hive was designed to appeal to a community comfortable with SQL. Its philosophy was that we don't need yet another scripting language. Hive supports map and reduce transform scripts in the language of the user's choice (which can be embedded within SQL clauses). It is widely used in Facebook by analysts comfortable with SQL as well as by data miners programming in Python. SQL compatibility efforts in Pig have been abandoned AFAIK - so the difference between the two projects is very clear.

Supporting SQL syntax also means that it's possible to integrate with existing BI tools like Microstrategy. Hive has an ODBC/JDBC driver (that's a work in progress) that should allow this to happen in the near future. It's also beginning to add support for indexes which should allow support for drill-down queries common in such environments.

Finally--this is not pertinent to the question directly--Hive is a framework for performing analytic queries. While its dominant use is to query flat files, there's no reason why it cannot query other stores. Currently Hive can be used to query data stored in Hbase (which is a key-value store like those found in the guts of most RDBMSes), and the HadoopDB project has used Hive to query a federated RDBMS tier.

How to hide the Google Invisible reCAPTCHA badge

Note: if you choose to hide the badge, please use
.grecaptcha-badge { visibility: hidden; }

You are allowed to hide the badge as long as you include the reCAPTCHA branding visibly in the user flow. Please include the following text:

This site is protected by reCAPTCHA and the Google
<a href="https://policies.google.com/privacy">Privacy Policy</a> and <a href="https://policies.google.com/terms">Terms of Service</a> apply.

more details here reCaptacha

Looking for a good Python Tree data structure

It might be worth writing your own tree wrapper based on an acyclic directed graph using the networkx library.

Check if value exists in enum in TypeScript

Update:

I've found that whenever I need to check if a value exists in an enum, I don't really need an enum and that a type is a better solution. So my enum in my original answer becomes:

export type ValidColors =
  | "red"
  | "orange"
  | "yellow"
  | "green"
  | "blue"
  | "purple";

Original answer:

For clarity, I like to break the values and includes calls onto separate lines. Here's an example:

export enum ValidColors {
  Red = "red",
  Orange = "orange",
  Yellow = "yellow",
  Green = "green",
  Blue = "blue",
  Purple = "purple",
}

function isValidColor(color: string): boolean {
  const options: string[] = Object.values(ButtonColors);
  return options.includes(color);
}

Differences between contentType and dataType in jQuery ajax function

enter image description here

In English:

  • ContentType: When sending data to the server, use this content type. Default is application/x-www-form-urlencoded; charset=UTF-8, which is fine for most cases.
  • Accepts: The content type sent in the request header that tells the server what kind of response it will accept in return. Depends on DataType.
  • DataType: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response. Can be text, xml, html, script, json, jsonp.

Associative arrays in Shell scripts

Another option, if portability is not your main concern, is to use associative arrays that are built in to the shell. This should work in bash 4.0 (available now on most major distros, though not on OS X unless you install it yourself), ksh, and zsh:

declare -A newmap
newmap[name]="Irfan Zulfiqar"
newmap[designation]=SSE
newmap[company]="My Own Company"

echo ${newmap[company]}
echo ${newmap[name]}

Depending on the shell, you may need to do a typeset -A newmap instead of declare -A newmap, or in some it may not be necessary at all.

jQuery multiple events to trigger the same function

It's simple to implement this with the built-in DOM methods without a big library like jQuery, if you want, it just takes a bit more code - iterate over an array of event names, and add a listener for each:

function validate() {
  // ...
}

const element = document.querySelector('#element');
['keyup', 'keypress', 'blur', 'change'].forEach((eventName) => {
  element.addEventListener(eventName, validate);
});

Parse XML using JavaScript

I'm guessing from your last question, asked 20 minutes before this one, that you are trying to parse (read and convert) the XML found through using GeoNames' FindNearestAddress.

If your XML is in a string variable called txt and looks like this:

<address>
  <street>Roble Ave</street>
  <mtfcc>S1400</mtfcc>
  <streetNumber>649</streetNumber>
  <lat>37.45127</lat>
  <lng>-122.18032</lng>
  <distance>0.04</distance>
  <postalcode>94025</postalcode>
  <placename>Menlo Park</placename>
  <adminCode2>081</adminCode2>
  <adminName2>San Mateo</adminName2>
  <adminCode1>CA</adminCode1>
  <adminName1>California</adminName1>
  <countryCode>US</countryCode>
</address>

Then you can parse the XML with Javascript DOM like this:

if (window.DOMParser)
{
    parser = new DOMParser();
    xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // Internet Explorer
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(txt);
}

And get specific values from the nodes like this:

//Gets house address number
xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue;

//Gets Street name
xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue;

//Gets Postal Code
xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;

JSFiddle


Feb. 2019 edit:

In response to @gaugeinvariante's concerns about xml with Namespace prefixes. Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:

NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge

_x000D_
_x000D_
// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt_x000D_
txt = `_x000D_
<address xmlns:p='example.com/postal' xmlns:s='example.com/street' xmlns:sn='example.com/streetNum'>_x000D_
  <s:street>Roble Ave</s:street>_x000D_
  <sn:streetNumber>649</sn:streetNumber>_x000D_
  <p:postalcode>94025</p:postalcode>_x000D_
</address>`;_x000D_
_x000D_
//Everything else the same_x000D_
if (window.DOMParser)_x000D_
{_x000D_
    parser = new DOMParser();_x000D_
    xmlDoc = parser.parseFromString(txt, "text/xml");_x000D_
}_x000D_
else // Internet Explorer_x000D_
{_x000D_
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");_x000D_
    xmlDoc.async = false;_x000D_
    xmlDoc.loadXML(txt);_x000D_
}_x000D_
_x000D_
//The prefix should not be included when you request the xml namespace_x000D_
//Gets "streetNumber" (note there is no prefix of "sn"_x000D_
console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Street name_x000D_
console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Postal Code_x000D_
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);
_x000D_
_x000D_
_x000D_

Difference between git pull and git pull --rebase

For this is important to understand the difference between Merge and Rebase.

Rebases are how changes should pass from the top of hierarchy downwards and merges are how they flow back upwards.

For details refer - http://www.derekgourlay.com/archives/428

Detect user scroll down or scroll up in jQuery

To differentiate between scroll up/down in jQuery, you could use:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

Add column to SQL Server

Adding a column using SSMS or ALTER TABLE .. ADD will not drop any existing data.

Send a base64 image in HTML email

Support, unfortunately, is brutal at best. Here's a post on the topic:

https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/

And the post content: enter image description here

How can I convert an Int to a CString?

Here's one way:

CString str;
str.Format("%d", 5);

In your case, try _T("%d") or L"%d" rather than "%d"

How to get a vCard (.vcf file) into Android contacts from website

There is now an import functionality on Android ICS 4.0.4.

First you must save your .vcf file on a storage (USB storage, or SDcard). Android will scan the selected storage to detect any .vcf file and will import it on the selected address book. The functionality is in the option menu of your contact list.

!Note: Be careful while doing this! Android will import EVERYTHING that is a .vcf in your storage. It's all or nothing, and the consequence can be trashing your address book.

What does $@ mean in a shell script?

From the manual:

@

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" .... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

Display List in a View MVC

You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams> and you are passing var model = tm.Name.ToList(); name list. You have to pass list of Teams.

You have to pass following model

var model = new List<Teams>();

model.Add(new Teams { Name =  new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name =  new List<string>(){"John","XYZ"} });
return View(model);

Darken background image on hover

I would add a div around the image and make the image change in opacity on hover and add an inset box shadow to the div on hover.

img:hover{
    opacity:.5;
}
.image:hover{
    box-shadow: inset 10px 10px 100px 100px #000;
}

<div class="image"><img src="image.jpg" /></div>

How to create Toast in Flutter?

For the toast message in flutter use bot_toast library. This library provides Feature-rich, support for displaying notifications, text, loading, attachments, etc. Toast

enter image description here

Python json.loads shows ValueError: Extra data

My json file was formatted exactly as the one in the question but none of the solutions here worked out. Finally I found a workaround on another Stackoverflow thread. Since this post is the first link in Google search, I put the that answer here so that other people come to this post in the future will find it more easily.

As it's been said there the valid json file needs "[" in the beginning and "]" in the end of file. Moreover, after each json item instead of "}" there must be a "},". All brackets without quotations! This piece of code just modifies the malformed json file into its correct format.

https://stackoverflow.com/a/51919788/2772087

Is there any way to call a function periodically in JavaScript?

yes - take a look at setInterval and setTimeout for executing code at certain times. setInterval would be the one to use to execute code periodically.

See a demo and answer here for usage

Simplest way to detect a mobile device in PHP

Simply you can follow the link. its very simple and very easy to use. I am using this. Its working fine.

http://mobiledetect.net/

use like this

//include the file
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;

// Any mobile device (phones or tablets).
if ( $detect->isMobile() ) {
 //do some code
}

// Any tablet device.
if( $detect->isTablet() ){
 //do some code
}

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

I know it's an old question but I want to help. You can put the transactional annotation on the service method you need, in this case findTopicByID(id) should have

@Transactional(propagation=Propagation.REQUIRED, readOnly=true, noRollbackFor=Exception.class)

more info about this annotation can be found here

About the other solutions:

fetch = FetchType.EAGER 

is not a good practice, it should be used ONLY if necessary.

Hibernate.initialize(topics.getComments());

The hibernate initializer binds your classes to the hibernate technology. If you are aiming to be flexible is not a good way to go.

Hope it helps

MySQL "Group By" and "Order By"

Here's one approach:

SELECT cur.textID, cur.fromEmail, cur.subject, 
     cur.timestamp, cur.read
FROM incomingEmails cur
LEFT JOIN incomingEmails next
    on cur.fromEmail = next.fromEmail
    and cur.timestamp < next.timestamp
WHERE next.timestamp is null
and cur.toUserID = '$userID' 
ORDER BY LOWER(cur.fromEmail)

Basically, you join the table on itself, searching for later rows. In the where clause you state that there cannot be later rows. This gives you only the latest row.

If there can be multiple emails with the same timestamp, this query would need refining. If there's an incremental ID column in the email table, change the JOIN like:

LEFT JOIN incomingEmails next
    on cur.fromEmail = next.fromEmail
    and cur.id < next.id

Java Object Null Check for method

You simply compare your object to null using the == (or !=) operator. E.g.:

public static double calculateInventoryTotal(Book[] books) {
    // First null check - the entire array
    if (books == null) {
        return 0;
    }

    double total = 0;

    for (int i = 0; i < books.length; i++) {
        // second null check - each individual element
        if (books[i] != null) {
            total += books[i].getPrice();
        }
    }

    return total;
}

Javascript - Open a given URL in a new tab by clicking a button

<BUTTON NAME='my_button' VALUE=sequence_no TYPE='SUBMIT' style="background-color:transparent ; border:none; color:blue;" onclick="this.form.target='_blank';return true;"><u>open new page</u></BUTTON>

This button will look like a URL and can be opened in a new tab.

How to sum all values in a column in Jaspersoft iReport Designer?

iReports Custom Fields for columns (sum, average, etc)

  1. Right-Click on Variables and click Create Variable

  2. Click on the new variable

    a. Notice the properties on the right

  3. Rename the variable accordingly

  4. Change the Value Class Name to the correct Data Type

    a. You can search by clicking the 3 dots

  5. Select the correct type of calculation

  6. Change the Expression

    a. Click the little icon

    b. Select the column you are looking to do the calculation for

    c. Click finish

  7. Set Initial Value Expression to 0

  8. Set the increment type to none

  9. Leave Incrementer Factory Class Name blank
  10. Set the Reset Type (usually report)

  11. Drag a new Text Field to stage (Usually in Last Page Footer, or Column Footer)

  12. Double Click the new Text Field
  13. Clear the expression “Text Field”
  14. Select the new variable

  15. Click finish

  16. Put the new text in a desirable position ?

How to sort an array of ints using a custom comparator?

java 8:

Arrays.stream(new int[]{10,4,5,6,1,2,3,7,9,8}).boxed().sorted((e1,e2)-> e2-e1).collect(Collectors.toList());

blur vs focusout -- any real differences?

The documentation for focusout says (emphasis mine):

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

The same distinction exists between the focusin and focus events.

How to get memory usage at runtime using C++?

in additional to your way
you could call system ps command and get memory usage from it output.
or read info from /proc/pid ( see PIOCPSINFO struct )

Only get hash value using md5sum (without filename)

Another way:

md5=$(md5sum ${my_iso_file} | sed '/ .*//' )

concatenate two strings

You can use concatenation operator and instead of declaring two variables only use one variable

String finalString =  cursor.getString(numcol) + cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE));

Can I obtain method parameter name using Java reflection?

So you should be able to do:

Whatever.declaredMethods
        .find { it.name == 'aMethod' }
        .parameters
        .collect { "$it.type : $it.name" }

But you'll probably get a list like so:

["int : arg0"]

I believe this will be fixed in Groovy 2.5+

So currently, the answer is:

  • If it's a Groovy class, then no, you can't get the name, but you should be able to in the future.
  • If it's a Java class compiled under Java 8, you should be able to.

See also:


For every method, then something like:

Whatever.declaredMethods
        .findAll { !it.synthetic }
        .collect { method -> 
            println method
            method.name + " -> " + method.parameters.collect { "[$it.type : $it.name]" }.join(';')
        }
        .each {
            println it
        }

Convert from DateTime to INT

EDIT: Casting to a float/int no longer works in recent versions of SQL Server. Use the following instead:

select datediff(day, '1899-12-30T00:00:00', my_date_field)
from mytable

Note the string date should be in an unambiguous date format so that it isn't affected by your server's regional settings.


In older versions of SQL Server, you can convert from a DateTime to an Integer by casting to a float, then to an int:

select cast(cast(my_date_field as float) as int)
from mytable

(NB: You can't cast straight to an int, as MSSQL rounds the value up if you're past mid day!)

If there's an offset in your data, you can obviously add or subtract this from the result

You can convert in the other direction, by casting straight back:

select cast(my_integer_date as datetime)
from mytable

how to reference a YAML "setting" from elsewhere in the same YAML file?

That your example is invalid is only because you chose a reserved character to start your scalars with. If you replace the * with some other non-reserved character (I tend to use non-ASCII characters for that as they are seldom used as part of some specification), you end up with perfectly legal YAML:

paths:
  root: /path/to/root/
  patha: ?root? + a
  pathb: ?root? + b
  pathc: ?root? + c

This will load into the standard representation for mappings in the language your parser uses and does not magically expand anything.
To do that use a locally default object type as in the following Python program:

# coding: utf-8

from __future__ import print_function

import ruamel.yaml as yaml

class Paths:
    def __init__(self):
        self.d = {}

    def __repr__(self):
        return repr(self.d).replace('ordereddict', 'Paths')

    @staticmethod
    def __yaml_in__(loader, data):
        result = Paths()
        loader.construct_mapping(data, result.d)
        return result

    @staticmethod
    def __yaml_out__(dumper, self):
        return dumper.represent_mapping('!Paths', self.d)

    def __getitem__(self, key):
        res = self.d[key]
        return self.expand(res)

    def expand(self, res):
        try:
            before, rest = res.split(u'?', 1)
            kw, rest = rest.split(u'? +', 1)
            rest = rest.lstrip() # strip any spaces after "+"
            # the lookup will throw the correct keyerror if kw is not found
            # recursive call expand() on the tail if there are multiple
            # parts to replace
            return before + self.d[kw] + self.expand(rest)
        except ValueError:
            return res

yaml_str = """\
paths: !Paths
  root: /path/to/root/
  patha: ?root? + a
  pathb: ?root? + b
  pathc: ?root? + c
"""

loader = yaml.RoundTripLoader
loader.add_constructor('!Paths', Paths.__yaml_in__)

paths = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)['paths']

for k in ['root', 'pathc']:
    print(u'{} -> {}'.format(k, paths[k]))

which will print:

root -> /path/to/root/
pathc -> /path/to/root/c

The expanding is done on the fly and handles nested definitions, but you have to be careful about not invoking infinite recursion.

By specifying the dumper, you can dump the original YAML from the data loaded in, because of the on-the-fly expansion:

dumper = yaml.RoundTripDumper
dumper.add_representer(Paths, Paths.__yaml_out__)
print(yaml.dump(paths, Dumper=dumper, allow_unicode=True))

this will change the mapping key ordering. If that is a problem you have to make self.d a CommentedMap (imported from ruamel.yaml.comments.py)

What does map(&:name) mean in Ruby?

Although we have great answers already, looking through a perspective of a beginner I'd like to add the additional information:

What does map(&:name) mean in Ruby?

This means, that you are passing another method as parameter to the map function. (In reality you're passing a symbol that gets converted into a proc. But this isn't that important in this particular case).

What is important is that you have a method named name that will be used by the map method as an argument instead of the traditional block style.

Split string with delimiters in C

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

/**
 *  splits str on delim and dynamically allocates an array of pointers.
 *
 *  On error -1 is returned, check errno
 *  On success size of array is returned, which may be 0 on an empty string
 *  or 1 if no delim was found.  
 *
 *  You could rewrite this to return the char ** array instead and upon NULL
 *  know it's an allocation problem but I did the triple array here.  Note that
 *  upon the hitting two delim's in a row "foo,,bar" the array would be:
 *  { "foo", NULL, "bar" } 
 * 
 *  You need to define the semantics of a trailing delim Like "foo," is that a
 *  2 count array or an array of one?  I choose the two count with the second entry
 *  set to NULL since it's valueless.
 *  Modifies str so make a copy if this is a problem
 */
int split( char * str, char delim, char ***array, int *length ) {
  char *p;
  char **res;
  int count=0;
  int k=0;

  p = str;
  // Count occurance of delim in string
  while( (p=strchr(p,delim)) != NULL ) {
    *p = 0; // Null terminate the deliminator.
    p++; // Skip past our new null
    count++;
  }

  // allocate dynamic array
  res = calloc( 1, count * sizeof(char *));
  if( !res ) return -1;

  p = str;
  for( k=0; k<count; k++ ){
    if( *p ) res[k] = p;  // Copy start of string
    p = strchr(p, 0 );    // Look for next null
    p++; // Start of next string
  }

  *array = res;
  *length = count;

  return 0;
}

char str[] = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC,";

int main() {
  char **res;
  int k=0;
  int count =0;
  int rc;

  rc = split( str, ',', &res, &count );
  if( rc ) {
    printf("Error: %s errno: %d \n", strerror(errno), errno);
  }

  printf("count: %d\n", count );
  for( k=0; k<count; k++ ) {
    printf("str: %s\n", res[k]);
  }

  free(res );
  return 0;
}

Should CSS always preceed Javascript?

Personally, I would not place too much emphasis on such "folk wisdom." What may have been true in the past might well not be true now. I would assume that all of the operations relating to a web-page's interpretation and rendering are fully asynchronous ("fetching" something and "acting upon it" are two entirely different things that might be being handled by different threads, etc.), and in any case entirely beyond your control or your concern.

I'd put CSS references in the "head" portion of the document, along with any references to external scripts. (Some scripts may demand to be placed in the body, and if so, oblige them.)

Beyond that ... if you observe that "this seems to be faster/slower than that, on this/that browser," treat this observation as an interesting but irrelevant curiosity and don't let it influence your design decisions. Too many things change too fast. (Anyone want to lay any bets on how many minutes it will be before the Firefox team comes out with yet another interim-release of their product? Yup, me neither.)

How to log Apache CXF Soap Request and Soap Response using Log4j?

Procedure for global setting of client/server logging of SOAP/REST requests/ responses with log4j logger. This way you set up logging for the whole application without having to change the code, war, jar files, etc.

  1. install file cxf-rt-features-logging-X.Y.Z.jar to your CLASS_PATH

  2. create file (path for example: /opt/cxf/cxf-logging.xml):

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://cxf.apache.org/core" xsi:schemaLocation="http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
    <cxf:bus>
     <cxf:features>
     <bean class="org.apache.cxf.ext.logging.LoggingFeature">
     <property name="prettyLogging" value="true"/>
     </bean>
     </cxf:features>
     </cxf:bus>
     </beans>
    
  3. set logging for org.apache.cxf (log4j 1.x) log4j.logger.org.apache.cxf=INFO,YOUR_APPENDER

  4. set these properties on java start-up

java ... -Dcxf.config.file.url=file:///opt/cxf/cxf-logging.xml -Dorg.apache.cxf.Logger=org.apache.cxf.common.logging.Log4jLogger -Dcom.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true -Dcom.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump=true -Dcom.sun.xml.ws.transport.http.HttpAdapter.dump=true -Dcom.sun.xml.internal.ws.transport.http.HttpAdapter.dump=true ...

I don't know why, but it is necessary to set variables as well com.sun.xml.*

Eventviewer eventid for lock and unlock

Using Windows 10 Home edition. I was unable to get my event viewer to capture events 4800 and 4801, even after installing the Windows Group Policy Editor, enabling auditing on all the relevant events, and restarting the computer. However, I was able to discover other events that are tied to locking and unlocking that you can use as accurate and reliable indicators of when the PC was locked. See configurations below - the first is for PC Locked (the event connected to displaying C:\Windows\System32\LogonUI.exe) - and the second is for PC Unlocked (the event for successful logon).

enter image description here

enter image description here

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

Write string to text file and ensure it always overwrites the existing content.

Use the File.WriteAllText method. It creates the file if it doesn't exist and overwrites it if it exists.

Adding Google Play services version to your app's manifest?

In my case i had to install google repository from the SDK manager.

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

There are a couple of parallization bugs in SQL server with abnormal input. OPTION(MAXDOP 1) will sidestep them.

EDIT: Old. My testing was done largely on SQL 2005. Most of these seem to not exist anymore, but every once in awhile we question the assumption when SQL 2014 does something dumb and we go back to the old way and it works. We never managed to demonstrate that it wasn't just a bad plan generation on more recent cases though since SQL server can be relied on to get the old way right in newer versions. Since all cases were IO bound queries MAXDOP 1 doesn't hurt.

How to stick a footer to bottom in css?

#Footer {
position:fixed;
bottom:0;
width:100%;
}

worked for me

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

As complement to Mark's answer, the compile function does not have access to scope, but the link function does.

I really recommend this video; Writing Directives by Misko Hevery (the father of AngularJS), where he describes differences and some techniques. (Difference between compile function and link function at 14:41 mark in the video).

Escaping special characters in Java Regular Expressions

The Pattern.quote(String s) sort of does what you want. However it leaves a little left to be desired; it doesn't actually escape the individual characters, just wraps the string with \Q...\E.

There is not a method that does exactly what you are looking for, but the good news is that it is actually fairly simple to escape all of the special characters in a Java regular expression:

regex.replaceAll("[\\W]", "\\\\$0")

Why does this work? Well, the documentation for Pattern specifically says that its permissible to escape non-alphabetic characters that don't necessarily have to be escaped:

It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.

For example, ; is not a special character in a regular expression. However, if you escape it, Pattern will still interpret \; as ;. Here are a few more examples:

  • > becomes \> which is equivalent to >
  • [ becomes \[ which is the escaped form of [
  • 8 is still 8.
  • \) becomes \\\) which is the escaped forms of \ and ( concatenated.

Note: The key is is the definition of "non-alphabetic", which in the documentation really means "non-word" characters, or characters outside the character set [a-zA-Z_0-9].

How to merge 2 JSON objects from 2 files using jq?

First, {"value": .value} can be abbreviated to just {value}.

Second, the --argfile option (available in jq 1.4 and jq 1.5) may be of interest as it avoids having to use the --slurp option.

Putting these together, the two objects in the two files can be combined in the specified way as follows:

$ jq -n --argfile o1 file1 --argfile o2 file2 '$o1 * $o2 | {value}'

The '-n' flag tells jq not to read from stdin, since inputs are coming from the --argfile options here.

Note on --argfile

The jq manual deprecates --argfile because its semantics are non-trivial: if the specified input file contains exactly one JSON entity, then that entity is read as is; otherwise, the items in the stream are wrapped in an array.

If you are uncomfortable using --argfile, there are several alternatives you may wish to consider. In doing so, be assured that using --slurpfile does not incur the inefficiencies of the -s command-line option when the latter is used with multiple files.

How to make space between LinearLayout children?

Since API Level 14 you can just add a (transparent) divider drawable:

android:divider="@drawable/divider"
android:showDividers="middle"

and it will handle the rest for you!

ModalPopupExtender OK Button click event not firing?

It appears that a button that is used as the OK or CANCEL button for a ModalPopupExtender cannot have a click event. I tested this out by removing the

OkControlID="ModalOKButton"

from the ModalPopupExtender tag, and the button click fires. I'll need to figure out another way to send the data to the server.

How do you test to see if a double is equal to NaN?

If your value under test is a Double (not a primitive) and might be null (which is obviously not a number too), then you should use the following term:

(value==null || Double.isNaN(value))

Since isNaN() wants a primitive (rather than boxing any primitive double to a Double), passing a null value (which can't be unboxed to a Double) will result in an exception instead of the expected false.

How can I make content appear beneath a fixed DIV element?

Wrap the menu contents with another div:

<div id="floatingMenu">
    <div>
        <a href="http://www.google.com">Test 1</a>
        <a href="http://www.google.com">Test 2</a>
        <a href="http://www.google.com">Test 3</a>
    </div>
</div>

And the CSS:

#floatingMenu {
    clear: both;
    position: fixed;
    width: 100%;
    height: 30px;
    background-color: #78AB46;
    top: 5px;
}

#floatingMenu > div {
    margin: auto;
    text-align: center;
}

And about your page below the menu, you can give it a padding-top as well:

#content {
    padding-top: 35px; /* top 5px plus height 30px */
}

python BeautifulSoup parsing table

Solved, this is how your parse their html results:

table = soup.find("table", { "class" : "lineItemsTable" })
for row in table.findAll("tr"):
    cells = row.findAll("td")
    if len(cells) == 9:
        summons = cells[1].find(text=True)
        plateType = cells[2].find(text=True)
        vDate = cells[3].find(text=True)
        location = cells[4].find(text=True)
        borough = cells[5].find(text=True)
        vCode = cells[6].find(text=True)
        amount = cells[7].find(text=True)
        print amount

Is it possible to append to innerHTML without destroying descendants' event listeners?

For any object array with header and data.jsfiddle

https://jsfiddle.net/AmrendraKumar/9ac75Lg0/2/

<table id="myTable" border='1|1'></table>

<script>
  const userObjectArray = [{
    name: "Ajay",
    age: 27,
    height: 5.10,
    address: "Bangalore"
  }, {
    name: "Vijay",
    age: 24,
    height: 5.10,
    address: "Bangalore"
  }, {
    name: "Dinesh",
    age: 27,
    height: 5.10,
    address: "Bangalore"
  }];
  const headers = Object.keys(userObjectArray[0]);
  var tr1 = document.createElement('tr');
  var htmlHeaderStr = '';
  for (let i = 0; i < headers.length; i++) {
    htmlHeaderStr += "<th>" + headers[i] + "</th>"
  }
  tr1.innerHTML = htmlHeaderStr;
  document.getElementById('myTable').appendChild(tr1);

  for (var j = 0; j < userObjectArray.length; j++) {
    var tr = document.createElement('tr');
    var htmlDataString = '';
    for (var k = 0; k < headers.length; k++) {
      htmlDataString += "<td>" + userObjectArray[j][headers[k]] + "</td>"
    }
    tr.innerHTML = htmlDataString;
    document.getElementById('myTable').appendChild(tr);
  }

</script>

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

In textpad.

Go to left top of the page. hold "shift key Now use right arrow key to select column. Now click "down arrow" key. And the entire column will be selected.

Creating an array of objects in Java

Here is the clear example of creating array of 10 employee objects, with a constructor that takes parameter:

public class MainClass
{  
    public static void main(String args[])
    {
        System.out.println("Hello, World!");
        //step1 : first create array of 10 elements that holds object addresses.
        Emp[] employees = new Emp[10];
        //step2 : now create objects in a loop.
        for(int i=0; i<employees.length; i++){
            employees[i] = new Emp(i+1);//this will call constructor.
        }
    }
}

class Emp{
    int eno;
    public Emp(int no){
        eno = no;
        System.out.println("emp constructor called..eno is.."+eno);
    }
}

Babel 6 regeneratorRuntime is not defined

I have async await working with webpack/babel build:

"devDependencies": {
    "babel-preset-stage-3": "^6.11.0"
}

.babelrc:

"presets": ["es2015", "stage-3"]

JavaScript blob filename without link

Late, but since I had the same problem I add my solution:

function newFile(data, fileName) {
    var json = JSON.stringify(data);
    //IE11 support
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        let blob = new Blob([json], {type: "application/json"});
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {// other browsers
        let file = new File([json], fileName, {type: "application/json"});
        let exportUrl = URL.createObjectURL(file);
        window.location.assign(exportUrl);
        URL.revokeObjectURL(exportUrl);
    }
}

Writing to a file in a for loop

It's preferable to use context managers to close the files automatically

with open("new.txt", "r"), open('xyz.txt', 'w') as textfile, myfile:
    for line in textfile:
        var1, var2 = line.split(",");
        myfile.writelines(var1)

PHP mySQL - Insert new record into table with auto-increment on primary key

I prefer this syntaxis:

$query = "INSERT INTO myTable SET fname='Fname',lname='Lname',website='Website'";

Iterating over each line of ls -l output

As already mentioned, awk is the right tool for this. If you don't want to use awk, instead of parsing output of "ls -l" line by line, you could iterate over all files and do an "ls -l" for each individual file like this:

for x in * ; do echo `ls -ld $x` ; done

OpenCV & Python - Image too big to display

In opencv, cv.namedWindow() just creates a window object as you determine, but not resizing the original image. You can use cv2.resize(img, resolution) to solve the problem.

Here's what it displays, a 740 * 411 resolution image. The original image

image = cv2.imread("740*411.jpg")
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Here, it displays a 100 * 200 resolution image after resizing. Remember the resolution parameter use column first then is row.

Image after resizing

image = cv2.imread("740*411.jpg")
image = cv2.resize(image, (200, 100))
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

sorting integers in order lowest to highest java

You can put them into a list and then sort them using their natural ordering, like so:

final List<Integer> list = Arrays.asList(11367, 11358, 11421, 11530, 11491, 11218, 11789);
Collections.sort( list );
// Use the sorted list

If the numbers are stored in the same variable, then you'll have to somehow put them into a List and then call sort, like so:

final List<Integer> list = new ArrayList<Integer>();
list.add( myVariable );
// Change myVariable to another number...
list.add( myVariable );
// etc...

Collections.sort( list );
// Use the sorted list

Jest spyOn function called

You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance before trying to spy on the method.

describe('my sweet test', () => {
 it('clicks it', () => {
    const app = shallow(<App />)
    const instance = app.instance()
    const spy = jest.spyOn(instance, 'myClickFunc')

    instance.forceUpdate();    

    const p = app.find('.App-intro')
    p.simulate('click')
    expect(spy).toHaveBeenCalled()
 })
})

Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html

Remove all special characters, punctuation and spaces from string

Differently than everyone else did using regex, I would try to exclude every character that is not what I want, instead of enumerating explicitly what I don't want.

For example, if I want only characters from 'a to z' (upper and lower case) and numbers, I would exclude everything else:

import re
s = re.sub(r"[^a-zA-Z0-9]","",s)

This means "substitute every character that is not a number, or a character in the range 'a to z' or 'A to Z' with an empty string".

In fact, if you insert the special character ^ at the first place of your regex, you will get the negation.

Extra tip: if you also need to lowercase the result, you can make the regex even faster and easier, as long as you won't find any uppercase now.

import re
s = re.sub(r"[^a-z0-9]","",s.lower())

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

Set-ExecutionPolicy Unrestricted -Scope CurrentUser

This will set the execution policy for the current user (stored in HKEY_CURRENT_USER) rather than the local machine (HKEY_LOCAL_MACHINE). This is useful if you don't have administrative control over the computer.

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

Make sure you have imported HttpClientModule instead of adding HttpClient direcly to the list of providers.

See https://angular.io/guide/http#setup for more info.

The HttpClientModule actually provides HttpClient for you. See https://angular.io/api/common/http/HttpClientModule:

Code sample:

import { HttpClientModule, /* other http imports */ } from "@angular/common/http";

@NgModule({
    // ...other declarations, providers, entryComponents, etc.
    imports: [
        HttpClientModule,
        // ...some other imports
    ],
})
export class AppModule { }

Is there a way to style a TextView to uppercase all of its letters?

I though that was a pretty reasonable request but it looks like you cant do it at this time. What a Total Failure. lol

Update

You can now use textAllCaps to force all caps.

How to clear/delete the contents of a Tkinter Text widget?

According to the tkinterbook the code to clear a text element should be:

text.delete(1.0,END)

This worked for me. source

It's different from clearing an entry element, which is done like this:

entry.delete(0,END) #note the 0 instead of 1.0

Calling functions in a DLL from C++

The following are the 5 steps required:

  1. declare the function pointer
  2. Load the library
  3. Get the procedure address
  4. assign it to function pointer
  5. call the function using function pointer

You can find the step by step VC++ IDE screen shot at http://www.softwareandfinance.com/Visual_CPP/DLLDynamicBinding.html

Here is the code snippet:

int main()
{
/***
__declspec(dllimport) bool GetWelcomeMessage(char *buf, int len); // used for static binding
 ***/
    typedef bool (*GW)(char *buf, int len);

    HMODULE hModule = LoadLibrary(TEXT("TestServer.DLL"));
    GW GetWelcomeMessage = (GW) GetProcAddress(hModule, "GetWelcomeMessage");

    char buf[128];
    if(GetWelcomeMessage(buf, 128) == true)
        std::cout << buf;
        return 0;
}

Array.size() vs Array.length

we can you use .length property to set or returns number of elements in an array. return value is a number

> set the length: let count = myArray.length;
> return lengthof an array : myArray.length

we can you .size in case we need to filter duplicate values and get the count of elements in a set.

const set = new set([1,1,2,1]); 
 console.log(set.size) ;`

Asp.net Hyperlink control equivalent to <a href="#"></a>

Just write <a href="#"></a>.

If that's what you want, you don't need a server-side control.

Static constant string (class member)

Inside class definitions you can only declare static members. They have to be defined outside of the class. For compile-time integral constants the standard makes the exception that you can "initialize" members. It's still not a definition, though. Taking the address would not work without definition, for example.

I'd like to mention that I don't see the benefit of using std::string over const char[] for constants. std::string is nice and all but it requires dynamic initialization. So, if you write something like

const std::string foo = "hello";

at namespace scope the constructor of foo will be run right before execution of main starts and this constructor will create a copy of the constant "hello" in the heap memory. Unless you really need RECTANGLE to be a std::string you could just as well write

// class definition with incomplete static member could be in a header file
class A {
    static const char RECTANGLE[];
};

// this needs to be placed in a single translation unit only
const char A::RECTANGLE[] = "rectangle";

There! No heap allocation, no copying, no dynamic initialization.

Cheers, s.

Best lightweight web server (only static content) for Windows

Consider thttpd. It can run under windows.

Quoting wikipedia:

"it is uniquely suited to service high volume requests for static data"

A version of thttpd-2.25b compiled under cygwin with cygwin dll's is available. It is single threaded and particularly good for servicing images.

Swing JLabel text change on the running application

Use setText(str) method of JLabel to dynamically change text displayed. In actionPerform of button write this:

jLabel.setText("new Value");

A simple demo code will be:

    JFrame frame = new JFrame("Demo");
    frame.setLayout(new BorderLayout());
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(250,100);

    final JLabel label = new JLabel("flag");
    JButton button = new JButton("Change flag");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            label.setText("new value");
        }
    });

    frame.add(label, BorderLayout.NORTH);
    frame.add(button, BorderLayout.CENTER);
    frame.setVisible(true);

Conversion failed when converting the varchar value to data type int in sql

Try this one -

CREATE PROC [dbo].[getVoucherNo]
AS BEGIN

     DECLARE 
            @Prefix VARCHAR(10) = 'J'
          , @startFrom INT = 1
          , @maxCode VARCHAR(100)
          , @sCode INT

     IF EXISTS(
          SELECT 1 
          FROM dbo.Journal_Entry
     ) BEGIN

          SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(Voucher_No,LEN(@startFrom)+1,ABS(LEN(Voucher_No)- LEN(@Prefix))) AS INT)) AS varchar(100)) 
          FROM dbo.Journal_Entry;

          SELECT @Prefix + 
               CAST(LEN(LEFT(@maxCode, 10) + 1) AS VARCHAR(10)) + -- !!! possible problem here
               CAST(@maxCode AS VARCHAR(100))

     END
     ELSE BEGIN

          SELECT (@Prefix + CAST(@startFrom AS VARCHAR)) 

     END

END

SQL update statement in C#

string constr = @"Data Source=(LocalDB)\v11.0;Initial Catalog=Bank;Integrated Security=True;Pooling=False";
SqlConnection con = new SqlConnection(constr);
DataSet ds = new DataSet();
con.Open();
SqlCommand cmd = new SqlCommand(" UPDATE Account  SET name = Aleesha, CID = 24 Where name =Areeba and CID =11 )";
cmd.ExecuteNonQuery();

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

The SSL errors are often thrown by network management software such as Cyberroam.

To answer your question,

you will have to enter badidea into Chrome every time you visit a website.

You might at times have to enter it more than once, as the site may try to pull in various resources before load, hence causing multiple SSL errors

Remove all special characters from a string

Here, check out this function:

function seo_friendly_url($string){
    $string = str_replace(array('[\', \']'), '', $string);
    $string = preg_replace('/\[.*\]/U', '', $string);
    $string = preg_replace('/&(amp;)?#?[a-z0-9]+;/i', '-', $string);
    $string = htmlentities($string, ENT_COMPAT, 'utf-8');
    $string = preg_replace('/&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);/i', '\\1', $string );
    $string = preg_replace(array('/[^a-z0-9]/i', '/[-]+/') , '-', $string);
    return strtolower(trim($string, '-'));
}

R data formats: RData, Rda, Rds etc

In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds file. Not so for Rda

> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)

## ASSIGN USING readRDS
> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5

## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to  <environment: R_GlobalEnv> 
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values. 
> x
[1] 1 2 3 4 5

Focus Next Element In Tab Index

Did you specify your own tabIndex values for each element you want to cycle through? if so, you can try this:

var lasTabIndex = 10; //Set this to the highest tabIndex you have
function OnFocusOut()
{
    var currentElement = $get(currentElementId); // ID set by OnFocusIn 

    var curIndex = $(currentElement).attr('tabindex'); //get the tab index of the current element
    if(curIndex == lastTabIndex) { //if we are on the last tabindex, go back to the beginning
        curIndex = 0;
    }
    $('[tabindex=' + (curIndex + 1) + ']').focus(); //set focus on the element that has a tab index one greater than the current tab index
}

You are using jquery, right?

How do you input command line arguments in IntelliJ IDEA?

Example I have a class Test:

Class Test

Then. Go to config to run class Test:

Step 1: Add Application

Add Application

Step 2:

Edit Configurations...

You can input arguments in the Program Arguments textbox.

What does mscorlib stand for?

Microsoft Core Library, ie they are at the heart of everything.

There is a more "massaged" explanation you may prefer:

"When Microsoft first started working on the .NET Framework, MSCorLib.dll was an acronym for Microsoft Common Object Runtime Library. Once ECMA started to standardize the CLR and parts of the FCL, MSCorLib.dll officially became the acronym for Multilanguage Standard Common Object Runtime Library."

From http://weblogs.asp.net/mreynolds/archive/2004/01/31/65551.aspx

Around 1999, to my personal memory, .Net was known as "COOL", so I am a little suspicious of this derivation. I never heard it called "COR", which is a silly-sounding name to a native English speaker.

How to filter empty or NULL names in a QuerySet?

You could do this:

Name.objects.exclude(alias__isnull=True)

If you need to exclude null values and empty strings, the preferred way to do so is to chain together the conditions like so:

Name.objects.exclude(alias__isnull=True).exclude(alias__exact='')

Chaining these methods together basically checks each condition independently: in the above example, we exclude rows where alias is either null or an empty string, so you get all Name objects that have a not-null, not-empty alias field. The generated SQL would look something like:

SELECT * FROM Name WHERE alias IS NOT NULL AND alias != ""

You can also pass multiple arguments to a single call to exclude, which would ensure that only objects that meet every condition get excluded:

Name.objects.exclude(some_field=True, other_field=True)

Here, rows in which some_field and other_field are true get excluded, so we get all rows where both fields are not true. The generated SQL code would look a little like this:

SELECT * FROM Name WHERE NOT (some_field = TRUE AND other_field = TRUE)

Alternatively, if your logic is more complex than that, you could use Django's Q objects:

from django.db.models import Q
Name.objects.exclude(Q(alias__isnull=True) | Q(alias__exact=''))

For more info see this page and this page in the Django docs.

As an aside: My SQL examples are just an analogy--the actual generated SQL code will probably look different. You'll get a deeper understanding of how Django queries work by actually looking at the SQL they generate.

Linq Select Group By

This will give you sequence of anonymous objects, containing date string and two properties with average price:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new { 
               LogDate = g.Key,
               AvgGoldPrice = (int)g.Average(x => x.GoldPrice), 
               AvgSilverPrice = (int)g.Average(x => x.SilverPrice)
            };

If you need to get list of PriceLog objects:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new PriceLog { 
               LogDateTime = DateTime.Parse(g.Key),
               GoldPrice = (int)g.Average(x => x.GoldPrice), 
               SilverPrice = (int)g.Average(x => x.SilverPrice)
            };

Lock, mutex, semaphore... what's the difference?

Using C programming on a Linux variant as a base case for examples.

Lock:

• Usually a very simple construct binary in operation either locked or unlocked

• No concept of thread ownership, priority, sequencing etc.

• Usually a spin lock where the thread continuously checks for the locks availability.

• Usually relies on atomic operations e.g. Test-and-set, compare-and-swap, fetch-and-add etc.

• Usually requires hardware support for atomic operation.

File Locks:

• Usually used to coordinate access to a file via multiple processes.

• Multiple processes can hold the read lock however when any single process holds the write lock no other process is allowed to acquire a read or write lock.

• Example : flock, fcntl etc..

Mutex:

• Mutex function calls usually work in kernel space and result in system calls.

• It uses the concept of ownership. Only the thread that currently holds the mutex can unlock it.

• Mutex is not recursive (Exception: PTHREAD_MUTEX_RECURSIVE).

• Usually used in Association with Condition Variables and passed as arguments to e.g. pthread_cond_signal, pthread_cond_wait etc.

• Some UNIX systems allow mutex to be used by multiple processes although this may not be enforced on all systems.

Semaphore:

• This is a kernel maintained integer whose values is not allowed to fall below zero.

• It can be used to synchronize processes.

• The value of the semaphore may be set to a value greater than 1 in which case the value usually indicates the number of resources available.

• A semaphore whose value is restricted to 1 and 0 is referred to as a binary semaphore.

BitBucket - download source as ZIP

In Bitbucket Server you can do a download by clicking on ... next to the branch and then Download

Bitbucket Server download

For more info see Download an archive from Bitbucket Server

How to unset (remove) a collection element after fetching it?

If you know the key which you unset then put directly by comma separated

unset($attr['placeholder'], $attr['autocomplete']);

A simple command line to download a remote maven2 artifact to the local repository?

Since version 2.1 of the Maven Dependency Plugin, there is a dependency:get goal for this purpose. To make sure you are using the right version of the plugin, you'll need to use the "fully qualified name":

mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get \
    -DrepoUrl=http://download.java.net/maven/2/ \
    -Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT

How can I map True/False to 1/0 in a Pandas DataFrame?

You also can do this directly on Frames

In [104]: df = DataFrame(dict(A = True, B = False),index=range(3))

In [105]: df
Out[105]: 
      A      B
0  True  False
1  True  False
2  True  False

In [106]: df.dtypes
Out[106]: 
A    bool
B    bool
dtype: object

In [107]: df.astype(int)
Out[107]: 
   A  B
0  1  0
1  1  0
2  1  0

In [108]: df.astype(int).dtypes
Out[108]: 
A    int64
B    int64
dtype: object

Invalid date in safari

I use moment to solve the problem. For example

var startDate = moment('2015-07-06 08:00', 'YYYY-MM-DD HH:mm').toDate();

How to change MySQL timezone in a database connection using Java?

For applications such as Squirrel SQL Client (http://squirrel-sql.sourceforge.net/) version 4 you can set "serverTimezone" under "driver properties" to GMT+1 (example of timezone "Europe/Vienna).

How to get the selected row values of DevExpress XtraGrid?

All you have to do is use the GetFocusedRowCellValue method of the gridView control and put it into the RowClick event.

For example:

private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
    if (this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni") == null)
        return;
    MessageBox.Show(""+this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni").ToString());            
}

what is the differences between sql server authentication and windows authentication..?

I think the main difference is security.

Windows Authentication means that the identity is handled as part of the windows handashaking and now password is ever 'out there' for interception.

SQL Authentication means that you have to store (or provide) a username and a password yourself making it much easier to breach. A heap of effort has gone into making windows authentication very robust and secure.

Might I suggest that if you do implement Windows Authentication use Groups and Roles to do it. Groups in Windows and Roles in SQL. Having to setup lots of users in SQL is a big pain when you can just setup the group and then add each user to the group. (I think most security should be done this way anyway).

Could not load type from assembly error

The solution to this for me was not mentioned above, so I thought I would add my answer to the long tail...

I ended up having an old reference to a class (an HttpHandler) in web.config that was no longer being used (and was no longer a valid reference). For some reason it was ignored while running in Studio (or maybe I have that class still accessible within my dev setup?) and so I only got this error once I tried deploying to IIS. I searched on the assembly name in web.config, removed the unused handler reference, then this error went away and everything works great. Hope this helps someone else.

How to trigger jQuery change event in code

Use the trigger() method

$(selector).trigger("change");

React: "this" is undefined inside a component function

in my case this was the solution = () => {}

methodName = (params) => {
//your code here with this.something
}

Write to custom log file from a Bash script

If you see the man page of logger:

$ man logger

LOGGER(1) BSD General Commands Manual LOGGER(1)

NAME logger — a shell command interface to the syslog(3) system log module

SYNOPSIS logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message ...]

DESCRIPTION Logger makes entries in the system log. It provides a shell command interface to the syslog(3) system log module.

It Clearly says that it will log to system log. If you want to log to file, you can use ">>" to redirect to log file.

How do I see which version of Swift I'm using?

hi frind code type in terminal swift -v

print teminal Welcome to Apple Swift version 5.2.4 (swiftlang-1103.0.32.9 clang-1103.0.32.53).

Adding onClick event dynamically using jQuery

Or you can use an arrow function to define it:

$(document).ready(() => {
  $('#bfCaptchaEntry').click(()=>{
    
  });
});

For better browser support:

$(document).ready(function() {
  $('#bfCaptchaEntry').click(function (){
    
  });
});

Using BufferedReader.readLine() in a while loop properly

You're calling br.readLine() a second time inside the loop.
Therefore, you end up reading two lines each time you go around.

How to copy file from host to container using Dockerfile

I got the following error using Docker 19.03.8 on CentOS 7:

COPY failed: stat /var/lib/docker/tmp/docker-builderXXXXXXX/abc.txt: no such file or directory

The solution for me was to build from Docker file with docker build . instead of docker build - < Dockerfile.

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

Jackson overcoming underscores in favor of camel-case

You should use the @JsonProperty on the field you want to change the default name mapping.

class User{
    @JsonProperty("first_name")
    protected String firstName;
    protected String getFirstName(){return firstName;}
}

For more info: the API

RequiredIf Conditional Validation Attribute

Expanding on the notes from Adel Mourad and Dan Hunex, I amended the code to provide an example that only accepts values that do not match the given value.

I also found that I didn't need the JavaScript.

I added the following class to my Models folder:

public class RequiredIfNotAttribute : ValidationAttribute, IClientValidatable
{
    private String PropertyName { get; set; }
    private Object InvalidValue { get; set; }
    private readonly RequiredAttribute _innerAttribute;

    public RequiredIfNotAttribute(String propertyName, Object invalidValue)
    {
        PropertyName = propertyName;
        InvalidValue = invalidValue;
        _innerAttribute = new RequiredAttribute();
    }

    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);

        if (dependentValue.ToString() != InvalidValue.ToString())
        {
            if (!_innerAttribute.IsValid(value))
            {
                return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
            }
        }
        return ValidationResult.Success;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = ErrorMessageString,
            ValidationType = "requiredifnot",
        };
        rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
        rule.ValidationParameters["invalidvalue"] = InvalidValue is bool ? InvalidValue.ToString().ToLower() : InvalidValue;

        yield return rule;
    }

I didn't need to make any changes to my view, but did make a change to the properties of my model:

    [RequiredIfNot("Id", 0, ErrorMessage = "Please select a Source")]
    public string TemplateGTSource { get; set; }

    public string TemplateGTMedium
    {
        get
        {
            return "Email";
        }
    }

    [RequiredIfNot("Id", 0, ErrorMessage = "Please enter a Campaign")]
    public string TemplateGTCampaign { get; set; }

    [RequiredIfNot("Id", 0, ErrorMessage = "Please enter a Term")]
    public string TemplateGTTerm { get; set; }

Hope this helps!

Vim delete blank lines

This works for me

:%s/^\s*$\n//gc

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

//*[text()='ABC'] 

returns

<street>ABC</street>
<comment>BLAH BLAH BLAH <br><br>ABC</comment>

join list of lists in python

Late to the party but ...

I'm new to python and come from a lisp background. This is what I came up with (check out the var names for lulz):

def flatten(lst):
    if lst:
        car,*cdr=lst
        if isinstance(car,(list,tuple)):
            if cdr: return flatten(car) + flatten(cdr)
            return flatten(car)
        if cdr: return [car] + flatten(cdr)
        return [car]

Seems to work. Test:

flatten((1,2,3,(4,5,6,(7,8,(((1,2)))))))

returns:

[1, 2, 3, 4, 5, 6, 7, 8, 1, 2]

Best/Most Comprehensive API for Stocks/Financial Data

I usually find that ProgrammableWeb is a good place to go when looking for APIs.

Change size of text in text input tag?

To change the font size of the <input /> tag in HTML, use this:

<input style="font-size:20px" type="text" value="" />

It will create a text input box and the text inside the text box will be 20 pixels.

How can I use MS Visual Studio for Android Development?

Yes you can:

http://www.gavpugh.com/2011/02/04/vs-android-developing-for-android-in-visual-studio/

enter image description here

In case you get "Unable to locate tools.jar. Expected to find it in C:\Program Files (x86)\Java\jre6\lib\tools.jar" you can add an environment variable JAVA_HOME that points to your Java JDK path, for example c:\sdks\glassfish3\jdk (restart MSVC afterwards)

An even better solution is using WinGDB Mobile Edition in Visual Studio: it lets you create and debug Android projects all inside Visual Studio:

http://ian-ni-lewis.blogspot.com/2011/01/its-like-coming-home-again.html

Download WinGDC for Android from http://www.wingdb.com/wgMobileEdition.htm

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

How can I view all historical changes to a file in SVN

There's no built-in command for it, so I usually just do something like this:

#!/bin/bash

# history_of_file
#
# Outputs the full history of a given file as a sequence of
# logentry/diff pairs.  The first revision of the file is emitted as
# full text since there's not previous version to compare it to.

function history_of_file() {
    url=$1 # current url of file
    svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -n | {

#       first revision as full text
        echo
        read r
        svn log -r$r $url@HEAD
        svn cat -r$r $url@HEAD
        echo

#       remaining revisions as differences to previous revision
        while read r
        do
            echo
            svn log -r$r $url@HEAD
            svn diff -c$r $url@HEAD
            echo
        done
    }
}

Then, you can call it with:

history_of_file $1

How to display tables on mobile using Bootstrap?

Bootstrap 3 introduces responsive tables:

<div class="table-responsive">
  <table class="table">
    ...
  </table>
</div>

Bootstrap 4 is similar, but with more control via some new classes:

...responsive across all viewports ... with .table-responsive. Or, pick a maximum breakpoint with which to have a responsive table up to by using .table-responsive{-sm|-md|-lg|-xl}.

Credit to Jason Bradley for providing an example:

Responsive Tables

How to store custom objects in NSUserDefaults

I create a library RMMapper (https://github.com/roomorama/RMMapper) to help save custom object into NSUserDefaults easier and more convenient, because implementing encodeWithCoder and initWithCoder is super boring!

To mark a class as archivable, just use: #import "NSObject+RMArchivable.h"

To save a custom object into NSUserDefaults:

#import "NSUserDefaults+RMSaveCustomObject.h"
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults rm_setCustomObject:user forKey:@"SAVED_DATA"];

To get custom obj from NSUserDefaults:

user = [defaults rm_customObjectForKey:@"SAVED_DATA"]; 

Why should text files end with a newline?

Because that’s how the POSIX standard defines a line:

3.206 Line
A sequence of zero or more non- <newline> characters plus a terminating <newline> character.

Therefore, lines not ending in a newline character aren't considered actual lines. That's why some programs have problems processing the last line of a file if it isn't newline terminated.

There's at least one hard advantage to this guideline when working on a terminal emulator: All Unix tools expect this convention and work with it. For instance, when concatenating files with cat, a file terminated by newline will have a different effect than one without:

$ more a.txt
foo
$ more b.txt
bar$ more c.txt
baz
$ cat {a,b,c}.txt
foo
barbaz

And, as the previous example also demonstrates, when displaying the file on the command line (e.g. via more), a newline-terminated file results in a correct display. An improperly terminated file might be garbled (second line).

For consistency, it’s very helpful to follow this rule – doing otherwise will incur extra work when dealing with the default Unix tools.


Think about it differently: If lines aren’t terminated by newline, making commands such as cat useful is much harder: how do you make a command to concatenate files such that

  1. it puts each file’s start on a new line, which is what you want 95% of the time; but
  2. it allows merging the last and first line of two files, as in the example above between b.txt and c.txt?

Of course this is solvable but you need to make the usage of cat more complex (by adding positional command line arguments, e.g. cat a.txt --no-newline b.txt c.txt), and now the command rather than each individual file controls how it is pasted together with other files. This is almost certainly not convenient.

… Or you need to introduce a special sentinel character to mark a line that is supposed to be continued rather than terminated. Well, now you’re stuck with the same situation as on POSIX, except inverted (line continuation rather than line termination character).


Now, on non POSIX compliant systems (nowadays that’s mostly Windows), the point is moot: files don’t generally end with a newline, and the (informal) definition of a line might for instance be “text that is separated by newlines” (note the emphasis). This is entirely valid. However, for structured data (e.g. programming code) it makes parsing minimally more complicated: it generally means that parsers have to be rewritten. If a parser was originally written with the POSIX definition in mind, then it might be easier to modify the token stream rather than the parser — in other words, add an “artificial newline” token to the end of the input.

Firing events on CSS class changes in jQuery

Whenever you change a class in your script, you could use a trigger to raise your own event.

$(this).addClass('someClass');
$(mySelector).trigger('cssClassChanged')
....
$(otherSelector).bind('cssClassChanged', data, function(){ do stuff });

but otherwise, no, there's no baked-in way to fire an event when a class changes. change() only fires after focus leaves an input whose input has been altered.

_x000D_
_x000D_
$(function() {_x000D_
  var button = $('.clickme')_x000D_
      , box = $('.box')_x000D_
  ;_x000D_
  _x000D_
  button.on('click', function() { _x000D_
    box.removeClass('box');_x000D_
    $(document).trigger('buttonClick');_x000D_
  });_x000D_
            _x000D_
  $(document).on('buttonClick', function() {_x000D_
    box.text('Clicked!');_x000D_
  });_x000D_
});
_x000D_
.box { background-color: red; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="box">Hi</div>_x000D_
<button class="clickme">Click me</button>
_x000D_
_x000D_
_x000D_

More info on jQuery Triggers

Detect click outside React component

I made a solution for all occasions.

You should use a High Order Component to wrap the component that you would like to listen for clicks outside it.

This component example has only one prop: "onClickedOutside" that receives a function.

ClickedOutside.js
import React, { Component } from "react";

export default class ClickedOutside extends Component {
  componentDidMount() {
    document.addEventListener("mousedown", this.handleClickOutside);
  }

  componentWillUnmount() {
    document.removeEventListener("mousedown", this.handleClickOutside);
  }

  handleClickOutside = event => {
    // IF exists the Ref of the wrapped component AND his dom children doesnt have the clicked component 
    if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
      // A props callback for the ClikedClickedOutside
      this.props.onClickedOutside();
    }
  };

  render() {
    // In this piece of code I'm trying to get to the first not functional component
    // Because it wouldn't work if use a functional component (like <Fade/> from react-reveal)
    let firstNotFunctionalComponent = this.props.children;
    while (typeof firstNotFunctionalComponent.type === "function") {
      firstNotFunctionalComponent = firstNotFunctionalComponent.props.children;
    }

    // Here I'm cloning the element because I have to pass a new prop, the "reference" 
    const children = React.cloneElement(firstNotFunctionalComponent, {
      ref: node => {
        this.wrapperRef = node;
      },
      // Keeping all the old props with the new element
      ...firstNotFunctionalComponent.props
    });

    return <React.Fragment>{children}</React.Fragment>;
  }
}

Changing Shell Text Color (Windows)

Try to look at the following link: Python | change text color in shell

Or read here: http://bytes.com/topic/python/answers/21877-coloring-print-lines

In general solution is to use ANSI codes while printing your string.

There is a solution that performs exactly what you need.

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

You can also edit the config.xml file in your JENKINS_HOME directory. Use c32hedge's response as a reference and set the workspace location to whatever you want between the tags

Counting Chars in EditText Changed Listener

how about just getting the length of char in your EditText and display it?

something along the line of

tv.setText(s.length() + " / " + String.valueOf(charCounts));

How to convert CSV to JSON in Node.js

You can try to use underscore.js

First convert the lines in arrays using the toArray function :

var letters = _.toArray(a,b,c,d);
var numbers = _.toArray(1,2,3,4);

Then object the arrays together using the object function :

var json = _.object(letters, numbers);

By then, the json var should contain something like :

{"a": 1,"b": 2,"c": 3,"d": 4}

Why is my toFixed() function not working?

Your conversion data is response[25] and follow the below steps.

var i = parseFloat(response[25]).toFixed(2)
console.log(i)//-6527.34

matplotlib error - no module named tkinter

For Windows users, there's no need to download the installer again. Just do the following:

  1. Go to start menu, type Apps & features,
  2. Search for "python" in the search box,
  3. Select the Python version (e.g. Python 3.8.3rc1(32-bit)) and click Modify,
  4. On the Modify Setup page click Modify,
  5. Tick td/tk and IDLE checkbox (which installs tkinter) and click next.

Wait for installation and you're done.

Sort an ArrayList based on an object field

You can use the Bean Comparator to sort on any property in your custom class.

Quick way to list all files in Amazon S3 bucket?

After zach I would also recommend boto, but I needed to make a slight difference to his code:

conn = boto.connect_s3('access-key', 'secret'key')
bucket = conn.lookup('bucket-name')
for key in bucket:
    print key.name

How to copy data to clipboard in C#

Clipboard.SetText("hello");

You'll need to use the System.Windows.Forms or System.Windows namespaces for that.

How do I comment out a block of tags in XML?

In Notepad++ you can select few lines and use CTRL+Q which will automaticaly make block comments for selected lines.

MySQL JOIN the most recent row only?

You can also do this

SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
FROM      customer c
LEFT JOIN  (
              SELECT * FROM  customer_data ORDER BY id DESC
          ) customer_data ON (customer_data.customer_id = c.customer_id)
GROUP BY  c.customer_id          
WHERE     CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%' 
LIMIT     10, 20;

Python speed testing - Time Difference - milliseconds

start = datetime.now() 

#code for which response time need to be measured.

end = datetime.now()
dif = end - start
dif_micro = dif.microseconds # time in microseconds
dif_millis = dif.microseconds / 1000 # time in millisseconds

MySQL high CPU usage

As this is the top post if you google for MySQL high CPU usage or load, I'll add an additional answer:

On the 1st of July 2012, a leap second was added to the current UTC-time to compensate for the slowing rotation of the earth due to the tides. When running ntp (or ntpd) this second was added to your computer's/server's clock. MySQLd does not seem to like this extra second on some OS'es, and yields a high CPU load. The quick fix is (as root):

$ /etc/init.d/ntpd stop
$ date -s "`date`"
$ /etc/init.d/ntpd start

Is there a macro to conditionally copy rows to another worksheet?

If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?

How to generate all permutations of a list?

And in Python 2.6 onwards:

import itertools
itertools.permutations([1,2,3])

(returned as a generator. Use list(permutations(l)) to return as a list.)

Get the current cell in Excel VB

If you're trying to grab a range with a dynamically generated string, then you just have to build the string like this:

Range(firstcol & firstrow & ":" & secondcol & secondrow).Select

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

For people who find this when attempting to run tests because via npm test or ng test using Karma or whatever else. Your .spec module needs a special router testing import to be able to build.

import { RouterTestingModule } from '@angular/router/testing';

TestBed.configureTestingModule({
    imports: [RouterTestingModule],
    declarations: [AppComponent],
});

http://www.kirjai.com/ng2-component-testing-routerlink-routeroutlet/

make arrayList.toArray() return more specific types

Like this:

List<String> list = new ArrayList<String>();

String[] a = list.toArray(new String[0]);

Before Java6 it was recommended to write:

String[] a = list.toArray(new String[list.size()]);

because the internal implementation would realloc a properly sized array anyway so you were better doing it upfront. Since Java6 the empty array is preferred, see .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?

If your list is not properly typed you need to do a cast before calling toArray. Like this:

    List l = new ArrayList<String>();

    String[] a = ((List<String>)l).toArray(new String[l.size()]);

Deploying my application at the root in Tomcat

Adding on to @Rob Hruska's sol, this setting in server.xml inside section works:

<Context path="" docBase="gateway" reloadable="true" override="true"> </Context>

Note: override="true" might be required in some cases.

Hyper-V: Create shared folder between host and guest with internal network

  • Open Hyper-V Manager
  • Create a new internal virtual switch (e.g. "Internal Network Connection")
  • Go to your Virtual Machine and create a new Network Adapter -> choose "Internal Network Connection" as virtual switch
  • Start the VM
  • Assign both your host as well as guest an IP address as well as a Subnet mask (IP4, e.g. 192.168.1.1 (host) / 192.168.1.2 (guest) and 255.255.255.0)
  • Open cmd both on host and guest and check via "ping" if host and guest can reach each other (if this does not work disable/enable the network adapter via the network settings in the control panel, restart...)
  • If successfull create a folder in the VM (e.g. "VMShare"), right-click on it -> Properties -> Sharing -> Advanced Sharing -> checkmark "Share this folder" -> Permissions -> Allow "Full Control" -> Apply
  • Now you should be able to reach the folder via the host -> to do so: open Windows Explorer -> enter the path to the guest (\192.168.1.xx...) in the address line -> enter the credentials of the guest (Choose "Other User" - it can be necessary to change the domain therefore enter ".\"[username] and [password])

There is also an easy way for copying via the clipboard:

  • If you start your VM and go to "View" you can enable "Enhanced Session". If you do it is not possible to drag and drop but to copy and paste.

Enhanced Session

Manually install Gradle and use it in Android Studio

Assume, you have installed the latest gradle once. But, If your particular project gradle version not match with the gradle version that already installed in the machine, the gradle sycn want to download that version. To prevent this download there is one trick. First You have to know the gradle version that already installed in your machine. Go to : C:\Users{username}.gradle\wrapper\dists, here you see the versions allready installed, remember the latest version, assume it is gradle-6.1.1-all.zip . Now, come back to Android Studio. In your Opened project, navigate Android Studio's project tree, open the file gradle/wrapper/gradle-wrapper.properties. Change this entry:

distributionUrl=http\://services.gradle.org/distributions/gradle-6.1.1-all.zip

This way we prevent downloading the gradle again and again. But avoid this thing, if the version really old. If that, you will find this warning :

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.1.1/userguide/command_line_interface.html#sec:command_line_warnings

No space left on device

Maybe you are out of inodes. Try df -i

                     2591792  136322 2455470    6% /home
/dev/sdb1            1887488 1887488       0  100% /data

Disk used 6% but inode table full.

How to convert time milliseconds to hours, min, sec format in JavaScript?

I needed time only up to one day, 24h, this was my take:

_x000D_
_x000D_
const milliseconds = 5680000;_x000D_
_x000D_
const hours = `0${new Date(milliseconds).getHours() - 1}`.slice(-2);_x000D_
const minutes = `0${new Date(milliseconds).getMinutes()}`.slice(-2);_x000D_
const seconds = `0${new Date(milliseconds).getSeconds()}`.slice(-2);_x000D_
_x000D_
const time = `${hours}:${minutes}:${seconds}`_x000D_
console.log(time);
_x000D_
_x000D_
_x000D_

you could get days this way as well if needed.

How to detect if a browser is Chrome using jQuery?

Sadly due to Opera's latest update !!window.chrome (and other tests on the window object) when testing in Opera returns true.

Conditionizr takes care of this for you and solves the Opera issue:

conditionizr.add('chrome', [], function () {
    return !!window.chrome && !/opera|opr/i.test(navigator.userAgent);
});

I'd highly suggest using it as none of the above are now valid.

This allows you to do:

if (conditionizr.chrome) {...}

Conditionizr takes care of other browser detects and is much faster and reliable than jQuery hacks.

Resync git repo with new .gitignore file

I know this is an old question, but gracchus's solution doesn't work if file names contain spaces. VonC's solution to file names with spaces is to not remove them utilizing --ignore-unmatch, then remove them manually, but this will not work well if there are a lot.

Here is a solution that utilizes bash arrays to capture all files.

# Build bash array of the file names
while read -r file; do 
    rmlist+=( "$file" )
done < <(git ls-files -i --exclude-standard)

git rm –-cached "${rmlist[@]}"

git commit -m 'ignore update'

Apache Tomcat :java.net.ConnectException: Connection refused

I've seen a lot of inadequate answers while trying to figure this one out. General response has been "you are trying to stop something that hasn't started" or "some other program is running on the port you need".

The problem for me turned out to be my firewall. I hadn't even considered this, but port 8005 (the port used for shutdown, thanks mindas), was blocked. I changed it, and now, no more error. Good luck.

How to use GROUP BY to concatenate strings in SQL Server?

An example would be

In Oracle you can use LISTAGG aggregate function.

Original records

name   type
------------
name1  type1
name2  type2
name2  type3

Sql

SELECT name, LISTAGG(type, '; ') WITHIN GROUP(ORDER BY name)
FROM table
GROUP BY name

Result in

name   type
------------
name1  type1
name2  type2; type3

Javascript loading CSV file into an array

I highly recommend looking into this plugin:

http://github.com/evanplaice/jquery-csv/

I used this for a project handling large CSV files and it handles parsing a CSV into an array quite well. You can use this to call a local file that you specify in your code, also, so you are not dependent on a file upload.

Once you include the plugin above, you can essentially parse the CSV using the following:

$.ajax({
    url: "pathto/filename.csv",
    async: false,
    success: function (csvd) {
        data = $.csv.toArrays(csvd);
    },
    dataType: "text",
    complete: function () {
        // call a function on complete 
    }
});

Everything will then live in the array data for you to manipulate as you need. I can provide further examples for handling the array data if you need.

There are a lot of great examples available on the plugin page to do a variety of things, too.

Print array elements on separate lines in Bash?

I've discovered that you can use eval to avoid using a subshell. Thus:

IFS=$'\n' eval 'echo "${my_array[*]}"'

Redeploy alternatives to JRebel

JRebel is free. Don't buy it. Select the "free" option (radio button) on the "buy" page. Then select "Social". After you sign up, you will get a fully functional JRebel license key. You can then download JRebel or use the key in your IDEs embedded version. The catch, (yes, there is a catch), you have to allow them to post on your behalf (advertise) once a month on your FB timeline or Twitter account. I gave them my twitter account, no biggie, I never use it and no one I know really uses it. So save $260.

Difference between string object and string literal

Some disassembly is always interesting...

$ cat Test.java 
public class Test {
    public static void main(String... args) {
        String abc = "abc";
        String def = new String("def");
    }
}

$ javap -c -v Test
Compiled from "Test.java"
public class Test extends java.lang.Object
  SourceFile: "Test.java"
  minor version: 0
  major version: 50
  Constant pool:
const #1 = Method  #7.#16;  //  java/lang/Object."<init>":()V
const #2 = String  #17;     //  abc
const #3 = class   #18;     //  java/lang/String
const #4 = String  #19;     //  def
const #5 = Method  #3.#20;  //  java/lang/String."<init>":(Ljava/lang/String;)V
const #6 = class   #21;     //  Test
const #7 = class   #22;     //  java/lang/Object
const #8 = Asciz   <init>;
...

{
public Test(); ...    

public static void main(java.lang.String[]);
  Code:
   Stack=3, Locals=3, Args_size=1
    0:    ldc #2;           // Load string constant "abc"
    2:    astore_1          // Store top of stack onto local variable 1
    3:    new #3;           // class java/lang/String
    6:    dup               // duplicate top of stack
    7:    ldc #4;           // Load string constant "def"
    9:    invokespecial #5; // Invoke constructor
   12:    astore_2          // Store top of stack onto local variable 2
   13:    return
}

How to encrypt and decrypt file in Android?

I had a similar problem and for encrypt/decrypt i came up with this solution:

public static byte[] generateKey(String password) throws Exception
{
    byte[] keyStart = password.getBytes("UTF-8");

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
    sr.setSeed(keyStart);
    kgen.init(128, sr);
    SecretKey skey = kgen.generateKey();
    return skey.getEncoded();
}

public static byte[] encodeFile(byte[] key, byte[] fileData) throws Exception
{

    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(fileData);

    return encrypted;
}

public static byte[] decodeFile(byte[] key, byte[] fileData) throws Exception
{
    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);

    byte[] decrypted = cipher.doFinal(fileData);

    return decrypted;
}

To save a encrypted file to sd do:

File file = new File(Environment.getExternalStorageDirectory() + File.separator + "your_folder_on_sd", "file_name");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] yourKey = generateKey("password");
byte[] filesBytes = encodeFile(yourKey, yourByteArrayContainigDataToEncrypt);
bos.write(fileBytes);
bos.flush();
bos.close();

To decode a file use:

byte[] yourKey = generateKey("password");
byte[] decodedData = decodeFile(yourKey, bytesOfYourFile);

For reading in a file to a byte Array there a different way out there. A Example: http://examples.javacodegeeks.com/core-java/io/fileinputstream/read-file-in-byte-array-with-fileinputstream/

How to check if a column exists in a datatable

For Multiple columns you can use code similar to one given below.I was just going through this and found answer to check multiple columns in Datatable.

 private bool IsAllColumnExist(DataTable tableNameToCheck, List<string> columnsNames)
    {
        bool iscolumnExist = true;
        try
        {
            if (null != tableNameToCheck && tableNameToCheck.Columns != null)
            {
                foreach (string columnName in columnsNames)
                {
                    if (!tableNameToCheck.Columns.Contains(columnName))
                    {
                        iscolumnExist = false;
                        break;
                    }
                }
            }
            else
            {
                iscolumnExist = false;
            }
        }            
        catch (Exception ex)
        {

        }
        return iscolumnExist;
    }

How do I do base64 encoding on iOS?

iOS has had built-in Base64 encoding and decoding methods (without using libresolv) since iOS 4. However, it was only declared in the iOS 7 SDK. Apple documentation states that you can use it when targeting iOS 4 and above.

NSData *myData = ... some data
NSString *base64String = [myData base64Encoding];
NSData *decodedData = [[NSData alloc] initWithBase64Encoding:base64String];

Which is the fastest algorithm to find prime numbers?

There is a 100% mathematical test that will check if a number P is prime or composite, called AKS Primality Test.

The concept is simple: given a number P, if all the coefficients of (x-1)^P - (x^P-1) are divisible by P, then P is a prime number, otherwise it is a composite number.

For instance, given P = 3, would give the polynomial:

   (x-1)^3 - (x^3 - 1)
 = x^3 + 3x^2 - 3x - 1 - (x^3 - 1)
 = 3x^2 - 3x

And the coefficients are both divisible by 3, therefore the number is prime.

And example where P = 4, which is NOT a prime would yield:

   (x-1)^4 - (x^4-1)
 = x^4 - 4x^3 + 6x^2 - 4x + 1 - (x^4 - 1)
 = -4x^3 + 6x^2 - 4x

And here we can see that the coefficients 6 is not divisible by 4, therefore it is NOT prime.

The polynomial (x-1)^P will P+1 terms and can be found using combination. So, this test will run in O(n) runtime, so I don't know how useful this would be since you can simply iterate over i from 0 to p and test for the remainder.

How do I clear inner HTML

The h1 tags unfortunately do not receive the onmouseout events.

The simple Javascript snippet below will work for all elements and uses only 1 mouse event.

Note: "The borders in the snippet are applied to provide a visual demarcation of the elements."

_x000D_
_x000D_
document.body.onmousemove = function(){ move("The dog is in its shed"); };_x000D_
_x000D_
document.body.style.border = "2px solid red";_x000D_
document.getElementById("h1Tag").style.border = "2px solid blue";_x000D_
_x000D_
function move(what) {_x000D_
    if(event.target.id == "h1Tag"){ document.getElementById("goy").innerHTML = "what"; } else { document.getElementById("goy").innerHTML = ""; }_x000D_
}
_x000D_
<h1 id="h1Tag">lalala</h1>_x000D_
<div id="goy"></div>
_x000D_
_x000D_
_x000D_

This can also be done in pure CSS by adding the hover selector css property to the h1 tag.

Shell command to sum integers, one per line?

I think AWK is what you are looking for:

awk '{sum+=$1}END{print sum}'

You can use this command either by passing the numbers list through the standard input or by passing the file containing the numbers as a parameter.

SQL select only rows with max value on a column

NOT mySQL, but for other people finding this question and using SQL, another way to resolve the problem is using Cross Apply in MS SQL

WITH DocIds AS (SELECT DISTINCT id FROM docs)

SELECT d2.id, d2.rev, d2.content
FROM DocIds d1
CROSS APPLY (
  SELECT Top 1 * FROM docs d
  WHERE d.id = d1.id
  ORDER BY rev DESC
) d2

Here's an example in SqlFiddle