Programs & Examples On #Object code

Assembly code vs Machine code vs Object code?

Assembly code is a human readable representation of machine code:

mov eax, 77
jmp anywhere

Machine code is pure hexadecimal code:

5F 3A E3 F1

I assume you mean object code as in an object file. This is a variant of machine code, with a difference that the jumps are sort of parameterized such that a linker can fill them in.

An assembler is used to convert assembly code into machine code (object code) A linker links several object (and library) files to generate an executable.

I have once written an assembler program in pure hex (no assembler available) luckily this was way back on the good old (ancient) 6502. But I'm glad there are assemblers for the pentium opcodes.

How to add shortcut keys for java code in eclipse

Type syso and ctrl + space for System.out.println()

change type of input field with jQuery

Type properties can't be changed you need to replace or overlay the input with a text input and send the value to the password input on submit.

SQL Server Script to create a new user

Full admin rights for the whole server, or a specific database? I think the others answered for a database, but for the server:

USE [master];
GO
CREATE LOGIN MyNewAdminUser 
    WITH PASSWORD    = N'abcd',
    CHECK_POLICY     = OFF,
    CHECK_EXPIRATION = OFF;
GO
EXEC sp_addsrvrolemember 
    @loginame = N'MyNewAdminUser', 
    @rolename = N'sysadmin';

You may need to leave off the CHECK_ parameters depending on what version of SQL Server Express you are using (it is almost always useful to include this information in your question).

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

I don't know why, but the accepted answer didn't work for me. Instead this worked:

if ($(this).hasClass("test") !== false) {}

Angular 4 - Observable catch error

catch needs to return an observable.

.catch(e => { console.log(e); return Observable.of(e); })

if you'd like to stop the pipeline after a caught error, then do this:

.catch(e => { console.log(e); return Observable.of(null); }).filter(e => !!e)

this catch transforms the error into a null val and then filter doesn't let falsey values through. This will however, stop the pipeline for ANY falsey value, so if you think those might come through and you want them to, you'll need to be more explicit / creative.

edit:

better way of stopping the pipeline is to do

.catch(e => Observable.empty())

jQuery: find element by text

In jQuery documentation it says:

The matching text can appear directly within the selected element, in any of that element's descendants, or a combination

Therefore it is not enough that you use :contains() selector, you also need to check if the text you search for is the direct content of the element you are targeting for, something like that:

function findElementByText(text) {
    var jSpot = $("b:contains(" + text + ")")
                .filter(function() { return $(this).children().length === 0;})
                .parent();  // because you asked the parent of that element

    return jSpot;
}

Can we overload the main method in Java?

Yes. 'main( )' method can be overloaded. I have tried to put in some piece of code to answer your question.

public class Test{
static public void main( String [] args )
        {
                System.out.println( "In the JVMs static main" );
                main( 5, 6, 7 );    //Calling overloaded static main method
                Test t = new Test( );
                String [] message  = { "Subhash", "Loves", "Programming" };
                t.main(5);
                t.main( 6, message );
        }

        public static void main( int ... args )
        {
                System.out.println( "In the static main called by JVM's main" );
                for( int val : args )
                {
                        System.out.println( val );
                }
        }

        public void main( int x )
        {
                System.out.println( "1: In the overloaded  non-static main with int with value " + x );
        }

        public void main( int x, String [] args )
        {
                System.out.println( "2: In the overloaded  non-static main with int with value " + x );
                for ( String val : args )
                {
                        System.out.println( val );
                }
        }
}

Output:

$ java Test
In the JVMs static main
In the static main called by JVM's main
5
6
7
1: In the overloaded  non-static main with int with value 5
2: In the overloaded  non-static main with int with value 6
Subhash
Loves
Programming
$

In the above code, both static-method as well as a non-static version of main methods are overloaded for demonstration purpose. Note that, by writing JVMs main, I mean to say, it is the main method that JVM uses first to execute a program.

Bootstrap modal appearing under background

Just add two lines of CSS:

.modal-backdrop{z-index: 1050;}
.modal{z-index: 1060;}

The .modal-backdrop should have 1050 value to set it over the navbar.

Declare variable MySQL trigger

Agree with neubert about the DECLARE statements, this will fix syntax error. But I would suggest you to avoid using openning cursors, they may be slow.

For your task: use INSERT...SELECT statement which will help you to copy data from one table to another using only one query.

INSERT ... SELECT Syntax.

Call a VBA Function into a Sub Procedure

Calling a Sub Procedure – 3 Way technique

Once you have a procedure, whether you created it or it is part of the Visual Basic language, you can use it. Using a procedure is also referred to as calling it.

Before calling a procedure, you should first locate the section of code in which you want to use it. To call a simple procedure, type its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"

msgbox strFullName
End Sub

Sub Exercise()
    CreateCustomer
End Sub

Besides using the name of a procedure to call it, you can also precede it with the Call keyword. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    Call CreateCustomer
End Sub

When calling a procedure, without or without the Call keyword, you can optionally type an opening and a closing parentheses on the right side of its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    CreateCustomer()
End Sub

Procedures and Access Levels

Like a variable access, the access to a procedure can be controlled by an access level. A procedure can be made private or public. To specify the access level of a procedure, precede it with the Private or the Public keyword. Here is an example:

Private Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

The rules that were applied to global variables are the same:

Private: If a procedure is made private, it can be called by other procedures of the same module. Procedures of outside modules cannot access such a procedure.

Also, when a procedure is private, its name does not appear in the Macros dialog box

Public: A procedure created as public can be called by procedures of the same module and by procedures of other modules.

Also, if a procedure was created as public, when you access the Macros dialog box, its name appears and you can run it from there

GROUP_CONCAT comma separator - MySQL

Or, if you are doing a split - join:

GROUP_CONCAT(split(thing, " "), '----') AS thing_name,

You may want to inclue WITHIN RECORD, like this:

GROUP_CONCAT(split(thing, " "), '----') WITHIN RECORD AS thing_name,

from BigQuery API page

How do I use a C# Class Library in a project?

  1. Add a reference to your library
  2. Import the namespace
  3. Consume the types in your library

How can I slice an ArrayList out of an ArrayList in Java?

If there is no existing method then I guess you can iterate from 0 to input.size()/2, taking each consecutive element and appending it to a new ArrayList.

EDIT: Actually, I think you can take that List and use it to instantiate a new ArrayList using one of the ArrayList constructors.

Removing input background colour for Chrome autocomplete?

and this worked for me (Chrome 76 tested)

input:-internal-autofill-selected {
    background-color: transparent;
}

Proxy with express.js

First install express and http-proxy-middleware

npm install express http-proxy-middleware --save

Then in your server.js

const express = require('express');
const proxy = require('http-proxy-middleware');

const app = express();
app.use(express.static('client'));

// Add middleware for http proxying 
const apiProxy = proxy('/api', { target: 'http://localhost:8080' });
app.use('/api', apiProxy);

// Render your site
const renderIndex = (req, res) => {
  res.sendFile(path.resolve(__dirname, 'client/index.html'));
}
app.get('/*', renderIndex);

app.listen(3000, () => {
  console.log('Listening on: http://localhost:3000');
});

In this example we serve the site on port 3000, but when a request end with /api we redirect it to localhost:8080.

http://localhost:3000/api/login redirect to http://localhost:8080/api/login

How to empty a list in C#?

Option #1: Use Clear() function to empty the List<T> and retain it's capacity.

  • Count is set to 0, and references to other objects from elements of the collection are also released.

  • Capacity remains unchanged.

Option #2 - Use Clear() and TrimExcess() functions to set List<T> to initial state.

  • Count is set to 0, and references to other objects from elements of the collection are also released.

  • Trimming an empty List<T> sets the capacity of the List to the default capacity.

Definitions

Count = number of elements that are actually in the List<T>

Capacity = total number of elements the internal data structure can hold without resizing.

Clear() Only

List<string> dinosaurs = new List<string>();    
dinosaurs.Add("Compsognathus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Deinonychus");
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
dinosaurs.Clear();
Console.WriteLine("\nClear()");
Console.WriteLine("\nCount: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);

Clear() and TrimExcess()

List<string> dinosaurs = new List<string>();
dinosaurs.Add("Triceratops");
dinosaurs.Add("Stegosaurus");
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
dinosaurs.Clear();
dinosaurs.TrimExcess();
Console.WriteLine("\nClear() and TrimExcess()");
Console.WriteLine("\nCount: {0}", dinosaurs.Count);
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);

How to change the background color of a UIButton while it's highlighted?

Details

  • Xcode 11.1 (11A1027), Swift 5

Solution

import UIKit

extension UIColor {
    func createOnePixelImage() -> UIImage? {
        let size = CGSize(width: 1, height: 1)
        UIGraphicsBeginImageContext(size)
        defer { UIGraphicsEndImageContext() }
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        context.setFillColor(cgColor)
        context.fill(CGRect(origin: .zero, size: size))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

extension UIButton {
    func setBackground(_ color: UIColor, for state: UIControl.State) {
        setBackgroundImage(color.createOnePixelImage(), for: state)
    }
}

Usage

button.setBackground(.green, for: .normal)

How do I get the scroll position of a document?

document.getElementById("elementID").scrollHeight

$("elementID").scrollHeight

git returns http error 407 from proxy after CONNECT

I had the similar issue and I resolved with below steps:

** Add proxy details in git**

git config --global http.sslVerify false
git config --global https.sslVerify false
git config --global http.proxy http://user:pass@yourproxy:port
git config --global https.proxy http://user:pass@yourproxy:port

How to highlight cell if value duplicate in same column for google spreadsheet?

I tried all the options and none worked.

Only google app scripts helped me.

source : https://ctrlq.org/code/19649-find-duplicate-rows-in-google-sheets

At the top of your document

1.- go to tools > script editor

2.- set the name of your script

3.- paste this code :

function findDuplicates() {
  // List the columns you want to check by number (A = 1)
  var CHECK_COLUMNS = [1];

  // Get the active sheet and info about it
  var sourceSheet = SpreadsheetApp.getActiveSheet();
  var numRows = sourceSheet.getLastRow();
  var numCols = sourceSheet.getLastColumn();

  // Create the temporary working sheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var newSheet = ss.insertSheet("FindDupes");

  // Copy the desired rows to the FindDupes sheet
  for (var i = 0; i < CHECK_COLUMNS.length; i++) {
    var sourceRange = sourceSheet.getRange(1,CHECK_COLUMNS[i],numRows);
    var nextCol = newSheet.getLastColumn() + 1;
    sourceRange.copyTo(newSheet.getRange(1,nextCol,numRows));
  }

  // Find duplicates in the FindDupes sheet and color them in the main sheet
  var dupes = false;
  var data = newSheet.getDataRange().getValues();
  for (i = 1; i < data.length - 1; i++) {
    for (j = i+1; j < data.length; j++) {
      if  (data[i].join() == data[j].join()) {
        dupes = true;
        sourceSheet.getRange(i+1,1,1,numCols).setBackground("red");
        sourceSheet.getRange(j+1,1,1,numCols).setBackground("red");
      }
    }
  }

  // Remove the FindDupes temporary sheet
  ss.deleteSheet(newSheet);

  // Alert the user with the results
  if (dupes) {
    Browser.msgBox("Possible duplicate(s) found and colored red.");
  } else {
    Browser.msgBox("No duplicates found.");
  }
};

4.- save and run

In less than 3 seconds, my duplicate row was colored. Just copy-past the script.

If you don't know about google apps scripts , this links could be help you:

https://zapier.com/learn/google-sheets/google-apps-script-tutorial/

https://developers.google.com/apps-script/overview

I hope this helps.

Find the location of a character in string

You could use grep as well:

grep('2', strsplit(string, '')[[1]])
#4 24

Using a different font with twitter bootstrap

First of all you have to include your font in your website (or your CSS, to be more specific) using an appropriate @font-face rule.
From here on there are multiple ways to proceed. One thing I would not do is to edit the bootstrap.css directly - since once you get a newer version your changes will be lost. You do however have the possibility to customize your bootstrap files (there's a customize page on their website). Just enter the name of your font with all the fallback names into the corresponding typography textbox. Of course you will have to do this whenever you get a new or updated version of your bootstrap files.
Another chance you have is to overwrite the bootstrap rules within a different stylesheet. If you do this you just have to use selectors that are as specific as (or more specific than) the bootstrap selectors.
Side note: If you care about browser support a single EOT version of your font might not be sufficient. See http://caniuse.com/eot for a support table.

Convert file to byte array and vice versa

Server side

@RequestMapping("/download")
public byte[] download() throws Exception {
    File f = new File("C:\\WorkSpace\\Text\\myDoc.txt");
     byte[] byteArray = new byte[(int) f.length()];
        byteArray = FileUtils.readFileToByteArray(f);
        return byteArray;
}

Client side

private ResponseEntity<byte[]> getDownload(){
    URI end = URI.create(your url which server has exposed i.e. bla 
              bla/download);
    return rest.getForEntity(end,byte[].class);

}

public static void main(String[] args) throws Exception {


    byte[] byteArray = new TestClient().getDownload().getBody();
    FileOutputStream fos = new 
    FileOutputStream("C:\\WorkSpace\\testClient\\abc.txt");

     fos.write(byteArray);
     fos.close(); 
     System.out.println("file written successfully..");


}

how to check if item is selected from a comboBox in C#

Here is the perfect coding which checks whether the Combo Box Item is Selected or not

if (string.IsNullOrEmpty(comboBox1.Text))
{
    MessageBox.Show("No Item is Selected"); 
}
else
{
    MessageBox.Show("Item Selected is:" + comboBox1.Text);
}

Creating java date object from year,month,day

Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.

Here is a quick example using LocalDate from the Joda Time library:

LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();

Here you can follow a quick start tutorial.

Error handling in C code

I've used both approaches, and they both worked fine for me. Whichever one I use, I always try to apply this principle:

If the only possible errors are programmer errors, don't return an error code, use asserts inside the function.

An assertion that validates the inputs clearly communicates what the function expects, while too much error checking can obscure the program logic. Deciding what to do for all the various error cases can really complicate the design. Why figure out how functionX should handle a null pointer if you can instead insist that the programmer never pass one?

How to use a variable for a key in a JavaScript object literal?

With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation: 

var obj = {
  [key]: value
}

Where key can be any sort of expression (e.g. a variable) returning a value.

So here your code would look like:

<something>.stop().animate({
  [thetop]: 10
}, 10)

Where thetop will be evaluated before being used as key.

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

You may set the default file association of ps1 files to be powershell.exe which will allow you to execute a powershell script by double clicking on it.

In Windows 10,

  1. Right click on a ps1 file
  2. Click Open with
  3. Click Choose another app
  4. In the popup window, select More apps
  5. Scroll to the bottom and select Look for another app on this PC.
  6. Browse to and select C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe.
  7. List item

That will change the file association and ps1 files will execute by double-clicking them. You may change it back to its default behavior by setting notepad.exe to the default app.

Source

Is there a JSON equivalent of XQuery/XPath?

If you're like me and you just want to do path-based lookups, but don't care about real XPath, lodash's _.get() can work. Example from lodash docs:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// ? 3

_.get(object, ['a', '0', 'b', 'c']);
// ? 3

_.get(object, 'a.b.c', 'default');
// ? 'default'

mysql datatype for telephone number and address

Consider normalizing to E.164 format. For full international support, you'd need a VARCHAR of 15 digits.

See Twilio's recommendation for more information on localization of phone numbers.

How to install an apk on the emulator in Android Studio?

In android studio emulator to run an apk file just drag the apk into the emulator.The emulator will install the apk

How do I run a batch file from my Java Application?

To run batch files using java if that's you're talking about...

String path="cmd /c start d:\\sample\\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);`

This should do it.

Does MySQL foreign_key_checks affect the entire database?

Actually, there are two foreign_key_checks variables: a global variable and a local (per session) variable. Upon connection, the session variable is initialized to the value of the global variable.
The command SET foreign_key_checks modifies the session variable.
To modify the global variable, use SET GLOBAL foreign_key_checks or SET @@global.foreign_key_checks.

Consult the following manual sections:
http://dev.mysql.com/doc/refman/5.7/en/using-system-variables.html
http://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html

PHP - SSL certificate error: unable to get local issuer certificate

I found new Solution without any required certification to call curl only add two line code.

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

For loop in Oracle SQL

You will certainly be able to do that using WITH clause, or use analytic functions available in Oracle SQL.

With some effort you'd be able to get anything out of them in terms of cycles as in ordinary procedural languages. Both approaches are pretty powerful compared to ordinary SQL.

http://www.dba-oracle.com/t_with_clause.htm

http://www.orafaq.com/node/55

It requires some effort though. Don't be afraid to post a concrete example.

Using simple pseudo table DUAL helps too.

nginx 502 bad gateway

For me the error was in default file of Nginx located at /etc/nginx/sites-available/default

I noticed the version of php-fpm used was 7.0 and the php version i downloaded was 7.2 I simply changed the version to 7.2 and it worked.

fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;

Create sequence of repeated values, in sequence?

Another base R option could be gl():

gl(5, 3)

Where the output is a factor:

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Levels: 1 2 3 4 5

If integers are needed, you can convert it:

as.numeric(gl(5, 3))

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5

Difference between JOIN and INNER JOIN

Similarly with OUTER JOINs, the word "OUTER" is optional. It's the LEFT or RIGHT keyword that makes the JOIN an "OUTER" JOIN.

However for some reason I always use "OUTER" as in LEFT OUTER JOIN and never LEFT JOIN, but I never use INNER JOIN, but rather I just use "JOIN":

SELECT ColA, ColB, ...
FROM MyTable AS T1
     JOIN MyOtherTable AS T2
         ON T2.ID = T1.ID
     LEFT OUTER JOIN MyOptionalTable AS T3
         ON T3.ID = T1.ID

Flutter Circle Design

You can use CustomMultiChildLayout to draw this kind of layouts. Here you can find a tutorial: How to Create Custom Layout Widgets in Flutter.

Echo a blank (empty) line to the console from a Windows batch file

Any of the below three options works for you:

echo[

echo(

echo. 

For example:

@echo off
echo There will be a blank line below
echo[
echo Above line is blank
echo( 
echo The above line is also blank.
echo. 
echo The above line is also blank.

How to change value of ArrayList element in java

I think the problem is that you think the statement ...

x = Integer.valueOf(9);

... causes that the value of '9' get 'stored' into(!) the Object on which x is referencing.

But thats wrong.

Instead the statement causes something similar as if you would call

x = new Integer(9); 

If you have a look to the java source code, you will see what happens in Detail.

Here is the code of the "valueOf(int i)" method in the "Integer" class:

public static Integer valueOf(int i) {
    assert IntegerCache.high >= 127;
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

and further, whenever the IntegerCache class is used for the first time the following script gets invoked:

static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            int i = parseInt(integerCacheHighPropValue);
            i = Math.max(i, 127);
            // Maximum array size is Integer.MAX_VALUE
            h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);
    }

You see that either a new Integer Object is created with "new Integer(i)" in the valueOf method ... ... or a reference to a Integer Object which is stored in the IntegerCache is returned.

In both cases x will reference to a new Object.

And this is why the reference to the Object in your list get lost when you call ...

x = Integer.valueOf(9);

Instead of doing so, in combination with a ListIterator use ...

i.set(Integer.valueOf(9));

... after you got the element you want to change with ...

i.next();

MySQL set current date in a DATETIME field on insert

Your best bet is to change that column to a timestamp. MySQL will automatically use the first timestamp in a row as a 'last modified' value and update it for you. This is configurable if you just want to save creation time.

See doc http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html

How to get the selected date of a MonthCalendar control in C#

For those who are still trying, this link helped me out, too; it just puts it all together:

http://dotnetslackers.com/VB_NET/re-36138_How_To_Get_Selected_Date_from_MonthCalendar_control.aspx

private void MonthCalendar1_DateChanged(object sender, System.Windows.Forms.DateRangeEventArgs e)
{
//Display the dates for selected range
Label1.Text = "Dates Selected from :" + (MonthCalendar1.SelectionRange.Start() + " to " + MonthCalendar1.SelectionRange.End);

//To display single selected of date
//MonthCalendar1.MaxSelectionCount = 1;

//To display single selected of date use MonthCalendar1.SelectionRange.Start/ MonthCalendarSelectionRange.End
Label2.Text = "Date Selected :" + MonthCalendar1.SelectionRange.Start;
}

Grouping into interval of 5 minutes within a time range

You should rather use GROUP BY UNIX_TIMESTAMP(time_stamp) DIV 300 instead of round(../300) because of the rounding I found that some records are counted into two grouped result sets.

How to list all the files in android phone by using adb shell?

just to add the full command:

adb shell ls -R | grep filename

this is actually a pretty fast lookup on Android

HTML input fields does not get focus when clicked

I had this issue using Bootstrap + contact form 7. I for some reason I put the label as the container of the form and that was the issue for not being selectable on mobile.

<label>
    <contact form>...</contact form>
</label>

Seemed to break all inputs except the first input and the submit.

How do I close an Android alertdialog

Replying to an old post but hopefully somebody might find this useful. Do this instead

final AlertDialog builder = new AlertDialog.Builder(getActivity()).create();

You can then go ahead and do,

builder.dismiss();

Calling JMX MBean method from a shell script

I've developed jmxfuse which exposes JMX Mbeans as a Linux FUSE filesystem with similar functionality as the /proc fs. It relies on Jolokia as the bridge to JMX. Attributes and operations are exposed for reading and writing.

http://code.google.com/p/jmxfuse/

For example, to read an attribute:

me@oddjob:jmx$ cd log4j/root/attributes
me@oddjob:jmx$ cat priority

to write an attribute:

me@oddjob:jmx$ echo "WARN" > priority

to invoke an operation:

me@oddjob:jmx$ cd Catalina/none/none/WebModule/localhost/helloworld/operations/addParameter
me@oddjob:jmx$ echo "myParam myValue" > invoke

How to print multiple lines of text with Python

The triple quotes answer is great for ASCII art, but for those wondering - what if my multiple lines are a tuple, list, or other iterable that returns strings (perhaps a list comprehension?), then how about:

print("\n".join(<*iterable*>))

For example:

print("\n".join(["{}={}".format(k, v) for k, v in os.environ.items() if 'PATH' in k]))

bash script read all the files in directory

To write it with a while loop you can do:

ls -f /var | while read -r file; do cmd $file; done

The primary disadvantage of this is that cmd is run in a subshell, which causes some difficulty if you are trying to set variables. The main advantages are that the shell does not need to load all of the filenames into memory, and there is no globbing. When you have a lot of files in the directory, those advantages are important (that's why I use -f on ls; in a large directory ls itself can take several tens of seconds to run and -f speeds that up appreciably. In such cases 'for file in /var/*' will likely fail with a glob error.)

Spring MVC Multipart Request with JSON

This is how I implemented Spring MVC Multipart Request with JSON Data.

Multipart Request with JSON Data (also called Mixed Multipart):

Based on RESTful service in Spring 4.0.2 Release, HTTP request with the first part as XML or JSON formatted data and the second part as a file can be achieved with @RequestPart. Below is the sample implementation.

Java Snippet:

Rest service in Controller will have mixed @RequestPart and MultipartFile to serve such Multipart + JSON request.

@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
    consumes = {"multipart/form-data"})
@ResponseBody
public boolean executeSampleService(
        @RequestPart("properties") @Valid ConnectionProperties properties,
        @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
    return projectService.executeSampleService(properties, file);
}

Front End (JavaScript) Snippet:

  1. Create a FormData object.

  2. Append the file to the FormData object using one of the below steps.

    1. If the file has been uploaded using an input element of type "file", then append it to the FormData object. formData.append("file", document.forms[formName].file.files[0]);
    2. Directly append the file to the FormData object. formData.append("file", myFile, "myfile.txt"); OR formData.append("file", myBob, "myfile.txt");
  3. Create a blob with the stringified JSON data and append it to the FormData object. This causes the Content-type of the second part in the multipart request to be "application/json" instead of the file type.

  4. Send the request to the server.

  5. Request Details:
    Content-Type: undefined. This causes the browser to set the Content-Type to multipart/form-data and fill the boundary correctly. Manually setting Content-Type to multipart/form-data will fail to fill in the boundary parameter of the request.

Javascript Code:

formData = new FormData();

formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
                "name": "root",
                "password": "root"                    
            })], {
                type: "application/json"
            }));

Request Details:

method: "POST",
headers: {
         "Content-Type": undefined
  },
data: formData

Request Payload:

Accept:application/json, text/plain, */*
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryEBoJzS3HQ4PgE1QB

------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="file"; filename="myfile.txt"
Content-Type: application/txt


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN
Content-Disposition: form-data; name="properties"; filename="blob"
Content-Type: application/json


------WebKitFormBoundaryvijcWI2ZrZQ8xEBN--

Removing numbers from string

Say st is your unformatted string, then run

st_nodigits=''.join(i for i in st if i.isalpha())

as mentioned above. But my guess that you need something very simple so say s is your string and st_res is a string without digits, then here is your code

l = ['0','1','2','3','4','5','6','7','8','9']
st_res=""
for ch in s:
 if ch not in l:
  st_res+=ch

How do I get indices of N maximum values in a NumPy array?

Method np.argpartition only returns the k largest indices, performs a local sort, and is faster than np.argsort(performing a full sort) when array is quite large. But the returned indices are NOT in ascending/descending order. Let's say with an example:

Enter image description here

We can see that if you want a strict ascending order top k indices, np.argpartition won't return what you want.

Apart from doing a sort manually after np.argpartition, my solution is to use PyTorch, torch.topk, a tool for neural network construction, providing NumPy-like APIs with both CPU and GPU support. It's as fast as NumPy with MKL, and offers a GPU boost if you need large matrix/vector calculations.

Strict ascend/descend top k indices code will be:

Enter image description here

Note that torch.topk accepts a torch tensor, and returns both top k values and top k indices in type torch.Tensor. Similar with np, torch.topk also accepts an axis argument so that you can handle multi-dimensional arrays/tensors.

How to install a Notepad++ plugin offline?

Here are my steps tried with NPP 7.8.2:

(1)Download the plugins zip (refer plugin-full-list json):

https://github.com/notepad-plus-plus/nppPluginList/blob/master/src/pl.x64.json

(2)Extract the files (normally .dll lib files) from zip to npp's plugins sub-folder

E.g., extract NppFTP-x64.zip into C:\Program Files\Notepad++\plugins\NppFTP

Keep in mind:

  (i)Must create sub-folder for each plugin
 (ii)The sub-folder's name must be EXACTLY SAME as the main .dll filename (e.g., NppFTP.dll)

(3)Restart npp, those plugin will be automatically loaded.

[Note-1]: I didn't do setting->import->plugin, it seems this is not required [Note-2]: You may need start npp with "run as administrator" option if you want to do import plugin.

C/C++ maximum stack size of program

I am not sure what you mean by doing a depth first search on a rectangular array, but I assume you know what you are doing.

If the stack limit is a problem you should be able to convert your recursive solution into an iterative solution that pushes intermediate values onto a stack which is allocated from the heap.

Read only file system on Android

it sames that must extract and repack initrc.img and edit init file with the code of mount /system

How can I change the text inside my <span> with jQuery?

$('#abc span').text('baa baa black sheep');
$('#abc span').html('baa baa <strong>black sheep</strong>');

text() if just text content. html() if it contains, well, html content.

plot different color for different categorical levels using matplotlib

Using Altair.

from altair import *
import pandas as pd

df = datasets.load_dataset('iris')
Chart(df).mark_point().encode(x='petalLength',y='sepalLength', color='species')

enter image description here

Make a td fixed size (width,height) while rest of td's can expand

This will take care of the empty td:

<td style="min-width: 20px;"></td>

Counting the number of occurences of characters in a string

This is the problem:

while(str.charAt(i)==ch)

That will keep going until it falls off the end... when i is the same as the length of the string, it will be asking for a character beyond the end of the string. You probably want:

while (i < str.length() && str.charAt(i) == ch)

You also need to set count to 0 at the start of each iteration of the bigger loop - the count resets, after all - and change

count = count + i;

to either:

count++;

... or get rid of count or i. They're always going to have the same value, after all. Personally I'd just use one variable, declared and initialized inside the loop. That's a general style point, in fact - it's cleaner to declare local variables when they're needed, rather than declaring them all at the top of the method.

However, then your program will loop forever, as this doesn't do anything useful:

str.substring(count);

Strings are immutable in Java - substring returns a new string. I think you want:

str = str.substring(count);

Note that this will still output "a2b2a2" for "aabbaa". Is that okay?

Date constructor returns NaN in IE, but works in Firefox and Chrome

You can use the following code to parse ISO8601 date string:

function parseISO8601(d) {
    var timestamp = d;
    if (typeof (d) !== 'number') {
        timestamp = Date.parse(d);
    }
    return new Date(timestamp);
};

How to get the value of an input field using ReactJS?

You should use constructor under the class MyComponent extends React.Component

constructor(props){
    super(props);
    this.onSubmit = this.onSubmit.bind(this);
  }

Then you will get the result of title

What does it mean by command cd /d %~dp0 in Windows

Let's dissect it. There are three parts:

  1. cd -- This is change directory command.
  2. /d -- This switch makes cd change both drive and directory at once. Without it you would have to do cd %~d0 & cd %~p0. (%~d0 Changs active drive, cd %~p0 change the directory).
  3. %~dp0 -- This can be dissected further into three parts:
    1. %0 -- This represents zeroth parameter of your batch script. It expands into the name of the batch file itself.
    2. %~0 -- The ~ there strips double quotes (") around the expanded argument.
    3. %dp0 -- The d and p there are modifiers of the expansion. The d forces addition of a drive letter and the p adds full path.

How to use forEach in vueJs?

In VueJS you can loop through an array like this : const array1 = ['a', 'b', 'c'];

Array.from(array1).forEach(element => 
 console.log(element)
      );

in my case I want to loop through files and add their types to another array:

 Array.from(files).forEach((file) => {
       if(this.mediaTypes.image.includes(file.type)) {
            this.media.images.push(file)
             console.log(this.media.images)
       }
   }

sorting dictionary python 3

I'm not sure whether this could help, but I had a similar problem and I managed to solve it, by defining an apposite function:

def sor_dic_key(diction):
    lista = []
    diction2 = {}
    for x in diction:
        lista.append([x, diction[x]])
    lista.sort(key=lambda x: x[0])
    for l in lista:
        diction2[l[0]] = l[1]
    return diction2

This function returns another dictionary with the same keys and relative values, but sorted by its keys. Similarly, I defined a function that could sort a dictionary by its values. I just needed to use x[1] instead of x[0] in the lambda function. I find this second function mostly useless, but one never can tell!

How Connect to remote host from Aptana Studio 3

Window -> Show View -> Other -> Studio/Remote

(Drag this tabbed window wherever)

Click the add FTP button (see below); #profit

Add New FTP Site...

Mask for an Input to allow phone numbers?

It can be done using a directive. Below is the plunker of the input mask I built.

https://plnkr.co/edit/hRsmd0EKci6rjGmnYFRr?p=preview

Code:

import {Directive, Attribute, ElementRef, OnInit, OnChanges, Input, SimpleChange } from 'angular2/core';
import {NgControl, DefaultValueAccessor} from 'angular2/common';

@Directive({
selector: '[mask-input]',
host: {
    //'(keyup)': 'onInputChange()',
    '(click)': 'setInitialCaretPosition()'
}, 
inputs: ['modify'],
providers: [DefaultValueAccessor]
})
export class MaskDirective implements OnChanges {
maskPattern: string;
placeHolderCounts: any;
dividers: string[];
modelValue: string;
viewValue: string;
intialCaretPos: any;
numOfChar: any;
@Input() modify: any; 

constructor(public model: NgControl, public ele: ElementRef, @Attribute("mask-input") maskPattern: string) {
    this.dividers = maskPattern.replace(/\*/g, "").split("");
    this.dividers.push("_");
    this.generatePattern(maskPattern);   
    this.numOfChar = 0;
}

ngOnChanges(changes: { [propertyName: string]: SimpleChange }) {
    this.onInputChange(changes);
}

onInputChange(changes: { [propertyName: string]: SimpleChange }) {             
    this.modelValue = this.getModelValue();
    var caretPosition = this.ele.nativeElement.selectionStart;
    if (this.viewValue != null) {
      this.numOfChar = this.getNumberOfChar(caretPosition);
    }
    var stringToFormat = this.modelValue;        

    if (stringToFormat.length < 10) {
        stringToFormat = this.padString(stringToFormat);
    }

    this.viewValue = this.format(stringToFormat);

    if (this.viewValue != null) {
        caretPosition = this.setCaretPosition(this.numOfChar);
    }

    this.model.viewToModelUpdate(this.modelValue);
    this.model.valueAccessor.writeValue(this.viewValue);
    this.ele.nativeElement.selectionStart = caretPosition;
    this.ele.nativeElement.selectionEnd = caretPosition;
}

generatePattern(patternString) {
    this.placeHolderCounts = (patternString.match(/\*/g) || []).length;
    for (var i = 0; i < this.placeHolderCounts; i++) {
        patternString = patternString.replace('*', "{" + i + "}");
    }
    this.maskPattern = patternString;
}

format(s) {
    var formattedString = this.maskPattern;
    for (var i = 0; i < this.placeHolderCounts; i++) {
        formattedString = formattedString.replace("{" + i + "}", s.charAt(i));
    }
    return formattedString;
}

padString(s) {
    var pad = "__________";
    return (s + pad).substring(0, pad.length);
}

getModelValue() {
    var modelValue = this.model.value;
    if (modelValue == null) {
        return "";
    }
    for (var i = 0; i < this.dividers.length; i++) {
        while (modelValue.indexOf(this.dividers[i]) > -1) {
            modelValue = modelValue.replace(this.dividers[i], "");
        }
    }
    return modelValue;
}

setInitialCaretPosition() {
    var caretPosition = this.setCaretPosition(this.modelValue.length);

    this.ele.nativeElement.selectionStart = caretPosition;
    this.ele.nativeElement.selectionEnd = caretPosition;

}

setCaretPosition(num) {
    var notDivider = true;
    var caretPos = 1;
    for (; num > 0; caretPos++) {
      var ch = this.viewValue.charAt(caretPos);
      if (!this.isDivider(ch)) {
        num--;
      }
    }
    return caretPos;
}

isDivider(ch) {
    for (var i = 0; i < this.dividers.length; i++) {
          if (ch == this.dividers[i]) {
              return true;
          }
    }
}

getNumberOfChar(pos) {
  var num = 0;
  var containDividers = false;
  for (var i = 0; i < pos; i++) {
    var ch = this.modify.charAt(i);

    if (!this.isDivider(ch)) {
      num++;
    }
    else {
      containDividers = true;
    }
  }
  if (containDividers) {
    return num;
  }
  else {
    return this.numOfChar;
  }
}

}

Note: there are still a few bugs.

Sqlite or MySql? How to decide?

Their feature sets are not at all the same. Sqlite is an embedded database which has no network capabilities (unless you add them). So you can't use it on a network.

If you need

  • Network access - for example accessing from another machine;
  • Any real degree of concurrency - for example, if you think you are likely to want to run several queries at once, or run a workload that has lots of selects and a few updates, and want them to go smoothly etc.
  • a lot of memory usage, for example, to buffer parts of your 1Tb database in your 32G of memory.

You need to use mysql or some other server-based RDBMS.

Note that MySQL is not the only choice and there are plenty of others which might be better for new applications (for example pgSQL).

Sqlite is a very, very nice piece of software, but it has never made claims to do any of these things that RDBMS servers do. It's a small library which runs SQL on local files (using locking to ensure that multiple processes don't screw the file up). It's really well tested and I like it a lot.

Also, if you aren't able to choose this correctly by yourself, you probably need to hire someone on your team who can.

How do I extract data from a DataTable?

You can set the datatable as a datasource to many elements.

For eg

gridView

repeater

datalist

etc etc

If you need to extract data from each row then you can use

table.rows[rowindex][columnindex]

or

if you know the column name

table.rows[rowindex][columnname]

If you need to iterate the table then you can either use a for loop or a foreach loop like

for ( int i = 0; i < table.rows.length; i ++ )
{
    string name = table.rows[i]["columnname"].ToString();
}

foreach ( DataRow dr in table.Rows )
{
    string name = dr["columnname"].ToString();
}

How do I add a auto_increment primary key in SQL Server database?

If the table already contains data and you want to change one of the columns to identity:

First create a new table that has the same columns and specify the primary key-kolumn:

create table TempTable
(
    Id int not null identity(1, 1) primary key
    --, Other columns...
)

Then copy all rows from the original table to the new table using a standard insert-statement.

Then drop the original table.

And finally rename TempTable to whatever you want using sp_rename:

http://msdn.microsoft.com/en-us/library/ms188351.aspx

Hyphen, underscore, or camelCase as word delimiter in URIs?

The standard best practice for REST APIs is to have a hyphen, not camelcase or underscores.

This comes from Mark Masse's "REST API Design Rulebook" from Oreilly.

In addition, note that Stack Overflow itself uses hyphens in the URL: .../hyphen-underscore-or-camelcase-as-word-delimiter-in-uris

As does WordPress: http://inventwithpython.com/blog/2012/03/18/how-much-math-do-i-need-to-know-to-program-not-that-much-actually

Select objects based on value of variable in object using jq

I had a similar related question: What if you wanted the original object format back (with key names, e.g. FOO, BAR)?

Jq provides to_entries and from_entries to convert between objects and key-value pair arrays. That along with map around the select

These functions convert between an object and an array of key-value pairs. If to_entries is passed an object, then for each k: v entry in the input, the output array includes {"key": k, "value": v}.

from_entries does the opposite conversion, and with_entries(foo) is a shorthand for to_entries | map(foo) | from_entries, useful for doing some operation to all keys and values of an object. from_entries accepts key, Key, name, Name, value and Value as keys.

jq15 < json 'to_entries | map(select(.value.location=="Stockholm")) | from_entries'

{
  "FOO": {
    "name": "Donald",
    "location": "Stockholm"
  },
  "BAR": {
    "name": "Walt",
    "location": "Stockholm"
  }
}

Using the with_entries shorthand, this becomes:

jq15 < json 'with_entries(select(.value.location=="Stockholm"))'
{
  "FOO": {
    "name": "Donald",
    "location": "Stockholm"
  },
  "BAR": {
    "name": "Walt",
    "location": "Stockholm"
  }
}

Dynamic variable names in Bash

Use declare

There is no need on using prefixes like on other answers, neither arrays. Use just declare, double quotes, and parameter expansion.

I often use the following trick to parse argument lists contanining one to n arguments formatted as key=value otherkey=othervalue etc=etc, Like:

# brace expansion just to exemplify
for variable in {one=foo,two=bar,ninja=tip}
do
  declare "${variable%=*}=${variable#*=}"
done
echo $one $two $ninja 
# foo bar tip

But expanding the argv list like

for v in "$@"; do declare "${v%=*}=${v#*=}"; done

Extra tips

# parse argv's leading key=value parameters
for v in "$@"; do
  case "$v" in ?*=?*) declare "${v%=*}=${v#*=}";; *) break;; esac
done
# consume argv's leading key=value parameters
while (( $# )); do
  case "$v" in ?*=?*) declare "${v%=*}=${v#*=}";; *) break;; esac
  shift
done

How to get the screen width and height in iOS?

I've translated some of the above Objective-C answers into Swift code. Each translation is proceeded with a reference to the original answer.

Main Answer

let screen = UIScreen.main.bounds
let screenWidth = screen.size.width
let screenHeight = screen.size.height

##Simple Function Answer

func windowHeight() -> CGFloat {
    return UIScreen.main.bounds.size.height
}

func windowWidth() -> CGFloat {
    return UIScreen.main.bounds.size.width
}

##Device Orientation Answer

let screenHeight: CGFloat
let statusBarOrientation = UIApplication.shared.statusBarOrientation
// it is important to do this after presentModalViewController:animated:
if (statusBarOrientation != .portrait
    && statusBarOrientation != .portraitUpsideDown) {
    screenHeight = UIScreen.main.bounds.size.width
} else {
    screenHeight = UIScreen.main.bounds.size.height
}

##Log Answer

let screenWidth = UIScreen.main.bounds.size.width
let screenHeight = UIScreen.main.bounds.size.height
println("width: \(screenWidth)")
println("height: \(screenHeight)")

git diff file against its last change

This does exist, but it's actually a feature of git log:

git log -p [--follow] [-1] <path>

Note that -p can also be used to show the inline diff from a single commit:

git log -p -1 <commit>

Options used:

  • -p (also -u or --patch) is hidden deeeeeeeep in the git-log man page, and is actually a display option for git-diff. When used with log, it shows the patch that would be generated for each commit, along with the commit information—and hides commits that do not touch the specified <path>. (This behavior is described in the paragraph on --full-diff, which causes the full diff of each commit to be shown.)
  • -1 shows just the most recent change to the specified file (-n 1 can be used instead of -1); otherwise, all non-zero diffs of that file are shown.
  • --follow is required to see changes that occurred prior to a rename.

As far as I can tell, this is the only way to immediately see the last set of changes made to a file without using git log (or similar) to either count the number of intervening revisions or determine the hash of the commit.

To see older revisions changes, just scroll through the log, or specify a commit or tag from which to start the log. (Of course, specifying a commit or tag returns you to the original problem of figuring out what the correct commit or tag is.)

Credit where credit is due:

  • I discovered log -p thanks to this answer.
  • Credit to FranciscoPuga and this answer for showing me the --follow option.
  • Credit to ChrisBetti for mentioning the -n 1 option and atatko for mentioning the -1 variant.
  • Credit to sweaver2112 for getting me to actually read the documentation and figure out what -p "means" semantically.

Convert an integer to a float number

Type Conversions T() where T is the desired datatype of the result are quite simple in GoLang.

In my program, I scan an integer i from the user input, perform a type conversion on it and store it in the variable f. The output prints the float64 equivalent of the int input. float32 datatype is also available in GoLang

Code:

package main
import "fmt"
func main() {
    var i int
    fmt.Println("Enter an Integer input: ")
    fmt.Scanf("%d", &i)
    f := float64(i)
    fmt.Printf("The float64 representation of %d is %f\n", i, f)
}

Solution:

>>> Enter an Integer input:
>>> 232332
>>> The float64 representation of 232332 is 232332.000000

How do I merge changes to a single file, rather than merging commits?

git checkout <target_branch>
git checkout <source_branch> <file_path>

htaccess Access-Control-Allow-Origin

Add an .htaccess file with the following directives to your fonts folder, if have problems accessing your fonts. Can easily be modified for use with .css or .js files.

<FilesMatch "\.(eot|ttf|otf|woff)$">
    Header set Access-Control-Allow-Origin "*"
</FilesMatch>

Linux find file names with given string recursively

use ack its simple. just type ack <string to be searched>

Pyspark: Filter dataframe based on multiple conditions

faster way (without pyspark.sql.functions)

    df.filter((df.d<5)&((df.col1 != df.col3) |
                    (df.col2 != df.col4) & 
                    (df.col1 ==df.col3)))\
    .show()

C# equivalent of C++ map<string,double>

Roughly:-

var accounts = new Dictionary<string, double>();

// Initialise to zero...

accounts["Fred"] = 0;
accounts["George"] = 0;
accounts["Fred"] = 0;

// Add cash.
accounts["Fred"] += 4.56;
accounts["George"] += 1.00;
accounts["Fred"] += 1.00;

Console.WriteLine("Fred owes me ${0}", accounts["Fred"]);

How can I parse a time string containing milliseconds in it with python?

To give the code that nstehr's answer refers to (from its source):

def timeparse(t, format):
    """Parse a time string that might contain fractions of a second.

    Fractional seconds are supported using a fragile, miserable hack.
    Given a time string like '02:03:04.234234' and a format string of
    '%H:%M:%S', time.strptime() will raise a ValueError with this
    message: 'unconverted data remains: .234234'.  If %S is in the
    format string and the ValueError matches as above, a datetime
    object will be created from the part that matches and the
    microseconds in the time string.
    """
    try:
        return datetime.datetime(*time.strptime(t, format)[0:6]).time()
    except ValueError, msg:
        if "%S" in format:
            msg = str(msg)
            mat = re.match(r"unconverted data remains:"
                           " \.([0-9]{1,6})$", msg)
            if mat is not None:
                # fractional seconds are present - this is the style
                # used by datetime's isoformat() method
                frac = "." + mat.group(1)
                t = t[:-len(frac)]
                t = datetime.datetime(*time.strptime(t, format)[0:6])
                microsecond = int(float(frac)*1e6)
                return t.replace(microsecond=microsecond)
            else:
                mat = re.match(r"unconverted data remains:"
                               " \,([0-9]{3,3})$", msg)
                if mat is not None:
                    # fractional seconds are present - this is the style
                    # used by the logging module
                    frac = "." + mat.group(1)
                    t = t[:-len(frac)]
                    t = datetime.datetime(*time.strptime(t, format)[0:6])
                    microsecond = int(float(frac)*1e6)
                    return t.replace(microsecond=microsecond)

        raise

How to switch between hide and view password

I had the same issue and it is very easy to implement.

All you have to do is wrap your EditText field in a (com.google.android.material.textfield.TextInputLayout) and in that add ( app:passwordToggleEnabled="true" ).

This will show the eye in the EditText field and when you click on it the password will appear and disappear when clicked again.

<com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColorHint="#B9B8B8"
                app:passwordToggleEnabled="true">

                <EditText
                    android:id="@+id/register_password"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="24dp"
                    android:layout_marginRight="44dp"
                    android:backgroundTint="#BEBEBE"
                    android:hint="Password"
                    android:inputType="textPassword"
                    android:padding="16dp"
                    android:textSize="18sp" />
            </com.google.android.material.textfield.TextInputLayout>

ASP.NET MVC controller actions that return JSON or partial html

Another nice way to deal with JSON data is using the JQuery getJSON function. You can call the

public ActionResult SomeActionMethod(int id) 
{ 
    return Json(new {foo="bar", baz="Blech"});
}

Method from the jquery getJSON method by simply...

$.getJSON("../SomeActionMethod", { id: someId },
    function(data) {
        alert(data.foo);
        alert(data.baz);
    }
);

Chain-calling parent initialisers in python

You can simply write :

class A(object):

    def __init__(self):
        print "Initialiser A was called"

class B(A):

    def __init__(self):
        A.__init__(self)
        # A.__init__(self,<parameters>) if you want to call with parameters
        print "Initialiser B was called"

class C(B):

    def __init__(self):
        # A.__init__(self) # if you want to call most super class...
        B.__init__(self)
        print "Initialiser C was called"

Bind a function to Twitter Bootstrap Modal Close

Bootstrap 3 & 4

$('#myModal').on('hidden.bs.modal', function () {
    // do something…
});

Bootstrap 3: getbootstrap.com/javascript/#modals-events

Bootstrap 4: getbootstrap.com/docs/4.1/components/modal/#events

Bootstrap 2.3.2

$('#myModal').on('hidden', function () {
    // do something…
});

See getbootstrap.com/2.3.2/javascript.html#modals ? Events

How to plot a 2D FFT in Matlab?

Here is an example from my HOW TO Matlab page:

close all; clear all;

img   = imread('lena.tif','tif');
imagesc(img)
img   = fftshift(img(:,:,2));
F     = fft2(img);

figure;

imagesc(100*log(1+abs(fftshift(F)))); colormap(gray); 
title('magnitude spectrum');

figure;
imagesc(angle(F));  colormap(gray);
title('phase spectrum');

This gives the magnitude spectrum and phase spectrum of the image. I used a color image, but you can easily adjust it to use gray image as well.

ps. I just noticed that on Matlab 2012a the above image is no longer included. So, just replace the first line above with say

img = imread('ngc6543a.jpg');

and it will work. I used an older version of Matlab to make the above example and just copied it here.

On the scaling factor

When we plot the 2D Fourier transform magnitude, we need to scale the pixel values using log transform to expand the range of the dark pixels into the bright region so we can better see the transform. We use a c value in the equation

s = c log(1+r) 

There is no known way to pre detrmine this scale that I know. Just need to try different values to get on you like. I used 100 in the above example.

enter image description here

PHP append one array to another (not array_push or +)

Another way to do this in PHP 5.6+ would be to use the ... token

$a = array('a', 'b');
$b = array('c', 'd');

array_push($a, ...$b);

// $a is now equals to array('a','b','c','d');

This will also work with any Traversable

$a = array('a', 'b');
$b = new ArrayIterator(array('c', 'd'));

array_push($a, ...$b);

// $a is now equals to array('a','b','c','d');

A warning though:

  • in PHP versions before 7.3 this will cause a fatal error if $b is an empty array or not traversable e.g. not an array
  • in PHP 7.3 a warning will be raised if $b is not traversable

Two Divs on the same row and center align both of them

Align to the center, using display: inline-block and text-align: center.

_x000D_
_x000D_
.outerdiv_x000D_
{_x000D_
    height:100px;_x000D_
    width:500px;_x000D_
    background: red;_x000D_
    margin: 0 auto;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
.innerdiv_x000D_
{_x000D_
    height:40px;_x000D_
    width: 100px;_x000D_
    margin: 2px;_x000D_
    box-sizing: border-box;_x000D_
    background: green;_x000D_
    display: inline-block;_x000D_
}
_x000D_
<div class="outerdiv">_x000D_
    <div class="innerdiv"></div>_x000D_
    <div class="innerdiv"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Align to the center using display: flex and justify-content: center

_x000D_
_x000D_
.outerdiv_x000D_
{_x000D_
    height:100px;_x000D_
    width:500px;_x000D_
    background: red;_x000D_
    display: flex;_x000D_
    flex-direction: row;_x000D_
    justify-content: center;_x000D_
}_x000D_
_x000D_
.innerdiv_x000D_
{_x000D_
    height:40px;_x000D_
    width: 100px;_x000D_
    margin: 2px;_x000D_
    box-sizing: border-box;_x000D_
    background: green;_x000D_
}
_x000D_
<div class="outerdiv">_x000D_
    <div class="innerdiv"></div>_x000D_
    <div class="innerdiv"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Align to the center vertically and horizontally using display: flex, justify-content: center and align-items:center.

_x000D_
_x000D_
.outerdiv_x000D_
{_x000D_
    height:100px;_x000D_
    width:500px;_x000D_
    background: red;_x000D_
    display: flex;_x000D_
    flex-direction: row;_x000D_
    justify-content: center;_x000D_
    align-items:center;_x000D_
}_x000D_
_x000D_
.innerdiv_x000D_
{_x000D_
    height:40px;_x000D_
    width: 100px;_x000D_
    margin: 2px;_x000D_
    box-sizing: border-box;_x000D_
    background: green;_x000D_
}
_x000D_
<div class="outerdiv">_x000D_
    <div class="innerdiv"></div>_x000D_
    <div class="innerdiv"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

REST API Token-based Authentication

Let me seperate up everything and solve approach each problem in isolation:

Authentication

For authentication, baseauth has the advantage that it is a mature solution on the protocol level. This means a lot of "might crop up later" problems are already solved for you. For example, with BaseAuth, user agents know the password is a password so they don't cache it.

Auth server load

If you dispense a token to the user instead of caching the authentication on your server, you are still doing the same thing: Caching authentication information. The only difference is that you are turning the responsibility for the caching to the user. This seems like unnecessary labor for the user with no gains, so I recommend to handle this transparently on your server as you suggested.

Transmission Security

If can use an SSL connection, that's all there is to it, the connection is secure*. To prevent accidental multiple execution, you can filter multiple urls or ask users to include a random component ("nonce") in the URL.

url = username:[email protected]/api/call/nonce

If that is not possible, and the transmitted information is not secret, I recommend securing the request with a hash, as you suggested in the token approach. Since the hash provides the security, you could instruct your users to provide the hash as the baseauth password. For improved robustness, I recommend using a random string instead of the timestamp as a "nonce" to prevent replay attacks (two legit requests could be made during the same second). Instead of providing seperate "shared secret" and "api key" fields, you can simply use the api key as shared secret, and then use a salt that doesn't change to prevent rainbow table attacks. The username field seems like a good place to put the nonce too, since it is part of the auth. So now you have a clean call like this:

nonce = generate_secure_password(length: 16);
one_time_key = nonce + '-' + sha1(nonce+salt+shared_key);
url = username:[email protected]/api/call

It is true that this is a bit laborious. This is because you aren't using a protocol level solution (like SSL). So it might be a good idea to provide some kind of SDK to users so at least they don't have to go through it themselves. If you need to do it this way, I find the security level appropriate (just-right-kill).

Secure secret storage

It depends who you are trying to thwart. If you are preventing people with access to the user's phone from using your REST service in the user's name, then it would be a good idea to find some kind of keyring API on the target OS and have the SDK (or the implementor) store the key there. If that's not possible, you can at least make it a bit harder to get the secret by encrypting it, and storing the encrypted data and the encryption key in seperate places.

If you are trying to keep other software vendors from getting your API key to prevent the development of alternate clients, only the encrypt-and-store-seperately approach almost works. This is whitebox crypto, and to date, no one has come up with a truly secure solution to problems of this class. The least you can do is still issue a single key for each user so you can ban abused keys.

(*) EDIT: SSL connections should no longer be considered secure without taking additional steps to verify them.

Python, creating objects

class Student(object):
    name = ""
    age = 0
    major = ""

    # The class "constructor" - It's actually an initializer 
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

def make_student(name, age, major):
    student = Student(name, age, major)
    return student

Note that even though one of the principles in Python's philosophy is "there should be one—and preferably only one—obvious way to do it", there are still multiple ways to do this. You can also use the two following snippets of code to take advantage of Python's dynamic capabilities:

class Student(object):
    name = ""
    age = 0
    major = ""

def make_student(name, age, major):
    student = Student()
    student.name = name
    student.age = age
    student.major = major
    # Note: I didn't need to create a variable in the class definition before doing this.
    student.gpa = float(4.0)
    return student

I prefer the former, but there are instances where the latter can be useful – one being when working with document databases like MongoDB.

Disable F5 and browser refresh using JavaScript

From the site Enrique posted:

window.history.forward(1);
document.attachEvent("onkeydown", my_onkeydown_handler);
function my_onkeydown_handler() {
    switch (event.keyCode) {
        case 116 : // 'F5'
            event.returnValue = false;
            event.keyCode = 0;
            window.status = "We have disabled F5";
            break;
    }
}

Extract data from XML Clob using SQL from Oracle Database

Try

SELECT EXTRACTVALUE(xmltype(testclob), '/DCResponse/ContextData/Field[@key="Decision"]') 
FROM traptabclob;

Here is a sqlfiddle demo

MySQl Error #1064

At first you need to add semi colon (;) after quantity INT NOT NULL) then remove ** from ,genre,quantity)**. to insert a value with numeric data type like int, decimal, float, etc you don't need to add single quote.

Cropping an UIImage

To crop retina images while keeping the same scale and orientation, use the following method in a UIImage category (iOS 4.0 and above):

- (UIImage *)crop:(CGRect)rect {
    if (self.scale > 1.0f) {
        rect = CGRectMake(rect.origin.x * self.scale,
                          rect.origin.y * self.scale,
                          rect.size.width * self.scale,
                          rect.size.height * self.scale);
    }

    CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
    CGImageRelease(imageRef);
    return result;
}

Foreach with JSONArray and JSONObject

Apparently, org.json.simple.JSONArray implements a raw Iterator. This means that each element is considered to be an Object. You can try to cast:

for(Object o: arr){
    if ( o instanceof JSONObject ) {
        parse((JSONObject)o);
    }
}

This is how things were done back in Java 1.4 and earlier.

How to declare and use 1D and 2D byte arrays in Verilog?

It is simple actually, like C programming you just need to pass the array indices on the right hand side while declaration. But yeah the syntax will be like [0:3] for 4 elements.

reg a[0:3]; 

This will create a 1D of array of single bit. Similarly 2D array can be created like this:

reg [0:3][0:2];

Now in C suppose you create a 2D array of int, then it will internally create a 2D array of 32 bits. But unfortunately Verilog is an HDL, so it thinks in bits rather then bunch of bits (though int datatype is there in Verilog), it can allow you to create any number of bits to be stored inside an element of array (which is not the case with C, you can't store 5-bits in every element of 2D array in C). So to create a 2D array, in which every individual element can hold 5 bit value, you should write this:

reg [0:4] a [0:3][0:2];

Inserting HTML into a div

As alternative you can use insertAdjacentHTML - however I dig into and make some performance tests - (2019.09.13 Friday) MacOs High Sierra 10.13.6 on Chrome 76.0.3809 (64-bit), Safari 12.1.2 (13604.5.6), Firefox 69.0.0 (64-bit) ). The test F is only for reference - it is out of the question scope because we need to insert dynamically html - but in F I do it by 'hand' (in static way) - theoretically (as far I know) this should be the fastest way to insert new html elements.

enter image description here

SUMMARY

  • The A innerHTML = (do not confuse with +=) is fastest (Safari 48k operations per second, Firefox 43k op/sec, Chrome 23k op/sec) The A is ~31% slower than ideal solution F only chrome but on safari and firefox is faster (!)
  • The B innerHTML +=... is slowest on all browsers (Chrome 95 op/sec, Firefox 88 op/sec, Sfari 84 op/sec)
  • The D jQuery is second slow on all browsers (Safari 14 op/sec, Firefox 11k op/sec, Chrome 7k op/sec)
  • The reference solution F (theoretically fastest) is not fastest on firefox and safari (!!!) - which is surprising
  • The fastest browser was Safari

More info about why innerHTML = is much faster than innerHTML += is here. You can perform test on your machine/browser HERE

_x000D_
_x000D_
let html = "<div class='box'>Hello <span class='msg'>World</span> !!!</div>"_x000D_
_x000D_
function A() {    _x000D_
  container.innerHTML = `<div id="A_oiio">A: ${html}</div>`;_x000D_
}_x000D_
_x000D_
function B() {    _x000D_
  container.innerHTML += `<div id="B_oiio">B: ${html}</div>`;_x000D_
}_x000D_
_x000D_
function C() {    _x000D_
  container.insertAdjacentHTML('beforeend', `<div id="C_oiio">C: ${html}</div>`);_x000D_
}_x000D_
_x000D_
function D() {    _x000D_
  $('#container').append(`<div id="D_oiio">D: ${html}</div>`);_x000D_
}_x000D_
_x000D_
function E() {_x000D_
  let d = document.createElement("div");_x000D_
  d.innerHTML = `E: ${html}`;_x000D_
  d.id = 'E_oiio';_x000D_
  container.appendChild(d);_x000D_
}_x000D_
_x000D_
function F() {    _x000D_
  let dm = document.createElement("div");_x000D_
  dm.id = "F_oiio";_x000D_
  dm.appendChild(document.createTextNode("F: "));_x000D_
_x000D_
  let d = document.createElement("div");_x000D_
  d.classList.add('box');_x000D_
  d.appendChild(document.createTextNode("Hello "));_x000D_
  _x000D_
  let s = document.createElement("span");_x000D_
  s.classList.add('msg');_x000D_
  s.appendChild(document.createTextNode("World"));_x000D_
_x000D_
  d.appendChild(s);_x000D_
  d.appendChild(document.createTextNode(" !!!"));_x000D_
  dm.appendChild( d );_x000D_
  _x000D_
  container.appendChild(dm);_x000D_
}_x000D_
_x000D_
_x000D_
A();_x000D_
B();_x000D_
C();_x000D_
D();_x000D_
E();_x000D_
F();
_x000D_
.warr { color: red } .msg { color: blue } .box {display: inline}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="warr">This snippet only for show code used in test (in jsperf.com) - it not perform test itself. </div>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

How to run multiple Python versions on Windows

cp c:\python27\bin\python.exe as python2.7.exe

cp c:\python34\bin\python.exe as python3.4.exe

they are all in the system path, choose the version you want to run

C:\Users\username>python2.7
Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>>

C:\Users\username>python3.4
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

When should we use mutex and when should we use semaphore

While @opaxdiablo answer is totally correct I would like to point out that the usage scenario of both things is quite different. The mutex is used for protecting parts of code from running concurrently, semaphores are used for one thread to signal another thread to run.

/* Task 1 */
pthread_mutex_lock(mutex_thing);
    // Safely use shared resource
pthread_mutex_unlock(mutex_thing);



/* Task 2 */
pthread_mutex_lock(mutex_thing);
   // Safely use shared resource
pthread_mutex_unlock(mutex_thing); // unlock mutex

The semaphore scenario is different:

/* Task 1 - Producer */
sema_post(&sem);   // Send the signal

/* Task 2 - Consumer */
sema_wait(&sem);   // Wait for signal

See http://www.netrino.com/node/202 for further explanations

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause

SELECT *  from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME  BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP

Is it possible to decrypt SHA1

SHA1 is a one way hash. So you can not really revert it.

That's why applications use it to store the hash of the password and not the password itself.

Like every hash function SHA-1 maps a large input set (the keys) to a smaller target set (the hash values). Thus collisions can occur. This means that two values of the input set map to the same hash value.

Obviously the collision probability increases when the target set is getting smaller. But vice versa this also means that the collision probability decreases when the target set is getting larger and SHA-1's target set is 160 bit.

Jeff Preshing, wrote a very good blog about Hash Collision Probabilities that can help you to decide which hash algorithm to use. Thanks Jeff.

In his blog he shows a table that tells us the probability of collisions for a given input set.

Hash Collision Probabilities Table

As you can see the probability of a 32-bit hash is 1 in 2 if you have 77163 input values.

A simple java program will show us what his table shows:

public class Main {

    public static void main(String[] args) {
        char[] inputValue = new char[10];

        Map<Integer, String> hashValues = new HashMap<Integer, String>();

        int collisionCount = 0;

        for (int i = 0; i < 77163; i++) {
            String asString = nextValue(inputValue);
            int hashCode = asString.hashCode();
            String collisionString = hashValues.put(hashCode, asString);
            if (collisionString != null) {
                collisionCount++;
                System.out.println("Collision: " + asString + " <-> " + collisionString);
            }
        }

        System.out.println("Collision count: " + collisionCount);
    }

    private static String nextValue(char[] inputValue) {
        nextValue(inputValue, 0);

        int endIndex = 0;
        for (int i = 0; i < inputValue.length; i++) {
            if (inputValue[i] == 0) {
                endIndex = i;
                break;
            }
        }

        return new String(inputValue, 0, endIndex);
    }

    private static void nextValue(char[] inputValue, int index) {
        boolean increaseNextIndex = inputValue[index] == 'z';

        if (inputValue[index] == 0 || increaseNextIndex) {
            inputValue[index] = 'A';
        } else {
            inputValue[index] += 1;
        }

        if (increaseNextIndex) {
            nextValue(inputValue, index + 1);
        }

    }

}

My output end with:

Collision: RvV <-> SWV
Collision: SvV <-> TWV
Collision: TvV <-> UWV
Collision: UvV <-> VWV
Collision: VvV <-> WWV
Collision: WvV <-> XWV
Collision count: 35135

It produced 35135 collsions and that's the nearly the half of 77163. And if I ran the program with 30084 input values the collision count is 13606. This is not exactly 1 in 10, but it is only a probability and the example program is not perfect, because it only uses the ascii chars between A and z.

Let's take the last reported collision and check

System.out.println("VvV".hashCode());
System.out.println("WWV".hashCode());

My output is

86390
86390

Conclusion:

If you have a SHA-1 value and you want to get the input value back you can try a brute force attack. This means that you have to generate all possible input values, hash them and compare them with the SHA-1 you have. But that will consume a lot of time and computing power. Some people created so called rainbow tables for some input sets. But these do only exist for some small input sets.

And remember that many input values map to a single target hash value. So even if you would know all mappings (which is impossible, because the input set is unbounded) you still can't say which input value it was.

Playing a MP3 file in a WinForm application

You can use the mciSendString API to play an MP3 or a WAV file:

[DllImport("winmm.dll")]
public static extern uint mciSendString( 
    string lpstrCommand,
    StringBuilder lpstrReturnString,
    int uReturnLength,
    IntPtr hWndCallback
);

mciSendString(@"close temp_alias", null, 0, IntPtr.Zero);
mciSendString(@"open ""music.mp3"" alias temp_alias", null, 0, IntPtr.Zero);
mciSendString("play temp_alias repeat", null, 0, IntPtr.Zero);

Strip off URL parameter with PHP

The safest "correct" method would be:

  1. Parse the url into an array with parse_url()
  2. Extract the query portion, decompose that into an array using parse_str()
  3. Delete the query parameters you want by unset() them from the array
  4. Rebuild the original url using http_build_query()

Quick and dirty is to use a string search/replace and/or regex to kill off the value.

Bootstrap 3 offset on right not left

You need to combine multiple classes (col-*-offset-* for left-margin and col-*-pull-* to pull it right)

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-xs-3 col-xs-offset-9">_x000D_
      I'm a right column_x000D_
    </div>_x000D_
    <div class="col-xs-3">_x000D_
      We're_x000D_
    </div>_x000D_
    <div class="col-xs-3">_x000D_
      four columns_x000D_
    </div>_x000D_
    <div class="col-xs-3">_x000D_
      using the_x000D_
    </div>_x000D_
    <div class="col-xs-3">_x000D_
      whole row_x000D_
    </div>_x000D_
    <div class="col-xs-3 col-xs-offset-9 col-xs-pull-9">_x000D_
      I'm a left column_x000D_
    </div>_x000D_
    <div class="col-xs-3">_x000D_
      We're_x000D_
    </div>_x000D_
    <div class="col-xs-3">_x000D_
      four columns_x000D_
    </div>_x000D_
    <div class="col-xs-3">_x000D_
      using the_x000D_
    </div>_x000D_
    <div class="col-xs-3">_x000D_
      whole row_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

So you don't need to separate it manually into different rows.

How to monitor Java memory usage?

Explicitly running System.gc() on a production system is a terrible idea. If the memory gets to any size at all, the entire system can freeze while a full GC is running. On a multi-gigabyte-sized server, this can easily be very noticeable, depending on how the jvm is configured, and how much headroom it has, etc etc - I've seen pauses of more than 30 seconds.

Another issue is that by explicitly calling GC you're not actually monitoring how the JVM is running the GC, you're actually altering it - depending on how you've configured the JVM, it's going to garbage collect when appropriate, and usually incrementally (It doesn't just run a full GC when it runs out of memory). What you'll be printing out will be nothing like what the JVM will do on it's own - for one thing you'll probably see fewer automatic / incremental GC's as you'll be clearing the memory manually.

As Nick Holt's post points out, options to print GC activity already exist as JVM flags.

You could have a thread that just prints out free and available at reasonable intervals, this will show you actual mem useage.

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

You can check for NaN by using var != var. NaN does not equal NaN.

EDIT: This is probably by far the worst method. It's confusing, terrible for readability, and overall bad practice.

MySQL - how to front pad zip code with "0"?

Ok, so you've switched the column from Number to VARCHAR(5). Now you need to update the zipcode field to be left-padded. The SQL to do that would be:

UPDATE MyTable
SET ZipCode = LPAD( ZipCode, 5, '0' );

This will pad all values in the ZipCode column to 5 characters, adding '0's on the left.

Of course, now that you've got all of your old data fixed, you need to make sure that your any new data is also zero-padded. There are several schools of thought on the correct way to do that:

  • Handle it in the application's business logic. Advantages: database-independent solution, doesn't involve learning more about the database. Disadvantages: needs to be handled everywhere that writes to the database, in all applications.

  • Handle it with a stored procedure. Advantages: Stored procedures enforce business rules for all clients. Disadvantages: Stored procedures are more complicated than simple INSERT/UPDATE statements, and not as portable across databases. A bare INSERT/UPDATE can still insert non-zero-padded data.

  • Handle it with a trigger. Advantages: Will work for Stored Procedures and bare INSERT/UPDATE statements. Disadvantages: Least portable solution. Slowest solution. Triggers can be hard to get right.

In this case, I would handle it at the application level (if at all), and not the database level. After all, not all countries use a 5-digit Zipcode (not even the US -- our zipcodes are actually Zip+4+2: nnnnn-nnnn-nn) and some allow letters as well as digits. Better NOT to try and force a data format and to accept the occasional data error, than to prevent someone from entering the correct value, even though it's format isn't quite what you expected.

Postgres - Transpose Rows to Columns

If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot

How to properly -filter multiple strings in a PowerShell copy script

-Filter only accepts a single string. -Include accepts multiple values, but qualifies the -Path argument. The trick is to append \* to the end of the path, and then use -Include to select multiple extensions. BTW, quoting strings is unnecessary in cmdlet arguments unless they contain spaces or shell special characters.

Get-ChildItem $originalPath\* -Include *.gif, *.jpg, *.xls*, *.doc*, *.pdf*, *.wav*, .ppt*

Note that this will work regardless of whether $originalPath ends in a backslash, because multiple consecutive backslashes are interpreted as a single path separator. For example, try:

Get-ChildItem C:\\\\\Windows

Split a string by another string in C#

I generally like to use my own extension for that:

string data = "THExxQUICKxxBROWNxxFOX";
var dataspt = data.Split("xx");
//>THE  QUICK  BROWN  FOX 


//the extension class must be declared as static
public static class StringExtension
{   
    public static string[] Split(this string str, string splitter)
    {
        return str.Split(new[] { splitter }, StringSplitOptions.None);
    }
}

This will however lead to an Exception, if Microsoft decides to include this method-overload in later versions. It is also the likely reason why Microsoft has not included this method in the meantime: At least one company I worked for, used such an extension in all their C# projects.

It may also be possible to conditionally define the method at runtime if it doesn't exist.

Import XXX cannot be resolved for Java SE standard classes

Right click on project - >BuildPath - >Configure BuildPath - >Libraries tab - >

Double click on JRE SYSTEM LIBRARY - >Then select alternate JRE

AngularJS - value attribute for select

If you use the track by option, the value attribute is correctly written, e.g.:

<div ng-init="a = [{label: 'one', value: 15}, {label: 'two', value: 20}]">
    <select ng-model="foo" ng-options="x for x in a track by x.value"/>
</div>

produces:

<select>
    <option value="" selected="selected"></option>
    <option value="15">one</option>
    <option value="20">two</option>
</select>

Check status of one port on remote host

In Command Prompt, you can use the command telnet.. For Example, to connect to IP 192.168.10.1 with port 80,

telnet 192.168.10.1 80

To enable telnet in Windows 7 and above click. From the linked article, enable telnet through control panel -> programs and features -> windows features -> telnet client, or just run this in an admin prompt:

dism /online /Enable-Feature /FeatureName:TelnetClient

Mockito. Verify method arguments

  • You don't need the eq matcher if you don't use other matchers.
  • You are not using the correct syntax - your method call should be outside the .verify(mock). You are now initiating verification on the result of the method call, without verifying anything (not making a method call). Hence all tests are passing.

You code should look like:

Mockito.verify(mock).mymethod(obj);
Mockito.verify(mock).mymethod(null);
Mockito.verify(mock).mymethod("something_else");

Store an array in HashMap

You can store objects in a HashMap.

HashMap<String, Object> map = new HashMap<String, Object>();

You'll just need to cast it back out correctly.

How do I view / replay a chrome network debugger har file saved with content?

Open chrome browser. right click anywhere on a page > inspect elements > go to network tab > drag and drop the .har file You should see the logs.

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

To begin - there are 4 issues that could be causing the common LocalDb SqlExpress Sql Server connectivity errors SQL Network Interfaces, error: 50 - Local Database Runtime error occurred, before you begin you need to rename the v11 or v12 to (localdb)\mssqllocaldb

Possible Issues
 \\ rename the conn string from v12.0 to MSSQLLocalDB -like so-> 
 `<connectionStrings>
      <add name="ProductsContext" connectionString="Data Source= (localdb)\mssqllocaldb; 
      ...`

I found that the simplest is to do the below - I have attached the pics and steps for help.

First verify which instance you have installed, you can do this by checking the registry& by running cmd

 1. `cmd> Sqllocaldb.exe i` 
 2. `cmd> Sqllocaldb.exe s "whicheverVersionYouWantFromListBefore"` 
if this step fails, you can delete with option `d` cmd> Sqllocaldb.exe d "someDb"
 3. `cmd> Sqllocaldb.exe c "createSomeNewDbIfyouWantDb"` 
 4. `cmd> Sqllocaldb.exe start "createSomeNewDbIfyouWantDb"`

SqlLOCALDb_edited.png


ADVANCED Trouble Shooting Registry configurations

Edit 1, from requests & comments: Here are the Registry path for all versions, in a generic format to track down the registry

Paths

// SQL SERVER RECENT VERSIONS
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\(instance-name)

// OLD SQL SERVER
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MSSQLServer
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer
// SQL SERVER 6.0 and above.

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\MSDTC
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SQLExecutive
// SQL SERVER 7.0 and above

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SQLServerAgent
HKEY_LOCAL_MACHINE\Software\Microsoft\Microsoft SQL Server 7
HKEY_LOCAL_MACHINE\Software\Microsoft\MSSQLServ65

Searching

SELECT registry_key, value_name, value_data  
FROM sys.dm_server_registry  
WHERE registry_key LIKE N'%SQLAgent%';

or Run this in SSMS Sql Management Studio, it will give a full list of all installs you have on the server

DECLARE     @SQL VARCHAR(MAX)
SET         @SQL = 'DECLARE @returnValue NVARCHAR(100)'
SELECT @SQL = @SQL + CHAR(13) + 'EXEC   master.dbo.xp_regread

 @rootkey      = N''HKEY_LOCAL_MACHINE'',
 @key          = N''SOFTWARE\Microsoft\Microsoft SQL Server\' + RegPath + '\MSSQLServer'',
 @value_name   = N''DefaultData'',
 @value        = @returnValue OUTPUT; 

 UPDATE #tempInstanceNames SET DefaultDataPath = @returnValue WHERE RegPath = ''' + RegPath + '''' + CHAR(13) FROM #tempInstanceNames 

 -- now, with these results, you can search the reg for the values inside reg
 EXEC (@SQL)
 SELECT      InstanceName, RegPath, DefaultDataPath
 FROM        #tempInstanceNames

Trouble Shooting Network configurations

SELECT registry_key, value_name, value_data  
FROM sys.dm_server_registry  
WHERE registry_key LIKE N'%SuperSocketNetLib%';  

onchange file input change img src and change image color

Below solution tested and its working, hope it will support in your project.
HTML code:
    <input type="file" name="asgnmnt_file" id="asgnmnt_file" class="span8" 
    style="display:none;" onchange="fileSelected(this)">
    <br><br>
    <img id="asgnmnt_file_img" src="uploads/assignments/abc.jpg" width="150" height="150" 
    onclick="passFileUrl()" style="cursor:pointer;">

JavaScript code:
    function passFileUrl(){
    document.getElementById('asgnmnt_file').click();
    }

    function fileSelected(inputData){
    document.getElementById('asgnmnt_file_img').src = window.URL.createObjectURL(inputData.files[0])
    }

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

dispatch_queue_t queue = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(queue, ^{
  // Do some computation here.

  // Update UI after computation.
  dispatch_async(dispatch_get_main_queue(), ^{
    // Update the UI on the main thread.
  });
});

How to get attribute of element from Selenium?

You are probably looking for get_attribute(). An example is shown here as well

def test_chart_renders_from_url(self):
    url = 'http://localhost:8000/analyse/'
    self.browser.get(url)
    org = driver.find_element_by_id('org')
    # Find the value of org?
    val = org.get_attribute("attribute name")

How to center the content inside a linear layout?

android:layout_gravity is used for the layout itself

Use android:gravity="center" for children of your LinearLayout

So your code should be:

<LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_weight="1" >

Regex pattern for checking if a string starts with a certain substring?

I really recommend using the String.StartsWith method over the Regex.IsMatch if you only plan to check the beginning of a string.

  • Firstly, the regular expression in C# is a language in a language with does not help understanding and code maintenance. Regular expression is a kind of DSL.
  • Secondly, many developers does not understand regular expressions: it is something which is not understandable for many humans.
  • Thirdly, the StartsWith method brings you features to enable culture dependant comparison which regular expressions are not aware of.

In your case you should use regular expressions only if you plan implementing more complex string comparison in the future.

How to generate a random string of 20 characters

Here you go. Just specify the chars you want to allow on the first line.

char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 20; i++) {
    char c = chars[random.nextInt(chars.length)];
    sb.append(c);
}
String output = sb.toString();
System.out.println(output);

If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use java.security.SecureRandom instead. Values produced by java.util.Random and java.util.concurrent.ThreadLocalRandom are mathematically predictable.

how to check confirm password field in form without reloading page

Solution Using jQuery

 <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>

 <style>
    #form label{float:left; width:140px;}
    #error_msg{color:red; font-weight:bold;}
 </style>

 <script>
    $(document).ready(function(){
        var $submitBtn = $("#form input[type='submit']");
        var $passwordBox = $("#password");
        var $confirmBox = $("#confirm_password");
        var $errorMsg =  $('<span id="error_msg">Passwords do not match.</span>');

        // This is incase the user hits refresh - some browsers will maintain the disabled state of the button.
        $submitBtn.removeAttr("disabled");

        function checkMatchingPasswords(){
            if($confirmBox.val() != "" && $passwordBox.val != ""){
                if( $confirmBox.val() != $passwordBox.val() ){
                    $submitBtn.attr("disabled", "disabled");
                    $errorMsg.insertAfter($confirmBox);
                }
            }
        }

        function resetPasswordError(){
            $submitBtn.removeAttr("disabled");
            var $errorCont = $("#error_msg");
            if($errorCont.length > 0){
                $errorCont.remove();
            }  
        }


        $("#confirm_password, #password")
             .on("keydown", function(e){
                /* only check when the tab or enter keys are pressed
                 * to prevent the method from being called needlessly  */
                if(e.keyCode == 13 || e.keyCode == 9) {
                    checkMatchingPasswords();
                }
             })
             .on("blur", function(){                    
                // also check when the element looses focus (clicks somewhere else)
                checkMatchingPasswords();
            })
            .on("focus", function(){
                // reset the error message when they go to make a change
                resetPasswordError();
            })

    });
  </script>

And update your form accordingly:

<form id="form" name="form" method="post" action="registration.php"> 
    <label for="username">Username : </label>
    <input name="username" id="username" type="text" /></label><br/>

    <label for="password">Password :</label> 
    <input name="password" id="password" type="password" /><br/>

    <label for="confirm_password">Confirm Password:</label>
    <input type="password" name="confirm_password" id="confirm_password" /><br/>

    <input type="submit" name="submit"  value="registration"  />
</form>

This will do precisely what you asked for:

  • validate that the password and confirm fields are equal without clicking the register button
  • If password and confirm password field will not match it will place an error message at the side of confirm password field and disable registration button

It is advisable not to use a keyup event listener for every keypress because really you only need to evaluate it when the user is done entering information. If someone types quickly on a slow machine, they may perceive lag as each keystroke will kick off the function.

Also, in your form you are using labels wrong. The label element has a "for" attribute which should correspond with the id of the form element. This is so that when visually impaired people use a screen reader to call out the form field, it will know text belongs to which field.

How do I view an older version of an SVN file?

You can update to an older revision:

svn update -r 666 file

Or you can just view the file directly:

svn cat -r 666 file | less

SQL Server Profiler - How to filter trace to only display events from one database?

By experiment I was able to observe this:

When SQL Profiler 2005 or SQL Profiler 2000 is used with database residing in SQLServer 2000 - problem mentioned problem persists, but when SQL Profiler 2005 is used with SQLServer 2005 database, it works perfect!

In Summary, the issue seems to be prevalent in SQLServer 2000 & rectified in SQLServer 2005.

The solution for the issue when dealing with SQLServer 2000 is (as explained by wearejimbo)

  1. Identify the DatabaseID of the database you want to filter by querying the sysdatabases table as below

    SELECT * 
    FROM master..sysdatabases 
    WHERE name like '%your_db_name%'   -- Remove this line to see all databases
    ORDER BY dbid
    
  2. Use the DatabaseID Filter (instead of DatabaseName) in the New Trace window of SQL Profiler 2000

How to use JavaScript to change div backgroundColor

This one might be a bit weird because I am really not a serious programmer and I am discovering things in programming the way penicillin was invented - sheer accident. So how to change an element on mouseover? Use the :hover attribute just like with a elements.

Example:

div.classname:hover
{
    background-color: black;
}

This changes any div with the class classname to have a black background on mousover. You can basically change any attribute. Tested in IE and Firefox

Happy programming!

Regular Expression for alphanumeric and underscores

Um...question: Does it need to have at least one character or no? Can it be an empty string?

^[A-Za-z0-9_]+$

Will do at least one upper or lower case alphanumeric or underscore. If it can be zero length, then just substitute the + for *

^[A-Za-z0-9_]*$

Edit:

If diacritics need to be included (such as cedilla - ç) then you would need to use the word character which does the same as the above, but includes the diacritic characters:

^\w+$

Or

^\w*$

Save text file UTF-8 encoded with VBA

The traditional way to transform a string to a UTF-8 string is as follows:

StrConv("hello world",vbFromUnicode)

So put simply:

Dim fnum As Integer
fnum = FreeFile
Open "myfile.txt" For Output As fnum
Print #fnum, StrConv("special characters: äöüß", vbFromUnicode)
Close fnum

No special COM objects required

Left-pad printf with spaces

If you want exactly 40 spaces before the string then you should just do:

printf("                                        %s\n", myStr );

If that is too dirty, you can do (but it will be slower than manually typing the 40 spaces): printf("%40s%s", "", myStr );

If you want the string to be lined up at column 40 (that is, have up to 39 spaces proceeding it such that the right most character is in column 40) then do this: printf("%40s", myStr);

You can also put "up to" 40 spaces AfTER the string by doing: printf("%-40s", myStr);

Warn user before leaving web page with unsaved changes

Adding to te idea of @codecaster you could add this to every page with a form (in my case i use it in global way so only on forms would have this warn) change his function to

if ( formSubmitting || document.getElementsByTagName('form').length == 0) 

Also put on forms submit including login and in cancel buttons links so when person press cancel or submit the form won't trigger the warn also in every page witouth a form...

<a class="btn btn-danger btn-md" href="back/url" onclick="setFormSubmitting()">Cancel</a>

'Found the synthetic property @panelState. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'

After installing an animation module then you create an animation file inside your app folder.

router.animation.ts

import { animate, state, style, transition, trigger } from '@angular/animations';
    export function routerTransition() {
        return slideToTop();
    }

    export function slideToRight() {
        return trigger('routerTransition', [
            state('void', style({})),
            state('*', style({})),
            transition(':enter', [
                style({ transform: 'translateX(-100%)' }),
                animate('0.5s ease-in-out', style({ transform: 'translateX(0%)' }))
            ]),
            transition(':leave', [
                style({ transform: 'translateX(0%)' }),
                animate('0.5s ease-in-out', style({ transform: 'translateX(100%)' }))
            ])
        ]);
    }

    export function slideToLeft() {
        return trigger('routerTransition', [
            state('void', style({})),
            state('*', style({})),
            transition(':enter', [
                style({ transform: 'translateX(100%)' }),
                animate('0.5s ease-in-out', style({ transform: 'translateX(0%)' }))
            ]),
            transition(':leave', [
                style({ transform: 'translateX(0%)' }),
                animate('0.5s ease-in-out', style({ transform: 'translateX(-100%)' }))
            ])
        ]);
    }

    export function slideToBottom() {
        return trigger('routerTransition', [
            state('void', style({})),
            state('*', style({})),
            transition(':enter', [
                style({ transform: 'translateY(-100%)' }),
                animate('0.5s ease-in-out', style({ transform: 'translateY(0%)' }))
            ]),
            transition(':leave', [
                style({ transform: 'translateY(0%)' }),
                animate('0.5s ease-in-out', style({ transform: 'translateY(100%)' }))
            ])
        ]);
    }

    export function slideToTop() {
        return trigger('routerTransition', [
            state('void', style({})),
            state('*', style({})),
            transition(':enter', [
                style({ transform: 'translateY(100%)' }),
                animate('0.5s ease-in-out', style({ transform: 'translateY(0%)' }))
            ]),
            transition(':leave', [
                style({ transform: 'translateY(0%)' }),
                animate('0.5s ease-in-out', style({ transform: 'translateY(-100%)' }))
            ])
        ]);
    }

Then you import this animation file to your any component.

In your component.ts file

import { routerTransition } from '../../router.animations';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss'],
  animations: [routerTransition()]
})

Don't forget to import animation in your app.module.ts

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

How do I add a bullet symbol in TextView?

Copy paste: •. I've done it with other weird characters, such as ? and ?.

Edit: here's an example. The two Buttons at the bottom have android:text="?" and "?".

How to print HTML content on click of a button, but not the page?

Below Code May Be Help You :

<html>
<head>
<script>
function printPage(id)
{
   var html="<html>";
   html+= document.getElementById(id).innerHTML;

   html+="</html>";

   var printWin = window.open('','','left=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,status  =0');
   printWin.document.write(html);
   printWin.document.close();
   printWin.focus();
   printWin.print();
   printWin.close();
}
</script>
</head>
<body>
<div id="block1">
<table border="1" >
</tr>
<th colspan="3">Block 1</th>
</tr>
<tr>
<th>1</th><th>XYZ</th><th>athock</th>
</tr>
</table>

</div>

<div id="block2">
    This is Block 2 content
</div>

<input type="button" value="Print Block 1" onclick="printPage('block1');"></input>
<input type="button" value="Print Block 2" onclick="printPage('block2');"></input>
</body>
</html>

How do I lock the orientation to portrait mode in a iPhone Web Application?

In coffee if anyone needs it.

    $(window).bind 'orientationchange', ->
        if window.orientation % 180 == 0
            $(document.body).css
                "-webkit-transform-origin" : ''
                "-webkit-transform" : ''
        else
            if window.orientation > 0
                $(document.body).css
                    "-webkit-transform-origin" : "200px 190px"
                    "-webkit-transform" : "rotate(-90deg)"
            else
                $(document.body).css
                    "-webkit-transform-origin" : "280px 190px"
                    "-webkit-transform" : "rotate(90deg)"

Resizing a button

Use inline styles:

<div class="button" style="width:60px;height:100px;">This is a button</div>

Fiddle

Get url parameters from a string in .NET

You can use the following workaround for it to work with the first parameter too:

var param1 =
    HttpUtility.ParseQueryString(url.Substring(
        new []{0, url.IndexOf('?')}.Max()
    )).Get("param1");

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

You need to pass your data in the request body as a raw string rather than FormUrlEncodedContent. One way to do so is to serialize it into a JSON string:

var json = JsonConvert.SerializeObject(data); // or JsonSerializer.Serialize if using System.Text.Json

Now all you need to do is pass the string to the post method.

var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json"); // use MediaTypeNames.Application.Json in Core 3.0+ and Standard 2.1+

var client = new HttpClient();
var response = await client.PostAsync(uri, stringContent);

Extracting double-digit months and days from a Python date

Look at the types of those properties:

In [1]: import datetime

In [2]: d = datetime.date.today()

In [3]: type(d.month)
Out[3]: <type 'int'>

In [4]: type(d.day)
Out[4]: <type 'int'>

Both are integers. So there is no automatic way to do what you want. So in the narrow sense, the answer to your question is no.

If you want leading zeroes, you'll have to format them one way or another. For that you have several options:

In [5]: '{:02d}'.format(d.month)
Out[5]: '03'

In [6]: '%02d' % d.month
Out[6]: '03'

In [7]: d.strftime('%m')
Out[7]: '03'

In [8]: f'{d.month:02d}'
Out[8]: '03'

Read input stream twice

You can wrap input stream with PushbackInputStream. PushbackInputStream allows to unread ("write back") bytes which were already read, so you can do like this:

public class StreamTest {
  public static void main(String[] args) throws IOException {
    byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    InputStream originalStream = new ByteArrayInputStream(bytes);

    byte[] readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 1 2 3

    readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 4 5 6

    // now let's wrap it with PushBackInputStream

    originalStream = new ByteArrayInputStream(bytes);

    InputStream wrappedStream = new PushbackInputStream(originalStream, 10); // 10 means that maximnum 10 characters can be "written back" to the stream

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3

    ((PushbackInputStream) wrappedStream).unread(readBytes, 0, readBytes.length);

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3


  }

  private static byte[] getBytes(InputStream is, int howManyBytes) throws IOException {
    System.out.print("Reading stream: ");

    byte[] buf = new byte[howManyBytes];

    int next = 0;
    for (int i = 0; i < howManyBytes; i++) {
      next = is.read();
      if (next > 0) {
        buf[i] = (byte) next;
      }
    }
    return buf;
  }

  private static void printBytes(byte[] buffer) throws IOException {
    System.out.print("Reading stream: ");

    for (int i = 0; i < buffer.length; i++) {
      System.out.print(buffer[i] + " ");
    }
    System.out.println();
  }


}

Please note that PushbackInputStream stores internal buffer of bytes so it really creates a buffer in memory which holds bytes "written back".

Knowing this approach we can go further and combine it with FilterInputStream. FilterInputStream stores original input stream as a delegate. This allows to create new class definition which allows to "unread" original data automatically. The definition of this class is following:

public class TryReadInputStream extends FilterInputStream {
  private final int maxPushbackBufferSize;

  /**
  * Creates a <code>FilterInputStream</code>
  * by assigning the  argument <code>in</code>
  * to the field <code>this.in</code> so as
  * to remember it for later use.
  *
  * @param in the underlying input stream, or <code>null</code> if
  *           this instance is to be created without an underlying stream.
  */
  public TryReadInputStream(InputStream in, int maxPushbackBufferSize) {
    super(new PushbackInputStream(in, maxPushbackBufferSize));
    this.maxPushbackBufferSize = maxPushbackBufferSize;
  }

  /**
   * Reads from input stream the <code>length</code> of bytes to given buffer. The read bytes are still avilable
   * in the stream
   *
   * @param buffer the destination buffer to which read the data
   * @param offset  the start offset in the destination <code>buffer</code>
   * @aram length how many bytes to read from the stream to buff. Length needs to be less than
   *        <code>maxPushbackBufferSize</code> or IOException will be thrown
   *
   * @return number of bytes read
   * @throws java.io.IOException in case length is
   */
  public int tryRead(byte[] buffer, int offset, int length) throws IOException {
    validateMaxLength(length);

    // NOTE: below reading byte by byte instead of "int bytesRead = is.read(firstBytes, 0, maxBytesOfResponseToLog);"
    // because read() guarantees to read a byte

    int bytesRead = 0;

    int nextByte = 0;

    for (int i = 0; (i < length) && (nextByte >= 0); i++) {
      nextByte = read();
      if (nextByte >= 0) {
        buffer[offset + bytesRead++] = (byte) nextByte;
      }
    }

    if (bytesRead > 0) {
      ((PushbackInputStream) in).unread(buffer, offset, bytesRead);
    }

    return bytesRead;

  }

  public byte[] tryRead(int maxBytesToRead) throws IOException {
    validateMaxLength(maxBytesToRead);

    ByteArrayOutputStream baos = new ByteArrayOutputStream(); // as ByteArrayOutputStream to dynamically allocate internal bytes array instead of allocating possibly large buffer (if maxBytesToRead is large)

    // NOTE: below reading byte by byte instead of "int bytesRead = is.read(firstBytes, 0, maxBytesOfResponseToLog);"
    // because read() guarantees to read a byte

    int nextByte = 0;

    for (int i = 0; (i < maxBytesToRead) && (nextByte >= 0); i++) {
      nextByte = read();
      if (nextByte >= 0) {
        baos.write((byte) nextByte);
      }
    }

    byte[] buffer = baos.toByteArray();

    if (buffer.length > 0) {
      ((PushbackInputStream) in).unread(buffer, 0, buffer.length);
    }

    return buffer;

  }

  private void validateMaxLength(int length) throws IOException {
    if (length > maxPushbackBufferSize) {
      throw new IOException(
        "Trying to read more bytes than maxBytesToRead. Max bytes: " + maxPushbackBufferSize + ". Trying to read: " +
        length);
    }
  }

}

This class has two methods. One for reading into existing buffer (defintion is analogous to calling public int read(byte b[], int off, int len) of InputStream class). Second which returns new buffer (this may be more effective if the size of buffer to read is unknown).

Now let's see our class in action:

public class StreamTest2 {
  public static void main(String[] args) throws IOException {
    byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    InputStream originalStream = new ByteArrayInputStream(bytes);

    byte[] readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 1 2 3

    readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 4 5 6

    // now let's use our TryReadInputStream

    originalStream = new ByteArrayInputStream(bytes);

    InputStream wrappedStream = new TryReadInputStream(originalStream, 10);

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); // NOTE: no manual call to "unread"(!) because TryReadInputStream handles this internally
    printBytes(readBytes); // prints 1 2 3

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); 
    printBytes(readBytes); // prints 1 2 3

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3);
    printBytes(readBytes); // prints 1 2 3

    // we can also call normal read which will actually read the bytes without "writing them back"
    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 4 5 6

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); // now we can try read next bytes
    printBytes(readBytes); // prints 7 8 9

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); 
    printBytes(readBytes); // prints 7 8 9


  }



}

Where should my npm modules be installed on Mac OS X?

npm root -g

to check the npm_modules global location

How to configure logging to syslog in Python?

Change the line to this:

handler = SysLogHandler(address='/dev/log')

This works for me

import logging
import logging.handlers

my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)

handler = logging.handlers.SysLogHandler(address = '/dev/log')

my_logger.addHandler(handler)

my_logger.debug('this is debug')
my_logger.critical('this is critical')

Difference between socket and websocket?

Regarding your question (b), be aware that the Websocket specification hasn't been finalised. According to the W3C:

Implementors should be aware that this specification is not stable.

Personally I regard Websockets to be waaay too bleeding edge to use at present. Though I'll probably find them useful in a year or so.

SQLite error 'attempt to write a readonly database' during insert?

I got this in my browser when I changed from using http://localhost to http://145.900.50.20 (where 145.900.50.20 is my local IP address) and then changed back to localhost -- it was necessary to stay with the IP address once I had changed to that once

Converting Go struct to JSON

You can define your own custom MarshalJSON and UnmarshalJSON methods and intentionally control what should be included, ex:

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    name string
}

func (u *User) MarshalJSON() ([]byte, error) {
    return json.Marshal(&struct {
        Name     string `json:"name"`
    }{
        Name:     "customized" + u.name,
    })
}

func main() {
    user := &User{name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

Karma: Running a single test file from command line

This option is no longer supported in recent versions of karma:

see https://github.com/karma-runner/karma/issues/1731#issuecomment-174227054

The files array can be redefined using the CLI as such:

karma start --files=Array("test/Spec/services/myServiceSpec.js")

or escaped:

karma start --files=Array\(\"test/Spec/services/myServiceSpec.js\"\)

References

What is the minimum I have to do to create an RPM file?

As an application distributor, fpm sounds perfect for your needs. There is an example here which shows how to package an app from source. FPM can produce both deb files and RPM files.

JavaScript get child element

I'd suggest doing something similar to:

function show_sub(cat) {
    if (!cat) {
        return false;
    }
    else if (document.getElementById(cat)) {
        var parent = document.getElementById(cat),
            sub = parent.getElementsByClassName('sub');
        if (sub[0].style.display == 'inline'){
            sub[0].style.display = 'none';
        }
        else {
            sub[0].style.display = 'inline';
        }
    }
}

document.getElementById('cat').onclick = function(){
    show_sub(this.id);
};????

JS Fiddle demo.

Though the above relies on the use of a class rather than a name attribute equal to sub.

As to why your original version "didn't work" (not, I must add, a particularly useful description of the problem), all I can suggest is that, in Chromium, the JavaScript console reported that:

Uncaught TypeError: Object # has no method 'getElementsByName'.

One approach to working around the older-IE family's limitations is to use a custom function to emulate getElementsByClassName(), albeit crudely:

function eBCN(elem,classN){
    if (!elem || !classN){
        return false;
    }
    else {
        var children = elem.childNodes;
        for (var i=0,len=children.length;i<len;i++){
            if (children[i].nodeType == 1
                &&
                children[i].className == classN){
                    var sub = children[i];
            }
        }
        return sub;
    }
}

function show_sub(cat) {
    if (!cat) {
        return false;
    }
    else if (document.getElementById(cat)) {
        var parent = document.getElementById(cat),
            sub = eBCN(parent,'sub');
        if (sub.style.display == 'inline'){
            sub.style.display = 'none';
        }
        else {
            sub.style.display = 'inline';
        }
    }
}

var D = document,
    listElems = D.getElementsByTagName('li');
for (var i=0,len=listElems.length;i<len;i++){
    listElems[i].onclick = function(){
        show_sub(this.id);
    };
}?

JS Fiddle demo.

Extract the last substring from a cell

Try this function in Excel:

Public Shared Function SPLITTEXT(Text As String, SplitAt As String, ReturnZeroBasedIndex As Integer) As String
        Dim s() As String = Split(Text, SplitAt)
        If ReturnZeroBasedIndex <= s.Count - 1 Then
            Return s(ReturnZeroBasedIndex)
        Else
            Return ""
        End If
    End Function

You use it like this:

First Name (A1) | Last Name (A2)

Value in cell A1 = Michael Zomparelli

I want the last name in column A2.

=SPLITTEXT(A1, " ", 1)

The last param is the zero-based index you want to return. So if you split on the space char then index 0 = Michael and index 1 = Zomparelli

The above function is a .Net function, but can easily be converted to VBA.

Vue js error: Component template should contain exactly one root element

I was confused as I knew VueJS should only contain 1 root element and yet I was still getting this same "template syntax error Component template should contain exactly one root element..." error on an extremely simple component. Turns out I had just mispelled </template> as </tempate> and that was giving me this same error in a few files I copied and pasted. In summary, check your syntax for any mispellings in your component.

How to open every file in a folder

Os

You can list all files in the current directory using os.listdir:

import os
for filename in os.listdir(os.getcwd()):
   with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
      # do your stuff

Glob

Or you can list only some files, depending on the file pattern using the glob module:

import glob
for filename in glob.glob('*.txt'):
   with open(os.path.join(os.cwd(), filename), 'r') as f: # open in readonly mode
      # do your stuff

It doesn't have to be the current directory you can list them in any path you want:

path = '/some/path/to/file'
for filename in glob.glob(os.path.join(path, '*.txt')):
   with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
      # do your stuff

Pipe Or you can even use the pipe as you specified using fileinput

import fileinput
for line in fileinput.input():
    # do your stuff

And then use it with piping:

ls -1 | python parse.py

How to parse JSON in Scala using standard Scala classes?

This is the way I do the Scala Parser Combinator Library:

import scala.util.parsing.combinator._
class ImprovedJsonParser extends JavaTokenParsers {

  def obj: Parser[Map[String, Any]] =
    "{" ~> repsep(member, ",") <~ "}" ^^ (Map() ++ _)

  def array: Parser[List[Any]] =
    "[" ~> repsep(value, ",") <~ "]"

  def member: Parser[(String, Any)] =
    stringLiteral ~ ":" ~ value ^^ { case name ~ ":" ~ value => (name, value) }

  def value: Parser[Any] = (
    obj
      | array
      | stringLiteral
      | floatingPointNumber ^^ (_.toDouble)
      |"true"
      |"false"
    )

}
object ImprovedJsonParserTest extends ImprovedJsonParser {
  def main(args: Array[String]) {
    val jsonString =
    """
      {
        "languages": [{
            "name": "English",
            "is_active": true,
            "completeness": 2.5
        }, {
            "name": "Latin",
            "is_active": false,
            "completeness": 0.9
        }]
      }
    """.stripMargin


    val result = parseAll(value, jsonString)
    println(result)

  }
}

How to check the version before installing a package using apt-get?

Linux Mint, Debian 9, Ubuntu 16.04 and older:

Short info:

apt policy <package_name>

Detailed info (With Description and Depends):

apt show <package_name>

Target a css class inside another css class

I use div instead of tables and am able to target classes within the main class, as below:

CSS

.main {
    .width: 800px;
    .margin: 0 auto;
    .text-align: center;
}
.main .table {
    width: 80%;
}
.main .row {
   / ***something ***/
}
.main .column {
    font-size: 14px;
    display: inline-block;
}
.main .left {
    width: 140px;
    margin-right: 5px;
    font-size: 12px;
}
.main .right {
    width: auto;
    margin-right: 20px;
    color: #fff;
    font-size: 13px;
    font-weight: normal;
}

HTML

<div class="main">
    <div class="table">
        <div class="row">
            <div class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>
        </div>
    </div>
</div>

If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:

.main #red { color: red; }

<div class="main">
    <div class="table">
        <div class="row">
            <div id="red" class="column left">Swing Over Bed</div>
            <div class="column right">650mm</div>
            <div class="column left">Swing In Gap</div>
            <div class="column right">800mm</div>
        </div>
    </div>
</div>

Vertical divider CSS

.headerDivider {
     border-left:1px solid #38546d; 
     border-right:1px solid #16222c; 
     height:80px;
     position:absolute;
     right:249px;
     top:10px; 
}

<div class="headerDivider"></div>

How to use a filter in a controller?

First of all inject $filter to your controller, making sure ngSanitize is loaded within your app, later within the controller usage is as follows:

$filter('linky')(text, target, attributes)

Always check out the angularjs docs

Running a cron job on Linux every six hours

You need to use *

0 */6 * * * /path/to/mycommand

Also you can refer to https://crontab.guru/ which will help you in scheduling better...

HTML Input="file" Accept Attribute File Type (CSV)

This didn't work for me under Safari 10:

<input type="file" accept=".csv" />

I had to write this instead:

<input type="file" accept="text/csv" />

Google Text-To-Speech API

I used the url as above: http://translate.google.com/translate_tts?tl=en&q=Hello%20World

And requested with python library..however I'm getting HTTP 403 FORBIDDEN

In the end I had to mock the User-Agent header with the browser's one to succeed.

How to insert &nbsp; in XSLT

&#160; works really well. However, it will display one of those strange characters in ANSI encoding. <xsl:text> worked best for me.

<xsl:text> </xsl:text>

how to avoid a new line with p tag?

Flexbox works.

_x000D_
_x000D_
.box{_x000D_
  display: flex;_x000D_
  flex-flow: row nowrap;_x000D_
  justify-content: center;_x000D_
  align-content: center;_x000D_
  align-items:center;_x000D_
  border:1px solid #e3f2fd;_x000D_
}_x000D_
.item{_x000D_
  flex: 1 1 auto;_x000D_
  border:1px solid #ffebee;_x000D_
}
_x000D_
<div class="box">_x000D_
  <p class="item">A</p>_x000D_
  <p class="item">B</p>_x000D_
  <p class="item">C</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

C# Generics and Type Checking

There is no way to use the switch statement for what you want it to do. The switch statement must be supplied with integral types, which does not include complex types such as a "Type" object, or any other object type for that matter.

PHP - Fatal error: Unsupported operand types

I had a similar error with the following code:-

foreach($myvar as $key => $value){
    $query = "SELECT stuff
            FROM table
            WHERE col1 = '$criteria1'
            AND col2 = '$criteria2'";

    $result = mysql_query($query) or die('Could not execute query - '.mysql_error(). __FILE__. __LINE__. $query);               
    $point_values = mysql_fetch_assoc($result);
    $top_five_actions[$key] += $point_values; //<--- Problem Line       
}

It turned out that my $point_values variable was occasionally returning false which caused the problem so I fixed it by wrapping it in mysql_num_rows check:-

if(mysql_num_rows($result) > 0) {
        $point_values = mysql_fetch_assoc($result);
        $top_five_actions[$key] += $point_values;
}

Not sure if this helps though?

Cheers

pandas: filter rows of DataFrame with operator chaining

This is unappealing as it requires I assign df to a variable before being able to filter on its values.

df[df["column_name"] != 5].groupby("other_column_name")

seems to work: you can nest the [] operator as well. Maybe they added it since you asked the question.

How do you automatically set text box to Uppercase?

<script type="text/javascript">
    function upperCaseF(a){
    setTimeout(function(){
        a.value = a.value.toUpperCase();
    }, 1);
}
</script>

<input type="text" required="" name="partno" class="form-control" placeholder="Enter a Part No*" onkeydown="upperCaseF(this)">

Parse an URL in JavaScript

Existing good jQuery plugin Purl (A JavaScript URL parser).This utility can be used in two ways - with jQuery or without...

Position a CSS background image x pixels from the right?

You can do it in CSS3:

background-position: right 20px bottom 20px;

It works in Firefox, Chrome, IE9+

Source: MDN

Is it possible to dynamically compile and execute C# code fragments?

You can compile a piece C# of code into memory and generate assembly bytes with Roslyn. It's already mentioned but would be worth adding some Roslyn example for this here. The following is the complete example:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;

namespace RoslynCompileSample
{
    class Program
    {
        static void Main(string[] args)
        {
            // define source code, then parse it (to the type used for compilation)
            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
                using System;

                namespace RoslynCompileSample
                {
                    public class Writer
                    {
                        public void Write(string message)
                        {
                            Console.WriteLine(message);
                        }
                    }
                }");

            // define other necessary objects for compilation
            string assemblyName = Path.GetRandomFileName();
            MetadataReference[] references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)
            };

            // analyse and generate IL code from syntax tree
            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                // write IL code into memory
                EmitResult result = compilation.Emit(ms);

                if (!result.Success)
                {
                    // handle exceptions
                    IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic => 
                        diagnostic.IsWarningAsError || 
                        diagnostic.Severity == DiagnosticSeverity.Error);

                    foreach (Diagnostic diagnostic in failures)
                    {
                        Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
                    }
                }
                else
                {
                    // load this 'virtual' DLL so that we can use
                    ms.Seek(0, SeekOrigin.Begin);
                    Assembly assembly = Assembly.Load(ms.ToArray());

                    // create instance of the desired class and call the desired function
                    Type type = assembly.GetType("RoslynCompileSample.Writer");
                    object obj = Activator.CreateInstance(type);
                    type.InvokeMember("Write",
                        BindingFlags.Default | BindingFlags.InvokeMethod,
                        null,
                        obj,
                        new object[] { "Hello World" });
                }
            }

            Console.ReadLine();
        }
    }
}

an htop-like tool to display disk activity in linux

nmon shows a nice display of disk activity per device. It is available for linux.

? Disk I/O ?????(/proc/diskstats)????????all data is Kbytes per second???????????????????????????????????????????????????????????????
?DiskName Busy  Read WriteKB|0          |25         |50          |75       100|                                                      ?
?sda        0%    0.0  127.9|>                                                |                                                      ?
?sda1       1%    0.0  127.9|>                                                |                                                      ?
?sda2       0%    0.0    0.0|>                                                |                                                      ?
?sda5       0%    0.0    0.0|>                                                |                                                      ?
?sdb       61%  385.6 9708.7|WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                 |                                                      ?
?sdb1      61%  385.6 9708.7|WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                 |                                                      ?
?sdc       52%  353.6 9686.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR   >                  |                                                      ?
?sdc1      53%  353.6 9686.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR   >                  |                                                      ?
?sdd       56%  359.6 9800.6|WWWWWWWWWWWWWWWWWWWWWWWWWWWW>                    |                                                      ?
?sdd1      56%  359.6 9800.6|WWWWWWWWWWWWWWWWWWWWWWWWWWWW>                    |                                                      ?
?sde       57%  371.6 9574.9|WWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                   |                                                      ?
?sde1      57%  371.6 9574.9|WWWWWWWWWWWWWWWWWWWWWWWWWWWWR>                   |                                                      ?
?sdf       53%  371.6 9740.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR    >                 |                                                      ?
?sdf1      53%  371.6 9740.7|WWWWWWWWWWWWWWWWWWWWWWWWWWR    >                 |                                                      ?
?md0        0% 1726.0 2093.6|>disk busy not available                         |                                                      ?
??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

A beginner's guide to SQL database design

I started with this book: Relational Database Design Clearly Explained (The Morgan Kaufmann Series in Data Management Systems) (Paperback) by Jan L. Harrington and found it very clear and helpful

and as you get up to speed this one was good too Database Systems: A Practical Approach to Design, Implementation and Management (International Computer Science Series) (Paperback)

I think SQL and database design are different (but complementary) skills.

How to hide a View programmatically?

Try this:

linearLayout.setVisibility(View.GONE);

How do I add the contents of an iterable to a set?

You can add elements of a list to a set like this:

>>> foo = set(range(0, 4))
>>> foo
set([0, 1, 2, 3])
>>> foo.update(range(2, 6))
>>> foo
set([0, 1, 2, 3, 4, 5])

How can I get the console logs from the iOS Simulator?

XCode > 6.0 AND iOS > 8.0 The below script works if you have XCode version > 8.0

I use the below small Script to tail the simulator logs onto the system console.

#!/bin/sh
sim_dir=`xcrun instruments -s | grep "iPhone 6 (8.2 Simulator)" | awk {'print $NF'} | tr -d '[]'`
tail -f ~/Library/Logs/CoreSimulator/$sim_dir/system.log

You can pass in the simulator type used in the Grep as an argument. As mentioned in the above posts, there are simctl and instruments command to view the type of simulators available for use depending on the Xcode version. To View the list of available devices/simulators.

xcrun instruments -s

OR

xcrun simctl list

Now you can pass in the Device code OR Simulator type as an argument to the script and replace the "iPhone 6 (8.2 Simulator)" inside grep to be $1

Get a list of checked checkboxes in a div using jQuery

$("#checkboxes").children("input:checked")

will give you an array of the elements themselves. If you just specifically need the names:

$("#checkboxes").children("input:checked").map(function() {
    return this.name;
});

How to input a string from user into environment variable from batch file

A rather roundabout way, just for completeness:

 for /f "delims=" %i in ('type CON') do set inp=%i

Of course that requires ^Z as a terminator, and so the Johannes answer is better in all practical ways.

Is there a command line utility for rendering GitHub flavored Markdown?

I found a website that will do this for you: http://tmpvar.com/markdown.html. Paste in your Markdown, and it'll display it for you. It seems to work just fine!

However, it doesn't seem to handle the syntax highlighting option for code; that is, the ~~~ruby feature doesn't work. It just prints 'ruby'.

How to get std::vector pointer to the raw data?

Take a pointer to the first element instead:

process_data (&something [0]);

Using "margin: 0 auto;" in Internet Explorer 8

Yes, you can read the spec a hundred times, and combine different bits and pieces until you have an interpretation that feels right – but that's exactly what the browser vendors did and that's why we're in the situation we are today.

In essence, when you apply a width of 100% to an element it should extend to 100% of it's parent's width, if that parent is a block element. You can't center it anymore with margin: 0 auto; then since it already takes up 100% of the available width.

To center anything with margin: 0 auto; you need to define an explicit width. To center an inline element, you can use text-align: center; on the parent element, although this could have unwanted side-effects if the parent has other children.

Where will log4net create this log file?

For the log folder and file stuff, go with @Bens answer.

I will comment on the creating log part, though. Imo there is no correct way. When coding loggers manually I do it the way you're doing it:

ILog logger = LogManager.GetLogger(typeof(CCController));

because it is short and concise.

That said, I do not create the logger instances inside the classes these days, I let my IoC container inject it for me.

html select option SELECTED

This is simple example by using ternary operator to set selected=selected

<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $key => $value) { ?>
  <option value="<?php echo $key;?>" <?php echo ($key ==  '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>

Django: Redirect to previous page after login

Django's built-in authentication works the way you want.

Their login pages include a next query string which is the page to return to after login.

Look at http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.login_required

Determine the path of the executing BASH script

For the relative path (i.e. the direct equivalent of Windows' %~dp0):

MY_PATH="`dirname \"$0\"`"
echo "$MY_PATH"

For the absolute, normalized path:

MY_PATH="`dirname \"$0\"`"              # relative
MY_PATH="`( cd \"$MY_PATH\" && pwd )`"  # absolutized and normalized
if [ -z "$MY_PATH" ] ; then
  # error; for some reason, the path is not accessible
  # to the script (e.g. permissions re-evaled after suid)
  exit 1  # fail
fi
echo "$MY_PATH"

How to add a named sheet at the end of all Excel sheets?

Try this:

Private Sub CreateSheet()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets.Add(After:= _
             ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
    ws.Name = "Tempo"
End Sub

Or use a With clause to avoid repeatedly calling out your object

Private Sub CreateSheet()
    Dim ws As Worksheet
    With ThisWorkbook
        Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
        ws.Name = "Tempo"
    End With
End Sub

Above can be further simplified if you don't need to call out on the same worksheet in the rest of the code.

Sub CreateSheet()
    With ThisWorkbook
        .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Temp"
    End With
End Sub

How to give a user only select permission on a database

For the GUI minded people, you can:

  • Right click the Database in Management Studio.
  • Choose Properties
  • Select Permissions
  • If your user does not show up in the list, choose Search and type their name
  • Select the user in the Users or Roles list
  • In the lower window frame, Check the Select permission under the Grant column

Allowing Java to use an untrusted certificate for SSL/HTTPS connection

Another option is to get a ".pem" (public key) file for that particular server, and install it locally into the heart of your JRE's "cacerts" file (use the keytool helper application), then it will be able to download from that server without complaint, without compromising the entire SSL structure of your running JVM and enabling download from other unknown cert servers...

What are the "standard unambiguous date" formats for string-to-date conversion in R?

In other words, is there a better solution than needing to specify the format?

Yes, there is now (ie in late 2016), thanks to anytime::anydate from the anytime package.

See the following for some examples from above:

R> anydate(c("01 Jan 2000", "01/01/2000", "2015/10/10"))
[1] "2000-01-01" "2000-01-01" "2015-10-10"
R> 

As you said, these are in fact unambiguous and should just work. And via anydate() they do. Without a format.

How to enable Ad Hoc Distributed Queries

You may check the following command

sp_configure 'show advanced options', 1;
RECONFIGURE;
GO  --Added        
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

SELECT a.*
FROM OPENROWSET('SQLNCLI', 'Server=Seattle1;Trusted_Connection=yes;',
     'SELECT GroupName, Name, DepartmentID
      FROM AdventureWorks2012.HumanResources.Department
      ORDER BY GroupName, Name') AS a;
GO

Or this documentation link

What is the best data type to use for money in C#?

Decimal. If you choose double you're leaving yourself open to rounding errors

No WebApplicationContext found: no ContextLoaderListener registered?

And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747

How to solve Object reference not set to an instance of an object.?

You need to initialize the list first:

protected List<string> list = new List<string>();

Using multiple .cpp files in c++ program?

You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive. Then you may call the other function.

other.h

void MyFunc();

main.cpp

#include "other.h"
int main() {
    MyFunc();
}

other.cpp

#include "other.h"
#include <iostream>
void MyFunc() {
    std::cout << "Ohai from another .cpp file!";
    std::cin.get();
}

Update cordova plugins in one command

If you install the third party package:

npm i cordova-check-plugins

You can then run a simple command of

cordova-check-plugins --update=auto --force

Keep in mind forcing anything always comes with potential risks of breaking changes.

As other answers have stated, the connecting NPM packages that manage these plugins also require a consequent update when updating the plugins, so now you can check them with:

npm outdated

And then sweeping update them with

npm update

Now tentatively serve your app again and check all of the things that have potentially gone awry from breaking changes. The joy of software development! :)

Step out of current function with GDB

You can use the finish command.

finish: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated as fin.

(See 5.2 Continuing and Stepping.)

Create a .tar.bz2 file Linux

You are not indicating what to include in the archive.

Go one level outside your folder and try:

sudo tar -cvjSf folder.tar.bz2 folder

Or from the same folder try

sudo tar -cvjSf folder.tar.bz2 *

Cheers!

How to get info on sent PHP curl request

If you set CURLINFO_HEADER_OUT to true, outgoing headers are available in the array returned by curl_getinfo(), under request_header key:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://foo.com/bar");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "someusername:secretpassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

curl_exec($ch);

$info = curl_getinfo($ch);
print_r($info['request_header']);

This will print:

GET /bar HTTP/1.1
Authorization: Basic c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk
Host: foo.com
Accept: */*

Note the auth details are base64-encoded:

echo base64_decode('c29tZXVzZXJuYW1lOnNlY3JldHBhc3N3b3Jk');
// prints: someusername:secretpassword

Also note that username and password need to be percent-encoded to escape any URL reserved characters (/, ?, &, : and so on) they might contain:

curl_setopt($ch, CURLOPT_USERPWD, urlencode($username).':'.urlencode($password));

How to toggle a boolean?

bool = bool != true;

One of the cases.

How to convert a string with Unicode encoding to a string of letters

Just wanted to contribute my version, using regex:

private static final String UNICODE_REGEX = "\\\\u([0-9a-f]{4})";
private static final Pattern UNICODE_PATTERN = Pattern.compile(UNICODE_REGEX);
...
String message = "\u0048\u0065\u006C\u006C\u006F World";
Matcher matcher = UNICODE_PATTERN.matcher(message);
StringBuffer decodedMessage = new StringBuffer();
while (matcher.find()) {
  matcher.appendReplacement(
      decodedMessage, String.valueOf((char) Integer.parseInt(matcher.group(1), 16)));
}
matcher.appendTail(decodedMessage);
System.out.println(decodedMessage.toString());

Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

I made a solution that works very nice for me:

function shadeColor(color, percent) {

    var R = parseInt(color.substring(1,3),16);
    var G = parseInt(color.substring(3,5),16);
    var B = parseInt(color.substring(5,7),16);

    R = parseInt(R * (100 + percent) / 100);
    G = parseInt(G * (100 + percent) / 100);
    B = parseInt(B * (100 + percent) / 100);

    R = (R<255)?R:255;  
    G = (G<255)?G:255;  
    B = (B<255)?B:255;  

    var RR = ((R.toString(16).length==1)?"0"+R.toString(16):R.toString(16));
    var GG = ((G.toString(16).length==1)?"0"+G.toString(16):G.toString(16));
    var BB = ((B.toString(16).length==1)?"0"+B.toString(16):B.toString(16));

    return "#"+RR+GG+BB;
}

Example Lighten:

shadeColor("#63C6FF",40);

Example Darken:

shadeColor("#63C6FF",-40);

Where can I download an offline installer of Cygwin?

may this post can solve your problem

see Full Installation Answer on that: What is the current full install size of Cygwin?