Programs & Examples On #Weak linking

How to create a drop-down list?

Spinner xml:

<Spinner
      android:id="@+id/spinner"
      android:layout_width="wrap_content"
      android:layout_height="match_parent" />

java:

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{

    private Spinner spinner;
    private static final String[] paths = {"item 1", "item 2", "item 3"};

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        spinner = (Spinner)findViewById(R.id.spinner);
        ArrayAdapter<String>adapter = new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_spinner_item,paths);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {

        switch (position) {
            case 0:
                // Whatever you want to happen when the first item gets selected
                break;
            case 1:
                // Whatever you want to happen when the second item gets selected
                break;
            case 2:
                // Whatever you want to happen when the thrid item gets selected
                break;

        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
            // TODO Auto-generated method stub
        }

}

Multipart forms from C# client

Below is the code which I'm using

    //This URL not exist, it's only an example.
    string url = "http://myBox.s3.amazonaws.com/";
    //Instantiate new CustomWebRequest class
    CustomWebRequest wr = new CustomWebRequest(url);
    //Set values for parameters
    wr.ParamsCollection.Add(new ParamsStruct("key", "${filename}"));
    wr.ParamsCollection.Add(new ParamsStruct("acl", "public-read"));
    wr.ParamsCollection.Add(new ParamsStruct("success_action_redirect", "http://www.yahoo.com"));
    wr.ParamsCollection.Add(new ParamsStruct("x-amz-meta-uuid", "14365123651274"));
    wr.ParamsCollection.Add(new ParamsStruct("x-amz-meta-tag", ""));
    wr.ParamsCollection.Add(new ParamsStruct("AWSAccessKeyId", "zzzz"));            
    wr.ParamsCollection.Add(new ParamsStruct("Policy", "adsfadsf"));
    wr.ParamsCollection.Add(new ParamsStruct("Signature", "hH6lK6cA="));
    //For file type, send the inputstream of selected file
    StreamReader sr = new StreamReader(@"file.txt");
    wr.ParamsCollection.Add(new ParamsStruct("file", sr, ParamsStruct.ParamType.File, "file.txt"));

    wr.PostData();

from the following link I've downloaded the same code http://www.codeproject.com/KB/cs/multipart_request_C_.aspx

Any Help

What is the maximum number of characters that nvarchar(MAX) will hold?

From char and varchar (Transact-SQL)

varchar [ ( n | max ) ]

Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.

How to get 0-padded binary representation of an integer in java?

You can use lib https://github.com/kssource/BitSequence. It accept a number and return bynary string, padded and/or grouped.

String s = new BitSequence(2, 16).toBynaryString(ALIGN.RIGHT, GROUP.CONTINOUSLY));  
return  
0000000000000010  

another examples:

[10, -20, 30]->00001010 11101100 00011110
i=-10->00000000000000000000000000001010
bi=10->1010
sh=10->00 0000 0000 1010
l=10->00000001 010
by=-10->1010
i=-10->bc->11111111 11111111 11111111 11110110

How to scroll to bottom in a ScrollView on activity startup

It needs to be done as following:

    getScrollView().post(new Runnable() {

        @Override
        public void run() {
            getScrollView().fullScroll(ScrollView.FOCUS_DOWN);
        }
    });

This way the view is first updated and then scrolls to the "new" bottom.

how to have two headings on the same line in html

The following code will allow you to have two headings on the same line, the first left-aligned and the second right-aligned, and has the added advantage of keeping both headings on the same baseline.

The HTML Part:

<h1 class="text-left-right">
    <span class="left-text">Heading Goes Here</span>
    <span class="byline">Byline here</span>
</h1>

And the CSS:

.text-left-right {
    text-align: right;
    position: relative;
}
.left-text {
    left: 0;
    position: absolute;
}
.byline {
    font-size: 16px;
    color: rgba(140, 140, 140, 1);
}

What are some alternatives to ReSharper?

A comprehensive list:

  • CodeRush, by DevExpress. (Considered the main alternative) Either this or ReSharper is the way to go. You cannot go wrong with either. Both have their fans, both are powerful, both have talented teams constantly improving them. We have all benefited from the competition between these two. I won't repeat the many good discussions/comparisons about them that can be found on Stack Overflow and elsewhere. 1

  • JustCode, by Telerik. This is new, still with kinks, but initial reports are positive. An advantage could be liscensing with other Telerik products and integration with them. 1

  • Many of the new Visual Studio 2010 features. See what's been added vs. what you need, it could be that the core install takes care of what you are interested in now.

  • Visual Assist X, More than 50 features make Visual Assist X an incredible productivity tool. Pick a category and learn more, or download a free trial and discover them all. 2

  • VSCommands, VSCommands provides code navigation and generation improvements which will make your everyday coding tasks blazing fast and, together with tens of essential IDE enhancements, it will take your productivity to another level. VSCommands comes in two flavours: Lite (free) and Pro (paid). 3

  • BrockSoft VSAid, VSAid (Visual Studio Aid) is a Microsoft Visual Studio add-in available, at no cost, for both personal and commercial use. Primarily aimed at Visual C++ developers (though useful for any Visual Studio project or solution), VSAid adds a new toolbar to the IDE which adds productivity-enhancing features such as being able to find and open project files quickly and cycle through related files at the click of a mouse button (or the stroke of a key!). 4

Alternative to google finance api

Updating answer a bit

1. Try Twelve Data API

For beginners try to run the following query with a JSON response:

https://api.twelvedata.com/time_series?symbol=AAPL&interval=1min&apikey=demo&source=docs

NO more real time Alpha Vantage API

For beginners you can try to get a JSON output from query such as

https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo

DON'T Try Yahoo Finance API (it is DEPRECATED or UNAVAILABLE NOW).

For beginners, you can generate a CSV with a simple API call:

http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=sb2b3jk

(This will generate and save a CSV for AAPL, GOOG, and MSFT)

Note that you must append the format to the query string (f=..). For an overview of all of the formats see this page.

For more examples, visit this page.

For XML and JSON-based data, you can do the following:

Don't use YQL (Yahoo Query Language)

For example:

http://developer.yahoo.com/yql/console/?q=select%20*%20from%20yahoo.finance
.quotes%20where%20symbol%20in%20(%22YHOO%22%2C%22AAPL%22%2C%22GOOG%22%2C%22
MSFT%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env

2. Use the webservice

For example, to get all stock quotes in XML:

http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote

To get all stock quotes in JSON, just add format=JSON to the end of the URL:

http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json

Alternatives:

  1. Currency API

    • 165+ real time currency rates, including few cryptos. Docs here.
  2. Financial Content API

  3. IEX

  4. Open Exchange Rates

  5. Polygon

  6. XE API

  7. Xignite API

  8. currencylayer API

  9. Other APIs - discussed at programmableWeb

Pass a variable to a PHP script running from the command line

if (isset($argv) && is_array($argv)) {
    $param = array();
    for ($x=1; $x<sizeof($argv);$x++) {
        $pattern = '#\/(.+)=(.+)#i';
        if (preg_match($pattern, $argv[$x])) {
            $key =  preg_replace($pattern, '$1', $argv[$x]);
            $val =  preg_replace($pattern, '$2', $argv[$x]);
            $_REQUEST[$key] = $val;
            $$key = $val;
        }
    }
}

I put parameters in $_REQUEST:

$_REQUEST[$key] = $val;

And it is also usable directly:

$$key=$val

Use it like this:

myFile.php /key=val

Take multiple lists into dataframe

There are several ways to create a dataframe from multiple lists.

list1=[1,2,3,4]
list2=[5,6,7,8]
list3=[9,10,11,12]
  1. pd.DataFrame({'list1':list1, 'list2':list2, 'list3'=list3})

  2. pd.DataFrame(data=zip(list1,list2,list3),columns=['list1','list2','list3'])

PSQLException: current transaction is aborted, commands ignored until end of transaction block

You need to rollback. The JDBC Postgres driver is pretty bad. But if you want to keep your transaction, and just rollback that error, you can use savepoints:

try {
_stmt = connection.createStatement();
_savePoint = connection.setSavepoint("sp01");
_result = _stmt.executeUpdate(sentence) > 0;
} catch (Exception e){
 if (_savePoint!=null){
 connection.rollback(_savePoint);
}
}

Read more here:

http://www.postgresql.org/docs/8.1/static/sql-savepoint.html

How to set width of mat-table column in angular?

using css we can adjust specific column width which i put in below code.

user.component.css

table{
 width: 100%;
}

.mat-column-username {
  word-wrap: break-word !important;
  white-space: unset !important;
  flex: 0 0 28% !important;
  width: 28% !important;
  overflow-wrap: break-word;
  word-wrap: break-word;

  word-break: break-word;

  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}

.mat-column-emailid {
  word-wrap: break-word !important;
  white-space: unset !important;
  flex: 0 0 25% !important;
  width: 25% !important;
  overflow-wrap: break-word;
  word-wrap: break-word;

  word-break: break-word;

  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}

.mat-column-contactno {
  word-wrap: break-word !important;
  white-space: unset !important;
  flex: 0 0 17% !important;
  width: 17% !important;
  overflow-wrap: break-word;
  word-wrap: break-word;

  word-break: break-word;

  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}

.mat-column-userimage {
  word-wrap: break-word !important;
  white-space: unset !important;
  flex: 0 0 8% !important;
  width: 8% !important;
  overflow-wrap: break-word;
  word-wrap: break-word;

  word-break: break-word;

  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}

.mat-column-userActivity {
  word-wrap: break-word !important;
  white-space: unset !important;
  flex: 0 0 10% !important;
  width: 10% !important;
  overflow-wrap: break-word;
  word-wrap: break-word;

  word-break: break-word;

  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}

How to set a primary key in MongoDB?

This is the syntax of creating primary key

db.< collection >.createIndex( < key and index type specification>, { unique: true } )

Let's take that our database have collection named student and it's document have key named student_id which we need to make a primary key. Then the command should be like below.

db.student.createIndex({student_id:1},{unique:true})

You can check whether this student_id set as primary key by trying to add duplicate value to the student collection.

prefer this document for further informations https://docs.mongodb.com/manual/core/index-unique/#create-a-unique-index

Executing a batch script on Windows shutdown

Programatically this can be achieved with SCHTASKS:

SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=1074)]]" /EC Security /tn on_shutdown_normal /tr "c:\some.bat" 

SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6006)]]" /EC Security /tn on_shutdown_6006 /tr "c:\some.bat" 

SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6008)]]" /EC Security /tn on_shutdown_6008 /tr "c:\some.bat" 

Getting "A potentially dangerous Request.Path value was detected from the client (&)"

I have faced this type of error. to call a function from the razor.

public ActionResult EditorAjax(int id, int? jobId, string type = ""){}

solved that by changing the line

from

<a href="/ScreeningQuestion/EditorAjax/5&jobId=2&type=additional" /> 

to

<a href="/ScreeningQuestion/EditorAjax/?id=5&jobId=2&type=additional" />

where my route.config is

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new string[] { "RPMS.Controllers" } // Parameter defaults
        );

How to make HTML Text unselectable

I altered the jQuery plugin posted above so it would work on live elements.

(function ($) {
$.fn.disableSelection = function () {
    return this.each(function () {
        if (typeof this.onselectstart != 'undefined') {
            this.onselectstart = function() { return false; };
        } else if (typeof this.style.MozUserSelect != 'undefined') {
            this.style.MozUserSelect = 'none';
        } else {
            this.onmousedown = function() { return false; };
        }
    });
};
})(jQuery);

Then you could so something like:

$(document).ready(function() {
    $('label').disableSelection();

    // Or to make everything unselectable
    $('*').disableSelection();
});

Enter key press behaves like a Tab in Javascript

Try this...

$(document).ready(function () {
    $.fn.enterkeytab = function () {
        $(this).on('keydown', 'input,select,text,button', function (e) {
            var self = $(this)
              , form = self.parents('form:eq(0)')
              , focusable
              , next
            ;
            if (e.keyCode == 13) {
                focusable = form.find('input,a,select').filter(':visible');
                next = focusable.eq(focusable.index(this) + 1);
                if (next.length) {
                    //if disable try get next 10 fields
                    if (next.is(":disabled")){
                        for(i=2;i<10;i++){
                            next = focusable.eq(focusable.index(this) + i);
                            if (!next.is(":disabled"))
                                break;
                        }
                    }
                    next.focus();
                }
                return false;
            }
        });
    }
    $("form").enterkeytab();
});

Reading images in python

you can try to use cv2 like this

import cv2

image= cv2.imread('image page')

cv2.imshow('image', image)

cv2.waitKey(0)

cv2.destroyAllWindows()

Android ListView with different layouts for each row

ListView was intended for simple use cases like the same static view for all row items.
Since you have to create ViewHolders and make significant use of getItemViewType(), and dynamically show different row item layout xml's, you should try doing that using the RecyclerView, which is available in Android API 22. It offers better support and structure for multiple view types.

Check out this tutorial on how to use the RecyclerView to do what you are looking for.

Redirect website after certain amount of time

You're probably looking for the meta refresh tag:

<html>
    <head>
        <meta http-equiv="refresh" content="3;url=http://www.somewhere.com/" />
    </head>
    <body>
        <h1>Redirecting in 3 seconds...</h1>
    </body>
</html>

Note that use of meta refresh is deprecated and frowned upon these days, but sometimes it's the only viable option (for example, if you're unable to do server-side generation of HTTP redirect headers and/or you need to support non-JavaScript clients etc).

Why is Java's SimpleDateFormat not thread-safe?

Release 3.2 of commons-lang will have FastDateParser class that is a thread-safe substitute of SimpleDateFormat for Gregorian calendar. See LANG-909 for more information.

How to override and extend basic Django admin templates?

for app index add this line to somewhere common py file like url.py

admin.site.index_template = 'admin/custom_index.html'

for app module index : add this line to admin.py

admin.AdminSite.app_index_template = "servers/servers-home.html"

for change list : add this line to admin class:

change_list_template = "servers/servers_changelist.html"

for app module form template : add this line to your admin class

change_form_template = "servers/server_changeform.html"

etc. and find other in same admin's module classes

How to restore the permissions of files and directories within git if they have been modified?

Git doesn't store file permissions other than executable scripts. Consider using something like git-cache-meta to save file ownership and permissions.

Git can only store two types of modes: 755 (executable) and 644 (not executable). If your file was 444 git would store it has 644.

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

This isn't appropriate in all situations but you can conditionally return false inside the component itself if a certain criteria is or isn't met.

It doesn't unmount the component, but it removes all rendered content. This would only be bad, in my mind, if you have event listeners in the component that should be removed when the component is no longer needed.

import React, { Component } from 'react';

export default class MyComponent extends Component {
    constructor(props) {
        super(props);

        this.state = {
            hideComponent: false
        }
    }

    closeThis = () => {
        this.setState(prevState => ({
            hideComponent: !prevState.hideComponent
        })
    });

    render() {
        if (this.state.hideComponent === true) {return false;}

        return (
            <div className={`content`} onClick={() => this.closeThis}>
                YOUR CODE HERE
            </div>
        );
    }
}

MS-DOS Batch file pause with enter key

You can do it with the pause command, example:

dir
pause
echo Now about to end...
pause

" netsh wlan start hostednetwork " command not working no matter what I try

This was a real issue for me, and quite a sneaky problem to try and remedy...

The problem I had was that a module that was installed on my WiFi adapter was conflicting with the Microsoft Virtual Adapter (or whatever it's actually called).

To fix it:

  1. Hold the Windows Key + Push R
  2. Type: ncpa.cpl in to the box, and hit OK.
  3. Identify the network adapter you want to use for the hostednetwork, right-click it, and select Properties.
  4. You'll see a big box in the middle of the properties window, under the heading The connection uses the following items:. Look down the list for anything that seems out of the ordinary, and uncheck it. Hit OK.
  5. Try running the netsh wlan start hostednetwork command again.
  6. Repeat steps 4 and 5 as necessary.

In my case my adapter was running a module called SoftEther Lightweight Network Protocol, which I believe is used to help connect to VPN Gate VPN servers via the SoftEther software.

If literally nothing else works, then I'd suspect something similar to the problem I encountered, namely that a module on your network adapter is interfering with the hostednetwork aspect of your driver.

Python Save to file

In order to write into a file in Python, we need to open it in write w, append a or exclusive creation x mode.

We need to be careful with the w mode, as it will overwrite into the file if it already exists. Due to this, all the previous data are erased.

Writing a string or sequence of bytes (for binary files) is done using the write() method. This method returns the number of characters written to the file.

with open('Failed.py','w',encoding = 'utf-8') as f:
   f.write("Write what you want to write in\n")
   f.write("this file\n\n")

This program will create a new file named Failed.py in the current directory if it does not exist. If it does exist, it is overwritten.

We must include the newline characters ourselves to distinguish the different lines.

Checking if a SQL Server login already exists

As a minor addition to this thread, in general you want to avoid using the views that begin with sys.sys* as Microsoft is only including them for backwards compatibility. For your code, you should probably use sys.server_principals. This is assuming you are using SQL 2005 or greater.

Linux: Which process is causing "device busy" when doing umount?

Also check /etc/exports. If you are exporting paths within the mountpoint via NFS, it will give this error when trying to unmount and nothing will show up in fuser or lsof.

how to remove "," from a string in javascript

Use String.replace(), e.g.

var str = "a,d,k";
str = str.replace( /,/g, "" );

Note the g (global) flag on the regular expression, which matches all instances of ",".

Update Tkinter Label from variable

This is the easiest one , Just define a Function and then a Tkinter Label & Button . Pressing the Button changes the text in the label. The difference that you would when defining the Label is that use the text variable instead of text. Code is tested and working.

    from tkinter import *
    master = Tk()
    
    def change_text():
        my_var.set("Second click")
    
    my_var = StringVar()
    my_var.set("First click")
    label = Label(mas,textvariable=my_var,fg="red")
    button = Button(mas,text="Submit",command = change_text)
    button.pack()
    label.pack()
    
    master.mainloop()

How to get data by SqlDataReader.GetValue by column name

thisReader.GetString(int columnIndex)

node.js string.replace doesn't work?

Isn't string.replace returning a value, rather than modifying the source string?

So if you wanted to modify variableABC, you'd need to do this:

var variableABC = "A B C";

variableABC = variableABC.replace('B', 'D') //output: 'A D C'

Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

I've created this tool years ago for the same purpose:
http://www.betterprogramming.com/htmlclipper.html

You're welcome to use and improve upon it.

How to get element value in jQuery

You can do the same by using jQuery on().

$("#list").on('click','li',(function() {
    var selected = $(this).text();   //or .html()
    alert(selected);
})

Shell Script Syntax Error: Unexpected End of File

in my case the issue was in the EOL Conversion. (End Of Line).

i created the file on windows and only after i converted the EOL from windows(CR LF) to unix(LF), everything went well.

I did the conversion with Notepad++ very easily from: Edit -> EOL Conversion -> Unix(LF)

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

For me put variable before calling did the trick:

OPENSSL_CONF=/usr/ssl/openssl.cnf openssl req -new -x509 -key privatekey.pem -out publickey.cer -days 365

Get list of data-* attributes using javascript / jQuery

As mentioned above modern browsers have the The HTMLElement.dataset API.
That API gives you a DOMStringMap, and you can retrieve the list of data-* attributes simply doing:

var dataset = el.dataset; // as you asked in the question

you can also retrieve a array with the data- property's key names like

var data = Object.keys(el.dataset);

or map its values by

Object.keys(el.dataset).map(function(key){ return el.dataset[key];});
// or the ES6 way: Object.keys(el.dataset).map(key=>{ return el.dataset[key];});

and like this you can iterate those and use them without the need of filtering between all attributes of the element like we needed to do before.

Expand/collapse section in UITableView in iOS

To implement the collapsible table section in iOS, the magic is how to control the number of rows for each section, or we can manage the height of rows for each section.

Also, we need to customize the section header so that we can listen to the tap event from the header area (whether it's a button or the whole header).

How to deal with the header? It's very simple, we extend the UITableViewCell class and make a custom header cell like so:

import UIKit

class CollapsibleTableViewHeader: UITableViewCell {

    @IBOutlet var titleLabel: UILabel!
    @IBOutlet var toggleButton: UIButton!

}

then use the viewForHeaderInSection to hook up the header cell:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  let header = tableView.dequeueReusableCellWithIdentifier("header") as! CollapsibleTableViewHeader

  header.titleLabel.text = sections[section].name
  header.toggleButton.tag = section
  header.toggleButton.addTarget(self, action: #selector(CollapsibleTableViewController.toggleCollapse), forControlEvents: .TouchUpInside)

  header.toggleButton.rotate(sections[section].collapsed! ? 0.0 : CGFloat(M_PI_2))

  return header.contentView
}

remember we have to return the contentView because this function expects a UIView to be returned.

Now let's deal with the collapsible part, here is the toggle function that toggle the collapsible prop of each section:

func toggleCollapse(sender: UIButton) {
  let section = sender.tag
  let collapsed = sections[section].collapsed

  // Toggle collapse
  sections[section].collapsed = !collapsed

  // Reload section
  tableView.reloadSections(NSIndexSet(index: section), withRowAnimation: .Automatic)
}

depends on how you manage the section data, in this case, I have the section data something like this:

struct Section {
  var name: String!
  var items: [String]!
  var collapsed: Bool!

  init(name: String, items: [String]) {
    self.name = name
    self.items = items
    self.collapsed = false
  }
}

var sections = [Section]()

sections = [
  Section(name: "Mac", items: ["MacBook", "MacBook Air", "MacBook Pro", "iMac", "Mac Pro", "Mac mini", "Accessories", "OS X El Capitan"]),
  Section(name: "iPad", items: ["iPad Pro", "iPad Air 2", "iPad mini 4", "Accessories"]),
  Section(name: "iPhone", items: ["iPhone 6s", "iPhone 6", "iPhone SE", "Accessories"])
]

at last, what we need to do is based on the collapsible prop of each section, control the number of rows of that section:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  return (sections[section].collapsed!) ? 0 : sections[section].items.count
}

I have a fully working demo on my Github: https://github.com/jeantimex/ios-swift-collapsible-table-section

demo

If you want to implement the collapsible sections in a grouped-style table, I have another demo with source code here: https://github.com/jeantimex/ios-swift-collapsible-table-section-in-grouped-section

Hope that helps.

Compiling an application for use in highly radioactive environments

How about running many instances of your application. If crashes are due to random memory bit changes, chances are some of your app instances will make it through and produce accurate results. It's probably quite easy (for someone with statistical background) to calculate how many instances do you need given bit flop probability to achieve as tiny overall error as you wish.

Windows batch: formatted date into variable

If you don't mind an one-time investment of 10 to 30 minutes to get a reliable solution (that doesn't depend on Windows' region settings), please read on.

Let's free our minds. Do you want to simplify the scripts to just look like this? (Assume you wants to set the LOG_DATETIME variable)

FOR /F "tokens=* USEBACKQ" %%F IN (`FormatNow "yyyy-MM-dd"`) DO (
  Set LOG_DATETIME=%%F
)

echo I am going to write log to Testing_%LOG_DATETIME%.log

You can. Simply build a FormatNow.exe with C# .NET and add it to your PATH.

Notes:

  1. You can use any Visual Studio edition, such as Visual Studio Express, to build the FormatNow.exe.
  2. In Visual Studio, choose the "Console Application" C# project, not "Windows Forms Application" project.
  3. Common sense: the built FormatNow.exe will need .NET Framework to run.
  4. Common sense: after adding FormatNow.exe to PATH variable, you need to restart CMD to take effect. It also applies to any change in environment variables.

Benefits:

  1. It's not slow (finishes within 0.2 seconds).
  2. Many formats are supported https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx e.g. FormatNow "ddd" to get only the day of week, FormatNow "yyyy" to get only the year
  3. It doesn't depend on Windows' region settings, so its output is much more reliable. On the other hand, %date% doesn't give a consistent format over different computers, and is not reliable.
  4. You don't need to create so many CMD variables and pollute the variable namespace.
  5. It would require 3 lines in the batch script to invoke the program and get the results. It should be reasonably short enough.

Source code of FormatNow.exe which I built with Visual Studio 2010 (I prefer to build it myself to avoid the risk of downloading an unknown, possibly malicious program). Just copy and paste the codes below, build the program once, and then you have a reliable date formatter for all future uses.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace FormatNow
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                if (args.Length < 1)
                {
                    throw new ArgumentException("Missing format");
                }
                string format = args[0];
                Console.Write(DateTime.Now.ToString(format, CultureInfo.InvariantCulture.DateTimeFormat));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

    }
}

In general, when dealing with complicated logics, we can make it simpler for by building a very small program and calling the program to capture the output back to a batch script variable instead. We are not students and we're not taking exams requiring us to follow the batch-script-only rule to solve problems. In real working environment, any (legal) method is allowed. Why should we still stick to the poor capabilities of Windows batch script that needs workarounds for many simple tasks? Why should we use the wrong tool for the job?

R dates "origin" must be supplied

I suspect you meant:

axis.Date(1, as.Date(sites$date, origin = "1970-01-01"))

as the 'x' argument to as.Date() has to be of type Date.

As an aside, this would have appropriate as a follow-up or edit of your previous question.

Calculate the execution time of a method

If you are interested in understand performance, the best answer is to use a profiler.

Otherwise, System.Diagnostics.StopWatch provides a high resolution timer.

How do I see the current encoding of a file in Sublime Text?

plugin ConverToUTF8 also has the functionality.

get next and previous day with PHP

Very easy with the dateTime() object, too.

$tomorrow = new DateTime('tomorrow');
echo $tomorrow->format("Y-m-d"); // Tomorrow's date

$yesterday = new DateTime('yesterday');
echo $yesterday->format("Y-m-d"); // Yesterday's date

How to sort an object array by date property?

I have just taken the Schwartzian transform depicted above and made as function. It takes an array, the sorting function and a boolean as input:

function schwartzianSort(array,f,asc){
    for (var i=array.length;i;){
      var o = array[--i];
      array[i] = [].concat(f.call(o,o,i),o);
    }
    array.sort(function(a,b){
      for (var i=0,len=a.length;i<len;++i){
        if (a[i]!=b[i]) return a[i]<b[i]?asc?-1:1:1;
      }
      return 0;
    });
    for (var i=array.length;i;){
      array[--i]=array[i][array[i].length-1];
    }
    return array;
  }

_x000D_
_x000D_
function schwartzianSort(array, f, asc) {_x000D_
  for (var i = array.length; i;) {_x000D_
    var o = array[--i];_x000D_
    array[i] = [].concat(f.call(o, o, i), o);_x000D_
  }_x000D_
  array.sort(function(a, b) {_x000D_
    for (var i = 0, len = a.length; i < len; ++i) {_x000D_
      if (a[i] != b[i]) return a[i] < b[i] ? asc ? -1 : 1 : 1;_x000D_
    }_x000D_
    return 0;_x000D_
  });_x000D_
  for (var i = array.length; i;) {_x000D_
    array[--i] = array[i][array[i].length - 1];_x000D_
  }_x000D_
  return array;_x000D_
}_x000D_
_x000D_
arr = []_x000D_
arr.push({_x000D_
  date: new Date(1494434112806)_x000D_
})_x000D_
arr.push({_x000D_
  date: new Date(1494434118181)_x000D_
})_x000D_
arr.push({_x000D_
  date: new Date(1494434127341)_x000D_
})_x000D_
_x000D_
console.log(JSON.stringify(arr));_x000D_
_x000D_
arr = schwartzianSort(arr, function(o) {_x000D_
  return o.date_x000D_
}, false)_x000D_
console.log("DESC", JSON.stringify(arr));_x000D_
_x000D_
arr = schwartzianSort(arr, function(o) {_x000D_
  return o.date_x000D_
}, true)_x000D_
console.log("ASC", JSON.stringify(arr));
_x000D_
_x000D_
_x000D_

Select the values of one property on all objects of an array in PowerShell

I think you might be able to use the ExpandProperty parameter of Select-Object.

For example, to get the list of the current directory and just have the Name property displayed, one would do the following:

ls | select -Property Name

This is still returning DirectoryInfo or FileInfo objects. You can always inspect the type coming through the pipeline by piping to Get-Member (alias gm).

ls | select -Property Name | gm

So, to expand the object to be that of the type of property you're looking at, you can do the following:

ls | select -ExpandProperty Name

In your case, you can just do the following to have a variable be an array of strings, where the strings are the Name property:

$objects = ls | select -ExpandProperty Name

How can I use a custom font in Java?

From the Java tutorial, you need to create a new font and register it in the graphics environment:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));

After this step is done, the font is available in calls to getAvailableFontFamilyNames() and can be used in font constructors.

How can I submit a POST form using the <a href="..."> tag?

I use a jQuery script to create "shadow" forms for my POSTable links.

Instead of <a href="/some/action?foo=bar">, I write <a data-post="/some/action" data-var-foo="bar" href="#do_action_foo_bar">. The script makes a hidden form with hidden inputs, and submits it when the link is clicked.

_x000D_
_x000D_
$("a[data-post]")
    .each(function() {
        let href = $(this).data("post"); if (!href) return;
        let $form = $("<form></form>").attr({ method:"POST",action:href }).css("display","none")
        let data = $(this).data()
        for (let dat in data) {
            if (dat.startsWith("postVar")) {
                let varname = dat.substring(7).toLowerCase()  // postVarId -> id
                let varval = data[dat]
                $form.append($("<input/>").attr({ type:"hidden",name:varname,value:varval }))
            }
        }
        $("body").append($form)
        $(this).data("postform",$form)
    })
    .click(function(ev) {
        ev.preventDefault()
        if ($(this).data("postform")) $(this).data("postform").submit(); else console.error("No .postform set in <a data-post>")
    })
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-post="/some/action" data-var-foo="bar" href="#do_action_foo_bar">click me</a>
_x000D_
_x000D_
_x000D_

How do I move an existing Git submodule within a Git repository?

Note: As mentioned in the comments this answer refers to the steps needed with older versions of git. Git now has native support for moving submodules:

Since git 1.8.5, git mv old/submod new/submod works as expected and does all the plumbing for you. You might want to use git 1.9.3 or newer, because it includes fixes for submodule moving.


The process is similar to how you'd remove a submodule (see How do I remove a submodule?):

  1. Edit .gitmodules and change the path of the submodule appropriately, and put it in the index with git add .gitmodules.
  2. If needed, create the parent directory of the new location of the submodule (mkdir -p new/parent).
  3. Move all content from the old to the new directory (mv -vi old/parent/submodule new/parent/submodule).
  4. Make sure Git tracks this directory (git add new/parent).
  5. Remove the old directory with git rm --cached old/parent/submodule.
  6. Move the directory .git/modules/old/parent/submodule with all its content to .git/modules/new/parent/submodule.
  7. Edit the .git/modules/new/parent/config file, make sure that worktree item points to the new locations, so in this example it should be worktree = ../../../../../new/parent/module. Typically there should be two more .. than directories in the direct path in that place.
  8. Edit the file new/parent/module/.git, make sure that the path in it points to the correct new location inside the main project .git folder, so in this example gitdir: ../../../.git/modules/new/parent/submodule.

    git status output looks like this for me afterwards:

    # On branch master
    # Changes to be committed:
    #   (use "git reset HEAD <file>..." to unstage)
    #
    #       modified:   .gitmodules
    #       renamed:    old/parent/submodule -> new/parent/submodule
    #
    
  9. Finally, commit the changes.

jQuery using append with effects

In my case:

$("div.which-stores-content").append("<div class="content">Content</div>);
$("div.content").hide().show("fast");

you can adjust your css with visibility:hidden -> visibility:visible and adjust the transitions etc transition: visibility 1.0s;

Cannot read property length of undefined

The id of the input seems is not WallSearch. Maybe you're confusing that name and id. They are two different properties. name is used to define the name by which the value is posted, while id is the unique identification of the element inside the DOM.

Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value property.

Can't access to HttpContext.Current

Have you included the System.Web assembly in the application?

using System.Web;

If not, try specifying the System.Web namespace, for example:

 System.Web.HttpContext.Current

Create table in SQLite only if it doesn't exist already

Am going to try and add value to this very good question and to build on @BrittonKerin's question in one of the comments under @David Wolever's fantastic answer. Wanted to share here because I had the same challenge as @BrittonKerin and I got something working (i.e. just want to run a piece of code only IF the table doesn't exist).

        # for completeness lets do the routine thing of connections and cursors
        conn = sqlite3.connect(db_file, timeout=1000) 

        cursor = conn.cursor() 

        # get the count of tables with the name  
        tablename = 'KABOOM' 
        cursor.execute("SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? ", (tablename, ))

        print(cursor.fetchone()) # this SHOULD BE in a tuple containing count(name) integer.

        # check if the db has existing table named KABOOM
        # if the count is 1, then table exists 
        if cursor.fetchone()[0] ==1 : 
            print('Table exists. I can do my custom stuff here now.... ')
            pass
        else: 
           # then table doesn't exist. 
           custRET = myCustFunc(foo,bar) # replace this with your custom logic

PHP code to remove everything but numbers

You would need to enclose the pattern in a delimiter - typically a slash (/) is used. Try this:

echo preg_replace("/[^0-9]/","",'604-619-5135');

Clone private git repo with dockerfile

For bitbucket repository, generate App Password (Bitbucket settings -> Access Management -> App Password, see the image) with read access to the repo and project.

bitbucket user menu

Then the command that you should use is:

git clone https://username:[email protected]/reponame/projectname.git

cor shows only NA or 1 for correlations - Why?

The NA can actually be due to 2 reasons. One is that there is a NA in your data. Another one is due to there being one of the values being constant. This results in standard deviation being equal to zero and hence the cor function returns NA.

How to layout multiple panels on a jFrame? (java)

You'll want to use a number of layout managers to help you achieve the basic results you want.

Check out A Visual Guide to Layout Managers for a comparision.

You could use a GridBagLayout but that's one of the most complex (and powerful) layout managers available in the JDK.

You could use a series of compound layout managers instead.

I'd place the graphics component and text area on a single JPanel, using a BorderLayout, with the graphics component in the CENTER and the text area in the SOUTH position.

I'd place the text field and button on a separate JPanel using a GridBagLayout (because it's the simplest I can think of to achieve the over result you want)

I'd place these two panels onto a third, master, panel, using a BorderLayout, with the first panel in the CENTER and the second at the SOUTH position.

But that's me

How might I find the largest number contained in a JavaScript array?

To find the largest number in an array you just need to use Math.max(...arrayName);. It works like this:

let myArr = [1, 2, 3, 4, 5, 6];
console.log(Math.max(...myArr));

To learn more about Math.max: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

Iterating through directories with Python

The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print statement you can see that each file is found:

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print os.path.join(subdir, file)

If you still get errors when running the above, please provide the error message.


Updated for Python3

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print(os.path.join(subdir, file))

Generics/templates in python?

Fortunately there has been some efforts for the generic programming in python . There is a library : generic

Here is the documentation for it: http://generic.readthedocs.org/en/latest/

It hasn't progress over years , but you can have a rough idea how to use & make your own library.

Cheers

How to select data where a field has a min value in MySQL?

this will give you result that has the minimum price on all records.

SELECT *
FROM pieces
WHERE price =  ( SELECT MIN(price) FROM pieces )

How do I instantiate a Queue object in java?

Queue in Java is defined as an interface and many ready-to-use implementation is present as part of JDK release. Here are some: LinkedList, Priority Queue, ArrayBlockingQueue, ConcurrentLinkedQueue, Linked Transfer Queue, Synchronous Queue etc.

SO You can create any of these class and hold it as Queue reference. for example

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {

 public static void main (String[] args) {
  Queue que = new LinkedList();
  que.add("first");
  que.offer("second");
  que.offer("third");
  System.out.println("Queue Print:: " + que);
  
  String head = que.element();
  System.out.println("Head element:: " + head);
  
  String element1 = que.poll();
  System.out.println("Removed Element:: " + element1);
  
  System.out.println("Queue Print after poll:: " + que);
  String element2 = que.remove();
  System.out.println("Removed Element:: " + element2);
  
  System.out.println("Queue Print after remove:: " + que);  
 }
}

You can also implement your own custom Queue implementing Queue interface.

How to write to an existing excel file without overwriting data (using pandas)?

Pandas docs says it uses openpyxl for xlsx files. Quick look through the code in ExcelWriter gives a clue that something like this might work out:

import pandas
from openpyxl import load_workbook

book = load_workbook('Masterfile.xlsx')
writer = pandas.ExcelWriter('Masterfile.xlsx', engine='openpyxl') 
writer.book = book

## ExcelWriter for some reason uses writer.sheets to access the sheet.
## If you leave it empty it will not know that sheet Main is already there
## and will create a new sheet.

writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

data_filtered.to_excel(writer, "Main", cols=['Diff1', 'Diff2'])

writer.save()

How to stop PHP code execution?

You could try to kill the PHP process:

exec('kill -9 ' . getmypid());

Where can I find a list of Mac virtual key codes?

The more canonical reference is in <HIToolbox/Events.h>:

/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h

In newer Versions of MacOS the "Events.h" moved to here:

/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h

How do you determine what technology a website is built on?

I use 1 plug in for Firefox that gives me the IP and country for the hosting website and it's Web Server name called Domain Details, and for javascript framework I use WTFramework

I still need to wonder what script it was written on, but it is a start :)

Hope it helps.

P.S. the output will be something like this:

alt text http://img88.imageshack.us/img88/2505/200812282328ha0.png

MySQL Error: : 'Access denied for user 'root'@'localhost'

Okay, I know this is an old thread but if you reached this page via Google like I did and none of the above solutions worked, what turned out to be the error was 100% foolishness on my end. I didn't connect to the server. Once connected everything was smooth sailing.

In case it helps to know my setup, I'm using Sequel Pro and trying to connect to it with Node using the NPM package, mysql. I didn't think I needed to actually connect (other than run Sequel Pro) because I was doing that from my app already.

enter image description here

How to Create Multiple Where Clause Query Using Laravel Eloquent?

Use This

$users = DB::table('users')
                    ->where('votes', '>', 100)
                    ->orWhere('name', 'John')
                    ->get();

How to actually search all files in Visual Studio

Press Ctrl+,

Then you will see a docked window under name of "Go to all"

This a picture of the "Go to all" in my IDE

Picture

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

Adding a leading zero to some values in column in MySQL

Change the field back to numeric and use ZEROFILL to keep the zeros

or

use LPAD()

SELECT LPAD('1234567', 8, '0');

How to see the changes between two commits without commits in-between?

What about this:

git diff abcdef 123456 | less

It's handy to just pipe it to less if you want to compare many different diffs on the fly.

Pandas: Appending a row to a dataframe and specify its index label

I shall refer to the same sample of data as posted in the question:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
print('The original data frame is: \n{}'.format(df))

Running this code will give you

The original data frame is:

          A         B         C         D
0  0.494824 -0.328480  0.818117  0.100290
1  0.239037  0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856  0.359811 -0.345560
3 -0.070814 -0.394711  0.081697 -1.178845
4 -1.638063  1.498027 -0.609325  0.882594
5 -0.510217  0.500475  1.039466  0.187076
6  1.116529  0.912380  0.869323  0.119459
7 -1.046507  0.507299 -0.373432 -1.024795

Now you wish to append a new row to this data frame, which doesn't need to be copy of any other row in the data frame. @Alon suggested an interesting approach to use df.loc to append a new row with different index. The issue, however, with this approach is if there is already a row present at that index, it will be overwritten by new values. This is typically the case for datasets when row index is not unique, like store ID in transaction datasets. So a more general solution to your question is to create the row, transform the new row data into a pandas series, name it to the index you want to have and then append it to the data frame. Don't forget to overwrite the original data frame with the one with appended row. The reason is df.append returns a view of the dataframe and does not modify its contents. Following is the code:

row = pd.Series({'A':10,'B':20,'C':30,'D':40},name=3)
df = df.append(row)
print('The new data frame is: \n{}'.format(df))

Following would be the new output:

The new data frame is:

           A          B          C          D
0   0.494824  -0.328480   0.818117   0.100290
1   0.239037   0.954912  -0.186825  -0.651935
2  -1.818285  -0.158856   0.359811  -0.345560
3  -0.070814  -0.394711   0.081697  -1.178845
4  -1.638063   1.498027  -0.609325   0.882594
5  -0.510217   0.500475   1.039466   0.187076
6   1.116529   0.912380   0.869323   0.119459
7  -1.046507   0.507299  -0.373432  -1.024795
3  10.000000  20.000000  30.000000  40.000000

How to install PHP mbstring on CentOS 6.2

As yum install php-mbstring then httpd -k restart didn't do it for me, I think these options should be compiled, as documented here:

Now, configure and build PHP. This is where you customize PHP with various options, like which extensions will be enabled. Run ./configure --help for a list of available options. In our example we'll do a simple configure with Apache 2 and MySQL support.

If you built Apache from source, as described above, the below example will match your path for apxs, but if you installed Apache some other way, you'll need to adjust the path to apxs accordingly. Note that some distros may rename apxs to apxs2.

cd ../php-NN
./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql --enable-mbstring
make
make install

If you decide to change your configure options after installation, you'll need to re-run the configure, make, and make install steps. You only need to restart apache for the new module to take effect. A recompile of Apache is not needed.

Note that unless told otherwise, 'make install' will also install PEAR, various PHP tools such as phpize, install the PHP CLI, and more.

Though this page says it's optional:

--enable-mbstring Allows multibyte character string support. This is optional, as slower custom code will be used if not available.

Parallel foreach with asynchronous lambda

You can use the ParallelForEachAsync extension method from AsyncEnumerator NuGet Package:

using Dasync.Collections;

var bag = new ConcurrentBag<object>();
await myCollection.ParallelForEachAsync(async item =>
{
  // some pre stuff
  var response = await GetData(item);
  bag.Add(response);
  // some post stuff
}, maxDegreeOfParallelism: 10);
var count = bag.Count;

Why can't I display a pound (£) symbol in HTML?

This works in all chrome, IE, Firefox.

In Database > table > field type .for example set the symbol column TO varchar(2) utf8_bin php code:

$symbol = '£';
echo mb_convert_encoding($symbol, 'UTF-8', 'HTML-ENTITIES');
or 
html_entity_decode($symbol, ENT_NOQUOTES, 'UTF-8');

And also make sure set the HTML OR XML encoding to encoding="UTF-8"

Note: You should make sure that database, document type and php code all have a same encoding

How ever the better solution would be using &pound;

Split varchar into separate columns in Oracle

Simple way is to convert into column

SELECT COLUMN_VALUE FROM TABLE (SPLIT ('19869,19572,19223,18898,10155,'))

CREATE TYPE split_tbl as TABLE OF VARCHAR2(32767);

CREATE OR REPLACE FUNCTION split (p_list VARCHAR2, p_del VARCHAR2 := ',')
   RETURN split_tbl
   PIPELINED IS
   l_idx PLS_INTEGER;
   l_list VARCHAR2 (32767) := p_list;
   l_value VARCHAR2 (32767);
BEGIN
   LOOP
      l_idx := INSTR (l_list, p_del);

      IF l_idx > 0 THEN
         PIPE ROW (SUBSTR (l_list, 1, l_idx - 1));
         l_list := SUBSTR (l_list, l_idx + LENGTH (p_del));
      ELSE
         PIPE ROW (l_list);
         EXIT;
      END IF;
   END LOOP;

   RETURN;
END split;

Easy way to password-protect php page

</html>
<head>
  <title>Nick Benvenuti</title>
  <link rel="icon" href="img/xicon.jpg" type="image/x-icon/">
  <link rel="stylesheet" href="CSS/main.css">
  <link rel="stylesheet" href="CSS/normalize.css">
  <script src="JS/jquery-1.12.0.min.js" type="text/javascript"></script>
</head>
<body>
<div id="phplogger">
  <script type="text/javascript">
  function tester() {
  window.location.href="admin.php";
  }
  function phpshower() {
  document.getElementById("phplogger").classList.toggle('shower');
  document.getElementById("phplogger").classList.remove('hider');
  }
  function phphider() {
  document.getElementById("phplogger").classList.toggle('hider');
  document.getElementById("phplogger").classList.remove('shower');
  }
</script>
<?php 
//if "login" variable is filled out, send email
  if (isset($_REQUEST['login']))  {

  //Login info
  $passbox = $_REQUEST['login'];
  $password = 'blahblahyoudontneedtoknowmypassword';

  //Login
  if($passbox == $password) {

  //Login response
  echo "<script text/javascript> phphider(); </script>";
  }
 }
?>
<div align="center" margin-top="50px">
<h1>Administrative Access Only</h1>
<h2>Log In:</h2>
 <form method="post">
  Password: <input name="login" type="text" /><br />
  <input type="submit" value="Login" id="submit-button" />
  </form>
</div>
</div>
<div align="center">
<p>Welcome to the developers and admins page!</p>
</div>
</body>
</html>

Basically what I did here is make a page all in one php file where when you enter the password if its right it will hide the password screen and bring the stuff that protected forward. and then heres the css which is a crucial part because it makes the classes that hide and show the different parts of the page.

  /*PHP CONTENT STARTS HERE*/
  .hider {
  visibility:hidden;
  display:none;
  }

  .shower {
  visibility:visible;
  }

  #phplogger {
  background-color:#333;
  color:blue;
  position:absolute;
  height:100%;
  width:100%;
  margin:0;
  top:0;
  bottom:0;
  }
  /*PHP CONTENT ENDS HERE*/

Suppress console output in PowerShell

Try redirecting the output like this:

$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose >$null 2>&1

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

I'm new to this topic, so I can't say a whole lot, but BLAS is pretty much the standard in scientific computing. BLAS is actually an API standard, which has many implementations. I'm honestly not sure which implementations are most popular or why.

If you want to also be able to do common linear algebra operations (solving systems, least squares regression, decomposition, etc.) look into LAPACK.

"unrecognized selector sent to instance" error in Objective-C

I got this issue trying some old format code in Swift3,

let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.respond))

changing the action:"respond:" to action: #selector(self.respond) fixed the issue for me.

AngularJS $resource RESTful example

$resource was meant to retrieve data from an endpoint, manipulate it and send it back. You've got some of that in there, but you're not really leveraging it for what it was made to do.

It's fine to have custom methods on your resource, but you don't want to miss out on the cool features it comes with OOTB.

EDIT: I don't think I explained this well enough originally, but $resource does some funky stuff with returns. Todo.get() and Todo.query() both return the resource object, and pass it into the callback for when the get completes. It does some fancy stuff with promises behind the scenes that mean you can call $save() before the get() callback actually fires, and it will wait. It's probably best just to deal with your resource inside of a promise then() or the callback method.

Standard use

var Todo = $resource('/api/1/todo/:id');

//create a todo
var todo1 = new Todo();
todo1.foo = 'bar';
todo1.something = 123;
todo1.$save();

//get and update a todo
var todo2 = Todo.get({id: 123});
todo2.foo += '!';
todo2.$save();

//which is basically the same as...
Todo.get({id: 123}, function(todo) {
   todo.foo += '!';
   todo.$save();
});

//get a list of todos
Todo.query(function(todos) {
  //do something with todos
  angular.forEach(todos, function(todo) {
     todo.foo += ' something';
     todo.$save();
  });
});

//delete a todo
Todo.$delete({id: 123});

Likewise, in the case of what you posted in the OP, you could get a resource object and then call any of your custom functions on it (theoretically):

var something = src.GetTodo({id: 123});
something.foo = 'hi there';
something.UpdateTodo();

I'd experiment with the OOTB implementation before I went and invented my own however. And if you find you're not using any of the default features of $resource, you should probably just be using $http on it's own.

Update: Angular 1.2 and Promises

As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.

To leverage promises with $resource, you need to use the $promise property on the returned value.

Example using promises

var Todo = $resource('/api/1/todo/:id');

Todo.get({id: 123}).$promise.then(function(todo) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Todo.query().$promise.then(function(todos) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Just keep in mind that the $promise property is a property on the same values it was returning above. So you can get weird:

These are equivalent

var todo = Todo.get({id: 123}, function() {
   $scope.todo = todo;
});

Todo.get({id: 123}, function(todo) {
   $scope.todo = todo;
});

Todo.get({id: 123}).$promise.then(function(todo) {
   $scope.todo = todo;
});

var todo = Todo.get({id: 123});
todo.$promise.then(function() {
   $scope.todo = todo;
});

How to convert all tables from MyISAM into InnoDB?

In the scripts below, replace <username>, <password> and <schema> with your specific data.

To show the statements that you can copy-paste into a mysql client session type the following:

echo 'SHOW TABLES;' \
 | mysql -u <username> --password=<password> -D <schema> \
 | awk '!/^Tables_in_/ {print "ALTER TABLE `"$0"` ENGINE = InnoDB;"}' \
 | column -t \

To simply execute the change, use this:

echo 'SHOW TABLES;' \
 | mysql -u <username> --password=<password> -D <schema> \
 | awk '!/^Tables_in_/ {print "ALTER TABLE `"$0"` ENGINE = InnoDB;"}' \
 | column -t \
 | mysql -u <username> --password=<password> -D <schema>

CREDIT: This is a variation of what was outlined in this article.

Setting POST variable without using form

Yes, simply set it to another value:

$_POST['text'] = 'another value';

This will override the previous value corresponding to text key of the array. The $_POST is superglobal associative array and you can change the values like a normal PHP array.

Caution: This change is only visible within the same PHP execution scope. Once the execution is complete and the page has loaded, the $_POST array is cleared. A new form submission will generate a new $_POST array.

If you want to persist the value across form submissions, you will need to put it in the form as an input tag's value attribute or retrieve it from a data store.

Using an HTTP PROXY - Python

You can do it even without the HTTP_PROXY environment variable. Try this sample:

import urllib2

proxy_support = urllib2.ProxyHandler({"http":"http://61.233.25.166:80"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)

html = urllib2.urlopen("http://www.google.com").read()
print html

In your case it really seems that the proxy server is refusing the connection.


Something more to try:

import urllib2

#proxy = "61.233.25.166:80"
proxy = "YOUR_PROXY_GOES_HERE"

proxies = {"http":"http://%s" % proxy}
url = "http://www.google.com/search?q=test"
headers={'User-agent' : 'Mozilla/5.0'}

proxy_support = urllib2.ProxyHandler(proxies)
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1))
urllib2.install_opener(opener)

req = urllib2.Request(url, None, headers)
html = urllib2.urlopen(req).read()
print html

Edit 2014: This seems to be a popular question / answer. However today I would use third party requests module instead.

For one request just do:

import requests

r = requests.get("http://www.google.com", 
                 proxies={"http": "http://61.233.25.166:80"})
print(r.text)

For multiple requests use Session object so you do not have to add proxies parameter in all your requests:

import requests

s = requests.Session()
s.proxies = {"http": "http://61.233.25.166:80"}

r = s.get("http://www.google.com")
print(r.text)

combining two string variables

you need to take out the quotes:

soda = a + b

(You want to refer to the variables a and b, not the strings "a" and "b")

In Python, how do I split a string and keep the separators?

  1. replace all seperator: (\W) with seperator + new_seperator: (\W;)

  2. split by the new_seperator: (;)

def split_and_keep(seperator, s):
  return re.split(';', re.sub(seperator, lambda match: match.group() + ';', s))

print('\W', 'foo/bar spam\neggs')

getting the screen density programmatically in android?

This also works:

 getResources().getDisplayMetrics().density;

This will give you:

0.75 - ldpi

1.0 - mdpi

1.5 - hdpi

2.0 - xhdpi

3.0 - xxhdpi

4.0 - xxxhdpi

enter image description here

ref: density

enter image description here

ref 2

Why is the Java main method static?

From java.sun.com (there's more information on the site) :

The main method is static to give the Java VM interpreter a way to start the class without creating an instance of the control class first. Instances of the control class are created in the main method after the program starts.

My understanding has always been simply that the main method, like any static method, can be called without creating an instance of the associated class, allowing it to run before anything else in the program. If it weren't static, you would have to instantiate an object before calling it-- which creates a 'chicken and egg' problem, since the main method is generally what you use to instantiate objects at the beginning of the program.

Throughput and bandwidth difference?

Imagine it this way: a mail truck can carry 5000 sheets of paper each trip so It's bandwidth is 5000. Does that mean it can carry 5000 letter each trip? Well, theoretically, if each letter didn't need an envelope telling us where it was coming from, going too, and possessing proof of payment (Envelope = Protocol Headers and Footers). But they do, so each letter (1 sheet of paper) requires an envelope (= to about 1 sheet of paper) to get it to it's destination. So in the worst case scenario (all envelopes only have one page letters), the truck would carry only 2500 sheets Throughput (Data that we want to send from source>destination, THE LETTERS) and would have 2500 sheets Overhead (Headers/Footer that we need to get the letter from source>destination but that the recipient won't be reading, THE ENVELOPES). The Throughput, 2500 Letters + the Overhead, 2500 Envelopes = Bandwidth, 5000 sheets of paper. Bigger letters (4 pages) still only require 1 envelope so that would move the ratio of Throughput to Overhead higher (i.e. Jumbo Frames) and make it more efficient, so if all the letters were 4 page letters throughput would change to 4000, and overhead would reduce to 1000, together equaling the 5000 Bandwidth of the truck.

Excel formula is only showing the formula rather than the value within the cell in Office 2010

Check the formatting (right click on cell, Format Cells). Under tab "Number" the category should be "General". If, for instance, it's "Text" anything typed in would be treated as a string rather than a formula to be interpreted.

How to find substring inside a string (or how to grep a variable)?

You can also compare with wildcards:

if [[ "$LIST" == *"$SOURCE"* ]]

How to allow <input type="file"> to accept only image files?

Use the accept attribute of the input tag. So to accept only PNG's, JPEG's and GIF's you can use the following code:

_x000D_
_x000D_
<input type="file" name="myImage" accept="image/x-png,image/gif,image/jpeg" />
_x000D_
_x000D_
_x000D_

Or simply:

_x000D_
_x000D_
<input type="file" name="myImage" accept="image/*" />
_x000D_
_x000D_
_x000D_

Note that this only provides a hint to the browser as to what file-types to display to the user, but this can be easily circumvented, so you should always validate the uploaded file on the server also.

It should work in IE 10+, Chrome, Firefox, Safari 6+, Opera 15+, but support is very sketchy on mobiles (as of 2015) and by some reports, this may actually prevent some mobile browsers from uploading anything at all, so be sure to test your target platforms well.

For detailed browser support, see http://caniuse.com/#feat=input-file-accept

Force git stash to overwrite added files

git stash show -p | git apply

and then git stash drop if you want to drop the stashed items.

How to extend available properties of User.Identity

I also had added on or extended additional columns into my AspNetUsers table. When I wanted to simply view this data I found many examples like the code above with "Extensions" etc... This really amazed me that you had to write all those lines of code just to get a couple values from the current users.

It turns out that you can query the AspNetUsers table like any other table:

 ApplicationDbContext db = new ApplicationDbContext();
 var user = db.Users.Where(x => x.UserName == User.Identity.Name).FirstOrDefault();

How to use a keypress event in AngularJS?

You need to add a directive, like this:

Javascript:

app.directive('myEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.myEnter);
                });

                event.preventDefault();
            }
        });
    };
});

HTML:

<div ng-app="" ng-controller="MainCtrl">
    <input type="text" my-enter="doSomething()">    
</div>

You must add a reference to assembly 'netstandard, Version=2.0.0.0

After upgrading from 4.6.1 framework to 4.7.2 we started getting this error:

"The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'." and ultimately the solution was to add the "netstandard" assembly reference mentioned above:

<compilation debug="true" targetFramework="4.7.1" >
    <assemblies>
      <add assembly="netstandard, Version=2.0.0.0, Culture=neutral, 
            PublicKeyToken=cc7b13ffcd2ddd51"/>
    </assemblies>
  </compilation>

How to validate a credit card number

A credit card number is not a bunch of random numbers. There is a formula for checking if it is correct.

After a quick Google search I found this JavaScript which will check a credit card number to be valid.

http://javascript.internet.com/forms/credit-card-number-validation.html

URL Broken: Internet archive: http://web.archive.org/web/20100129174150/http://javascript.internet.com/forms/credit-card-number-validation.html?

<!-- TWO STEPS TO INSTALL CREDIT CARD NUMBER VALIDATION:

  1.  Copy the code into the HEAD of your HTML document
  2.  Add the last code into the BODY of your HTML document  -->

<!-- STEP ONE: Paste this code into the HEAD of your HTML document  -->

<HEAD>

  <script type="text/javascript">
    <!--
    /* This script and many more are available free online at
    The JavaScript Source!! http://javascript.internet.com
    Created by: David Leppek :: https://www.azcode.com/Mod10

    Basically, the algorithm takes each digit, from right to left and muliplies each second
    digit by two. If the multiple is two-digits long (i.e.: 6 * 2 = 12) the two digits of
    the multiple are then added together for a new number (1 + 2 = 3). You then add up the
    string of numbers, both unaltered and new values and get a total sum. This sum is then
    divided by 10 and the remainder should be zero if it is a valid credit card. Hense the
    name Mod 10 or Modulus 10.
    */
    function Mod10(ccNumb) {  // v2.0
      var valid = "0123456789"  // Valid digits in a credit card number
      var len = ccNumb.length;  // The length of the submitted cc number
      var iCCN = parseInt(ccNumb);  // Integer of ccNumb
      var sCCN = ccNumb.toString();  // String of ccNumb
      sCCN = sCCN.replace (/^\s+|\s+$/g,'');  // Strip spaces
      var iTotal = 0;  // Integer total set at zero
      var bNum = true;  // By default assume it is a number
      var bResult = false;  // By default assume it is NOT a valid cc
      var temp;  // Temporary variable for parsing string
      var calc;  // Used for calculation of each digit

      // Determine if the ccNumb is in fact all numbers
      for (var j=0; j<len; j++) {
        temp = "" + sCCN.substring(j, j+1);
        if (valid.indexOf(temp) == "-1"){
          bNum = false;
        }
      }

      // If it is NOT a number, you can either alert to the fact, or just pass a failure
      if (!bNum) {
        /* alert("Not a Number"); */
        bResult = false;
      }

      // Determine if it is the proper length
      if ((len == 0) && (bResult)) {  // Nothing, the field is blank AND passed above # check
        bResult = false;
      }
      else { // ccNumb is a number and the proper length - let's
             //  see if it is a valid card number

        if (len >= 15) {  // 15 or 16 for Amex or V/MC
          for (var i=len;i>0;i--) {  // LOOP through the digits of the card
            calc = parseInt(iCCN) % 10;  // Right most digit
            calc = parseInt(calc);  // Assure it is an integer
            iTotal += calc;  // Running total of the card number as we loop - Do Nothing to first digit
            i--;  // Decrement the count - move to the next digit in the card
            iCCN = iCCN / 10;                               // Subtracts right most digit from ccNumb
            calc = parseInt(iCCN) % 10;     // NEXT right most digit
            calc = calc *2;                                 // multiply the digit by two

            // Instead of some screwy method of converting 16 to a string
            // and then parsing 1 and 6 and then adding them to make 7,
            // I use a simple switch statement to change the value
            // of calc2 to 7 if 16 is the multiple.
            switch(calc) {
              case 10: calc = 1; break;  // 5*2=10 & 1+0 = 1
              case 12: calc = 3; break;  // 6*2=12 & 1+2 = 3
              case 14: calc = 5; break;  // 7*2=14 & 1+4 = 5
              case 16: calc = 7; break;  // 8*2=16 & 1+6 = 7
              case 18: calc = 9; break;  // 9*2=18 & 1+8 = 9
              default: calc = calc;      // 4*2= 8 &   8 = 8  - the same for all lower numbers
            }
            iCCN = iCCN / 10;  // Subtracts right most digit from ccNum
            iTotal += calc;  // Running total of the card number as we loop
          } // END OF LOOP

          if ((iTotal%10)==0){  // Check to see if the sum Mod 10 is zero
            bResult = true;  // This IS (or could be) a valid credit card number.
          }
          else {
            bResult = false;  // This could NOT be a valid credit card number
          }
        }
      }

      // Change alert to on-page display or other indication as needed.
      if (bResult) {
        alert("This IS a valid Credit Card Number!");
      }
      if (!bResult) {
        alert("This is NOT a valid Credit Card Number!");
      }
      return bResult; // Return the results
    }
    // -->
  </script>

</HEAD>


<!-- STEP TWO: Copy this code into the BODY of your HTML document  -->

<BODY>

<div align="center">
  <form name="Form1">
    <table width="50%" border="0" cellspacing="0" cellpadding="5">
      <tr>
        <td width="50%" align="right">Credit Card Number:   </td>
        <td width="50%">
          <input name="CreditCard" type="text" value="4012888888881881" size="18" maxlength="16" style="border: 1px solid #000098; padding: 3px;">
        </td>
      </tr>
      <tr>
        <td colspan="2" align="center">
          <input type="button" name="Button" style="color: #fff; background: #000098; font-weight:bold; border: solid 1px #000;" value="TEST CARD NUMBER" onClick="return Mod10(document.Form1.CreditCard.value);">
        </td>
      </tr>
    </table>
  </form>
</div>

<p><center>
  <font face="arial, helvetica" size"-2">Free JavaScripts provided<br>
  by <a href="http://javascriptsource.com">The JavaScript Source</a></font>
</center><p>

<!-- Script Size:  4.97 KB -->

css3 transition animation on load?

CSS only with a delay of 3s

a few points to take here:

  • multiple animations in one call
  • we create a wait animation that just delays the actual one (the second one in our case).

Code:

header {
    animation: 3s ease-out 0s 1 wait, 0.21s ease-out 3s 1 slideInFromBottom;
}

@keyframes wait {
    from { transform: translateY(20px); }
    to { transform: translateY(20px); }
}

@keyframes slideInFromBottom {
  from { transform: translateY(20px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

How to find day of week in php in a specific timezone

Standard letter-based representations of date parts are great, except the fact they're not so intuitive. The much more convenient way is to identify basic abstractions and a number of specific implementations. Besides, with this approach, you can benefir from autocompletion.

Since we're talking about datetimes here, it seems plausible that the basic abstraction is ISO8601DateTime. One of the specific implementations is current datetime, the one you need when a makes a request to your backend, hence Now() class. Second one which is of some use for you is a datetime adjusted to some timezone. Not surprisingly, it's called AdjustedAccordingToTimeZone. And finally, you need a day of the week in a passed datetime's timezone: there is a LocalDayOfWeek class for that. So the code looks like the following:

(new LocalDayOfWeek(
    new AdjustedAccordingToTimeZone(
        new Now(),
        new TimeZoneFromString($_POST['timezone'])
    )
))
    ->value();

For more about this approach, take a look here.

Find UNC path of a network drive?

$CurrentFolder = "H:\Documents"
$Query = "Select * from Win32_NetworkConnection where LocalName = '" + $CurrentFolder.Substring( 0, 2 ) + "'"
( Get-WmiObject -Query $Query ).RemoteName

OR

$CurrentFolder = "H:\Documents"
$Tst = $CurrentFolder.Substring( 0, 2 )
( Get-WmiObject -Query "Select * from Win32_NetworkConnection where LocalName = '$Tst'" ).RemoteName

downloading all the files in a directory with cURL

Here is how I did to download quickly with cURL (I'm not sure how many files it can download though) :

setlocal EnableDelayedExpansion

cd where\to\download

set STR=
for /f "skip=2 delims=" %%F in ('P:\curl -l -u user:password ftp://ftp.example.com/directory/anotherone/') do set STR=-O "ftp://ftp.example.com/directory/anotherone/%%F" !STR!
path\to\curl.exe -v -u user:password !STR!

Why skip=2 ? To get ride of . and ..

Why delims= ? To support names with spaces

Not showing placeholder for input type="date" field

Found a better way to solve your problem. I think this will help you. when focused out, the box will change type into text so it will show your placeholder. when focused in, its type changes into date so the calendar view will be shown.

<input placeholder="Date" class="textbox-n" type="text" onfocusin="(this.type='date')" onfocusout="(this.type='text')"  id="date"> 

How to resolve "Server Error in '/' Application" error?

You may get this error when trying to browse an ASP.NET application.

The debug information shows that "This error can be caused by a virtual directory not being configured as an application in IIS."

However, this error occurs primarily out of two scenarios.

  1. When you create an new web application using Visual Studio .NET, it automatically creates the virtual directory and configures it as an application. However, if you manually create the virtual directory and it is not configured as an application, then you will not be able to browse the application and may get the above error. The debug information you get as mentioned above, is applicable to this scenario.

To resolve it, right click on the virtual directory - select properties and then click on "Create" next to the "Application" Label and the text box. It will automatically create the "application" using the virtual directory's name. Now the application can be accessed.

  1. When you have sub-directories in your application, you can have web.config file for the sub-directory. However, there are certain properties which cannot be set in the web.config of the sub-directory such as authentication, session state (you may see that the error message shows the line number where the authentication or session state is declared in the web.config of the sub-directory). The reason is, these settings cannot be overridden at the sub-directory level unless the sub-directory is also configured as an application (as mentioned in the above point).

Mostly, we have the practice of adding web.config in the sub-directory if we want to protect access to the sub-directory files (say, the directory is admin and we wish to protect the admin pages from unauthorized users).

Convert a file path to Uri in Android

Normal answer for this question if you really want to get something like content//media/external/video/media/18576 (e.g. for your video mp4 absolute path) and not just file///storage/emulated/0/DCIM/Camera/20141219_133139.mp4:

MediaScannerConnection.scanFile(this,
          new String[] { file.getAbsolutePath() }, null,
          new MediaScannerConnection.OnScanCompletedListener() {
      public void onScanCompleted(String path, Uri uri) {
          Log.i("onScanCompleted", uri.getPath());
      }
 });

Accepted answer is wrong (cause it will not return content//media/external/video/media/*)

Uri.fromFile(file).toString() only returns something like file///storage/emulated/0/* which is a simple absolute path of a file on the sdcard but with file// prefix (scheme)

You can also get content uri using MediaStore database of Android

TEST (what returns Uri.fromFile and what returns MediaScannerConnection):

File videoFile = new File("/storage/emulated/0/video.mp4");

Log.i(TAG, Uri.fromFile(videoFile).toString());

MediaScannerConnection.scanFile(this, new String[] { videoFile.getAbsolutePath() }, null,
        (path, uri) -> Log.i(TAG, uri.toString()));

Output:

I/Test: file:///storage/emulated/0/video.mp4

I/Test: content://media/external/video/media/268927

Referring to a Column Alias in a WHERE Clause

The most effective way to do it without repeating your code is use of HAVING instead of WHERE

SELECT logcount, logUserID, maxlogtm
   , DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
HAVING daysdiff > 120

How to select the first, second, or third element with a given class name?

In the future (perhaps) you will be able to use :nth-child(an+b of s)

Actually, browser support for the “of” filter is very limited. Only Safari seems to support the syntax.

https://css-tricks.com/almanac/selectors/n/nth-child/

How to display svg icons(.svg files) in UI using React Component?

If you use create-react-app 2.0 you can now do do it like this:

import { ReactComponent as YourSvg } from './your-svg.svg';

And then use it just like you would normally use a component:

const App = () => (
 <div>
   <YourSvg />
 </div>
);

No String-argument constructor/factory method to deserialize from String value ('')

I found a different way to handle this error. (the variables is according to the original question)

   JsonNode parsedNodes = mapper.readValue(jsonMessage , JsonNode.class);
        Response response = xmlMapper.enable(ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,ACCEPT_SINGLE_VALUE_AS_ARRAY )
                .disable(FAIL_ON_UNKNOWN_PROPERTIES, FAIL_ON_IGNORED_PROPERTIES)
                .convertValue(parsedNodes, Response.class);

Enable the display of line numbers in Visual Studio

Visual Studio has line numbering:

Tools -> Options -> Text Editor -> All Languages -> check the "Line numbers" checkbox.

sklearn plot confusion matrix with labels

To add to @akilat90's update about sklearn.metrics.plot_confusion_matrix:

You can use the ConfusionMatrixDisplay class within sklearn.metrics directly and bypass the need to pass a classifier to plot_confusion_matrix. It also has the display_labels argument, which allows you to specify the labels displayed in the plot as desired.

The constructor for ConfusionMatrixDisplay doesn't provide a way to do much additional customization of the plot, but you can access the matplotlib axes obect via the ax_ attribute after calling its plot() method. I've added a second example showing this.

I found it annoying to have to rerun a classifier over a large amount of data just to produce the plot with plot_confusion_matrix. I am producing other plots off the predicted data, so I don't want to waste my time re-predicting every time. This was an easy solution to that problem as well.

Example:

from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay

cm = confusion_matrix(y_true, y_preds, normalize='all')
cmd = ConfusionMatrixDisplay(cm, display_labels=['business','health'])
cmd.plot()

confusion matrix example 1

Example using ax_:

cm = confusion_matrix(y_true, y_preds, normalize='all')
cmd = ConfusionMatrixDisplay(cm, display_labels=['business','health'])
cmd.plot()
cmd.ax_.set(xlabel='Predicted', ylabel='True')

confusion matrix example

How do I remove repeated elements from ArrayList?

In Java 8:

List<String> deduped = list.stream().distinct().collect(Collectors.toList());

Please note that the hashCode-equals contract for list members should be respected for the filtering to work properly.

Can someone explain __all__ in Python?

Linked to, but not explicitly mentioned here, is exactly when __all__ is used. It is a list of strings defining what symbols in a module will be exported when from <module> import * is used on the module.

For example, the following code in a foo.py explicitly exports the symbols bar and baz:

__all__ = ['bar', 'baz']

waz = 5
bar = 10
def baz(): return 'baz'

These symbols can then be imported like so:

from foo import *

print(bar)
print(baz)

# The following will trigger an exception, as "waz" is not exported by the module
print(waz)

If the __all__ above is commented out, this code will then execute to completion, as the default behaviour of import * is to import all symbols that do not begin with an underscore, from the given namespace.

Reference: https://docs.python.org/tutorial/modules.html#importing-from-a-package

NOTE: __all__ affects the from <module> import * behavior only. Members that are not mentioned in __all__ are still accessible from outside the module and can be imported with from <module> import <member>.

postgresql - replace all instances of a string within text field

You can use the replace function

UPDATE your_table SET field = REPLACE(your_field, 'cat','dog')

The function definition is as follows (got from here):

replace(string text, from text, to text)

and returns the modified text. You can also check out this sql fiddle.

rawQuery(query, selectionArgs)

if your SQL query is this

SELECT id,name,roll FROM student WHERE name='Amit' AND roll='7'

then rawQuery will be

String query="SELECT id, name, roll FROM student WHERE name = ? AND roll = ?";
String[] selectionArgs = {"Amit","7"} 
db.rawQuery(query, selectionArgs);

How to capture a backspace on the onkeydown event

not sure if it works outside of firefox:

callback (event){
  if (event.keyCode === event.DOM_VK_BACK_SPACE || event.keyCode === event.DOM_VK_DELETE)
    // do something
  }
}

if not, replace event.DOM_VK_BACK_SPACE with 8 and event.DOM_VK_DELETE with 46 or define them as constant (for better readability)

How to dynamically change a web page's title?

The code is
document.title = 'test'

Drawing circles with System.Drawing

With this code you can easily draw a circle... C# is great and easy my friend

public partial class Form1 : Form
{


public Form1()
    {
        InitializeComponent();
    }

  private void button1_Click(object sender, EventArgs e)
    {
        Graphics myGraphics = base.CreateGraphics();
        Pen myPen = new Pen(Color.Red);
        SolidBrush mySolidBrush = new SolidBrush(Color.Red);
        myGraphics.DrawEllipse(myPen, 50, 50, 150, 150);
    }
 }

How to adjust gutter in Bootstrap 3 grid system?

You could create a CSS class for this and apply it to your columns. Since the gutter (spacing between columns) is controlled by padding in Bootstrap 3, adjust the padding accordingly:

.col {
  padding-right:7px;
  padding-left:7px;
}

Demo: http://bootply.com/93473

EDIT If you only want the spacing between columns you can select all cols except first and last like this..

.col:not(:first-child,:last-child) {
  padding-right:7px;
  padding-left:7px;
}

Updated Bootply

For Bootstrap 4 see: Remove gutter space for a specific div only

Laravel blank white screen

in my case, the BLANK WHITE SCREEN issue was as simple as a typo or wrong character on the env file. I was implementing socialite, so when I was setting up the .env credentials for Google+ like this:

G+_CLIENT_ID = Your G+ Client ID
G+_CLIENT_SECRET = Your G+ Client secret
G+_REDIRECT = 'http://localhost:8000/callback/google'

But, the .env file can't use the '+' sign, so I have to make this correction:

GOOGLE_CLIENT_ID = Your G+ Client ID
GOOGLE_CLIENT_SECRET = Your G+ Client secret
GOOGLE_REDIRECT = 'http://localhost:8000/callback/google'

I hope this help you find a dumb error...

rewrite a folder name using .htaccess

mod_rewrite can only rewrite/redirect requested URIs. So you would need to request /apple/… to get it rewritten to a corresponding /folder1/….

Try this:

RewriteEngine on
RewriteRule ^apple/(.*) folder1/$1

This rule will rewrite every request that starts with the URI path /apple/… internally to /folder1/….


Edit    As you are actually looking for the other way round:

RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /apple/$1 [L,R=301]

This rule is designed to work together with the other rule above. Requests of /folder1/… will be redirected externally to /apple/… and requests of /apple/… will then be rewritten internally back to /folder1/….

What are projection and selection?

Projection: what ever typed in select clause i.e, 'column list' or '*' or 'expressions' that becomes under projection.

*selection:*what type of conditions we are applying on that columns i.e, getting the records that comes under selection.

For example:

  SELECT empno,ename,dno,job from Emp 
     WHERE job='CLERK'; 

in the above query the columns "empno,ename,dno,job" those comes under projection, "where job='clerk'" comes under selection

Responsive css styles on mobile devices ONLY

What's you've got there should be fine to work, but there is no actual "Is Mobile/Tablet" media query so you're always going to be stuck.

There are media queries for common breakpoints , but with the ever changing range of devices they're not guaranteed to work moving forwards.

The idea is that your site maintains the same brand across all sizes, so you should want the styles to cascade across the breakpoints and only update the widths and positioning to best suit that viewport.

To further the answer above, using Modernizr with a no-touch test will allow you to target touch devices which are most likely tablets and smart phones, however with the new releases of touch based screens that is not as good an option as it once was.

Array Length in Java

`

int array[]=new int[3]; array.length;

so here we have created an array with a memory space of 3... this is how it looks actually

0th 1st 2nd ...........> Index 2 4 5 ...........> Number

So as u see the size of this array is 3 but the index of array is only up to 2 since any array starts with 0th index.

second statement' output shall be 3 since the length of the array is 3... Please don't get confused between the index value and the length of the array....

cheers!

Checking that a List is not empty in Hamcrest

Well there's always

assertThat(list.isEmpty(), is(false));

... but I'm guessing that's not quite what you meant :)

Alternatively:

assertThat((Collection)list, is(not(empty())));

empty() is a static in the Matchers class. Note the need to cast the list to Collection, thanks to Hamcrest 1.2's wonky generics.

The following imports can be used with hamcrest 1.3

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.*;

How do I write a Windows batch script to copy the newest file from a directory?

To allow this to work with filenames using spaces, a modified version of the accepted answer is needed:

FOR /F "delims=" %%I IN ('DIR . /B /O:-D') DO COPY "%%I" <<NewDir>> & GOTO :END
:END

How to print a debug log?

You need to change your frame of mind. You are writing PHP, not whatever else it is that you are used to write. Debugging in PHP is not done in a console environment.

In PHP, you have 3 categories of debugging solutions:

  1. Output to a webpage (see dBug library for a nicer view of things).
  2. Write to a log file
  3. In session debugging with xDebug

Learn to use those instead of trying to make PHP behave like whatever other language you are used to.

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

View.GONE makes the view invisible without the view taking up space in the layout. View.INVISIBLE makes the view just invisible still taking up space.

You are first using GONE and then INVISIBLE on the same view.Since, the code is executed sequentially, first the view becomes GONE then it is overridden by the INVISIBLE type still taking up space.

You should add button listener on the button and inside the onClick() method make the views visible. This should be the logic according to me in your onCreate() method.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_setting);

    final DatePicker dp2 = (DatePicker) findViewById(R.id.datePick2);
    final Button btn2 = (Button) findViewById(R.id.btnDate2);
    final Button btn3 = (Button) findViewById(R.id.btnVisibility);

    dp2.setVisibility(View.INVISIBLE);
    btn2.setVisibility(View.INVISIBLE);

    bt3.setOnClickListener(new View.OnCLickListener(){ 
    @Override
    public void onClick(View view)
    {
        dp2.setVisibility(View.VISIBLE);
        bt2.setVisibility(View.VISIBLE);
    }
  });
}

I think this should work easily. Hope this helps.

How to specify the port an ASP.NET Core application is hosted on?

Follow up answer to help anyone doing this with the VS docker integration. I needed to change to port 8080 to run using the "flexible" environment in google appengine.

You'll need the following in your Dockerfile:

ENV ASPNETCORE_URLS=http://+:8080
EXPOSE 8080

and you'll need to modify the port in docker-compose.yml as well:

    ports:
      - "8080"

Use Ant for running program with command line arguments

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

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

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

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

Putting it all together gives:

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

You can use it as follows:

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

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

selecting unique values from a column

There is a specific keyword for the achieving the same.

SELECT DISTINCT( Date ) AS Date 
FROM   buy 
ORDER  BY Date DESC; 

How can I format DateTime to web UTC format?

string.Format("{0:yyyy-MM-ddTHH:mm:ss.FFFZ}", DateTime.UtcNow)

returns 2017-02-10T08:12:39.483Z

Percentage Height HTML 5/CSS

Sometimes, you may want to conditionally set the height of a div, such as when the entire content is less than the height of the screen. Setting all parent elements to 100% will cut off content when it is longer than the screen size.

So, the way to get around this is to set the min-height:

Continue to let the parent elements automatically adjust their height Then in your main div, subtract the pixel sizes of the header and footer div from 100vh (viewport units). In css, something like:

min-height: calc(100vh - 246px);

100vh is full length of the screen, minus the surrounding divs. By setting min-height and not height, content longer than screen will continue to flow, instead of getting cut off.

Python: BeautifulSoup - get an attribute value based on the name attribute

If tdd='<td class="abc"> 75</td>'
In Beautifulsoup 

if(tdd.has_attr('class')):
   print(tdd.attrs['class'][0])


Result:  abc

Is there a no-duplicate List implementation out there?

You should seriously consider dhiller's answer:

  1. Instead of worrying about adding your objects to a duplicate-less List, add them to a Set (any implementation), which will by nature filter out the duplicates.
  2. When you need to call the method that requires a List, wrap it in a new ArrayList(set) (or a new LinkedList(set), whatever).

I think that the solution you posted with the NoDuplicatesList has some issues, mostly with the contains() method, plus your class does not handle checking for duplicates in the Collection passed to your addAll() method.

Command to delete all pods in all kubernetes namespaces

kubectl delete daemonsets,replicasets,services,deployments,pods,rc --all

to get rid of them pesky replication controllers too.

Hashset vs Treeset

Message Edit ( complete rewrite ) When order does not matter, that's when. Both should give Log(n) - it would be of utility to see if either is over five percent faster than the other. HashSet can give O(1) testing in a loop should reveal whether it is.

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

You can try to turn support on in spring's converter

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // add converter suport Content-Type: 'application/x-www-form-urlencoded'
        converters.stream()
                .filter(AllEncompassingFormHttpMessageConverter.class::isInstance)
                .map(AllEncompassingFormHttpMessageConverter.class::cast)
                .findFirst()
                .ifPresent(converter -> converter.addSupportedMediaTypes(MediaType.APPLICATION_FORM_URLENCODED_VALUE));
    }

}

How to apply CSS page-break to print a table with lots of rows?

I eventually realised that my bulk content that was overflowing the table and not breaking properly simply didn't even need to be inside a table.

While it's not a technical solution, it solved my problem to simply end the table when I no longer needed a table; then started a new one for the footer.

Hope it helps someone... good luck!

How do I check out a specific version of a submodule using 'git submodule'?

Step 1: Add the submodule

   git submodule add git://some_repository.git some_repository

Step 2: Fix the submodule to a particular commit

By default the new submodule will be tracking HEAD of the master branch, but it will NOT be updated as you update your primary repository. In order to change the submodule to track a particular commit or different branch, change directory to the submodule folder and switch branches just like you would in a normal repository.

   git checkout -b some_branch origin/some_branch

Now the submodule is fixed on the development branch instead of HEAD of master.

From Two Guys Arguing — Tie Git Submodules to a Particular Commit or Branch .

How to use shared memory with Linux in C

try this code sample, I tested it, source: http://www.makelinux.net/alp/035

#include <stdio.h> 
#include <sys/shm.h> 
#include <sys/stat.h> 

int main () 
{
  int segment_id; 
  char* shared_memory; 
  struct shmid_ds shmbuffer; 
  int segment_size; 
  const int shared_segment_size = 0x6400; 

  /* Allocate a shared memory segment.  */ 
  segment_id = shmget (IPC_PRIVATE, shared_segment_size, 
                 IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR); 
  /* Attach the shared memory segment.  */ 
  shared_memory = (char*) shmat (segment_id, 0, 0); 
  printf ("shared memory attached at address %p\n", shared_memory); 
  /* Determine the segment's size. */ 
  shmctl (segment_id, IPC_STAT, &shmbuffer); 
  segment_size  =               shmbuffer.shm_segsz; 
  printf ("segment size: %d\n", segment_size); 
  /* Write a string to the shared memory segment.  */ 
  sprintf (shared_memory, "Hello, world."); 
  /* Detach the shared memory segment.  */ 
  shmdt (shared_memory); 

  /* Reattach the shared memory segment, at a different address.  */ 
  shared_memory = (char*) shmat (segment_id, (void*) 0x5000000, 0); 
  printf ("shared memory reattached at address %p\n", shared_memory); 
  /* Print out the string from shared memory.  */ 
  printf ("%s\n", shared_memory); 
  /* Detach the shared memory segment.  */ 
  shmdt (shared_memory); 

  /* Deallocate the shared memory segment.  */ 
  shmctl (segment_id, IPC_RMID, 0); 

  return 0; 
} 

VB.NET 'If' statement with 'Or' conditional has both sides evaluated?

It's your "fault" in that that's how Or is defined, so it's the behaviour you should expect:

In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. The OrElse Operator (Visual Basic) performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.

But you don't have to endure it. You can use OrElse to get short-circuiting behaviour.

So you probably want:

If (example Is Nothing OrElse Not example.Item = compare.Item) Then
    'Proceed
End If

I can't say it reads terribly nicely, but it should work...

Intersect Two Lists in C#

From performance point of view if two lists contain number of elements that differ significantly, you can try such approach (using conditional operator ?:):

1.First you need to declare a converter:

Converter<string, int> del = delegate(string s) { return Int32.Parse(s); };

2.Then you use a conditional operator:

var r = data1.Count > data2.Count ?
 data2.ConvertAll<int>(del).Intersect(data1) :
 data1.Select(v => v.ToString()).Intersect(data2).ToList<string>().ConvertAll<int>(del);

You convert elements of shorter list to match the type of longer list. Imagine an execution speed if your first set contains 1000 elements and second only 10 (or opposite as it doesn't matter) ;-)

As you want to have a result as List, in a last line you convert the result (only result) back to int.

ASP.Net 2012 Unobtrusive Validation with jQuery

It seems like there is a lot of incorrect information about the ValidationSettings:UnobtrusiveValidationMode value. To Disable it you need to do the following.

<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />

The word None, not WebForms should be used to disable this feature.

Bootstrap css hides portion of container below navbar navbar-fixed-top

I guess the problem you have is related to the dynamic height that the fixed navbar at the top has. For example, when a user logs in, you need to display some kind of "Hello [User Name]" and when the name is too wide, the navbar needs to use more height so this text doesn't overlap with the navbar menu. As the navbar has the style "position: fixed", the body stays underneath it and a taller part of it becomes hidden so you need to "dynamically" change the padding at the top every time the navbar height changes which would happen in the following case scenarios:

  1. The page is loaded / reloaded.
  2. The browser window is resized as this could hit a different responsive breakpoint.
  3. The navbar content is modified directly or indirectly as this could provoke a height change.

This dynamicity is not covered by regular CSS so I can only think of one way to solve this problem if the user has JavaScript enabled. Please try the following jQuery code snippet to resolve case scenarios 1 and 2; for case scenario 3 please remember to call the function onResize() after any change in the navbar content:

_x000D_
_x000D_
var onResize = function() {_x000D_
  // apply dynamic padding at the top of the body according to the fixed navbar height_x000D_
  $("body").css("padding-top", $(".navbar-fixed-top").height());_x000D_
};_x000D_
_x000D_
// attach the function to the window resize event_x000D_
$(window).resize(onResize);_x000D_
_x000D_
// call it also when the page is ready after load or reload_x000D_
$(function() {_x000D_
  onResize();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Trim leading and trailing spaces from a string in awk

If you want to trim all spaces, only in lines that have a comma, and use awk, then the following will work for you:

awk -F, '/,/{gsub(/ /, "", $0); print} ' input.txt

If you only want to remove spaces in the second column, change the expression to

awk -F, '/,/{gsub(/ /, "", $2); print$1","$2} ' input.txt

Note that gsub substitutes the character in // with the second expression, in the variable that is the third parameter - and does so in-place - in other words, when it's done, the $0 (or $2) has been modified.

Full explanation:

-F,            use comma as field separator 
               (so the thing before the first comma is $1, etc)
/,/            operate only on lines with a comma 
               (this means empty lines are skipped)
gsub(a,b,c)    match the regular expression a, replace it with b, 
               and do all this with the contents of c
print$1","$2   print the contents of field 1, a comma, then field 2
input.txt      use input.txt as the source of lines to process

EDIT I want to point out that @BMW's solution is better, as it actually trims only leading and trailing spaces with two successive gsub commands. Whilst giving credit I will give an explanation of how it works.

gsub(/^[ \t]+/,"",$2);    - starting at the beginning (^) replace all (+ = zero or more, greedy)
                             consecutive tabs and spaces with an empty string
gsub(/[ \t]+$/,"",$2)}    - do the same, but now for all space up to the end of string ($)
1                         - ="true". Shorthand for "use default action", which is print $0
                          - that is, print the entire (modified) line

Get Image Height and Width as integer values?

getimagesize('image.jpg') function works only if allow_url_fopen is set to 1 or On inside php.ini file on the server, if it is not enabled, one should use ini_set('allow_url_fopen',1); on top of the file where getimagesize() function is used.

Is there a way to pass optional parameters to a function?

def my_func(mandatory_arg, optional_arg=100):
    print(mandatory_arg, optional_arg)

http://docs.python.org/2/tutorial/controlflow.html#default-argument-values

I find this more readable than using **kwargs.

To determine if an argument was passed at all, I use a custom utility object as the default value:

MISSING = object()

def func(arg=MISSING):
    if arg is MISSING:
        ...

C subscripted value is neither array nor pointer nor vector when assigning an array element value

C lets you use the subscript operator [] on arrays and on pointers. When you use this operator on a pointer, the resultant type is the type to which the pointer points to. For example, if you apply [] to int*, the result would be an int.

That is precisely what's going on: you are passing int*, which corresponds to a vector of integers. Using subscript on it once makes it int, so you cannot apply the second subscript to it.

It appears from your code that arr should be a 2-D array. If it is implemented as a "jagged" array (i.e. an array of pointers) then the parameter type should be int **.

Moreover, it appears that you are trying to return a local array. In order to do that legally, you need to allocate the array dynamically, and return a pointer. However, a better approach would be declaring a special struct for your 4x4 matrix, and using it to wrap your fixed-size array, like this:

// This type wraps your 4x4 matrix
typedef struct {
    int arr[4][4];
} FourByFour;
// Now rotate(m) can use FourByFour as a type
FourByFour rotate(FourByFour m) {
    FourByFour D;
    for(int i = 0; i < 4; i ++ ){
        for(int n = 0; n < 4; n++){
            D.arr[i][n] = m.arr[n][3 - i];
        }
    }
    return D;
}
// Here is a demo of your rotate(m) in action:
int main(void) {
    FourByFour S = {.arr = {
        { 1, 4, 10, 3 },
        { 0, 6, 3, 8 },
        { 7, 10 ,8, 5 },
        { 9, 5, 11, 2}
    } };
    FourByFour r = rotate(S);
    for(int i=0; i < 4; i ++ ){
        for(int n=0; n < 4; n++){
            printf("%d ", r.arr[i][n]);
        }
        printf("\n");
    }
    return 0;
}

This prints the following:

3 8 5 2 
10 3 8 11 
4 6 10 5 
1 0 7 9 

Create excel ranges using column numbers in vba?

Function fncToLetters(vintCol As Integer) As String

        Dim mstrDigits As String

    ' Convert a positive number n to its digit representation in base 26.
    mstrDigits = ""
    Do While vintCol > 0
        mstrDigits = Chr(((vintCol - 1) Mod 26) + 65) & mstrDigits
        vintCol = Int((vintCol - 1) / 26)
    Loop

    fncToLetters = mstrDigits

End Function

Difference between "@id/" and "@+id/" in Android

you refer to Android resources , which are already defined in Android system, with @android:id/.. while to access resources that you have defined/created in your project, you use @id/..

More Info

As per your clarifications in the chat, you said you have a problem like this :

If we use android:id="@id/layout_item_id" it doesn't work. Instead @+id/ works so what's the difference here? And that was my original question.

Well, it depends on the context, when you're using the XML attribute of android:id, then you're specifying a new id, and are instructing the parser (or call it the builder) to create a new entry in R.java, thus you have to include a + sign.

While in the other case, like android:layout_below="@id/myTextView" , you're referring to an id that has already been created, so parser links this to the already created id in R.java.

More Info Again

As you said in your chat, note that android:layout_below="@id/myTextView" won't recognize an element with id myTextViewif it is written after the element you're using it in.

Make child div stretch across width of page

You can do:

margin-left: -50%;
margin-right: -50%;

How to iterate over the file in python

The traceback indicates that probably you have an empty line at the end of the file. You can fix it like this:

f = open('test.txt','r')
g = open('test1.txt','w') 
while True:
    x = f.readline()
    x = x.rstrip()
    if not x: break
    print >> g, int(x, 16)

On the other hand it would be better to use for x in f instead of readline. Do not forget to close your files or better to use with that close them for you:

with open('test.txt','r') as f:
    with open('test1.txt','w') as g: 
        for x in f:
            x = x.rstrip()
            if not x: continue
            print >> g, int(x, 16)

Change the jquery show()/hide() animation?

There are the slideDown, slideUp, and slideToggle functions native to jquery 1.3+, and they work quite nicely...

https://api.jquery.com/category/effects/

You can use slideDown just like this:

$("test").slideDown("slow");

And if you want to combine effects and really go nuts I'd take a look at the animate function which allows you to specify a number of CSS properties to shape tween or morph into. Pretty fancy stuff, that.

Remove all stylings (border, glow) from textarea

If you want to remove EVERYTHING :

textarea {
    border: none;
    background-color: transparent;
    resize: none;
    outline: none;
}

Update label from another thread

You cannot update UI from any other thread other than the UI thread. Use this to update thread on the UI thread.

 private void AggiornaContatore()
 {         
     if(this.lblCounter.InvokeRequired)
     {
         this.lblCounter.BeginInvoke((MethodInvoker) delegate() {this.lblCounter.Text = this.index.ToString(); ;});    
     }
     else
     {
         this.lblCounter.Text = this.index.ToString(); ;
     }
 }

Please go through this chapter and more from this book to get a clear picture about threading:

http://www.albahari.com/threading/part2.aspx#_Rich_Client_Applications

Powershell: convert string to number

Simply casting the string as an int won't work reliably. You need to convert it to an int32. For this you can use the .NET convert class and its ToInt32 method. The method requires a string ($strNum) as the main input, and the base number (10) for the number system to convert to. This is because you can not only convert to the decimal system (the 10 base number), but also to, for example, the binary system (base 2).

Give this method a try:

[string]$strNum = "1.500"
[int]$intNum = [convert]::ToInt32($strNum, 10)

$intNum

Opening PDF String in new window with javascript

You might want to explore using the data URI. It would look something like.

window.open("data:application/pdf," + escape(pdfString));

I wasn't immediately able to get this to work, possible because formating of the binary string provided. I also usually use base64 encoded data when using the data URI. If you are able to pass the content from the backend encoded you can use..

window.open("data:application/pdf;base64, " + base64EncodedPDF);

Hopefully this is the right direction for what you need. Also note this will not work at all in IE6/7 because they do not support Data URIs.

How to Delete a topic in apache kafka

Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable to true) on all brokers first.

Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable is by default true.

Follow this step by step process for manual deletion of topics

  1. Stop Kafka server
  2. Delete the topic directory, on each broker (as defined in the logs.dirs and log.dir properties) with rm -rf command
  3. Connect to Zookeeper instance: zookeeper-shell.sh host:port
  4. From within the Zookeeper instance:
    1. List the topics using: ls /brokers/topics
    2. Remove the topic folder from ZooKeeper using: rmr /brokers/topics/yourtopic
    3. Exit the Zookeeper instance (Ctrl+C)
  5. Restart Kafka server
  6. Confirm if it was deleted or not by using this command kafka-topics.sh --list --zookeeper host:port

Getting return value from stored procedure in C#

There are multiple problems here:

  1. It is not possible. You are trying to return a varchar. Stored procedure return values can only be integer expressions. See official RETURN documentation: https://msdn.microsoft.com/en-us/library/ms174998.aspx.
  2. Your sqlcomm was never executed. You have to call sqlcomm.ExecuteNonQuery(); in order to execute your command.

Here is a solution using OUTPUT parameters. This was tested with:

  • Windows Server 2012
  • .NET v4.0.30319
  • C# 4.0
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Validate]
    @a varchar(50),
    @b varchar(50) OUTPUT
AS
BEGIN
    DECLARE @b AS varchar(50) = (SELECT Password FROM dbo.tblUser WHERE Login = @a)
    SELECT @b;
END
SqlConnection SqlConn = ...
var sqlcomm = new SqlCommand("Validate", SqlConn);

string returnValue = string.Empty;

try
{
    SqlConn.Open();
    sqlcomm.CommandType = CommandType.StoredProcedure;

    SqlParameter param = new SqlParameter("@a", SqlDbType.VarChar);
    param.Direction = ParameterDirection.Input;
    param.Value = Username;
    sqlcomm.Parameters.Add(param);

    SqlParameter output = sqlcomm.Parameters.Add("@b", SqlDbType.VarChar);
    ouput.Direction = ParameterDirection.Output;

    sqlcomm.ExecuteNonQuery(); // This line was missing

    returnValue = output.Value.ToString();

    // ... the rest of code

} catch (SqlException ex) {
    throw ex;
}

How can I get the list of files in a directory using C or C++?

Just something that I want to share and thank you for the reading material. Play around with the function for a bit to understand it. You may like it. e stood for extension, p is for path, and s is for path separator.

If the path is passed without ending separator, a separator will be appended to the path. For the extension, if an empty string is inputted then the function will return any file that does not have an extension in its name. If a single star was inputted than all files in the directory will be returned. If e length is greater than 0 but is not a single * then a dot will be prepended to e if e had not contained a dot at the zero position.

For a returning value. If a zero-length map is returned then nothing was found but the directory was open okay. If index 999 is available from the return value but the map size is only 1 then that meant there was a problem with opening the directory path.

Note that for efficiency, this function can be split into 3 smaller functions. On top of that, you can create a caller function that will detect which function it is going to call based on the input. Why is that more efficient? Said if you are going to grab everything that is a file, doing that method the subfunction that built for grabbing all the files will just grab all that are files and does not need to evaluate any other unnecessary condition everytime it found a file.

That would also apply to when you grab files that do not have an extension. A specific built function for that purpose would only evaluate for weather if the object found is a file and then whether or not if the name of the file has a dot in it.

The saving may not be much if you only read directories with not so much files. But if you are reading a mass amount of directory or if the directory has couple hundred thousands of files, it could be a huge saving.

#include <stdio.h>
#include <sys/stat.h>
#include <iostream>
#include <dirent.h>
#include <map>

std::map<int, std::string> getFile(std::string p, std::string e = "", unsigned char s = '/'){
    if ( p.size() > 0 ){
        if (p.back() != s) p += s;
    }
    if ( e.size() > 0 ){
        if ( e.at(0) != '.' && !(e.size() == 1 && e.at(0) == '*') ) e = "." + e;
    }

    DIR *dir;
    struct dirent *ent;
    struct stat sb;
    std::map<int, std::string> r = {{999, "FAILED"}};
    std::string temp;
    int f = 0;
    bool fd;

    if ( (dir = opendir(p.c_str())) != NULL ){
        r.erase (999);
        while ((ent = readdir (dir)) != NULL){
            temp = ent->d_name;
            fd = temp.find(".") != std::string::npos? true : false;
            temp = p + temp;

            if (stat(temp.c_str(), &sb) == 0 && S_ISREG(sb.st_mode)){
                if ( e.size() == 1 && e.at(0) == '*' ){
                    r[f] = temp;
                    f++;
                } else {
                    if (e.size() == 0){
                        if ( fd == false ){
                            r[f] = temp;
                            f++;
                        }
                        continue;
                    }

                    if (e.size() > temp.size()) continue;

                    if ( temp.substr(temp.size() - e.size()) == e ){
                        r[f] = temp;
                        f++;
                    }
                }
            }
        }

        closedir(dir);
        return r;
    } else {
        return r;
    }
}

void printMap(auto &m){
    for (const auto &p : m) {
        std::cout << "m[" << p.first << "] = " << p.second << std::endl;
    }
}

int main(){
    std::map<int, std::string> k = getFile("./", "");
    printMap(k);
    return 0;
}

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    <RequireAll>
        Require all granted
    </RequireAll>
</Directory>

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

https://gist.github.com/samvaughton/6790739

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

How can I undo a mysql statement that I just executed?

in case you do not only need to undo your last query (although your question actually only points on that, I know) and therefore if a transaction might not help you out, you need to implement a workaround for this:

copy the original data before commiting your query and write it back on demand based on the unique id that must be the same in both tables; your rollback-table (with the copies of the unchanged data) and your actual table (containing the data that should be "undone" than). for databases having many tables, one single "rollback-table" containing structured dumps/copies of the original data would be better to use then one for each actual table. it would contain the name of the actual table, the unique id of the row, and in a third field the content in any desired format that represents the data structure and values clearly (e.g. XML). based on the first two fields this third one would be parsed and written back to the actual table. a fourth field with a timestamp would help cleaning up this rollback-table.

since there is no real undo in SQL-dialects despite "rollback" in a transaction (please correct me if I'm wrong - maybe there now is one), this is the only way, I guess, and you have to write the code for it on your own.

Passing multiple variables to another page in url

Pretty simple but another said you dont pass session variables through the url bar 1.You dont need to because a session is passed throughout the whole website from header when you put in header file 2.security risks
Here is first page code

$url = "http://localhost/main.php?email=" . urlencode($email_address) . "&eventid=" . urlencode($event_id);

2nd page when getting the variables from the url bar is:

if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['eventid']) && !empty($_GET['eventid'])){ ////do whatever here }

Now if you want to do it the proper way of using the session you created then ignore my above code and call the session variables on the second page for instance create a session on the first page lets say for example:

 $_SESSION['WEB_SES'] = $email_address . "^" . $event_id;

obvious that you would have already assigned values to the session variables in the code above, you can call the session name whatever you want to i just used the example web_ses , the second page all you need to do is start a session and see if the session is there and check the variables and do whatever with them, example:

 session_start();
 if (isset($_SESSION['WEB_SES'])){
 $Array = explode("^", $_SESSION['WEB_SES']);
 $email = $Array[0];
 $event_id = $Array[1]
 echo "$email";
 echo "$event_id";
 }

Like I said before the good thing about sessions are they can be carried throughout the entire website if this type of code in put in the header file that gets called upon on all pages that load, you can simple use the variable wherever and whenever. Hope this helps :)

Java switch statement multiple cases

The second option is completely fine. I'm not sure why a responder said it was not possible. This is fine, and I do this all the time:

switch (variable)
{
    case 5:
    case 6:
    etc.
    case 100:
        doSomething();
    break;
}

Make: how to continue after a command fails?

Try the -i flag (or --ignore-errors). The documentation seems to suggest a more robust way to achieve this, by the way:

To ignore errors in a command line, write a - at the beginning of the line's text (after the initial tab). The - is discarded before the command is passed to the shell for execution.

For example,

clean:
  -rm -f *.o

This causes rm to continue even if it is unable to remove a file.

All examples are with rm, but are applicable to any other command you need to ignore errors from (i.e. mkdir).

install cx_oracle for python

Try to reinstall it with the following code:

!pip install --proxy http://username:[email protected]:8080 --upgrade --force-reinstall cx_Oracle

What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

Well, like Dean said, you can look at the registry and do what he did. To check if he really has CLR .NET Framework installed, you should look for the MSCorEE.dll file in the %SystemRoot%\System32 directory.

Is there a JSON equivalent of XQuery/XPath?

Defiant.js looks also pretty cool, here's a simple example:

var obj = {
        "car": [
            {"id": 10, "color": "silver", "name": "Volvo"},
            {"id": 11, "color": "red",    "name": "Saab"},
            {"id": 12, "color": "red",    "name": "Peugeot"},
            {"id": 13, "color": "yellow", "name": "Porsche"}
        ],
        "bike": [
            {"id": 20, "color": "black", "name": "Cannondale"},
            {"id": 21, "color": "red",   "name": "Shimano"}
        ]
    },
    search = JSON.search(obj, '//car[color="yellow"]/name');

console.log( search );
// ["Porsche"]

var reds = JSON.search(obj, '//*[color="red"]');

for (var i=0; i<reds.length; i++) {
    console.log( reds[i].name );
}
// Saab
// Peugeot
// Shimano

TSQL CASE with if comparison in SELECT statement

Should be:

SELECT registrationDate, 
       (SELECT CASE
        WHEN COUNT(*)< 2 THEN 'Ama'
        WHEN COUNT(*)< 5 THEN 'SemiAma' 
        WHEN COUNT(*)< 7 THEN 'Good'  
        WHEN COUNT(*)< 9 THEN 'Better' 
        WHEN COUNT(*)< 12 THEN 'Best'
        ELSE 'Outstanding'
        END as a FROM Articles 
        WHERE Articles.userId = Users.userId) as ranking,
        (SELECT COUNT(*) 
        FROM Articles 
        WHERE userId = Users.userId) as articleNumber,
hobbies, etc...
FROM USERS

What does "javax.naming.NoInitialContextException" mean?

In extremely non-technical terms, it may mean that you forgot to put "ejb:" or "jdbc:" or something at the very beginning of the URI you are trying to connect.

Expression ___ has changed after it was checked

I think a most simple solution would be as follows:

  1. Make one implementation of assigning a value to some variable i.e. via function or setter.
  2. Create a class variable (static working: boolean) in the class where this function exists and every time you call the function, simply make it true whichever you like. Within the function, if the value of working is true, then simply return right away without doing anything. else, perform the task you want. Make sure to change this variable to false once the task is completed i.e. at the end of the line of codes or within the subscribe method when you are done assigning values!

varbinary to string on SQL Server

The following expression worked for me:

SELECT CONVERT(VARCHAR(1000), varbinary_value, 2);

Here are more details on the choice of style (the third parameter).

What is the difference between `sorted(list)` vs `list.sort()`?

What is the difference between sorted(list) vs list.sort()?

  • list.sort mutates the list in-place & returns None
  • sorted takes any iterable & returns a new list, sorted.

sorted is equivalent to this Python implementation, but the CPython builtin function should run measurably faster as it is written in C:

def sorted(iterable, key=None):
    new_list = list(iterable)    # make a new list
    new_list.sort(key=key)       # sort it
    return new_list              # return it

when to use which?

  • Use list.sort when you do not wish to retain the original sort order (Thus you will be able to reuse the list in-place in memory.) and when you are the sole owner of the list (if the list is shared by other code and you mutate it, you could introduce bugs where that list is used.)
  • Use sorted when you want to retain the original sort order or when you wish to create a new list that only your local code owns.

Can a list's original positions be retrieved after list.sort()?

No - unless you made a copy yourself, that information is lost because the sort is done in-place.

"And which is faster? And how much faster?"

To illustrate the penalty of creating a new list, use the timeit module, here's our setup:

import timeit
setup = """
import random
lists = [list(range(10000)) for _ in range(1000)]  # list of lists
for l in lists:
    random.shuffle(l) # shuffle each list
shuffled_iter = iter(lists) # wrap as iterator so next() yields one at a time
"""

And here's our results for a list of randomly arranged 10000 integers, as we can see here, we've disproven an older list creation expense myth:

Python 2.7

>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[3.75168503401801, 3.7473005310166627, 3.753129180986434]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[3.702025591977872, 3.709248117986135, 3.71071034099441]

Python 3

>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[2.797430992126465, 2.796825885772705, 2.7744789123535156]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[2.675589084625244, 2.8019039630889893, 2.849375009536743]

After some feedback, I decided another test would be desirable with different characteristics. Here I provide the same randomly ordered list of 100,000 in length for each iteration 1,000 times.

import timeit
setup = """
import random
random.seed(0)
lst = list(range(100000))
random.shuffle(lst)
"""

I interpret this larger sort's difference coming from the copying mentioned by Martijn, but it does not dominate to the point stated in the older more popular answer here, here the increase in time is only about 10%

>>> timeit.repeat("lst[:].sort()", setup=setup, number = 10000)
[572.919036605, 573.1384446719999, 568.5923951]
>>> timeit.repeat("sorted(lst[:])", setup=setup, number = 10000)
[647.0584738299999, 653.4040515829997, 657.9457361929999]

I also ran the above on a much smaller sort, and saw that the new sorted copy version still takes about 2% longer running time on a sort of 1000 length.

Poke ran his own code as well, here's the code:

setup = '''
import random
random.seed(12122353453462456)
lst = list(range({length}))
random.shuffle(lst)
lists = [lst[:] for _ in range({repeats})]
it = iter(lists)
'''
t1 = 'l = next(it); l.sort()'
t2 = 'l = next(it); sorted(l)'
length = 10 ** 7
repeats = 10 ** 2
print(length, repeats)
for t in t1, t2:
    print(t)
    print(timeit(t, setup=setup.format(length=length, repeats=repeats), number=repeats))

He found for 1000000 length sort, (ran 100 times) a similar result, but only about a 5% increase in time, here's the output:

10000000 100
l = next(it); l.sort()
610.5015971539542
l = next(it); sorted(l)
646.7786222379655

Conclusion:

A large sized list being sorted with sorted making a copy will likely dominate differences, but the sorting itself dominates the operation, and organizing your code around these differences would be premature optimization. I would use sorted when I need a new sorted list of the data, and I would use list.sort when I need to sort a list in-place, and let that determine my usage.

How to determine when a Git branch was created?

Combined with the answer from Andrew Sohn (https://stackoverflow.com/a/14265207/1929406)

branchcreated=$(git reflog show --date=format:'%Y-%m-%d %H:%M:%S' --all | sed 's!^.*refs/!refs/!' | grep '/master' | tail -1| cut -d'{' -f 2| cut -d'}' -f 1 | xargs)
echo $branchcreated

How to create javascript delay function

You do not need to use an anonymous function with setTimeout. You can do something like this:

setTimeout(doSomething, 3000);

function doSomething() {
   //do whatever you want here
}

Access Https Rest Service using Spring RestTemplate

Here is some code that will give you the general idea.

You need to create a custom ClientHttpRequestFactory in order to trust the certificate. It looks like this:

final ClientHttpRequestFactory clientHttpRequestFactory =
        new MyCustomClientHttpRequestFactory(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER, serverInfo);
    restTemplate.setRequestFactory(clientHttpRequestFactory);

This is the implementation for MyCustomClientHttpRequestFactory:

public class MyCustomClientHttpRequestFactory  extends SimpleClientHttpRequestFactory {

private final HostnameVerifier hostNameVerifier;
private final ServerInfo serverInfo;

public MyCustomClientHttpRequestFactory (final HostnameVerifier hostNameVerifier,
    final ServerInfo serverInfo) {
    this.hostNameVerifier = hostNameVerifier;
    this.serverInfo = serverInfo;
}

@Override
protected void prepareConnection(final HttpURLConnection connection, final String httpMethod)
    throws IOException {
    if (connection instanceof HttpsURLConnection) {
        ((HttpsURLConnection) connection).setHostnameVerifier(hostNameVerifier);
        ((HttpsURLConnection) connection).setSSLSocketFactory(initSSLContext()
            .getSocketFactory());
    }
    super.prepareConnection(connection, httpMethod);
}

private SSLContext initSSLContext() {
    try {
        System.setProperty("https.protocols", "TLSv1");

        // Set ssl trust manager. Verify against our server thumbprint
        final SSLContext ctx = SSLContext.getInstance("TLSv1");
        final SslThumbprintVerifier verifier = new SslThumbprintVerifier(serverInfo);
        final ThumbprintTrustManager thumbPrintTrustManager =
            new ThumbprintTrustManager(null, verifier);
        ctx.init(null, new TrustManager[] { thumbPrintTrustManager }, null);
        return ctx;
    } catch (final Exception ex) {
        LOGGER.error(
            "An exception was thrown while trying to initialize HTTP security manager.", ex);
        return null;
    }
}

In this case my serverInfo object contains the thumbprint of the server. You need to implement the TrustManager interface to get the SslThumbprintVerifier or any other method you want to verify your certificate (you can also decide to also always return true).

The value org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER allows all host names. If you need to verify the host name, you will need to implement it differently.

I'm not sure about the user and password and how you implemented it. Often, you need to add a header to the restTemplate named Authorization with a value that looks like this: Base: <encoded user+password>. The user+password must be Base64 encoded.

jQuery Event Keypress: Which key was pressed?

 // in jquery source code...
 if (!event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode)) {
     event.which = event.charCode || event.keyCode;
 }

 // So you have just to use
 $('#searchbox input').bind('keypress', function(e) {
     if (e.which === 13) {
         alert('ENTER WAS PRESSED');
     }
 });

What is the difference between static func and class func in Swift?

According to the Swift 2.2 Book published by apple:

“You indicate type methods by writing the static keyword before the method’s func keyword. Classes may also use the class keyword to allow subclasses to override the superclass’s implementation of that method.”

Error 'tunneling socket' while executing npm install

I spent days trying all the above answers and ensuring I had the proxy and other settings in my node config correct. All were and it was still failing. I was/am using a Windows 10 machine and behind a corp proxy.

For some legacy reason, I had HTTP_PROXY and HTTPS_PROXY set in my user environment variables which overrides the node ones (unknown to me), so correcting these (the HTTPS_PROXY one was set to https, so I changed to HTTP) fixed the problem for me.

This is the problem when we can have the Same variables in Multiple places, you don't know what one is being used!

AngularJs event to call after content is loaded

fixed - 2015.06.09

Use a directive and the angular element ready method like so:

js

.directive( 'elemReady', function( $parse ) {
   return {
       restrict: 'A',
       link: function( $scope, elem, attrs ) {    
          elem.ready(function(){
            $scope.$apply(function(){
                var func = $parse(attrs.elemReady);
                func($scope);
            })
          })
       }
    }
})

html

<div elem-ready="someMethod()"></div>

or for those using controller-as syntax...

<div elem-ready="vm.someMethod()"></div>

The benefit of this is that you can be as broad or granular w/ your UI as you like and you are removing DOM logic from your controllers. I would argue this is the recommended Angular way.

You may need to prioritize this directive in case you have other directives operating on the same node.

Changing PowerShell's default output encoding to UTF-8

To be short, use:

write-output "your text" | out-file -append -encoding utf8 "filename"

How to set null to a GUID property

You can use typeof(Guid), "00000000-0000-0000-0000-000000000000" for DefaultValue of the property.

Laravel: Get base url

I found an other way to just get the base url to to display the value of environment variable APP_URL

env('APP_URL')

which will display the base url like http://domains_your//yours_website. beware it assumes that you had set the environment variable in .env file (that is present in the root folder).

How to trigger a file download when clicking an HTML button or JavaScript

I think this is the solution you were looking for

<button type="submit" onclick="window.location.href='file.doc'">Download!</button>

I hade a case where my Javascript generated a CSV file. Since there is no remote URL to download it I use the following implementation.

downloadCSV: function(data){
    var MIME_TYPE = "text/csv";

    var blob = new Blob([data], {type: MIME_TYPE});
    window.location.href = window.URL.createObjectURL(blob);
}

Remove the newline character in a list read from a file

You can use the strip() function to remove trailing (and leading) whitespace; passing it an argument will let you specify which whitespace:

for i in range(len(lists)):
    grades.append(lists[i].strip('\n'))

It looks like you can just simplify the whole block though, since if your file stores one ID per line grades is just lists with newlines stripped:

Before

lists = files.readlines()
grades = []

for i in range(len(lists)):
    grades.append(lists[i].split(","))

After

grades = [x.strip() for x in files.readlines()]

(the above is a list comprehension)


Finally, you can loop over a list directly, instead of using an index:

Before

for i in range(len(grades)):
    # do something with grades[i]

After

for thisGrade in grades:
    # do something with thisGrade

Have bash script answer interactive prompts

I found the best way to send input is to use cat and a text file to pass along whatever input you need.

cat "input.txt" | ./Script.sh

returning a Void object

It is possible to create instances of Void if you change the security manager, so something like this:

static Void getVoid() throws SecurityException, InstantiationException,
        IllegalAccessException, InvocationTargetException {
    class BadSecurityManager extends SecurityManager {
    
        @Override
        public void checkPermission(Permission perm) { }
    
        @Override
        public void checkPackageAccess(String pkg) { }

    }
    System.setSecurityManager(badManager = new BadSecurityManager());
    Constructor<?> constructor = Void.class.getDeclaredConstructors()[0];
    if(!constructor.isAccessible()) {
        constructor.setAccessible(true);
    }
    return (Void) constructor.newInstance();
}

Obviously this is not all that practical or safe; however, it will return an instance of Void if you are able to change the security manager.

Getting fb.me URL

Facebook uses Bit.ly's services to shorten links from their site. While pages that have a username turns into "fb.me/<username>", other links associated with Facebook turns into "on.fb.me/*****". To you use the on.fb.me service, just use your Bit.ly account. Note that if you change the default link shortener on your Bit.ly account to j.mp from bit.ly this service won't work.

How can prevent a PowerShell window from closing so I can see the error?

The simplest and easiest way is to execute your particular script with -NoExit param.

1.Open run box by pressing:

Win + R

2.Then type into input prompt:

PowerShell -NoExit "C:\folder\script.ps1"

and execute.

Entity framework left join

I was able to do this by calling the DefaultIfEmpty() on the main model. This allowed me to left join on lazy loaded entities, seems more readable to me:

        var complaints = db.Complaints.DefaultIfEmpty()
            .Where(x => x.DateStage1Complete == null || x.DateStage2Complete == null)
            .OrderBy(x => x.DateEntered)
            .Select(x => new
            {
                ComplaintID = x.ComplaintID,
                CustomerName = x.Customer.Name,
                CustomerAddress = x.Customer.Address,
                MemberName = x.Member != null ? x.Member.Name: string.Empty,
                AllocationName = x.Allocation != null ? x.Allocation.Name: string.Empty,
                CategoryName = x.Category != null ? x.Category.Ssl_Name : string.Empty,
                Stage1Start = x.Stage1StartDate,
                Stage1Expiry = x.Stage1_ExpiryDate,
                Stage2Start = x.Stage2StartDate,
                Stage2Expiry = x.Stage2_ExpiryDate
            });

How to preview an image before and after upload?

                    #######################
                    ###  the img page   ###
                    #######################


<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $('#f').live('change' ,function(){
            $('#fo').ajaxForm({target: '#d'}).submit();
        });
    });
</script>
<form id="fo" name="fo" action="nextimg.php" enctype="multipart/form-data" method="post">
    <input type="file" name="f" id="f" value="start upload" />
    <input type="submit" name="sub" value="upload" />
</form>
<div id="d"></div>


                    #############################
                    ###    the nextimg page   ###
                    #############################


<?php
     $name=$_FILES['f']['name'];
     $tmp=$_FILES['f']['tmp_name'];
     $new=time().$name;
     $new="upload/".$new;
     move_uploaded_file($tmp,$new);
     if($_FILES['f']['error']==0)
     {
?>
     <h1>PREVIEW</h1><br /><img src="<?php echo $new;?>" width="100" height="100" />
<?php
     }
?>

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

I encountered similar problem recently. The fix is to set the display property of the li items in the ordered list to list-item, and not display block, and ensure that the display property of ol is not list-item. i.e

li { display: list-item;}

With this, the html parser sees all li as the list item and assign the appropriate value to it, and sees the ol, as an inline-block or block element based on your settings, and doesn't try to assign any count value to it.

Call child method from parent

I think that the most basic way to call methods is by setting a request on the child component. Then as soon as the child handles the request, it calls a callback method to reset the request.

The reset mechanism is necessary to be able to send the same request multiple times after each other.

In parent component

In the render method of the parent:

const { request } = this.state;
return (<Child request={request} onRequestHandled={()->resetRequest()}/>);

The parent needs 2 methods, to communicate with its child in 2 directions.

sendRequest() {
  const request = { param: "value" };
  this.setState({ request });
}

resetRequest() {
  const request = null;
  this.setState({ request });
}

In child component

The child updates its internal state, copying the request from the props.

constructor(props) {
  super(props);
  const { request } = props;
  this.state = { request };
}

static getDerivedStateFromProps(props, state) {
  const { request } = props;
  if (request !== state.request ) return { request };
  return null;
}

Then finally it handles the request, and sends the reset to the parent:

componentDidMount() {
  const { request } = this.state;
  // todo handle request.

  const { onRequestHandled } = this.props;
  if (onRequestHandled != null) onRequestHandled();
}

What file uses .md extension and how should I edit them?

BBEdit will also display MD on the mac.

and here is a quicklook plugin to display them when you preview them.

Visual Studio Code pylint: Unable to import 'protorpc'

First I will check the python3 path where it lives

enter image description here

And then in the VS Code settings just add that path, for example:

"python.pythonPath": "/usr/local/bin/python3"