Programs & Examples On #Class extensions

Modify XML existing content in C#

Well, If you want to update a node in XML, the XmlDocument is fine - you needn't use XmlTextWriter.

XmlDocument doc = new XmlDocument();
doc.Load("D:\\build.xml");
XmlNode root = doc.DocumentElement;
XmlNode myNode = root.SelectSingleNode("descendant::books");
myNode.Value = "blabla";
doc.Save("D:\\build.xml");

LINQ query on a DataTable

I realize this has been answered a few times over, but just to offer another approach:

I like to use the .Cast<T>() method, it helps me maintain sanity in seeing the explicit type defined and deep down I think .AsEnumerable() calls it anyways:

var results = from myRow in myDataTable.Rows.Cast<DataRow>() 
                  where myRow.Field<int>("RowNo") == 1 select myRow;

or

var results = myDataTable.Rows.Cast<DataRow>()
                      .FirstOrDefault(x => x.Field<int>("RowNo") == 1);

As noted in comments, no other assemblies needed as it's part of Linq (Reference)

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

Faced the same problem, I was not able to run wordpress docker container with mysql version 8 as its default authentication mechanism is caching_sha2_password instead of mysql_native_password.

In order to fix this problem we must reset default authentication mechanism to mysql_native_password.

Find my.cnf file in your mysql installation, usually on a linux machine it is at the following location - /etc/mysql

Edit my.cnf file and add following line just under heading [mysqld]

default_authentication_plugin= mysql_native_password

Save the file then log into mysql command line using root user

run command FLUSH PRIVILEGES;

Removing border from table cells

Probably you just needed this CSS rule:

table {
   border-spacing: 0px;
}

http://jsfiddle.net/Bz3Jt/3/

Docker - Cannot remove dead container

Running on Centos7 & Docker 1.8.2, I was unable to use Zgr3doo's solution to umount by devicemapper ( I think the response I got was that the volume wasn't mounted/found. )

I think I also had a similar thing happen with sk8terboi87 ? 's answer: I believe the message was that the volumes couldn't be unmounted, and it listed the specific volumes that it tried to umount in order to delete the dead containers.

What did work for me was stopping docker first, and then deleting the directories manually. I was able to determine which ones they were by the error output of previous command to delete all the dead containers.

Apologies for the vague descriptions above. I found this SO question days after I handled the dead containers. .. However, I noticed a similar pattern today:

$ sudo docker stop fervent_fermi; sudo docker rm fervent_fermi fervent_fermi
Error response from daemon: Cannot destroy container fervent_fermi: Driver devicemapper failed to remove root filesystem a11bae452da3dd776354aae311da5be5ff70ac9ebf33d33b66a24c62c3ec7f35: Device is Busy
Error: failed to remove containers: [fervent_fermi]

$ sudo systemctl docker stop
$ sudo rm -rf /var/lib/docker/devicemapper/mnt/a11bae452da3dd776354aae311da5be5ff70ac9ebf33d33b66a24c62c3ec7f35
$

I did notice, when using this approach that docker re-created the images with different names:

a11bae452da3     trend_av_docker   "bash"   2 weeks ago    Dead    compassionate_ardinghelli

This may have been due to the container being issued with restart=always, however, the container ID matches the ID of the container that previously used the volume that I force-deleted. There were no difficulties deleting this new container:

$ sudo docker rm -v compassionate_ardinghelli
compassionate_ardinghelli

How to plot all the columns of a data frame in R

With lattice:

library(lattice)

df <- data.frame(time = 1:10,
                 a = cumsum(rnorm(10)),
                 b = cumsum(rnorm(10)),
                 c = cumsum(rnorm(10)))

form <- as.formula(paste(paste(names(df)[- 1],  collapse = ' + '),  
                         'time',  sep = '~'))

xyplot(form,  data = df,  type = 'b',  outer = TRUE)

How to calculate the CPU usage of a process by PID in Linux from C?

Instead of parsing this from proc, one can use functions like getrusage() or clock_gettime() and calculate the cpu usage as a ratio or wallclock time and time the process/thread used on the cpu.

c# Image resizing to different size while preserving aspect ratio

Here's a less specific extension method that works with Image rather than doing the loading and saving for you. It also allows you to specify interpolation method and correctly renders edges when you use NearestNeighbour interpolation.

The image will be rendered within the bounds of the area you specify so you always know your output width and height. e.g:

Scaled within bounds

namespace YourApp
{
    #region Namespaces
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Drawing.Drawing2D;
    #endregion

    /// <summary>Generic helper functions related to graphics.</summary>
    public static class ImageExtensions
    {
        /// <summary>Resizes an image to a new width and height value.</summary>
        /// <param name="image">The image to resize.</param>
        /// <param name="newWidth">The width of the new image.</param>
        /// <param name="newHeight">The height of the new image.</param>
        /// <param name="mode">Interpolation mode.</param>
        /// <param name="maintainAspectRatio">If true, the image is centered in the middle of the returned image, maintaining the aspect ratio of the original image.</param>
        /// <returns>The new image. The old image is unaffected.</returns>
        public static Image ResizeImage(this Image image, int newWidth, int newHeight, InterpolationMode mode = InterpolationMode.Default, bool maintainAspectRatio = false)
        {
            Bitmap output = new Bitmap(newWidth, newHeight, image.PixelFormat);

            using (Graphics gfx = Graphics.FromImage(output))
            {
                gfx.Clear(Color.FromArgb(0, 0, 0, 0));
                gfx.InterpolationMode = mode;
                if (mode == InterpolationMode.NearestNeighbor)
                {
                    gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    gfx.SmoothingMode = SmoothingMode.HighQuality;
                }

                double ratioW = (double)newWidth / (double)image.Width;
                double ratioH = (double)newHeight / (double)image.Height;
                double ratio = ratioW < ratioH ? ratioW : ratioH;
                int insideWidth = (int)(image.Width * ratio);
                int insideHeight = (int)(image.Height * ratio);

                gfx.DrawImage(image, new Rectangle((newWidth / 2) - (insideWidth / 2), (newHeight / 2) - (insideHeight / 2), insideWidth, insideHeight));
            }

            return output;
        }
    }
}

Getting Image from API in Angular 4/5+?

angular 5 :

 getImage(id: string): Observable<Blob> {
    return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});
}

Graphical HTTP client for windows

I too have been frustrated by the lack of good graphical http clients available for Windows. So over the past couple years I've been developing one myself: I'm Only Resting, "a feature-rich WinForms-based HTTP client." It's open source (Apache License, Version 2.0) with freely available downloads.

It currently has fairly complete coverage of HTTP features except for file uploads, and it provides a very good user interface with great request and response management.

Here's a screenshot:

enter image description here
(source: swensensoftware.com)

Procedure expects parameter which was not supplied

If Template is not set (i.e. ==null), this error will be raised, too.

More comments:

If you know the parameter value by the time you add parameters, you can also use AddWithValue

The EXEC is not required. You can reference the @template parameter in the SELECT directly.

How to convert the ^M linebreak to 'normal' linebreak in a file opened in vim?

To save keystrokes, you can avoid typing Ctrl+VCtrl+M by placing this in a mapping. Just open a file containing a ^M character, yank it, and paste it into a line like this in your .vimrc:

nnoremap <Leader>d :%s/^M//g<CR>

How to insert new cell into UITableView in Swift

Use beginUpdates and endUpdates to insert a new cell when the button clicked.

As @vadian said in comment, begin/endUpdates has no effect for a single insert/delete/move operation

First of all, append data in your tableview array

Yourarray.append([labeltext])  

Then update your table and insert a new row

// Update Table Data
tblname.beginUpdates()
tblname.insertRowsAtIndexPaths([
NSIndexPath(forRow: Yourarray.count-1, inSection: 0)], withRowAnimation: .Automatic)
tblname.endUpdates()

This inserts cell and doesn't need to reload the whole table but if you get any problem with this, you can also use tableview.reloadData()


Swift 3.0

tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: yourArray.count-1, section: 0)], with: .automatic)
tableView.endUpdates()

Objective-C

[self.tblname beginUpdates];
NSArray *arr = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:Yourarray.count-1 inSection:0]];
[self.tblname insertRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tblname endUpdates];

Windows 7 environment variable not working in path

My issue turned out to be embarrassingly simple:

Restart command prompt and the new variables should update

How to iterate through a list of objects in C++

You're close.

std::list<Student>::iterator it;
for (it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;
}

Note that you can define it inside the for loop:

for (std::list<Student>::iterator it = data.begin(); it != data.end(); ++it){
    std::cout << it->name;
}

And if you are using C++11 then you can use a range-based for loop instead:

for (auto const& i : data) {
    std::cout << i.name;
}

Here auto automatically deduces the correct type. You could have written Student const& i instead.

Min / Max Validator in Angular 2 Final

This question has already been answered. I'd like to extend the answer from @amd. Sometimes you might need a default value.

For example, to validate against a specific value, I'd like to provide it as follows-

<input integerMinValue="20" >

But the minimum value of a 32 bit signed integer is -2147483648. To validate against this value, I don't like to provide it. I'd like to write as follows-

<input integerMinValue >

To achieve this you can write your directive as follows

import {Directive, Input} from '@angular/core';
import {AbstractControl, NG_VALIDATORS, ValidationErrors, Validator, Validators} from '@angular/forms';

@Directive({
    selector: '[integerMinValue]',
    providers: [{provide: NG_VALIDATORS, useExisting: IntegerMinValidatorDirective, multi: true}]
})
export class IntegerMinValidatorDirective implements Validator {

    private minValue = -2147483648;

    @Input('integerMinValue') set min(value: number) {
        if (value) {
            this.minValue = +value;
        }
    }

    validate(control: AbstractControl): ValidationErrors | null {
        return Validators.min(this.minValue)(control);
    }

}

How to remove a variable from a PHP session array

Is the $_SESSION['name'] variable an array? If you want to delete a specific key from within an array, you have to refer to that exact key in the unset() call, otherwise you delete the entire array, e.g.

$name = array(0 => 'a', 1 => 'b', 2 => 'c');
unset($name); // deletes the entire array
unset($name[1]); // deletes only the 'b' entry

Another minor problem with your snippet: You're mixing GET query parameters in with a POST form. Is there any reason why you can't do the forms with 'name' being passed in a hidden field? It's best to not mix get and post variables, especially if you use $_REQUEST elsewhere. You can run into all kinds of fun trying to figure out why $_GET['name'] isn't showing up the same as $_POST['name'], because the server's got a differnt EGPCS order set in the 'variables_order' .ini setting.

<form blah blah blah method="post">
  <input type="hidden" name="name" value="<?= htmlspecialchars($list1) ?>" />
  <input type="submit" name="add" value="Add />
</form>

And note the htmlspecialchars() call. If either $list1 or $list2 contain a double quote ("), it'll break your HTML

Run class in Jar file

You want:

java -cp myJar.jar myClass

The Documentation gives the following example:

C:> java -classpath C:\java\MyClasses\myclasses.jar utility.myapp.Cool

Java regular expression OR operator

You can just use the pipe on its own:

"string1|string2"

for example:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));

Output:

blah, blah, string3

The main reason to use parentheses is to limit the scope of the alternatives:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));

has the same output. but if you just do this:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));

you get:

blah, stringblah, string3

because you've said "string1" or "2".

If you don't want to capture that part of the expression use ?::

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));

replace NULL with Blank value or Zero in sql server

You can use the COALESCE function to automatically return null values as 0. Syntax is as shown below:

SELECT COALESCE(total_amount, 0) from #Temp1

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

Alternatively you can grant the user DROP_ANY_TABLE privilege if need be and the procedure will run as is without the need for any alteration. Dangerous maybe but depends what you're doing :)

Generate Json schema from XML schema (XSD)

Disclaimer: I am the author of Jsonix, a powerful open-source XML<->JSON JavaScript mapping library.

Today I've released the new version of the Jsonix Schema Compiler, with the new JSON Schema generation feature.

Let's take the Purchase Order schema for example. Here's a fragment:

  <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>

  <xsd:complexType name="PurchaseOrderType">
    <xsd:sequence>
      <xsd:element name="shipTo" type="USAddress"/>
      <xsd:element name="billTo" type="USAddress"/>
      <xsd:element ref="comment" minOccurs="0"/>
      <xsd:element name="items"  type="Items"/>
    </xsd:sequence>
    <xsd:attribute name="orderDate" type="xsd:date"/>
  </xsd:complexType>

You can compile this schema using the provided command-line tool:

java -jar jsonix-schema-compiler-full.jar
    -generateJsonSchema
    -p PO
    schemas/purchaseorder.xsd

The compiler generates Jsonix mappings as well the matching JSON Schema.

Here's what the result looks like (edited for brevity):

{
    "id":"PurchaseOrder.jsonschema#",
    "definitions":{
        "PurchaseOrderType":{
            "type":"object",
            "title":"PurchaseOrderType",
            "properties":{
                "shipTo":{
                    "title":"shipTo",
                    "allOf":[
                        {
                            "$ref":"#/definitions/USAddress"
                        }
                    ]
                },
                "billTo":{
                    "title":"billTo",
                    "allOf":[
                        {
                            "$ref":"#/definitions/USAddress"
                        }
                    ]
                }, ...
            }
        },
        "USAddress":{ ... }, ...
    },
    "anyOf":[
        {
            "type":"object",
            "properties":{
                "name":{
                    "$ref":"http://www.jsonix.org/jsonschemas/w3c/2001/XMLSchema.jsonschema#/definitions/QName"
                },
                "value":{
                    "$ref":"#/definitions/PurchaseOrderType"
                }
            },
            "elementName":{
                "localPart":"purchaseOrder",
                "namespaceURI":""
            }
        }
    ]
}

Now this JSON Schema is derived from the original XML Schema. It is not exactly 1:1 transformation, but very very close.

The generated JSON Schema matches the generatd Jsonix mappings. So if you use Jsonix for XML<->JSON conversion, you should be able to validate JSON with the generated JSON Schema. It also contains all the required metadata from the originating XML Schema (like element, attribute and type names).

Disclaimer: At the moment this is a new and experimental feature. There are certain known limitations and missing functionality. But I'm expecting this to manifest and mature very fast.

Links:

Linq select object from list depending on objects attribute

I assume you are getting an exception because of Single. Your list may have more than one answer marked as correct, that is why Single will throw an exception use First, or FirstOrDefault();

Answer answer = Answers.FirstOrDefault(a => a.Correct);

Also if you want to get list of all items marked as correct you may try:

List<Answer> correctedAnswers =  Answers.Where(a => a.Correct).ToList();

If your desired result is Single, then the mistake you are doing in your query is comparing an item with the bool value. Your comparison

a == a.Correct

is wrong in the statement. Your single query should be:

Answer answer = Answers.Single(a => a.Correct == true);

Or shortly as:

Answer answer = Answers.Single(a => a.Correct);

Is there a download function in jsFiddle?

Use http://jsfiddle.net//show/light/

then just use inspect element function of browser. you will get code in iframe tab. . in chrome just right click and cick on edit as html tab. and copy the html content. that is your actual code.

Parse String date in (yyyy-MM-dd) format

tl;dr

LocalDate.parse( "2013-09-18" )

… and …

myLocalDate.toString()  // Example: 2013-09-18

java.time

The Question and other Answers are out-of-date. The troublesome old legacy date-time classes are now supplanted by the java.time classes.

ISO 8601

Your input string happens to comply with standard ISO 8601 format, YYYY-MM-DD. The java.time classes use ISO 8601 formats by default when parsing and generating string representations of date-time values. So no need to specify a formatting pattern.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate ld = LocalDate.parse( "2013-09-18" );

About java.time

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

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

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

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

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

Listing all foreign keys in a db including description

    SELECT  
    i1.CONSTRAINT_NAME, i1.TABLE_NAME,i1.COLUMN_NAME,
    i1.REFERENCED_TABLE_SCHEMA,i1.REFERENCED_TABLE_NAME, i1.REFERENCED_COLUMN_NAME,
    i2.UPDATE_RULE, i2.DELETE_RULE 
    FROM   
    information_schema.KEY_COLUMN_USAGE AS i1  
    INNER JOIN 
    information_schema.REFERENTIAL_CONSTRAINTS AS i2 
    ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME 
    WHERE i1.REFERENCED_TABLE_NAME IS NOT NULL  
    AND  i1.TABLE_SCHEMA  ='db_name';

restricting to a specific column in a table table

AND i1.table_name = 'target_tb_name' AND i1.column_name = 'target_col_name'

Where does Chrome store extensions?

For my Mac, extensions were here:

~/Library/Application Support/Google/Chrome/Default/Extensions/

if you go to chrome://extensions you'll find the "ID" of each extension. That is going to be a directory within Extensions directory. It is there you'll find all of the extension's files.

How to merge two arrays in JavaScript and de-duplicate items

You can achieve it simply using Underscore.js's => uniq:

array3 = _.uniq(array1.concat(array2))

console.log(array3)

It will print ["Vijendra", "Singh", "Shakya"].

How to set 24-hours format for date on java?

Try below code

    String dateStr = "Jul 27, 2011 8:35:29 PM";
    DateFormat readFormat = new SimpleDateFormat( "MMM dd, yyyy hh:mm:ss aa");
    DateFormat writeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
    Date date = null;
    try {
       date = readFormat.parse( dateStr );
    } catch ( ParseException e ) {
        e.printStackTrace();
    }

    String formattedDate = "";
    if( date != null ) {
    formattedDate = writeFormat.format( date );
    }

    System.out.println(formattedDate);

Good Luck!!!

Check for various formats.

How to check if a std::thread is still running?

This simple mechanism you can use for detecting finishing of a thread without blocking in join method.

std::thread thread([&thread]() {
    sleep(3);
    thread.detach();
});

while(thread.joinable())
    sleep(1);

Python: How would you save a simple settings/config file?

Save and load a dictionary. You will have arbitrary keys, values and arbitrary number of key, values pairs.

How to update ruby on linux (ubuntu)?

If you are like me using ubuntu 10.10 & cant find the lastest version which is now

  • ruby1.9.3

this is where you can get it http://www.ubuntuupdates.org/package/brightbox_ruby_ng_experimental/maverick/main/base/ruby1.9.3

or download the *.deb file :)

& remember that it wont alter you old version of ruby

How do you list the primary key of a SQL Server table?

Is using MS SQL Server you can do the following:

--List all tables primary keys
select * from information_schema.table_constraints
where constraint_type = 'Primary Key'

You can also filter on the table_name column if you want a specific table.

Opening a folder in explorer and selecting a file

string windir = Environment.GetEnvironmentVariable("windir");
if (string.IsNullOrEmpty(windir.Trim())) {
    windir = "C:\\Windows\\";
}
if (!windir.EndsWith("\\")) {
    windir += "\\";
}    

FileInfo fileToLocate = null;
fileToLocate = new FileInfo("C:\\Temp\\myfile.txt");

ProcessStartInfo pi = new ProcessStartInfo(windir + "explorer.exe");
pi.Arguments = "/select, \"" + fileToLocate.FullName + "\"";
pi.WindowStyle = ProcessWindowStyle.Normal;
pi.WorkingDirectory = windir;

//Start Process
Process.Start(pi)

How to ignore conflicts in rpm installs

From the context, the conflict was caused by the version of the package.
Let's take a look the manual about rpm:

--force
    Same as using --replacepkgs, --replacefiles, and --oldpackage.

--oldpackage
    Allow an upgrade to replace a newer package with an older one.

So, you can execute the command rpm -Uvh info-4.13a-2.rpm --force to solve your issue.

How to check whether a string is a valid HTTP URL?

Uri uri = null;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri) || null == uri)
    return false;
else
    return true;

Here url is the string you have to test.

Difference between two DateTimes C#?

Are you perhaps looking for:

int Difference = (a-b).Hours;

How to pass List from Controller to View in MVC 3

Passing data to view is simple as passing object to method. Take a look at Controller.View Method

protected internal ViewResult View(
    Object model
)

Something like this

//controller

List<MyObject> list = new List<MyObject>();

return View(list);


//view

@model List<MyObject>

// and property Model is type of List<MyObject>

@foreach(var item in Model)
{
    <span>@item.Name</span>
}

Placing a textview on top of imageview in android

you can try this too. I use just framelayout.

 <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/cover"
                android:gravity="bottom">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:text="Hello !"
                    android:id="@+id/welcomeTV"
                    android:textColor="@color/textColor"
                    android:layout_gravity="left|bottom" />
            </FrameLayout>

gem install: Failed to build gem native extension (can't find header files)

My initial solution was to resolve the above errors by installing ruby-devel, patch and rubygems.

My issue was a bit different as bcrypt 3.1.11 still had issues compiling and installing on Fedora 23. I needed additional packages. So after ensuring I had the above installed, I was still having issues:

gcc: error: conftest.c: No such file or directory

gcc: error: /usr/lib/rpm/redhat/redhat-hardened-cc1: No such file or directory

From here I had to do the following:

  • I ensured that I wasn't lacking any C compiler tools sudo dnf group install "C Development Tools and Libraries"

  • Then I ran sudo dnf install redhat-rpm-config to resolve the gcc issue listed above.

You can find a write up here on Fedore Project. You may also find answers to other needs as well.

Uncaught SyntaxError: Unexpected token with JSON.parse

You should validate your JSON string here.

A valid JSON string must have double quotes around the keys:

JSON.parse({"u1":1000,"u2":1100})       // will be ok

If there are no quotes, it will cause an error:

JSON.parse({u1:1000,u2:1100})    
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2

Using single quotes will also cause an error:

JSON.parse({'u1':1000,'u2':1100})    
// error Uncaught SyntaxError: Unexpected token ' in JSON at position 1

Javascript variable access in HTML

<html>
<head>
<script>
    function putText() {
        var simpleText = "hello_world";
        var finalSplitText = simpleText.split("_");
        var splitText = finalSplitText[0];
        document.getElementById("destination").innerHTML = "I need the value of " + splitText + " variable here";
    }
</script>
</head>
<body onLoad = putText()>
    <a id="destination" href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>

How do I link a JavaScript file to a HTML file?

You can add script tags in your HTML document, ideally inside the which points to your javascript files. Order of the script tags are important. Load the jQuery before your script files if you want to use jQuery from your script.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="relative/path/to/your/javascript.js"></script>

Then in your javascript file you can refer to jQuery either using $ sign or jQuery. Example:

jQuery.each(arr, function(i) { console.log(i); }); 

Remove portion of a string after a certain character

Below is the most efficient method (by run-time) to cut off everything after the first By in a string. If By does not exist, the full string is returned. The result is in $sResult.

$sInputString = "Posted On April 6th By Some Dude";
$sControl = "By";

//Get Position Of 'By'
$iPosition = strpos($sInputString, " ".$sControl);
if ($iPosition !== false)
  //Cut Off If String Exists
  $sResult = substr($sInputString, 0, $iPosition);
else
  //Deal With String Not Found
  $sResult = $sInputString;

//$sResult = "Posted On April 6th"

If you don't want to be case sensitive, use stripos instead of strpos. If you think By might exist more than once and want to cut everything after the last occurrence, use strrpos.

Below is a less efficient method but it takes up less code space. This method is also more flexible and allows you to do any regular expression.

$sInputString = "Posted On April 6th By Some Dude";
$pControl = "By";

$sResult = preg_replace("' ".$pControl.".*'s", '', $sInputString);

//$sResult = "Posted On April 6th"

For example, if you wanted to remove everything after the day:

$sInputString = "Posted On April 6th By Some Dude";
$pControl = "[0-9]{1,2}[a-z]{2}"; //1 or 2 numbers followed by 2 lowercase letters.

$sResult = preg_replace("' ".$pControl.".*'s", '', $sInputString);

//$sResult = "Posted On April"

For case insensitive, add the i modifier like this:

$sResult = preg_replace("' ".$pControl.".*'si", '', $sInputString);

To get everything past the last By if you think there might be more than one, add an extra .* at the beginning like this:

$sResult = preg_replace("'.* ".$pControl.".*'si", '', $sInputString);

But here is also a really powerful way you can use preg_match to do what you may be trying to do:

$sInputString = "Posted On April 6th By Some Dude";

$pPattern = "'Posted On (.*?) By (.*?)'s";
if (preg_match($pPattern, $sInputString, $aMatch)) {
  //Deal With Match
  //$aMatch[1] = "April 6th"
  //$aMatch[2] = "Some Dude"
} else {
  //No Match Found
}

Regular expressions might seem confusing at first but they can be really powerful and your best friend once you master them! Good luck!

Overwriting txt file in java

This simplifies it a bit and it behaves as you want it.

FileWriter f = new FileWriter("../playlist/"+existingPlaylist.getText()+".txt");

try {
 f.write(source);
 ...
} catch(...) {
} finally {
 //close it here
}

NSURLErrorDomain error codes description

The NSURLErrorDomain error codes are listed here https://developer.apple.com/documentation/foundation/1508628-url_loading_system_error_codes

However, 400 is just the http status code (http://www.w3.org/Protocols/HTTP/HTRESP.html) being returned which means you've got something wrong with your request.

Debug/run standard java in Visual Studio Code IDE and OS X?

I can tell you for Windows.

  1. Install Java Extension Pack and Code Runner Extension from VS Code Extensions.

  2. Edit your java home location in VS Code settings, "java.home": "C:\\Program Files\\Java\\jdk-9.0.4".

  3. Check if javac is recognized in VS Code internal terminal. If this check fails, try opening VS Code as administrator.

  4. Create a simple Java program in Main.java file as:

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world");     
    }
}

Note: Do not add package in your main class.

  1. Right click anywhere on the java file and select run code.

  2. Check the output in the console.

Done, hope this helps.

Difference between map and collect in Ruby?

The collect and collect! methods are aliases to map and map!, so they can be used interchangeably. Here is an easy way to confirm that:

Array.instance_method(:map) == Array.instance_method(:collect)
 => true

Add leading zeroes/0's to existing Excel values to certain length

The more efficient (less obtrusive) way of doing this is through custom formatting.

  1. Highlight the column/array you want to style.
  2. Click ctrl + 1 or Format -> Format Cells.
  3. In the Number tab, choose Custom.
  4. Set the Custom formatting to 000#. (zero zero zero #)

Note that this does not actually change the value of the cell. It only displays the leading zeroes in the worksheet.

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

I was having similar issues connecting to OpenSUSE 13.1 MySQL database with LibreOffice. Update LibreOffice to latest stable "Still" package, then make sure the database is accessible using a tool such as phpMyAdmin. Make sure your user is linked to localhost and not "%" (any). This worked for me, I am able to add data thru LibreOffice.

Side note - LibreOffice Base will not supply "native connection" via MySQL on first attempt, you will need to use the back button, then try again to see the options.

Hope this helps.

CodeIgniter: Load controller within controller

Just use

..............

self::index();

..............

How to Execute stored procedure from SQL Plus?

You have two options, a PL/SQL block or SQL*Plus bind variables:

var z number

execute  my_stored_proc (-1,2,0.01,:z)

print z

Moment js date time comparison

for date-time comparison, you can use valueOf function of the moment which provides milliseconds of the date-time, which is best for comparison:

_x000D_
_x000D_
let date1 = moment('01-02-2020','DD-MM-YYYY').valueOf()_x000D_
let date2 = moment('11-11-2012','DD-MM-YYYY').valueOf()_x000D_
_x000D_
//     alert((date1 > date2 ? 'date1' : 'date2') + " is greater..."  )_x000D_
_x000D_
if (date1 > date2) {_x000D_
   alert("date1 is greater..." )_x000D_
} else {_x000D_
   alert("date2 is greater..." )_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Deleting all files from a folder using PHP?

Posted a general purpose file and folder handling class for copy, move, delete, calculate size, etc., that can handle a single file or a set of folders.

https://gist.github.com/4689551

To use:

To copy (or move) a single file or a set of folders/files:

$files = new Files();
$results = $files->copyOrMove('source/folder/optional-file', 'target/path', 'target-file-name-for-single-file.only', 'copy');

Delete a single file or all files and folders in a path:

$files = new Files();
$results = $files->delete('source/folder/optional-file.name');

Calculate the size of a single file or a set of files in a set of folders:

$files = new Files();
$results = $files->calculateSize('source/folder/optional-file.name');

What is the use of printStackTrace() method in Java?

I was kind of curious about this too, so I just put together a little sample code where you can see what it is doing:

try {
    throw new NullPointerException();
}
catch (NullPointerException e) {
    System.out.println(e);
}

try {
    throw new IOException();
}
catch (IOException e) {
    e.printStackTrace();
}
System.exit(0);

Calling println(e):

java.lang.NullPointerException

Calling e.printStackTrace():

java.io.IOException
      at package.Test.main(Test.java:74)

How to add element in Python to the end of list using list.insert?

You'll have to pass the new ordinal position to insert using len in this case:

In [62]:

a=[1,2,3,4]
a.insert(len(a),5)
a
Out[62]:
[1, 2, 3, 4, 5]

AJAX cross domain call

You can use YQL to do the request without needing to host your own proxy. I have made a simple function to make it easier to run commands:

function RunYQL(command, callback){
     callback_name = "__YQL_callback_"+(new Date()).getTime();
     window[callback_name] = callback;
     a = document.createElement('script');
     a.src = "http://query.yahooapis.com/v1/public/yql?q="
             +escape(command)+"&format=json&callback="+callback_name;
     a.type = "text/javascript";
     document.getElementsByTagName("head")[0].appendChild(a);
}

If you have jQuery, you may use $.getJSON instead.

A sample may be this:

RunYQL('select * from html where url="http://www.google.com/"',
       function(data){/* actions */}
);

socket.error: [Errno 48] Address already in use

I am new to Python, but after my brief research I found out that this is typical of sockets being binded. It just so happens that the socket is still being used and you may have to wait to use it. Or, you can just add:

tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

This should make the port available within a shorter time. In my case, it made the port available almost immediately.

Do I really need to encode '&' as '&amp;'?

The link has a fairly good example of when and why you may need to escape & to &amp;

https://jsfiddle.net/vh2h7usk/1/

Interestingly, I had to escape the character in order to represent it properly in my answer here. If I were to use the built-in code sample option (from the answer panel), I can just type in &amp; and it appears as it should. But if I were to manually use the <code></code> element, then I have to escape in order to represent it correctly :)

Is there any way to wait for AJAX response and halt execution?

When using promises they can be used in a promise chain. async=false will be deprecated so using promises is your best option.

function functABC() {
  return new Promise(function(resolve, reject) {
    $.ajax({
      url: 'myPage.php',
      data: {id: id},
      success: function(data) {
        resolve(data) // Resolve promise and go to then()
      },
      error: function(err) {
        reject(err) // Reject the promise and go to catch()
      }
    });
  });
}

functABC().then(function(data) {
  // Run this when your request was successful
  console.log(data)
}).catch(function(err) {
  // Run this when promise was rejected via reject()
  console.log(err)
})

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

To solve this problem you should use drawable -> new -> image asset and then add your images. You will then find the mipmap folder contains your images, and you can use it by @mibmab/img.

Why do I get access denied to data folder when using adb?

I had a lot of trouble with this also. I still don't fully understand the permission and root run, but this worked for me (one of the previous answers partly) to copy database file from /data/data/[package name]/databases/my_db.db . Running shell root, or su in shell for some reason didn't work, nor did copying the db file (I could navigate to the directory though), nor did sqlite3.

So, this worked! In DOS command prompt:

C:\Program Files\Android\android-sdk\platform-tools>adb shell
1|shell@android:/ $ run-as de.vogella.android.locationapi.maps
run-as de.vogella.android.locationapi.maps
1|shell@android:/data/data/de.vogella.android.locationapi.maps $ cd /data
cd /data
shell@android:/data $ cd data
cd data
shell@android:/data/data $ cd de.vogella.android.locationapi.maps
cd de.vogella.android.locationapi.maps
shell@android:/data/data/de.vogella.android.locationapi.maps $ cd databases
cd databases
shell@android:/data/data/de.vogella.android.locationapi.maps/databases $ ls
ls
bus_timetable_lines.db
bus_timetable_lines.db-journal
shell@android:/data/data/de.vogella.android.locationapi.maps/databases $ cat bus
_timetable_lines.db > /sdcard/db_copy.db
 bus_timetable_lines.db > /sdcard/db_copy.db                                   <
shell@android:/data/data/de.vogella.android.locationapi.maps/databases $exit   ^
exit
shell@android:/ $ exit
exit

C:\Program Files\Android\android-sdk\platform-tools>

Now go to SDCARD directory and get your file db_copy.db . Even that was hidden, but I managed to email it. Back in Windows, I was able to open db file with SQLite Database Browser. :)

Splitting a table cell into two columns in HTML

Please try this way.

<table border="1">
    <tr>
        <th scope="col">Header</th>
        <th scope="col">Header</th>
        <th colspan="2">Header</th>
    </tr> 
    <tr>
        <td scope="row">&nbsp;</td>
        <td scope="row">&nbsp;</td>
        <td scope="col">Split this one</td>
        <td scope="col">into two columns</td>
    </tr>
</table>

com.microsoft.sqlserver.jdbc.SQLServerDriver not found error

You are looking at sqljdbc4.2 version like :

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

but, for sqljdbc4 version statement should be:

Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

I think if you change your first version to write the correct Class.forName , your application will run.

Catch an exception thrown by an async void method

Your code doesn't do what you might think it does. Async methods return immediately after the method begins waiting for the async result. It's insightful to use tracing in order to investigate how the code is actually behaving.

The code below does the following:

  • Create 4 tasks
  • Each task will asynchronously increment a number and return the incremented number
  • When the async result has arrived it is traced.

 

static TypeHashes _type = new TypeHashes(typeof(Program));        
private void Run()
{
    TracerConfig.Reset("debugoutput");

    using (Tracer t = new Tracer(_type, "Run"))
    {
        for (int i = 0; i < 4; i++)
        {
            DoSomeThingAsync(i);
        }
    }
    Application.Run();  // Start window message pump to prevent termination
}


private async void DoSomeThingAsync(int i)
{
    using (Tracer t = new Tracer(_type, "DoSomeThingAsync"))
    {
        t.Info("Hi in DoSomething {0}",i);
        try
        {
            int result = await Calculate(i);
            t.Info("Got async result: {0}", result);
        }
        catch (ArgumentException ex)
        {
            t.Error("Got argument exception: {0}", ex);
        }
    }
}

Task<int> Calculate(int i)
{
    var t = new Task<int>(() =>
    {
        using (Tracer t2 = new Tracer(_type, "Calculate"))
        {
            if( i % 2 == 0 )
                throw new ArgumentException(String.Format("Even argument {0}", i));
            return i++;
        }
    });
    t.Start();
    return t;
}

When you observe the traces

22:25:12.649  02172/02820 {          AsyncTest.Program.Run 
22:25:12.656  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.657  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 0    
22:25:12.658  02172/05220 {          AsyncTest.Program.Calculate    
22:25:12.659  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.659  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 1    
22:25:12.660  02172/02756 {          AsyncTest.Program.Calculate    
22:25:12.662  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.662  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 2    
22:25:12.662  02172/02820 {          AsyncTest.Program.DoSomeThingAsync     
22:25:12.662  02172/02820 Information AsyncTest.Program.DoSomeThingAsync Hi in DoSomething 3    
22:25:12.664  02172/02756          } AsyncTest.Program.Calculate Duration 4ms   
22:25:12.666  02172/02820          } AsyncTest.Program.Run Duration 17ms  ---- Run has completed. The async methods are now scheduled on different threads. 
22:25:12.667  02172/02756 Information AsyncTest.Program.DoSomeThingAsync Got async result: 1    
22:25:12.667  02172/02756          } AsyncTest.Program.DoSomeThingAsync Duration 8ms    
22:25:12.667  02172/02756 {          AsyncTest.Program.Calculate    
22:25:12.665  02172/05220 Exception   AsyncTest.Program.Calculate Exception thrown: System.ArgumentException: Even argument 0   
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     
22:25:12.668  02172/02756 Exception   AsyncTest.Program.Calculate Exception thrown: System.ArgumentException: Even argument 2   
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     
22:25:12.724  02172/05220          } AsyncTest.Program.Calculate Duration 66ms      
22:25:12.724  02172/02756          } AsyncTest.Program.Calculate Duration 57ms      
22:25:12.725  02172/05220 Error       AsyncTest.Program.DoSomeThingAsync Got argument exception: System.ArgumentException: Even argument 0  

Server stack trace:     
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     

Exception rethrown at [0]:      
   at System.Runtime.CompilerServices.TaskAwaiter.EndAwait()    
   at System.Runtime.CompilerServices.TaskAwaiter`1.EndAwait()  
   at AsyncTest.Program.DoSomeThingAsyncd__8.MoveNext() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 106    
22:25:12.725  02172/02756 Error       AsyncTest.Program.DoSomeThingAsync Got argument exception: System.ArgumentException: Even argument 2  

Server stack trace:     
   at AsyncTest.Program.c__DisplayClassf.Calculateb__e() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 124   
   at System.Threading.Tasks.Task`1.InvokeFuture(Object futureAsObj)    
   at System.Threading.Tasks.Task.InnerInvoke()     
   at System.Threading.Tasks.Task.Execute()     

Exception rethrown at [0]:      
   at System.Runtime.CompilerServices.TaskAwaiter.EndAwait()    
   at System.Runtime.CompilerServices.TaskAwaiter`1.EndAwait()  
   at AsyncTest.Program.DoSomeThingAsyncd__8.MoveNext() in C:\Source\AsyncTest\AsyncTest\Program.cs:line 0      
22:25:12.726  02172/05220          } AsyncTest.Program.DoSomeThingAsync Duration 70ms   
22:25:12.726  02172/02756          } AsyncTest.Program.DoSomeThingAsync Duration 64ms   
22:25:12.726  02172/05220 {          AsyncTest.Program.Calculate    
22:25:12.726  02172/05220          } AsyncTest.Program.Calculate Duration 0ms   
22:25:12.726  02172/05220 Information AsyncTest.Program.DoSomeThingAsync Got async result: 3    
22:25:12.726  02172/05220          } AsyncTest.Program.DoSomeThingAsync Duration 64ms   

You will notice that the Run method completes on thread 2820 while only one child thread has finished (2756). If you put a try/catch around your await method you can "catch" the exception in the usual way although your code is executed on another thread when the calculation task has finished and your contiuation is executed.

The calculation method traces the thrown exception automatically because I did use the ApiChange.Api.dll from the ApiChange tool. Tracing and Reflector helps a lot to understand what is going on. To get rid of threading you can create your own versions of GetAwaiter BeginAwait and EndAwait and wrap not a task but e.g. a Lazy and trace inside your own extension methods. Then you will get much better understanding what the compiler and what the TPL does.

Now you see that there is no way to get in a try/catch your exception back since there is no stack frame left for any exception to propagate from. Your code might be doing something totally different after you did initiate the async operations. It might call Thread.Sleep or even terminate. As long as there is one foreground thread left your application will happily continue to execute asynchronous tasks.


You can handle the exception inside the async method after your asynchronous operation did finish and call back into the UI thread. The recommended way to do this is with TaskScheduler.FromSynchronizationContext. That does only work if you have an UI thread and it is not very busy with other things.

How to install SignTool.exe for Windows 10

Best solution end of 2020:

Just download Windows 10 SDK from Microsoft here:
https://go.microsoft.com/fwlink/?LinkID=698771

In setup, choose only Windows App Certification App (it's only 120 MB)

enter image description here

You can find signtool.exe here:
%PROGRAMFILES(X86)%\Windows Kits\10\bin\x64

Cheers!

How to convert 'binary string' to normal string in Python3?

Decode it.

>>> b'a string'.decode('ascii')
'a string'

To get bytes from string, encode it.

>>> 'a string'.encode('ascii')
b'a string'

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

         ` Adding the following to pom.xml will resolve the issue.      <pluginRepositories>
        <pluginRepository>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
            <layout>default</layout>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <releases>
                <updatePolicy>never</updatePolicy>
            </releases>
        </pluginRepository>
   </pluginRepositories>
    
   <repositories>
        <repository>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
            <layout>default</layout>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
   </repositories>   `

C++ String Declaring

using the standard <string> header

std::string Something = "Some Text";

http://www.dreamincode.net/forums/topic/42209-c-strings/

What size do you use for varchar(MAX) in your parameter declaration?

For those of us who did not see -1 by Michal Chaniewski, the complete line of code:

cmd.Parameters.Add("@blah",SqlDbType.VarChar,-1).Value = "some large text";

installing cPickle with python 3.5

cPickle comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle, you can do this:

>>> import _pickle as cPickle

However, in 3.x, it's easier just to use pickle.

No need to install anything. If something requires cPickle in python 3.x, then that's probably a bug.

Select first row in each GROUP BY group?

In Postgres you can use array_agg like this:

SELECT  customer,
        (array_agg(id ORDER BY total DESC))[1],
        max(total)
FROM purchases
GROUP BY customer

This will give you the id of each customer's largest purchase.

Some things to note:

  • array_agg is an aggregate function, so it works with GROUP BY.
  • array_agg lets you specify an ordering scoped to just itself, so it doesn't constrain the structure of the whole query. There is also syntax for how you sort NULLs, if you need to do something different from the default.
  • Once we build the array, we take the first element. (Postgres arrays are 1-indexed, not 0-indexed).
  • You could use array_agg in a similar way for your third output column, but max(total) is simpler.
  • Unlike DISTINCT ON, using array_agg lets you keep your GROUP BY, in case you want that for other reasons.

Android: long click on a button -> perform actions

To get both functions working for a clickable image that will respond to both short and long clicks, I tried the following that seems to work perfectly:

    image = (ImageView) findViewById(R.id.imageViewCompass);
    image.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            shortclick();
        }
     });

    image.setOnLongClickListener(new View.OnLongClickListener() {
    public boolean onLongClick(View v) {
        longclick();
        return true;
    }
});

//Then the functions that are called:

 public void shortclick()
{
 Toast.makeText(this, "Why did you do that? That hurts!!!", Toast.LENGTH_LONG).show();

}

 public void longclick()
{
 Toast.makeText(this, "Why did you do that? That REALLY hurts!!!", Toast.LENGTH_LONG).show();

}

It seems that the easy way of declaring the item in XML as clickable and then defining a function to call on the click only applies to short clicks - you must have a listener to differentiate between short and long clicks.

LDAP root query syntax to search more than one specific OU

It's simple. Just change the port. Use 3268 instead of 389. If your domain name DOMAIN.LOCAL, in search put DC=DOMAIN,DC=LOCAL

Port 3268: This port is used for queries that are specifically targeted for the global catalog. LDAP requests sent to port 3268 can be used to search objects in the entire forest. However, only the attributes marked for replication to the global catalog can be returned.

Port 389: This port is used for requesting information from the Domain Controller. LDAP requests sent to port 389 can be used to search objects only within the global catalog’s home domain. However, the application can possible to obtain all of the attributes searched objects.

What is the proper way to display the full InnerException?

Just use exception.ToString()

http://msdn.microsoft.com/en-us/library/system.exception.tostring.aspx

The default implementation of ToString obtains the name of the class that threw the current exception, the message, the result of calling ToString on the inner exception, and the result of calling Environment.StackTrace. If any of these members is null, its value is not included in the returned string.

If there is no error message or if it is an empty string (""), then no error message is returned. The name of the inner exception and the stack trace are returned only if they are not null.

exception.ToString() will also call .ToString() on that exception's inner exception, and so on...

How to print the full NumPy array, without truncation?

Use numpy.set_printoptions:

import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)

How do you format code on save in VS Code

To automatically format code on save:

  • Press Ctrl , to open user preferences
  • Enter the following code in the opened settings file

    {
        "editor.formatOnSave": true
    }
    
  • Save file

Source

How to get back to the latest commit after checking out a previous commit?

git checkout master

master is the tip, or the last commit. gitk will only show you up to where you are in the tree at the time. git reflog will show all the commits, but in this case, you just want the tip, so git checkout master.

Where can I get a list of Ansible pre-defined variables?

I use this simple playbook:

---
# vars.yml
#
# Shows the value of all variables/facts.
#
# Example:
#
#   ansible-playbook vars.yml -e 'hosts=localhost'
#
- hosts: localhost
  tasks:
    - fail: "You must specify a value for `hosts` variable - e.g.: ansible-playbook vars.yml -e 'hosts=localhost'"
      when: hosts is not defined

- hosts: "{{ hosts }}"
  tasks:
    - debug: var=vars
    - debug: var=hostvars[inventory_hostname]

Equivalent to 'app.config' for a library (DLL)

In response to the original question, I typically add the config file in my test project as a link; you can then use the DeploymentItem attribute to addit to the Out folder of the test run.

[TestClass]
[DeploymentItem("MyProject.Cache.dll.config")]
public class CacheTest
{
    .
    .
    .
    .
}

In response to the comments that Assemblies can't be project specific, they can and it provides great flexibility esp. when working with IOC frameworks.

I lose my data when the container exits

the similar problem (and no way Dockerfile alone could fix it) brought me to this page.

stage 0: for all, hoping Dockerfile could fix it: until --dns and --dns-search will appear in Dockerfile support - there is no way to integrate intranet based resources into.

stage 1: after building image using Dockerfile (by the way it's a serious glitch Dockerfile must be in the current folder), having an image to deploy what's intranet based, by running docker run script. example: docker run -d \ --dns=${DNSLOCAL} \ --dns=${DNSGLOBAL} \ --dns-search=intranet \ -t pack/bsp \ --name packbsp-cont \ bash -c " \ wget -r --no-parent http://intranet/intranet-content.tar.gz \ tar -xvf intranet-content.tar.gz \ sudo -u ${USERNAME} bash --norc"

stage 2: applying docker run script in daemon mode providing local dns records to have ability to download and deploy local stuff.

important point: run script should be ending with something like /usr/bin/sudo -u ${USERNAME} bash --norc to keep container running even after the installation scripts finishes.

no, it's not possible to run container in interactive mode for the full automation matter as it will remain inside internal shall command prompt until CTRL-p CTRL-q being pressed.

no, if interacting bash will not be executed at the end of the installation script, the container will terminate immediately after finishes script execution, loosing all installation results.

stage 3: container is still running in background but it's unclear whether container has ended installation procedure or not yet. using following block to determine execution procedure finishes: while ! docker container top ${CONTNAME} | grep "00[[:space:]]\{12\}bash \--norc" - do echo "." sleep 5 done the script will proceed further only after completed installation. and this is the right moment to call: commit, providing current container id as well as destination image name (it may be the same as on the build/run procedure but appended with the local installation purposes tag. example: docker commit containerID pack/bsp:toolchained. see this link on how to get proper containerID

stage 4: container has been updated with the local installs as well as it has been committed into newly assigned image (the one having purposes tag added). it's safe now to stop container running. example: docker stop packbsp-cont

stage5: any moment the container with local installs require to run, start it with the image previously saved. example: docker run -d -t pack/bsp:toolchained

Algorithm to detect overlapping periods

Simple check to see if two time periods overlap:

bool overlap = a.start < b.end && b.start < a.end;

or in your code:

bool overlap = tStartA < tEndB && tStartB < tEndA;

(Use <= instead of < if you change your mind about wanting to say that two periods that just touch each other overlap.)

PowerShell array initialization

The solution I found was to use the New-Object cmdlet to initialize an array of the proper size.

$array = new-object object[] 5 
for($i=0; $i -lt $array.Length;$i++)
{
    $array[$i] = $FALSE
}

What is the role of the bias in neural networks?

A layer in a neural network without a bias is nothing more than the multiplication of an input vector with a matrix. (The output vector might be passed through a sigmoid function for normalisation and for use in multi-layered ANN afterwards but that’s not important.)

This means that you’re using a linear function and thus an input of all zeros will always be mapped to an output of all zeros. This might be a reasonable solution for some systems but in general it is too restrictive.

Using a bias, you’re effectively adding another dimension to your input space, which always takes the value one, so you’re avoiding an input vector of all zeros. You don’t lose any generality by this because your trained weight matrix needs not be surjective, so it still can map to all values previously possible.

2d ANN:

For a ANN mapping two dimensions to one dimension, as in reproducing the AND or the OR (or XOR) functions, you can think of a neuronal network as doing the following:

On the 2d plane mark all positions of input vectors. So, for boolean values, you’d want to mark (-1,-1), (1,1), (-1,1), (1,-1). What your ANN now does is drawing a straight line on the 2d plane, separating the positive output from the negative output values.

Without bias, this straight line has to go through zero, whereas with bias, you’re free to put it anywhere. So, you’ll see that without bias you’re facing a problem with the AND function, since you can’t put both (1,-1) and (-1,1) to the negative side. (They are not allowed to be on the line.) The problem is equal for the OR function. With a bias, however, it’s easy to draw the line.

Note that the XOR function in that situation can’t be solved even with bias.

Centering a div block without the width

<div class="product_container">
<div class="outer-center">
<div class="product inner-center">
    </div>
</div>
<div class="clear"></div>
</div>

.outer-center
{
float: right;
right: 50%;
position: relative;
}
.inner-center 
{
float: right;
right: -50%;
position: relative;
}
.clear 
{
clear: both;
}

.product_container
{
overflow:hidden;
}

If you dont provide "overflow:hidden" for ".product_container" the "outer-center" div will overlap other nearby contents to the right of it. Any links or buttons to the right of "outer-center" wont work. Try background color for "outer-center" to understand the need of "overflow :hidden"

Is it possible to program Android to act as physical USB keyboard?

This is possible, without any additional drivers needed.

You can emulate PC's USB keyboard with small USB dongle-sized device and then use your Android device to send keyboard (and/or mouse) data over Bluetooth.

Take a look on descriptive video in Indiegogo campaign: http://igg.me/at/hiDBLUE/x/3400885

BTW: The product technical documents is available here: http://www.flyfish-tech.com/hiDBLUE

How can I stream webcam video with C#?

I've used VideoCapX for our project. It will stream out as MMS/ASF stream which can be open by media player. You can then embed media player into your webpage.

If you won't need much control, or if you want to try out VideoCapX without writing a code, try U-Broadcast, they use VideoCapX behind the scene.

React Native version mismatch

This is not a fix, but in my case, I had multiple RN apps installed on my device and I was unknowingly attempting to 'Reload` from within the wrong application. (I'm developing two apps simultaneously at the moment) So make sure you're in the correct application!

How to detect idle time in JavaScript elegantly?

Here is a simple script using JQuery that handles mousemove and keypress events. If the time expires, the page reload.

<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
    //Increment the idle time counter every minute.
    var idleInterval = setInterval(timerIncrement, 60000); // 1 minute

    //Zero the idle timer on mouse movement.
    $(this).mousemove(function (e) {
        idleTime = 0;
    });
    $(this).keypress(function (e) {
        idleTime = 0;
    });
});

function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime > 19) { // 20 minutes
        window.location.reload();
    }
}
</script>   

converting Java bitmap to byte array

Ted Hopp is correct, from the API Documentation :

public void copyPixelsToBuffer (Buffer dst)

"... After this method returns, the current position of the buffer is updated: the position is incremented by the number of elements written in the buffer. "

and

public ByteBuffer get (byte[] dst, int dstOffset, int byteCount)

"Reads bytes from the current position into the specified byte array, starting at the specified offset, and increases the position by the number of bytes read."

What is the difference between i++ & ++i in a for loop?

Both i++ and ++i are short-hand for i = i + 1.

In addition to changing the value of i, they also return the value of i, either before adding one (i++) or after adding one (++i).

In a loop the third component is a piece of code that is executed after each iteration.

for (int i=0; i<10; i++)

The value of that part is not used, so the above is just the same as

for(int i=0; i<10; i = i+1)

or

for(int i=0; i<10; ++i)

Where it makes a difference (between i++ and ++i )is in these cases

while(i++ < 10)

for (int i=0; i++ < 10; )

How to move a file?

This is what I'm using at the moment:

import os, shutil
path = "/volume1/Users/Transfer/"
moveto = "/volume1/Users/Drive_Transfer/"
files = os.listdir(path)
files.sort()
for f in files:
    src = path+f
    dst = moveto+f
    shutil.move(src,dst)

Now fully functional. Hope this helps you.

Edit:

I've turned this into a function, that accepts a source and destination directory, making the destination folder if it doesn't exist, and moves the files. Also allows for filtering of the src files, for example if you only want to move images, then you use the pattern '*.jpg', by default, it moves everything in the directory

import os, shutil, pathlib, fnmatch

def move_dir(src: str, dst: str, pattern: str = '*'):
    if not os.path.isdir(dst):
        pathlib.Path(dst).mkdir(parents=True, exist_ok=True)
    for f in fnmatch.filter(os.listdir(src), pattern):
        shutil.move(os.path.join(src, f), os.path.join(dst, f))

How to read from a file or STDIN in Bash?

The following solution reads from a file if the script is called with a file name as the first parameter $1 otherwise from standard input.

while read line
do
  echo "$line"
done < "${1:-/dev/stdin}"

The substitution ${1:-...} takes $1 if defined otherwise the file name of the standard input of the own process is used.

HTML/CSS - Adding an Icon to a button

<a href="#" class="btnTest">Test</a>


.btnTest{
   background:url('images/icon.png') no-repeat left center;
   padding-left:20px;
}    

How to use SharedPreferences in Android to store, fetch and edit values

Store in SharedPreferences

SharedPreferences preferences = getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("name", name);
editor.commit();

Fetch in SharedPreferences

SharedPreferences preferences=getSharedPreferences("temp", getApplicationContext().MODE_PRIVATE);
String name=preferences.getString("name",null);

Note: "temp" is sharedpreferences name and "name" is input value. if value does't exit then return null

Measuring text height to be drawn on Canvas ( Android )

You can simply get the text size for a Paint object using getTextSize() method. For example:

Paint mTextPaint = new Paint (Paint.ANTI_ALIAS_FLAG);
//use densityMultiplier to take into account different pixel densities
final float densityMultiplier = getContext().getResources()
            .getDisplayMetrics().density;  
mTextPaint.setTextSize(24.0f*densityMultiplier);

//...

float size = mTextPaint.getTextSize();

How to make an AlertDialog in Flutter?

Or you can use RFlutter Alert library for that. It is easily customizable and easy-to-use. Its default style includes rounded corners and you can add buttons as much as you want.

Basic Alert:

Alert(context: context, title: "RFLUTTER", desc: "Flutter is awesome.").show();

Alert with Button:

Alert(
    context: context,
    type: AlertType.error,
    title: "RFLUTTER ALERT",
    desc: "Flutter is more awesome with RFlutter Alert.",
    buttons: [
    DialogButton(
        child: Text(
        "COOL",
        style: TextStyle(color: Colors.white, fontSize: 20),
        ),
        onPressed: () => Navigator.pop(context),
        width: 120,
    )
    ],
).show();

You can also define generic alert styles.

*I'm one of developer of RFlutter Alert.

Target Unreachable, identifier resolved to null in JSF 2.2

  1. You need

    @ManagedBean(name="userBean")

  2. Make sure you have getUser() method.

  3. Type of setUser() method should be void.

  4. Make sure that User class has proper setters and getters as well.

How to differentiate single click event and double click event?

Based on Adrien Schuler (thank you so much!!!) answer, for Datatables.net and for many uses, here is a modification:

Function

/**
 * For handle click and single click in child's objects
 * @param {any} selector Parents selector, like 'tr'
 * @param {any} single_click_callback Callback for single click
 * @param {any} double_click_callback Callback for dblclick
 * @param {any} timeout Timeout, optional, 300 by default
 */
jQuery.fn.single_double_click = function (selector, single_click_callback, double_click_callback, timeout) {
    return this.each(function () {
        let clicks = 0;
        jQuery(this).on('click', selector, function (event) {
            let self = this;
            clicks++;
            if (clicks == 1) {
                setTimeout(function () {
                    if (clicks == 1) {
                        single_click_callback.call(self, event);
                    } else {
                        double_click_callback.call(self, event);
                    }
                    clicks = 0;
                }, timeout || 300);
            }
        });
    });
}

Use

$("#MyTableId").single_double_click('tr',
            function () {   //  Click
                let row = MyTable.row(this);
                let id = row.id();
                let data = row.data();
                console.log("Click in "+id+" "+data);
            },
            function () {   //  DBLClick
                let row = MyTable.row(this);
                let id = row.id();
                let data = row.data();
                console.log("DBLClick in "+id+" "+data);
            }
        );

How to "EXPIRE" the "HSET" child key in redis?

You can expire Redis hashes in ease, Eg using python

import redis
conn = redis.Redis('localhost')
conn.hmset("hashed_user", {'name': 'robert', 'age': 32})
conn.expire("hashed_user", 10)

This will expire all child keys in hash hashed_user after 10 seconds

same from redis-cli,

127.0.0.1:6379> HMSET testt username wlc password P1pp0 age 34
OK
127.0.0.1:6379> hgetall testt
1) "username"
2) "wlc"
3) "password"
4) "P1pp0"
5) "age"
6) "34"
127.0.0.1:6379> expire testt 10
(integer) 1
127.0.0.1:6379> hgetall testt
1) "username"
2) "wlc"
3) "password"
4) "P1pp0"
5) "age"
6) "34"

after 10 seconds

127.0.0.1:6379> hgetall testt
(empty list or set)

CSS Box Shadow Bottom Only

Try this

-moz-box-shadow:0 5px 5px rgba(182, 182, 182, 0.75);
-webkit-box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);
box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);

You can see it in http://jsfiddle.net/wJ7qp/

Where can I find my Facebook application id and secret key?

It is under Account -> Application Settings, click on your application's profile, then go to Edit Application.

How to automatically close cmd window after batch file execution?

This works for me

cd "C:\Program Files\SmartBear\SoapUI-5.6.0\bin"

start SoapUI-5.6.0.exe -w "C:\DATA\SoapUi\Workspaces\Production-workspace.xml"

exit

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

You seem to be doing file name comparisons, so I would just add that OrdinalIgnoreCase is closest to what NTFS does (it's not exactly the same, but it's closer than InvariantCultureIgnoreCase)

Java reverse an int value without using array

Reversing integer

  int n, reverse = 0;
  Scanner in = new Scanner(System.in);
  n = in.nextInt();

  while(n != 0)
  {
      reverse = reverse * 10;
      reverse = reverse + n%10;
      n = n/10;
  }

  System.out.println("Reverse of the number is " + reverse);

SQL How to replace values of select return?

You have a number of choices:

  1. Join with a domain table with TRUE, FALSE Boolean value.
  2. Use (as pointed in this answer)

    SELECT CASE WHEN hide = 0 THEN FALSE ELSE TRUE END FROM
    

    Or if Boolean is not supported:

    SELECT CASE WHEN hide = 0 THEN 'false' ELSE 'true' END FROM
    

Maven fails to find local artifact

When this happened to me, it was because I'd blindly copied my settings.xml from a template and it still had the blank <localRepository/> element. This means that there's no local repository used when resolving dependencies (though your installed artifacts do still get put in the default location). When I'd replaced that with <localRepository>${user.home}\.m2\repository</localRepository> it started working.

For *nix, that would be <localRepository>${user.home}/.m2/repository</localRepository>, I suppose.

How can I rename column in laravel using migration?

first thing you want to do is to create your migration file.

Type in your command line

php artisan make:migration rename_stk_column --table="YOUR TABLE" --create

After creating the file. Open the new created migration file in your app folder under database/migrations.

In your up method insert this:

Schema::table('stnk', function(Blueprint $table)
    {
        $table->renameColumn('id', 'id_stnk');
    });
}

and in your down method:

    Schema::table('stnk', function(Blueprint $table)
    {
        $table->renameColumn('id_stnk', 'id);
    });
}

then in your command line just type

php artisan migrate

Then wollah! you have just renamed id to id_stnk. BTW you can use

php artisan migrate:rollback

to undo the changes. Goodluck

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I would change the query in the following ways:

  1. Do the aggregation in subqueries. This can take advantage of more information about the table for optimizing the group by.
  2. Combine the second and third subqueries. They are aggregating on the same column. This requires using a left outer join to ensure that all data is available.
  3. By using count(<fieldname>) you can eliminate the comparisons to is null. This is important for the second and third calculated values.
  4. To combine the second and third queries, it needs to count an id from the mde table. These use mde.mdeid.

The following version follows your example by using union all:

SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
       SUM(TOTALMAILED) as TotalMailed,
       SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
       SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
              NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract
       where SentDate is not null
       group by SentDate
      ) union all
      (select MDE.ReturnMailDate AS ReceiptDate, 0,
              COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
              SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract MDE left outer join
            DTSharedData.dbo.ScanData SD
            ON SD.ScanDataID = MDE.ReturnScanDataID
       group by MDE.ReturnMailDate;
      )
     ) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;

The following does something similar using full outer join:

SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
       sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
       mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
      from MailDataExtract
      where SentDate is not null
      group by cast(SentDate as date)
     ) sd full outer join
    (select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
            COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
            SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
     from MailDataExtract MDE left outer join
          DTSharedData.dbo.ScanData SD
          ON SD.ScanDataID = MDE.ReturnScanDataID
     group by cast(MDE.ReturnMailDate as date)
    ) mde
    on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;

Reading a simple text file

In Mono For Android....

try
{
    System.IO.Stream StrIn = this.Assets.Open("MyMessage.txt");
    string Content = string.Empty;
    using (System.IO.StreamReader StrRead = new System.IO.StreamReader(StrIn))
    {
      try
      {
            Content = StrRead.ReadToEnd();
            StrRead.Close();
      }  
      catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }
      }
          StrIn.Close();
          StrIn = null;
}
catch (Exception ex) { csFunciones.MostarMsg(this, ex.Message); }

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

As scompt.com explained, the query might fail. Use this code the get the error of the query or the correct result:

$username = $_POST['username'];
$password = $_POST['password'];

$result = mysql_query("
SELECT * FROM Users 
WHERE UserName LIKE '".mysql_real_escape_string($username)."'
");

if($result)
{
    while($row = mysql_fetch_array($result))
    {
        echo $row['FirstName'];
    }
} else {
    echo 'Invalid query: ' . mysql_error() . "\n";
    echo 'Whole query: ' . $query; 
}

See the documentation for mysql_query() for further information.

The actual error was the single quotes so that the variable $username was not parsed. But you should really use mysql_real_escape_string($username) to avoid SQL injections.

Creating a random string with A-Z and 0-9 in Java

RandomStringUtils from Apache commons-lang might help:

RandomStringUtils.randomAlphanumeric(17).toUpperCase()

2017 update: RandomStringUtils has been deprecated, you should now use RandomStringGenerator.

Deleting DataFrame row in Pandas based on column value

The given answer is correct nontheless as someone above said you can use df.query('line_race != 0') which depending on your problem is much faster. Highly recommend.

Cross-browser custom styling for file upload button

Any easy way to cover ALL file inputs is to just style your input[type=button] and drop this in globally to turn file inputs into buttons:

$(document).ready(function() {
    $("input[type=file]").each(function () {
        var thisInput$ = $(this);
        var newElement = $("<input type='button' value='Choose File' />");
        newElement.click(function() {
            thisInput$.click();
        });
        thisInput$.after(newElement);
        thisInput$.hide();
    });
});

Here's some sample button CSS that I got from http://cssdeck.com/labs/beautiful-flat-buttons:

input[type=button] {
  position: relative;
  vertical-align: top;
  width: 100%;
  height: 60px;
  padding: 0;
  font-size: 22px;
  color:white;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);
  background: #454545;
  border: 0;
  border-bottom: 2px solid #2f2e2e;
  cursor: pointer;
  -webkit-box-shadow: inset 0 -2px #2f2e2e;
  box-shadow: inset 0 -2px #2f2e2e;
}
input[type=button]:active {
  top: 1px;
  outline: none;
  -webkit-box-shadow: none;
  box-shadow: none;
}

How do I exit the results of 'git diff' in Git Bash on windows?

None of the above solutions worked for me on Windows 8

But the following command works fine

SHIFT + Q

Typescript ReferenceError: exports is not defined

npm install @babel/plugin-transform-modules-commonjs

and add to to .babelrc plugins resolved my question.

PHP float with 2 decimal places: .00

You can use round function

round("10.221",2);

Will return 10.22

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

You need to provide iterables as the values for the Pandas DataFrame columns:

df2 = pd.DataFrame({'A':[a],'B':[b]})

Restricting JTextField input to Integers

You can also use JFormattedTextField, which is much simpler to use. Example:

public static void main(String[] args) {
    NumberFormat format = NumberFormat.getInstance();
    NumberFormatter formatter = new NumberFormatter(format);
    formatter.setValueClass(Integer.class);
    formatter.setMinimum(0);
    formatter.setMaximum(Integer.MAX_VALUE);
    formatter.setAllowsInvalid(false);
    // If you want the value to be committed on each keystroke instead of focus lost
    formatter.setCommitsOnValidEdit(true);
    JFormattedTextField field = new JFormattedTextField(formatter);

    JOptionPane.showMessageDialog(null, field);

    // getValue() always returns something valid
    System.out.println(field.getValue());
}

jQuery Toggle Text?

The most beautiful answer is... Extend jQuery with this function...

$.fn.extend({
    toggleText: function(a, b){
        return this.text(this.text() == b ? a : b);
    }
});

HTML:

<button class="example"> Initial </button>

Use:

$(".example").toggleText('Initial', 'Secondary');

I've used the logic ( x == b ? a : b ) in the case that the initial HTML text is slightly different (an extra space, period, etc...) so you'll never get a duplicate showing of the intended initial value

(Also why I purposely left spaces in the HTML example ;-)

Another possibility for HTML toggle use brought to my attention by Meules [below] is:

$.fn.extend({
        toggleHtml: function(a, b){
            return this.html(this.html() == b ? a : b);
        }
    });

HTML:

<div>John Doe was an unknown.<button id='readmore_john_doe'> Read More... </button></div>

Use:

$("readmore_john_doe").click($.toggleHtml(
    'Read More...', 
    'Until they found his real name was <strong>Doe John</strong>.')
);

(or something like this)

Select method of Range class failed via VBA

I believe you are having the same problem here.
The sheet must be active before you can select a range on it.

Also, don't omit the sheet name qualifier:

Sheets("BxWsn Simulation").Select
Sheets("BxWsn Simulation").Range("Result").Select

Or,

With Sheets("BxWsn Simulation")
  .Select
  .Range("Result").Select
End WIth

which is the same.

See last changes in svn

Open you working copy folder in console (terminal) and choose commands below. To see last changes: If you have commited last changes use:

svn diff -rPREV

If you left changes in working copy (that's bad practice) than use:

svn diff

To see log of commits: If you're working in branch:

svn log --stop-on-copy 

If you're working with trunk:

svn log | head

or just

svn log

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

This is a "feature" of the M2E plugin that had been introduced a while ago. It's not directly related to the JBoss EAR plugin but also happens with most other Maven plugins.

If you have a plugin execution defined in your pom (like the execution of maven-ear-plugin:generate-application-xml), you also need to add additional config information for M2E that tells M2E what to do when the build is run in Eclipse, e.g. should the plugin execution be ignored or executed by M2E, should it be also done for incremental builds, ... If that information is missing, M2E complains about it by showing this error message:

"Plugin execution not covered by lifecycle configuration"

See here for a more detailed explanation and some sample config that needs to be added to the pom to make that error go away:

https://www.eclipse.org/m2e/documentation/m2e-execution-not-covered.html

Print: Entry, ":CFBundleIdentifier", Does Not Exist

the 0.44 is ok to run,but 0.45 can not,maybe is the version problem i solved this by the following command: rninit init TaxiApp --source [email protected];

Compiling a java program into an executable

I would use GCJ (GNU Compiler for Java) in your situation. It's an AOT (ahead of time) compiler for Java, much like GCC is for C. Instead of interpreting code, or generating intermediate java code to be run at a later time by the Java VM, it generates machine code.

GCJ is available on almost any Linux system through its respective package manager (if available). After installation, the GCJ compiler should be added to the path so that it can be invoked through the terminal. If you're using Windows, you can download and install GCJ through Cygwin or MinGW.

I would strongly recommend, however, that you rewrite your source for another language that is meant to be compiled, such as C++. Java is meant to be a portable, interpreted language. Compiling it to machine code is completely against what the language was developed for.

Selenium Webdriver submit() vs click()

There is a difference between click() and submit().

submit() submits the form and executes the url that is given by the "action" attribute. If you have any javascript-function or jquery-plugin running to submit the form e.g. via ajax, submit() will ignore it. With click() the javascript-functions will be executed.

How to include a quote in a raw Python string

Nevermind, the answer is raw triple-quoted strings:

r"""what"ever"""

How do you create a temporary table in an Oracle database?

CREATE TABLE table_temp_list_objects AS
SELECT o.owner, o.object_name FROM sys.all_objects o WHERE o.object_type ='TABLE';

List all sequences in a Postgres db 8.1 with SQL

I know the question was about postgresql version 8 but I wrote this simple way here for people who want to get sequences in version 10 and upper

you can use the bellow query

select * from pg_sequences

view-pg-sequences

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations

Then you can do things like:

var day = moment("12-25-1995", "MM-DD-YYYY");

or

var day = moment("25/12/1995", "DD/MM/YYYY");

then operate on the date

day.add('days', 7)

and to get the native javascript date

day.toDate();

Count the number of times a string appears within a string

Here, I'll over-architect the answer using LINQ. Just shows that there's more than 'n' ways to cook an egg:

public int countTrue(string data)
{
    string[] splitdata = data.Split(',');

    var results = from p in splitdata
            where p.Contains("true")
            select p;

    return results.Count();
}

onKeyDown event not working on divs in React

You're thinking too much in pure Javascript. Get rid of your listeners on those React lifecycle methods and use event.key instead of event.keyCode (because this is not a JS event object, it is a React SyntheticEvent). Your entire component could be as simple as this (assuming you haven't bound your methods in a constructor).

onKeyPressed(e) {
  console.log(e.key);
}

render() {
  let player = this.props.boards.dungeons[this.props.boards.currentBoard].player;
  return (
    <div 
      className="player"
      style={{ position: "absolute" }}
      onKeyDown={this.onKeyPressed}
    >
      <div className="light-circle">
        <div className="image-wrapper">
          <img src={IMG_URL+player.img} />
        </div>
      </div>
    </div>
  )
}

Javascript : natural sort of alphanumerical strings

To compare values you can use a comparing method-

function naturalSorter(as, bs){
    var a, b, a1, b1, i= 0, n, L,
    rx=/(\.\d+)|(\d+(\.\d+)?)|([^\d.]+)|(\.\D+)|(\.$)/g;
    if(as=== bs) return 0;
    a= as.toLowerCase().match(rx);
    b= bs.toLowerCase().match(rx);
    L= a.length;
    while(i<L){
        if(!b[i]) return 1;
        a1= a[i],
        b1= b[i++];
        if(a1!== b1){
            n= a1-b1;
            if(!isNaN(n)) return n;
            return a1>b1? 1:-1;
        }
    }
    return b[i]? -1:0;
}

But for speed in sorting an array, rig the array before sorting, so you only have to do lower case conversions and the regular expression once instead of in every step through the sort.

function naturalSort(ar, index){
    var L= ar.length, i, who, next, 
    isi= typeof index== 'number', 
    rx=  /(\.\d+)|(\d+(\.\d+)?)|([^\d.]+)|(\.(\D+|$))/g;
    function nSort(aa, bb){
        var a= aa[0], b= bb[0], a1, b1, i= 0, n, L= a.length;
        while(i<L){
            if(!b[i]) return 1;
            a1= a[i];
            b1= b[i++];
            if(a1!== b1){
                n= a1-b1;
                if(!isNaN(n)) return n;
                return a1>b1? 1: -1;
            }
        }
        return b[i]!= undefined? -1: 0;
    }
    for(i= 0; i<L; i++){
        who= ar[i];
        next= isi? ar[i][index] || '': who;
        ar[i]= [String(next).toLowerCase().match(rx), who];
    }
    ar.sort(nSort);
    for(i= 0; i<L; i++){
        ar[i]= ar[i][1];
    }
}

HTML input arrays

As far as I know, there isn't anything on the HTML specs because browsers aren't supposed to do anything different for these fields. They just send them as they normally do and PHP is the one that does the parsing into an array, as do other languages.

CSS Styling for a Button: Using <input type="button> instead of <button>

In your .button CSS, try display:inline-block. See this JSFiddle

Extract the first (or last) n characters of a string

You can easily obtain Right() and Left() functions starting from the Rbase package:

  • right function

    right = function (string, char) {
        substr(string,nchar(string)-(char-1),nchar(string))
    }
    
  • left function

    left = function (string,char) {
        substr(string,1,char)
    }
    

you can use those two custom-functions exactly as left() and right() in excel. Hope you will find it useful

Safe navigation operator (?.) or (!.) and null property paths

! is non-null assertion operator (post-fix expression) - it just saying to type checker that you're sure that a is not null or undefined.

the operation a! produces a value of the type of a with null and undefined excluded


Optional chaining finally made it to typescript (3.7)

The optional chaining operator ?. permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The ?. operator functions similarly to the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

Syntax:

obj?.prop // Accessing object's property
obj?.[expr] // Optional chaining with expressions
arr?.[index] // Array item access with optional chaining
func?.(args) // Optional chaining with function calls

Pay attention:

Optional chaining is not valid on the left-hand side of an assignment

const object = {};
object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment

Java: Static vs inner class

Let's look in the source of wisdom for such questions: Joshua Bloch's Effective Java:

Technically, there is no such thing as a static inner class. According to Effective Java, the correct terminology is a static nested class. A non-static nested class is indeed an inner class, along with anonymous classes and local classes.

And now to quote:

Each instance of a non-static nested class is implicitly associated with an enclosing instance of its containing class... It is possible to invoke methods on the enclosing instance.

A static nested class does not have access to the enclosing instance. It uses less space too.

Swift - how to make custom header for UITableView?

This worked for me - Swift 3

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let headerCell = tableView.dequeueReusableCell(withIdentifier: "customTableCell") as! CustomTableCell
        return headerCell
    }

How to call an async method from a getter or setter?

You can't call it asynchronously, since there is no asynchronous property support, only async methods. As such, there are two options, both taking advantage of the fact that asynchronous methods in the CTP are really just a method that returns Task<T> or Task:

// Make the property return a Task<T>
public Task<IEnumerable> MyList
{
    get
    {
         // Just call the method
         return MyAsyncMethod();
    }
}

Or:

// Make the property blocking
public IEnumerable MyList
{
    get
    {
         // Block via .Result
         return MyAsyncMethod().Result;
    }
}

Where can I find a list of escape characters required for my JSON ajax return type?

Right away, I can tell that at least the double quotes in the HTML tags are gonna be a problem. Those are probably all you'll need to escape for it to be valid JSON; just replace

"

with

\"

As for outputting user-input text, you do need to make sure you run it through HttpUtility.HtmlEncode() to avoid XSS attacks and to make sure that it doesn't screw up the formatting of your page.

JavaFX 2.1 TableView refresh items

Since JavaFX 8u60 you can use(assuming tableView is an instance of TableView class):

tableView.refresh();

From the documentation:

Calling refresh() forces the TableView control to recreate and repopulate the cells necessary to populate the visual bounds of the control. In other words, this forces the TableView to update what it is showing to the user. This is useful in cases where the underlying data source has changed in a way that is not observed by the TableView itself.

What is the difference between private and protected members of C++ classes?

Public members of a class A are accessible for all and everyone.

Protected members of a class A are not accessible outside of A's code, but is accessible from the code of any class derived from A.

Private members of a class A are not accessible outside of A's code, or from the code of any class derived from A.

So, in the end, choosing between protected or private is answering the following questions: How much trust are you willing to put into the programmer of the derived class?

By default, assume the derived class is not to be trusted, and make your members private. If you have a very good reason to give free access of the mother class' internals to its derived classes, then you can make them protected.

Passing an array/list into a Python function

You don't need to use the asterisk to accept a list.

Simply give the argument a name in the definition, and pass in a list like

def takes_list(a_list):
    for item in a_list:
         print item

Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

1- close the project

2- close Android Studio IDE

3- delete the .idea directory

4- delete all .iml files

5- open Android Studio IDE and import the project

React proptype array with shape

This was my solution to protect against an empty array as well:

import React, { Component } from 'react';
import { arrayOf, shape, string, number } from 'prop-types';

ReactComponent.propTypes = {
  arrayWithShape: (props, propName, componentName) => {
    const arrayWithShape = props[propName]
    PropTypes.checkPropTypes({ arrayWithShape:
        arrayOf(
          shape({
            color: string.isRequired,
            fontSize: number.isRequired,
          }).isRequired
      ).isRequired
    }, {arrayWithShape}, 'prop', componentName);
    if(arrayWithShape.length < 1){
      return new Error(`${propName} is empty`)
    }
  }
}

Setting a WebRequest's body data

The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:

var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic   N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "[email protected]");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

The code above depends on the nuget package RestSharp, which you can easily install.

How to count TRUE values in a logical vector

Another way is

> length(z[z==TRUE])
[1] 498

While sum(z) is nice and short, for me length(z[z==TRUE]) is more self explaining. Though, I think with a simple task like this it does not really make a difference...

If it is a large vector, you probably should go with the fastest solution, which is sum(z). length(z[z==TRUE]) is about 10x slower and table(z)[TRUE] is about 200x slower than sum(z).

Summing up, sum(z) is the fastest to type and to execute.

Add "Are you sure?" to my excel button, how can I?

On your existing button code, simply insert this line before the procedure:

If MsgBox("This will erase everything! Are you sure?", vbYesNo) = vbNo Then Exit Sub

This will force it to quit if the user presses no.

Show/Hide Table Rows using Javascript classes

JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.

$("tr1").show();

$("tr1").hide();

w3cSchool link to JQuery show and hide

Shorthand for if-else statement

Using the ternary :? operator [spec].

var hasName = (name === 'true') ? 'Y' :'N';

The ternary operator lets us write shorthand if..else statements exactly like you want.

It looks like:

(name === 'true') - our condition

? - the ternary operator itself

'Y' - the result if the condition evaluates to true

'N' - the result if the condition evaluates to false

So in short (question)?(result if true):(result is false) , as you can see - it returns the value of the expression so we can simply assign it to a variable just like in the example above.

HTML img tag: title attribute vs. alt attribute?

No, I think alt is better because the purpose of that attribute is to provide "alternate" text in the event that the image cannot be view (whether it be that the image is missing or that the browser itself is incapable of displaying it).

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

CURLOPT_RETURNTRANSFER set to true doesnt work on hosting server

If it works fine on your local environment, probably your remote server's IP is being blocked by the server at the target URL you've set for cURL to use. You need to verify that your remote server is allowed to access the URL you've set for CURLOPT_URL.

Why does PEP-8 specify a maximum line length of 79 characters?

because if you push it beyond the 80th column it means that either you are writing a very long and complex line of code that does too much (and so you should refactor), or that you indented too much (and so you should refactor).

How to pass data from child component to its parent in ReactJS?

from child component to parent component as below

parent component

class Parent extends React.Component {
   state = { message: "parent message" }
   callbackFunction = (childData) => {
       this.setState({message: childData})
   },
   render() {
        return (
            <div>
                 <Child parentCallback = {this.callbackFunction}/>
                 <p> {this.state.message} </p>
            </div>
        );
   }
}

child component

class Child extends React.Component{
    sendBackData = () => {
         this.props.parentCallback("child message");
    },
    render() { 
       <button onClick={sendBackData}>click me to send back</button>
    }
};

I hope this work

Change application's starting activity

Just go to your AndroidManifest.xml file and add like below

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

then save and run your android project.

Count distinct values

You can use this:

select count(customer) as count, pets
from table
group by pets

<SELECT multiple> - how to allow only one item selected?

I had some dealings with the select \ multi-select this is what did the trick for me

<select name="mySelect" multiple="multiple">
    <option>Foo</option>
    <option>Bar</option>
    <option>Foo Bar</option>
    <option>Bar Foo</option>
</select>

CSS align one item right with flexbox

To align one flex child to the right set it withmargin-left: auto;

From the flex spec:

One use of auto margins in the main axis is to separate flex items into distinct "groups". The following example shows how to use this to reproduce a common UI pattern - a single bar of actions with some aligned on the left and others aligned on the right.

.wrap div:last-child {
  margin-left: auto;
}

Updated fiddle

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note:

You could achieve a similar effect by setting flex-grow:1 on the middle flex item (or shorthand flex:1) which would push the last item all the way to the right. (Demo)

The obvious difference however is that the middle item becomes bigger than it may need to be. Add a border to the flex items to see the difference.

Demo

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div {_x000D_
  border: 3px solid tomato;_x000D_
}_x000D_
.margin div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.grow div:nth-child(2) {_x000D_
  flex: 1;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap margin">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<div class="wrap grow">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I set the size of an HTML text box?

Your markup:

<input type="text" class="resizedTextbox" />

The CSS:

.resizedTextbox {width: 100px; height: 20px}

Keep in mind that text box size is a "victim" of the W3C box model. What I mean by victim is that the height and width of a text box is the sum of the height/width properties assigned above, in addition to the padding height/width, and the border width. For this reason, your text boxes will be slightly different sizes in different browsers depending on the default padding in different browsers. Although different browsers tend to define different padding to text boxes, most reset style sheets don't tend to include <input /> tags in their reset sheets, so this is something to keep in mind.

You can standardize this by defining your own padding. Here is your CSS with specified padding, so the text box looks the same in all browsers:

.resizedTextbox {width: 100px; height: 20px; padding: 1px}

I added 1 pixel padding because some browsers tend to make the text box look too crammed if the padding is 0px. Depending on your design, you may want to add even more padding, but it is highly recommend you define the padding yourself, otherwise you'll be leaving it up to different browsers to decide for themselves. For even more consistency across browsers, you should also define the border yourself.

SQL update fields of one table from fields of another one

I have been working with IBM DB2 database for more then decade and now trying to learn PostgreSQL.

It works on PostgreSQL 9.3.4, but does not work on DB2 10.5:

UPDATE B SET
     COLUMN1 = A.COLUMN1,
     COLUMN2 = A.COLUMN2,
     COLUMN3 = A.COLUMN3
FROM A
WHERE A.ID = B.ID

Note: Main problem is FROM cause that is not supported in DB2 and also not in ANSI SQL.

It works on DB2 10.5, but does NOT work on PostgreSQL 9.3.4:

UPDATE B SET
    (COLUMN1, COLUMN2, COLUMN3) =
               (SELECT COLUMN1, COLUMN2, COLUMN3 FROM A WHERE ID = B.ID)

FINALLY! It works on both PostgreSQL 9.3.4 and DB2 10.5:

UPDATE B SET
     COLUMN1 = (SELECT COLUMN1 FROM A WHERE ID = B.ID),
     COLUMN2 = (SELECT COLUMN2 FROM A WHERE ID = B.ID),
     COLUMN3 = (SELECT COLUMN3 FROM A WHERE ID = B.ID)

How do I remove the file suffix and path portion from a path string in Bash?

Beware of the suggested perl solution: it removes anything after the first dot.

$ echo some.file.with.dots | perl -pe 's/\..*$//;s{^.*/}{}'
some

If you want to do it with perl, this works:

$ echo some.file.with.dots | perl -pe 's/(.*)\..*$/$1/;s{^.*/}{}'
some.file.with

But if you are using Bash, the solutions with y=${x%.*} (or basename "$x" .ext if you know the extension) are much simpler.

Converting string to byte array in C#

If you already have a byte array then you will need to know what type of encoding was used to make it into that byte array.

For example, if the byte array was created like this:

byte[] bytes = Encoding.ASCII.GetBytes(someString);

You will need to turn it back into a string like this:

string someString = Encoding.ASCII.GetString(bytes);

If you can find in the code you inherited, the encoding used to create the byte array then you should be set.

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

If your application is a Java EE application running on Oracle WebLogic as the application server, a possible cause for this issue is the Statement Cache Size setting in WebLogic.

If the Statement Cache Size setting for a particular data source is about equal to, or greater than, the Oracle database maximum open cursor count setting, then all of the open cursors can be consumed by cached SQL statements that are held open by WebLogic, resulting in the ORA-01000 error.

To address this, reduce the Statement Cache Size setting for each WebLogic datasource that points to the Oracle database to be significantly less than the maximum cursor count setting on the database.

In the WebLogic 10 Admin Console, the Statement Cache Size setting for each data source can be found at Services (left nav) > Data Sources > (individual data source) > Connection Pool tab.

How can I obfuscate (protect) JavaScript?

Obfuscation can never really work. For anyone who really wants to get at your code, it's just a speed bump. Worse, it keeps your users from fixing bugs (and shipping the fixes back to you), and makes it harder for you to diagnose problems in the field. Its a waste of your time and money.

Talk to a lawyer about intellectual property law and what your legal options are. "Open Source" does not mean "people can read the source". Instead, Open Source is a particular licensing model granting permission to freely use and modify your code. If you don't grant such a license then people copying your code are in violation and (in most of the world) you have legal options to stop them.

The only way you can really protect your code is to not ship it. Move the important code server-side and have your public Javascript code do Ajax calls to it.

See my full answer about obfuscators here.

Formatting DataBinder.Eval data

<asp:Label ID="ServiceBeginDate" runat="server" Text='<%# (DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:yyyy}") == "0001") ? "" : DataBinder.Eval(Container.DataItem, "ServiceBeginDate", "{0:MM/dd/yyyy}") %>'>
</asp:Label>

How to program a delay in Swift 3

After a lot of research, I finally figured this one out.

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { // Change `2.0` to the desired number of seconds.
   // Code you want to be delayed
}

This creates the desired "wait" effect in Swift 3 and Swift 4.

Inspired by a part of this answer.

Change :hover CSS properties with JavaScript

If you use lightweight html ux lang, check here an example, write:

div root
 .onmouseover = ev => {root.style.backgroundColor='red'}
 .onmouseleave = ev => {root.style.backgroundColor='initial'}

The code above performes the css :hover metatag.

Sorting arrays in NumPy by column

import numpy as np
a=np.array([[21,20,19,18,17],[16,15,14,13,12],[11,10,9,8,7],[6,5,4,3,2]])
y=np.argsort(a[:,2],kind='mergesort')# a[:,2]=[19,14,9,4]
a=a[y]
print(a)

Desired output is [[6,5,4,3,2],[11,10,9,8,7],[16,15,14,13,12],[21,20,19,18,17]]

note that argsort(numArray) returns the indices of an numArray as it was supposed to be arranged in a sorted manner.

example

x=np.array([8,1,5]) 
z=np.argsort(x) #[1,3,0] are the **indices of the predicted sorted array**
print(x[z]) #boolean indexing which sorts the array on basis of indices saved in z

answer would be [1,5,8]

Rewrite left outer join involving multiple tables from Informix to Oracle

I'm guessing that you want something like

SELECT tab1.a, tab2.b, tab3.c, tab4.d
  FROM table1 tab1 
       JOIN table2 tab2 ON (tab1.fg = tab2.fg)
       LEFT OUTER JOIN table4 tab4 ON (tab1.ss = tab4.ss)
       LEFT OUTER JOIN table3 tab3 ON (tab4.xya = tab3.xya and tab3.desc = 'XYZ')
       LEFT OUTER JOIN table5 tab5 on (tab4.kk = tab5.kk AND
                                       tab3.dd = tab5.dd)

What is ":-!!" in C code?

The : is a bitfield. As for !!, that is logical double negation and so returns 0 for false or 1 for true. And the - is a minus sign, i.e. arithmetic negation.

It's all just a trick to get the compiler to barf on invalid inputs.

Consider BUILD_BUG_ON_ZERO. When -!!(e) evaluates to a negative value, that produces a compile error. Otherwise -!!(e) evaluates to 0, and a 0 width bitfield has size of 0. And hence the macro evaluates to a size_t with value 0.

The name is weak in my view because the build in fact fails when the input is not zero.

BUILD_BUG_ON_NULL is very similar, but yields a pointer rather than an int.

Is there a C# case insensitive equals operator?

string.Equals(StringA, StringB, StringComparison.CurrentCultureIgnoreCase);

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

@Mihai-Andrei Dinculescu's answer worked for me, e.g.:

  • Adding a <httpProtocol>in the web.config's <system.webServer> section
  • Returning empty response for OPTIONS requests via the mentioned Application_BeginRequest() in global.asax

Except that his check for Request.Headers.AllKeys.Contains("Origin") did NOT work for me, because the request contained an origing, so with lowercase. I think my browser (Chrome) sends it like this for CORS requests.

I solved this a bit more generically by using a case insensitive variant of his Contains check instead: if (culture.CompareInfo.IndexOf(string.Join(",", Request.Headers.AllKeys), "Origin", CompareOptions.IgnoreCase) >= 0) {

Clone contents of a GitHub repository (without the folder itself)

If the folder is not empty, a slightly modified version of @JohnLittle's answer worked for me:

git init
git remote add origin https://github.com/me/name.git
git pull origin master

As @peter-cordes pointed out, the only difference is using https protocol instead of git, for which you need to have SSH keys configured.

Adding files to a GitHub repository

Open github app. Then, add the Folder of files into the github repo file onto your computer (You WILL need to copy the repo onto your computer. Most repo files are located in the following directory: C:\Users\USERNAME\Documents\GitHub\REPONAME) Then, in the github app, check our your repo. You can easily commit from there.

Convert cells(1,1) into "A1" and vice versa

The Address property of a cell can get this for you:

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)

returns A1.

The other way around can be done with the Row and Column property of Range:

MsgBox Range("A1").Row & ", " & Range("A1").Column

returns 1,1.

ETag vs Header Expires

Expires and Cache-Control are "strong caching headers"

Last-Modified and ETag are "weak caching headers"

First the browser check Expires/Cache-Control to determine whether or not to make a request to the server

If have to make a request, it will send Last-Modified/ETag in the HTTP request. If the Etag value of the document matches that, the server will send a 304 code instead of 200, and no content. The browser will load the contents from its cache.

PowerShell Remoting giving "Access is Denied" error

Had similar problems recently. Would suggest you carefully check if the user you're connecting with has proper authorizations on the remote machine.

You can review permissions using the following command.

Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell

Found this tip here (updated link, thanks "unbob"):

https://devblogs.microsoft.com/scripting/configure-remote-security-settings-for-windows-powershell/

It fixed it for me.

Android getText from EditText field

Use this:

  setContentView(R.layout.yourlayout);

  //after setting yor layout do the following
  EditText email = (EdiText) findViewById(R.id.vnosEmaila);
  String val = email.getText().toString;   // Use the toString method to convert the return value to a String.

  //Your Toast with String val; 
  Toast toast = Toast.makeText(EmailGumb.this, val, Toast.LENGTH_LONG);
  toast.setGravity(Gravity.CENTER, 0, 0);
  toast.show();

Thanks

Boolean.parseBoolean("1") = false...?

As a note ,
for those who need to have null value for things other than "true" or "false" strings , you can use the function below

public Boolean tryParseBoolean(String inputBoolean)
{    
    if(!inputBoolean.equals("true")&&!inputBoolean.equals("false")) return null;
    return Boolean.valueOf(inputBoolean);
}

How would I find the second largest salary from the employee table?

select max(Salary) from Employee 
where Salary
  not in (Select top4 salary from Employee);

because answer is as follows

max(5,6,7,8)

so 5th highest record will be displayed, first four will not be considered

Return single column from a multi-dimensional array

very simple go for this

$str;
foreach ($arrays as $arr) {
$str .= $arr["tag_name"] . ",";
}
$str = trim($str, ',');//removes the final comma 

Kotlin: How to get and set a text to TextView in Android using Kotlin?

In kotlin don't use getters and setters as like in java.The correct format of the kotlin is given below.

val textView: TextView = findViewById(R.id.android_text) as TextView
textView.setOnClickListener {
    textView.text = getString(R.string.name)
}

To get the values from the Textview we have to use this method

 val str: String = textView.text.toString()

 println("the value is $str")

Zoom to fit: PDF Embedded in HTML

For me this worked(I wanted to zoom in since the container of my pdf was small):

    <embed src="filename.pdf#page=1&zoom=300" width="575" height="500">

How to insert a row in an HTML table body in JavaScript

You can use the following example:

<table id="purches">
    <thead>
        <tr>
            <th>ID</th>
            <th>Transaction Date</th>
            <th>Category</th>
            <th>Transaction Amount</th>
            <th>Offer</th>
        </tr>
    </thead>

    <!--  <tr th:each="person: ${list}"    >
            <td><li th:each="person: ${list}" th:text="|${person.description}|"></li></td>
            <td><li th:each="person: ${list}" th:text="|${person.price}|"></li></td>
            <td><li th:each="person: ${list}" th:text="|${person.available}|"></li></td>
            <td><li th:each="person: ${list}" th:text="|${person.from}|"></li></td>
            </tr>
    -->

    <tbody id="feedback">
    </tbody>
</table>

JavaScript file:

$.ajax({
    type: "POST",
    contentType: "application/json",
    url: "/search",
    data: JSON.stringify(search),
    dataType: 'json',
    cache: false,
    timeout: 600000,
    success: function (data) {
        //  var json = "<h4>Ajax Response</h4><pre>"  + JSON.stringify(data, null, 4) + "</pre>";
        // $('#feedback').html(json);
        //
        console.log("SUCCESS: ", data);
        //$("#btn-search").prop("disabled", false);

        for (var i = 0; i < data.length; i++) {
            //$("#feedback").append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td></tr>');
            $('#feedback').append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td></tr>');

            alert(data[i].accountNumber)
        }
    },
    error: function (e) {
        var json = "<h4>Ajax Response</h4><pre>" + e.responseText + "</pre>";
        $('#feedback').html(json);

        console.log("ERROR: ", e);
        $("#btn-search").prop("disabled", false);
    }
});

Alternate table with new not null Column in existing table in SQL

You will either have to specify a DEFAULT, or add the column with NULLs allowed, update all the values, and then change the column to NOT NULL.

ALTER TABLE <YourTable> 
ADD <NewColumn> <NewColumnType> NOT NULL DEFAULT <DefaultValue>

Is there a way to get colored text in GitHubflavored Markdown?

You can not color plain text in a GitHub README.md file. You can however add color to code samples in your GitHub README.md file with the tags below.

To do this, just add tags, such as these samples, to your README.md file:

```json
   // Code for coloring
```
```html
   // Code for coloring
```
```js
   // Code for coloring
```
```css
   // Code for coloring
```
// etc.

**Colored Code Example, JavaScript:** place this code below, in your GitHub README.md file and see how it colors the code for you.
  import { Component } from '@angular/core';
  import { MovieService } from './services/movie.service';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [ MovieService ]
  })
  export class AppComponent {
    title = 'app works!';
  }

No "pre" or "code" tags are needed.

This is now covered in the GitHub Markdown documentation (about half way down the page, there's an example using Ruby). GitHub uses Linguist to identify and highlight syntax - you can find a full list of supported languages (as well as their markdown keywords) over in the Linguist's YAML file.

DEMO

How to write the Fibonacci Sequence?

There is lots of information about the Fibonacci Sequence on wikipedia and on wolfram. A lot more than you may need. Anyway it is a good thing to learn how to use these resources to find (quickly if possible) what you need.

Write Fib sequence formula to infinite

In math, it's given in a recursive form:

fibonacci from wikipedia

In programming, infinite doesn't exist. You can use a recursive form translating the math form directly in your language, for example in Python it becomes:

def F(n):
    if n == 0: return 0
    elif n == 1: return 1
    else: return F(n-1)+F(n-2)

Try it in your favourite language and see that this form requires a lot of time as n gets bigger. In fact, this is O(2n) in time.

Go on on the sites I linked to you and will see this (on wolfram):

Fibonacci Equation

This one is pretty easy to implement and very, very fast to compute, in Python:

from math import sqrt
def F(n):
    return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))

An other way to do it is following the definition (from wikipedia):

The first number of the sequence is 0, the second number is 1, and each subsequent number is equal to the sum of the previous two numbers of the sequence itself, yielding the sequence 0, 1, 1, 2, 3, 5, 8, etc.

If your language supports iterators you may do something like:

def F():
    a,b = 0,1
    while True:
        yield a
        a, b = b, a + b

Display startNumber to endNumber only from Fib sequence.

Once you know how to generate Fibonacci Numbers you just have to cycle trough the numbers and check if they verify the given conditions.

Suppose now you wrote a f(n) that returns the n-th term of the Fibonacci Sequence (like the one with sqrt(5) )

In most languages you can do something like:

def SubFib(startNumber, endNumber):
    n = 0
    cur = f(n)
    while cur <= endNumber:
        if startNumber <= cur:
            print cur
        n += 1
        cur = f(n)

In python I'd use the iterator form and go for:

def SubFib(startNumber, endNumber):
    for cur in F():
        if cur > endNumber: return
        if cur >= startNumber:
            yield cur

for i in SubFib(10, 200):
    print i

My hint is to learn to read what you need. Project Euler (google for it) will train you to do so :P Good luck and have fun!

Python exit commands - why so many and when should each be used?

Different Means of Exiting

os._exit():

  • Exit the process without calling the cleanup handlers.

exit(0):

  • a clean exit without any errors / problems.

exit(1):

  • There was some issue / error / problem and that is why the program is exiting.

sys.exit():

  • When the system and python shuts down; it means less memory is being used after the program is run.

quit():

  • Closes the python file.

Summary

Basically they all do the same thing, however, it also depends on what you are doing it for.

I don't think you left anything out and I would recommend getting used to quit() or exit().

You would use sys.exit() and os._exit() mainly if you are using big files or are using python to control terminal.

Otherwise mainly use exit() or quit().

How/When does Execute Shell mark a build as failure in Jenkins?

So by adding the #!/bin/sh will allow you to execute with no option.

It also helped me in fixing an issue where I was executing bash script from Jenkins master on my Linux slave. By just adding #!/bin/bash above my actual script in "Execute Shell" block it fixed my issue as otherwise it was executing windows git provided version of bash shell that was giving an error.

How to select where ID in Array Rails ActiveRecord without exception

Now .find and .find_by_id methods are deprecated in rails 4. So instead we can use below:

Comment.where(id: [2, 3, 5])

It will work even if some of the ids don't exist. This works in the

user.comments.where(id: avoided_ids_array)

Also for excluding ID's

Comment.where.not(id: [2, 3, 5])

What is the difference between print and puts?

A big difference is if you are displaying arrays. Especially ones with NIL. For example:

print [nil, 1, 2]

gives

[nil, 1, 2]

but

puts [nil, 1, 2]

gives

1
2

Note, no appearing nil item (just a blank line) and each item on a different line.

converting date time to 24 hour format

H vs h is difference between 24 hour vs 12 hour format.

How to convert enum names to string in c

There is no simple way to achieves this directly. But P99 has macros that allow you to create such type of function automatically:

 P99_DECLARE_ENUM(color, red, green, blue);

in a header file, and

 P99_DEFINE_ENUM(color);

in one compilation unit (.c file) should then do the trick, in that example the function then would be called color_getname.

Simple parse JSON from URL on Android and display in listview

You could use AsyncTask, you'll have to customize to fit your needs, but something like the following


Async task has three primary methods:

  1. onPreExecute() - most commonly used for setting up and starting a progress dialog

  2. doInBackground() - Makes connections and receives responses from the server (Do NOT try to assign response values to GUI elements, this is a common mistake, that cannot be done in a background thread).

  3. onPostExecute() - Here we are out of the background thread, so we can do user interface manipulation with the response data, or simply assign the response to specific variable types.

First we will start the class, initialize a String to hold the results outside of the methods but inside the class, then run the onPreExecute() method setting up a simple progress dialog.

class MyAsyncTask extends AsyncTask<String, String, Void> {

    private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
    InputStream inputStream = null;
    String result = ""; 

    protected void onPreExecute() {
        progressDialog.setMessage("Downloading your data...");
        progressDialog.show();
        progressDialog.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface arg0) {
                MyAsyncTask.this.cancel(true);
            }
        });
    }

Then we need to set up the connection and how we want to handle the response:

    @Override
    protected Void doInBackground(String... params) {

        String url_select = "http://yoururlhere.com";

        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

        try {
            // Set up HTTP post

            // HttpClient is more then less deprecated. Need to change to URLConnection
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url_select);
            httpPost.setEntity(new UrlEncodedFormEntity(param));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            // Read content & Log
            inputStream = httpEntity.getContent();
        } catch (UnsupportedEncodingException e1) {
            Log.e("UnsupportedEncodingException", e1.toString());
            e1.printStackTrace();
        } catch (ClientProtocolException e2) {
            Log.e("ClientProtocolException", e2.toString());
            e2.printStackTrace();
        } catch (IllegalStateException e3) {
            Log.e("IllegalStateException", e3.toString());
            e3.printStackTrace();
        } catch (IOException e4) {
            Log.e("IOException", e4.toString());
            e4.printStackTrace();
        }
        // Convert response to string using String Builder
        try {
            BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
            StringBuilder sBuilder = new StringBuilder();

            String line = null;
            while ((line = bReader.readLine()) != null) {
                sBuilder.append(line + "\n");
            }

            inputStream.close();
            result = sBuilder.toString();

        } catch (Exception e) {
            Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
        }
    } // protected Void doInBackground(String... params)

Lastly, here we will parse the return, in this example it was a JSON Array and then dismiss the dialog:

    protected void onPostExecute(Void v) {
        //parse JSON data
        try {
            JSONArray jArray = new JSONArray(result);    
            for(i=0; i < jArray.length(); i++) {

                JSONObject jObject = jArray.getJSONObject(i);

                String name = jObject.getString("name");
                String tab1_text = jObject.getString("tab1_text");
                int active = jObject.getInt("active");

            } // End Loop
            this.progressDialog.dismiss();
        } catch (JSONException e) {
            Log.e("JSONException", "Error: " + e.toString());
        } // catch (JSONException e)
    } // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>

How do I set the selected item in a comboBox to match my string using C#?

For me this worked only:

foreach (ComboBoxItem cbi in someComboBox.Items)
{
    if (cbi.Content as String == "sometextIntheComboBox")
    {
        someComboBox.SelectedItem = cbi;
        break;
    }
}

MOD: and if You have your own objects as items set up in the combobox, then substitute the ComboBoxItem with one of them like:

foreach (Debitor d in debitorCombo.Items)
{
    if (d.Name == "Chuck Norris")
    {
        debitorCombo.SelectedItem = d;
        break;
    }
}