Programs & Examples On #Tscrollbox

Blur or dim background when Android PopupWindow active

Since PopupWindow just adds a View to WindowManager you can use updateViewLayout (View view, ViewGroup.LayoutParams params) to update the LayoutParams of your PopupWindow's contentView after calling show..().

Setting the window flag FLAG_DIM_BEHIND will dimm everything behind the window. Use dimAmount to control the amount of dim (1.0 for completely opaque to 0.0 for no dim).

Keep in mind that if you set a background to your PopupWindow it will put your contentView into a container, which means you need to update it's parent.

With background:

PopupWindow popup = new PopupWindow(contentView, width, height);
popup.setBackgroundDrawable(background);
popup.showAsDropDown(anchor);

View container = (View) popup.getContentView().getParent();
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams p = (WindowManager.LayoutParams) container.getLayoutParams();
// add flag
p.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
p.dimAmount = 0.3f;
wm.updateViewLayout(container, p);

Without background:

PopupWindow popup = new PopupWindow(contentView, width, height);
popup.setBackgroundDrawable(null);
popup.showAsDropDown(anchor);

WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams p = (WindowManager.LayoutParams) contentView.getLayoutParams();
// add flag
p.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
p.dimAmount = 0.3f;
wm.updateViewLayout(contentView, p);

Marshmallow Update:

On M PopupWindow wraps the contentView inside a FrameLayout called mDecorView. If you dig into the PopupWindow source you will find something like createDecorView(View contentView).The main purpose of mDecorView is to handle event dispatch and content transitions, which are new to M. This means we need to add one more .getParent() to access the container.

With background that would require a change to something like:

View container = (View) popup.getContentView().getParent().getParent();

Better alternative for API 18+

A less hacky solution using ViewGroupOverlay:

1) Get a hold of the desired root layout

ViewGroup root = (ViewGroup) getWindow().getDecorView().getRootView();

2) Call applyDim(root, 0.5f); or clearDim()

public static void applyDim(@NonNull ViewGroup parent, float dimAmount){
    Drawable dim = new ColorDrawable(Color.BLACK);
    dim.setBounds(0, 0, parent.getWidth(), parent.getHeight());
    dim.setAlpha((int) (255 * dimAmount));

    ViewGroupOverlay overlay = parent.getOverlay();
    overlay.add(dim);
}

public static void clearDim(@NonNull ViewGroup parent) {
    ViewGroupOverlay overlay = parent.getOverlay();
    overlay.clear();
}

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

_x000D_
_x000D_
 function exportToExcel() {_x000D_
        var tab_text = "<tr bgcolor='#87AFC6'>";_x000D_
        var textRange; var j = 0, rows = '';_x000D_
        tab = document.getElementById('student-detail');_x000D_
        tab_text = tab_text + tab.rows[0].innerHTML + "</tr>";_x000D_
        var tableData = $('#student-detail').DataTable().rows().data();_x000D_
        for (var i = 0; i < tableData.length; i++) {_x000D_
            rows += '<tr>'_x000D_
                + '<td>' + tableData[i].value1 + '</td>'_x000D_
                + '<td>' + tableData[i].value2 + '</td>'_x000D_
                + '<td>' + tableData[i].value3 + '</td>'_x000D_
                + '<td>' + tableData[i].value4 + '</td>'_x000D_
                + '<td>' + tableData[i].value5 + '</td>'_x000D_
                + '<td>' + tableData[i].value6 + '</td>'_x000D_
                + '<td>' + tableData[i].value7 + '</td>'_x000D_
                + '<td>' +  tableData[i].value8 + '</td>'_x000D_
                + '<td>' + tableData[i].value9 + '</td>'_x000D_
                + '<td>' + tableData[i].value10 + '</td>'_x000D_
                + '</tr>';_x000D_
        }_x000D_
        tab_text += rows;_x000D_
        var data_type = 'data:application/vnd.ms-excel;base64,',_x000D_
            template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table border="2px">{table}</table></body></html>',_x000D_
            base64 = function (s) {_x000D_
                return window.btoa(unescape(encodeURIComponent(s)))_x000D_
            },_x000D_
            format = function (s, c) {_x000D_
                return s.replace(/{(\w+)}/g, function (m, p) {_x000D_
                    return c[p];_x000D_
                })_x000D_
            }_x000D_
_x000D_
        var ctx = {_x000D_
            worksheet: "Sheet 1" || 'Worksheet',_x000D_
            table: tab_text_x000D_
        }_x000D_
        document.getElementById("dlink").href = data_type + base64(format(template, ctx));_x000D_
        document.getElementById("dlink").download = "StudentDetails.xls";_x000D_
        document.getElementById("dlink").traget = "_blank";_x000D_
        document.getElementById("dlink").click();_x000D_
    }
_x000D_
_x000D_
_x000D_

Here Value 1 to 10 are column names that you are getting

How do I increase the cell width of the Jupyter/ipython notebook in my browser?

To get this to work with jupyter (version 4.0.6) I created ~/.jupyter/custom/custom.css containing:

/* Make the notebook cells take almost all available width */
.container {
    width: 99% !important;
}   

/* Prevent the edit cell highlight box from getting clipped;
 * important so that it also works when cell is in edit mode*/
div.cell.selected {
    border-left-width: 1px !important;
}

What Process is using all of my disk IO

atop also works well and installs easily even on older CentOS 5.x systems which can't run iotop. Hit d to show disk details, ? for help.

ATOP - mybox                           2014/09/08  15:26:00                           ------                            10s elapsed
PRC |  sys    0.33s |  user   1.08s |                | #proc    161  |  #zombie    0 |  clones    31 |                | #exit         16  |
CPU |  sys   4% |  user     11% |  irq       0%  | idle    306%  |  wait     79% |               |  steal     1%  | guest     0%  |
cpu |  sys   2% |  user      8% |  irq       0%  | idle     11%  |  cpu000 w 78% |               |  steal     0%  | guest     0%  |
cpu |  sys   1% |  user      1% |  irq       0%  | idle     98%  |  cpu001 w  0% |               |  steal     0%  | guest     0%  |
cpu |  sys   1% |  user      1% |  irq       0%  | idle     99%  |  cpu003 w  0% |               |  steal     0%  | guest     0%  |
cpu |  sys   0% |  user      1% |  irq       0%  | idle     99%  |  cpu002 w  0% |               |  steal     0%  | guest     0%  |
CPL |  avg1    2.09 |  avg5    2.09 |  avg15   2.09  |               |  csw    54184 |  intr   33581 |                | numcpu     4  |
MEM |  tot     8.0G |  free   81.9M |  cache   2.9G  | dirty   0.8M  |  buff  174.7M |  slab  305.0M |                |               |
SWP |  tot     2.0G |  free    2.0G |                |               |               |               |  vmcom   8.4G  | vmlim   6.0G  |
LVM |  Group00-root |  busy     85% |  read       0  | write  30658  |  KiB/w      4 |  MBr/s   0.00 |  MBw/s  11.98  | avio 0.28 ms  |
DSK |          xvdb |  busy     85% |  read       0  | write  23706  |  KiB/w      5 |  MBr/s   0.00 |  MBw/s  11.97  | avio 0.36 ms  |
NET |  transport    |  tcpi    2705 |  tcpo    2008  | udpi      36  |  udpo      43 |  tcpao     14 |  tcppo     45  | tcprs      1  |
NET |  network      |  ipi     2788 |  ipo     2072  | ipfrw      0  |  deliv   2768 |               |  icmpi      7  | icmpo     20  |
NET |  eth0    ---- |  pcki    2344 |  pcko    1623  | si 1455 Kbps  |  so  781 Kbps |  erri       0 |  erro       0  | drpo       0  |
NET |  lo      ---- |  pcki     423 |  pcko     423  | si   88 Kbps  |  so   88 Kbps |  erri           0 |  erro       0  | drpo       0  |
NET |  eth1    ---- |  pcki  22 |  pcko      26  | si    3 Kbps  |  so    5 Kbps |  erri       0 |  erro       0  | drpo       0  |

  PID                   RDDSK                    WRDSK                   WCANCL                    DSK                   CMD        1/1
 9862                      0K                   53124K                       0K                    98%                   java
  358                      0K                     636K                       0K                     1%                   jbd2/dm-0-8
13893                      0K                     192K                      72K                     0%                   java
 1699                      0K                      60K                       0K                     0%                   syslogd
 4668                      0K                      24K                       0K                     0%                   zabbix_agentd

This clearly shows java pid 9862 is the culprit.

Adding items to end of linked list

The above programs might give you NullPointerException. This is an easier way to add an element to the end of linkedList.

public class LinkedList {
    Node head;

    public static class Node{
        int data;
        Node next;

        Node(int item){
            data = item;
            next = null;
        }
    }
    public static void main(String args[]){
        LinkedList ll = new LinkedList();
        ll.head = new Node(1);
        Node second = new Node(2);
        Node third = new Node(3);
        Node fourth = new Node(4);

        ll.head.next = second;
        second.next = third;
        third.next = fourth;
        fourth.next = null;

        ll.printList();
        System.out.println("Add element 100 to the last");
        ll.addLast(100);
        ll.printList();
    }
    public void printList(){
        Node t = head;
        while(n != null){
            System.out.println(t.data);
            t = t.next;
        }

    }

    public void addLast(int item){
        Node new_item = new Node(item);
        if(head == null){
            head = new_item;
            return;
        }
        new_item.next = null;

        Node last = head;
        Node temp = null;
        while(last != null){
            if(last != null)
                temp = last;
            last = last.next;
        }   

        temp.next = new_item;   
        return;
    }
}

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

export DOCKER_HOST=tcp://localhost:2375 is perfect for anyone who doesn't have sudo access and the user doesn't have access to unix:///var/run/docker.sock

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

you can return a FileResult from your MVC action.

*********************MVC action************

    public FileResult OpenPDF(parameters)
    {
       //code to fetch your pdf byte array
       return File(pdfBytes, "application/pdf");
    }

**************js**************

Use formpost to post your data to action

    var inputTag = '<input name="paramName" type="text" value="' + payloadString + '">';
    var form = document.createElement("form");
    jQuery(form).attr("id", "pdf-form").attr("name", "pdf-form").attr("class", "pdf-form").attr("target", "_blank");
    jQuery(form).attr("action", "/Controller/OpenPDF").attr("method", "post").attr("enctype", "multipart/form-data");
    jQuery(form).append(inputTag);
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
    return false;

You need to create a form to post your data, append it your dom, post your data and remove the form your document body.

However, form post wouldn't post data to new tab only on EDGE browser. But a get request works as it's just opening new tab with a url containing query string for your action parameters.

How to get the value from the GET parameters?

this question has too many answers, so i'm adding another one.

/**
 * parses and returns URI query parameters 
 * 
 * @param {string} param parm
 * @param {bool?} asArray if true, returns an array instead of a scalar 
 * @returns {Object|Array} 
 */
function getURIParameter(param, asArray) {
    return document.location.search.substring(1).split('&').reduce(function(p,c) {
        var parts = c.split('=', 2).map(function(param) { return decodeURIComponent(param); });
        if(parts.length == 0 || parts[0] != param) return (p instanceof Array) && !asArray ? null : p;
        return asArray ? p.concat(parts.concat(true)[1]) : parts.concat(true)[1];
    }, []);
}

usage:

getURIParameter("id")  // returns the last id or null if not present
getURIParameter("id", true) // returns an array of all ids

this copes with empty parameters (those keys present without "=value"), exposure of both a scalar and array-based value retrieval API, as well as proper URI component decoding.

Catch paste input

This code is working for me either paste from right click or direct copy paste

   $('.textbox').on('paste input propertychange', function (e) {
        $(this).val( $(this).val().replace(/[^0-9.]/g, '') );
    })

When i paste Section 1: Labour Cost it becomes 1 in text box.

To allow only float value i use this code

 //only decimal
    $('.textbox').keypress(function(e) {
        if(e.which == 46 && $(this).val().indexOf('.') != -1) {
            e.preventDefault();
        } 
       if (e.which == 8 || e.which == 46) {
            return true;
       } else if ( e.which < 48 || e.which > 57) {
            e.preventDefault();
      }
    });

/usr/bin/codesign failed with exit code 1

If the error immediately preceding the codesign error says something like 'resource fork, Finder information, or similar detritus not allowed'

Then navigate to the .app file in Terminal and type:

xattr -cr < path_to_app_bundle >

ref: https://developer.apple.com/library/content/qa/qa1940/_index.html

Using success/error/finally/catch with Promises in AngularJS

What type of granularity are you looking for? You can typically get by with:

$http.get(url).then(
  //success function
  function(results) {
    //do something w/results.data
  },
  //error function
  function(err) {
    //handle error
  }
);

I've found that "finally" and "catch" are better off when chaining multiple promises.

C# Inserting Data from a form into an access Database

 private void Add_Click(object sender, EventArgs e) {
 OleDbConnection con = new OleDbConnection(@ "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\HP\Desktop\DS Project.mdb");
 OleDbCommand cmd = con.CreateCommand();
 con.Open();
 cmd.CommandText = "Insert into DSPro (Playlist) values('" + textBox1.Text + "')";
 cmd.ExecuteNonQuery();
 MessageBox.Show("Record Submitted", "Congrats");
 con.Close();
} 

Update Fragment from ViewPager

Update Fragment from ViewPager

You need to implement getItemPosition(Object obj) method.

This method is called when you call

notifyDataSetChanged()

on your ViewPagerAdaper. Implicitly this method returns POSITION_UNCHANGED value that means something like this: "Fragment is where it should be so don't change anything."

So if you need to update Fragment you can do it with:

  • Always return POSITION_NONE from getItemPosition() method. It which means: "Fragment must be always recreated"
  • You can create some update() method that will update your Fragment(fragment will handle updates itself)

Example of second approach:

public interface Updateable {
   public void update();
}


public class MyFragment extends Fragment implements Updateable {

   ...

   public void update() {
     // do your stuff
   }
}

And in FragmentPagerAdapter you'll do something like this:

@Override
public int getItemPosition(Object object) {
   MyFragment f = (MyFragment ) object;
   if (f != null) {
      f.update();
   }
  return super.getItemPosition(object);
}

And if you'll choose first approach it can looks like:

@Override
public int getItemPosition(Object object) {
   return POSITION_NONE;
}

Note: It's worth to think a about which approach you'll pick up.

What's the maximum value for an int in PHP?

It depends on your OS, but 2147483647 is the usual value, according to the manual.

Show a popup/message box from a Windows batch file

A better option

set my_message=Hello world&& start cmd /c "@echo off & mode con cols=15 lines=2 & echo %my_message% & pause>nul"


Description:
lines= amount of lines,plus 1
cols= amount of characters in the message, plus 3 (However, minimum must be 15)

Auto-calculated cols version:

set my_message=Hello world&& (echo %my_message%>EMPTY_FILE123 && FOR %? IN (EMPTY_FILE123 ) DO SET strlength=%~z? && del EMPTY_FILE123 ) && start cmd /c "@echo off && mode con lines=2 cols=%strlength% && echo %my_message% && pause>nul"

How to use Apple's new .p8 certificate for APNs in firebase console

You can create the .p8 file for it in https://developer.apple.com/account/

Then go to Certificates, Identifiers & Profiles > Keys > add

apple_key

Select Apple Push Notification service (APNs), put a Key Name (whatever).

Then click on "continue", after "register" and you get it and you can download it.

How to set the title text color of UIButton?

referring to radio buttons ,you can also do it with Segmented Control as following:

step 1: drag a segmented control to your view in the attribute inspector change the title of the two segments ,for example "Male" and "Female"

step 2: create an outlet & an action for it in the code

step 3: create a variable for future use to contain choice's data

in the code do as following:

@IBOutlet weak var genderSeg: UISegmentedControl!

var genderPick : String = ""


 @IBAction func segAction(_ sender: Any) {

    if genderSeg.selectedSegmentIndex == 0 {
         genderPick = "Male"
        print(genderPick)
    } else if genderSeg.selectedSegmentIndex == 1 {
        genderPick = "Female"
          print(genderPick)
    }
}

C# declare empty string array

You can try this

string[] arr = {};

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

This way also you can achieve desired output

_x000D_
_x000D_
var jsonobj={};_x000D_
var count=0;_x000D_
$(document).on('click','#btnadd', function() {_x000D_
    jsonobj[count]=new Array({ "1"  : $("#txtone").val()},{ "2"  : $("#txttwo").val()});_x000D_
    count++;_x000D_
    console.clear();_x000D_
    console.log(jsonobj);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span>value 1</span><input id="txtone" type="text"/>_x000D_
<span>value 2</span><input id="txttwo" type="text"/>_x000D_
<button id="btnadd">Add</button>
_x000D_
_x000D_
_x000D_

JavaScript string newline character?

A note - when using ExtendScript JavaScript (the Adobe Scripting language used in applications like Photoshop CS3+), the character to use is "\r". "\n" will be interpreted as a font character, and many fonts will thus have a block character instead.

For example (to select a layer named 'Note' and add line feeds after all periods):

var layerText = app.activeDocument.artLayers.getByName('Note').textItem.contents;
layerText = layerText.replace(/\. /g,".\r");

System.Security.SecurityException when writing to Event Log

Same issue on Windows 7 64bits. Run as administrator solved the problem.

How do I directly modify a Google Chrome Extension File? (.CRX)

Now Chrome is multi-user so Extensions should be nested under the OS user profile then the Chrome user profile, My first Chrome user was called Profile 1, my Extensions path was C:\Users\ username \AppData\Local\Google\Chrome\User Data\ Profile 1 \Extensions\.

To find yours Navigate to chrome://version/ (I use about: out of laziness).

Notice the Profile Path and just append \Extensions\ and you have yours.

Hope this brings this info on this question up to date more.

Plot a horizontal line using matplotlib

If you want to draw a horizontal line in the axes, you might also try ax.hlines() method. You need to specify y position and xmin and xmax in the data coordinate (i.e, your actual data range in the x-axis). A sample code snippet is:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1, 21, 200)
y = np.exp(-x)

fig, ax = plt.subplots()
ax.plot(x, y)
ax.hlines(y=0.2, xmin=4, xmax=20, linewidth=2, color='r')

plt.show()

The snippet above will plot a horizontal line in the axes at y=0.2. The horizontal line starts at x=4 and ends at x=20. The generated image is:

enter image description here

Can you get a Windows (AD) username in PHP?

You can say getenv('USERNAME')

Insert json file into mongodb

Use

mongoimport --jsonArray --db test --collection docs --file example2.json

Its probably messing up because of the newline characters.

MySQL Error 1215: Cannot add foreign key constraint

I had the same error once. I just simply restarted the MySQL server and fixed the problem.

extract date only from given timestamp in oracle sql

In Oracle 11g, To get the complete date from the Timestamp, use this-

Select TRUNC(timestamp) FROM TABLE_NAME;

To get the Year from the Timestamp, use this-

Select EXTRACT(YEAR FROM TRUNC(timestamp)) from TABLE_NAME;

To get the Month from the Timestamp, use this-

Select EXTRACT(MONTH FROM TRUNC(timestamp)) from TABLE_NAME;

To get the Day from the Timestamp, use this-

Select EXTRACT(DAY FROM TRUNC(timestamp)) from TABLE_NAME;

How to use sbt from behind proxy?

Using

sbt -Dhttp.proxyHost=yourServer-Dhttps.proxyHost=yourServer -Dhttp.proxyPort=yourPort -Dhttps.proxyPort=yourPort

works in Ubuntu 15.10 x86_64 x86_64 GNU/Linux.

Replace yourServer by the proper address without the http:// nor https:// prefixes in Dhttp and Dhttps, respectively. Remember to avoid the quotation marks. No usr/pass included in the code-line, to include that just add -Dhttp.proxyUser=usr -Dhttp.proxyPassword=pass with the same typing criteria. Thanks @Jacek Laskowski!. Cheers

Cannot construct instance of - Jackson

You need to use a concrete class and not an Abstract class while deserializing. if the Abstract class has several implementations then, in that case, you can use it as below-

  @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
    @JsonSubTypes({ 
      @Type(value = Bike.class, name = "bike"), 
      @Type(value = Auto.class, name = "auto"), 
      @Type(value = Car.class, name = "car")
    })
    public abstract class Vehicle {
        // fields, constructors, getters, setters
    }

Do standard windows .ini files allow comments?

USE A SEMI-COLON AT BEGINING OF LINE --->> ; <<---

Ex.

; last modified 1 April 2001 by John Doe
[owner]
name=John Doe
organization=Acme Widgets Inc.

How to do a redirect to another route with react-router?

With react-router v2.8.1 (probably other 2.x.x versions as well, but I haven't tested it) you can use this implementation to do a Router redirect.

import { Router } from 'react-router';

export default class Foo extends Component {

  static get contextTypes() {
    return {
      router: React.PropTypes.object.isRequired,
    };
  }

  handleClick() {
    this.context.router.push('/some-path');
  }
}

How to concatenate two numbers in javascript?

I'd prefer the concat way :

const numVar1 = 5;
const numVar2 = 6;
const value = "".concat(numVar1, numVar2);
// or directly with values
const value2 = "".concat(5, 6);

You can also use an array which can help in some use cases :

const value3 = [5, 6, numVar1].join('');

Get Windows version in a batch file

On more recent versions (win 7 onwards) you can have powershell do the job for you.

for /F %%i in ('powershell -command "& {$([System.Environment]::OSVersion.Version.Major),$([System.Environment]::OSVersion.Version.Minor) -join '.' }"') do set VER=%%i

goto %VER%


:6.1
REM specific code for windows 7

:10.0
REM specific code for windows 10

see this table for version numbers

Check if date is a valid one

How to check if a string is a valid date using Moment, when the date and date format are different

Sorry, but did any of the given solutions on this thread actually answer the question that was asked?

I have a String date and a date format which is different. Ex.: date: 2016-10-19 dateFormat: "DD-MM-YYYY". I need to check if this date is a valid date.

The following works for me...

const date = '2016-10-19';
const dateFormat = 'DD-MM-YYYY';
const toDateFormat = moment(new Date(date)).format(dateFormat);
moment(toDateFormat, dateFormat, true).isValid();

// Note: `new Date()` circumvents the warning that
// Moment throws (https://momentjs.com/guides/#/warnings/js-date/),
// but may not be optimal.

But honestly, don't understand why moment.isDate()(as documented) only accepts an object. Should also support a string in my opinion.

No tests found with test runner 'JUnit 4'

There are two reasons for this Exception:

  1. The source code hasn’t been compiled YET.
  2. Or on the contrary, the source code has been compiled BUT it cannot been found by JUnit.

For reason one, it has no leg to stand. Because like many people said: the ‘old’ methods work perfectly. Only the new-added methods cannot been identified. Then the second reason became the only explanation: JUnit can NOT find the freshly compiled classes. Having that in mind, I did this: Right click the project ->Java Build Path -> Edit Source item: project_name/src/test/java’s Output folder, change the Output folder into a ‘Specific output folder(path relative to project_name). Provide this value: target/test-class. Be hold: This is the default test source codes’ output folder defined by Maven. It has been overwrote by M2E (or me). That’s why JUnit cannot find it. So my guess is many people who had run into this lovely exception are most likely dealing with a Web project which is managed by Maven. Am I right?! This also contributed my conclusion that reason one should be excluded -- “old” methods can be found is because they had been automatically compiled when the Tomcat was (re)started. Into the ‘wrong’ path maybe, but JUnit found it anyway.

Before I had figured this out. I tried many things as advised: update to the latest JUnit4, Back and forth between build path and use as source folder, capital Test vs test, etc. Nothing happened until I specifically identified the output location for the test source. With all those explanation, my second reason should be re-phrased as this: the new codes had not been timely compiled to the right path! Good luck.

Evenly space multiple views within a container view

I am having a similar problem and discovered this post. However, none of the currently provided answers solve the problem in the way you want. They don't make the spacing equally, but rather distribute the center of the labels equally. It is important to understand that this is not the same. I've constructed a little diagram to illustrate this.

View Spacing Illustration

There are 3 views, all 20pt tall. Using any of the suggested methods equally distributes the centers of the views and give you the illustrated layout. Notice that the y-center of the views are spaced equally. However, the spacing between superview and top view is 15pt, while the spacing between the subviews is just 5pt. To have the views spaced equally these should both be 10pt, i.e. all blue arrows should be 10pt.

Nevertheless, I haven't come up with a good generic solution, yet. Currently my best idea is to insert "spacing views" between the subviews and setting the heights of the spacing views to be equal.

Iterate through the fields of a struct in Go

After you've retrieved the reflect.Value of the field by using Field(i) you can get a interface value from it by calling Interface(). Said interface value then represents the value of the field.

There is no function to convert the value of the field to a concrete type as there are, as you may know, no generics in go. Thus, there is no function with the signature GetValue() T with T being the type of that field (which changes of course, depending on the field).

The closest you can achieve in go is GetValue() interface{} and this is exactly what reflect.Value.Interface() offers.

The following code illustrates how to get the values of each exported field in a struct using reflection (play):

import (
    "fmt"
    "reflect"
)

func main() {
    x := struct{Foo string; Bar int }{"foo", 2}

    v := reflect.ValueOf(x)

    values := make([]interface{}, v.NumField())

    for i := 0; i < v.NumField(); i++ {
        values[i] = v.Field(i).Interface()
    }

    fmt.Println(values)
}

Convert INT to DATETIME (SQL)

Try this:

select CONVERT(datetime, convert(varchar(10), 20120103))

Iterating on a file doesn't work the second time

The file object is a buffer. When you read from the buffer, that portion that you read is consumed (the read position is shifted forward). When you read through the entire file, the read position is at the end of the file (EOF), so it returns nothing because there is nothing left to read.

If you have to reset the read position on a file object for some reason, you can do:

f.seek(0)

How to to send mail using gmail in Laravel?

first login to your gmail account and under My account > Sign In And Security > Sign In to google, enable two step verification, then you can generate app password, and you can use that app password in .env file.

Your .env file will then look something like this

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=apppassword
MAIL_ENCRYPTION=tls

Don't forget to run php artisan config:cache after you make changes in your .env file.

Strange "java.lang.NoClassDefFoundError" in Eclipse

When you launch your program, it stores the launch configuration that you may latter modify. If something changed in your build/run process, you may have wrong settings. For example I used to work with maven, and some launch configuration reference a maven2_classpath_container. When deleting the launch configuration and running the program again, it can work again.

Xcode project not showing list of simulators

Cmd below solved my problem:

$ sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

In my case, I upgraded to Xcode 8 and downloaded another version 7.3.1 later (renamed it to "Xcode 7.3.1"), then cannot get the simulator list in Xcode 8.

How to access Spring context in jUnit tests annotated with @RunWith and @ContextConfiguration?

If your test class extends the Spring JUnit classes
(e.g., AbstractTransactionalJUnit4SpringContextTests or any other class that extends AbstractSpringContextTests), you can access the app context by calling the getContext() method.
Check out the javadocs for the package org.springframework.test.

Can I dispatch an action in reducer?

Starting another dispatch before your reducer is finished is an anti-pattern, because the state you received at the beginning of your reducer will not be the current application state anymore when your reducer finishes. But scheduling another dispatch from within a reducer is NOT an anti-pattern. In fact, that is what the Elm language does, and as you know Redux is an attempt to bring the Elm architecture to JavaScript.

Here is a middleware that will add the property asyncDispatch to all of your actions. When your reducer has finished and returned the new application state, asyncDispatch will trigger store.dispatch with whatever action you give to it.

// This middleware will just add the property "async dispatch" to all actions
const asyncDispatchMiddleware = store => next => action => {
  let syncActivityFinished = false;
  let actionQueue = [];

  function flushQueue() {
    actionQueue.forEach(a => store.dispatch(a)); // flush queue
    actionQueue = [];
  }

  function asyncDispatch(asyncAction) {
    actionQueue = actionQueue.concat([asyncAction]);

    if (syncActivityFinished) {
      flushQueue();
    }
  }

  const actionWithAsyncDispatch =
    Object.assign({}, action, { asyncDispatch });

  const res = next(actionWithAsyncDispatch);

  syncActivityFinished = true;
  flushQueue();

  return res;
};

Now your reducer can do this:

function reducer(state, action) {
  switch (action.type) {
    case "fetch-start":
      fetch('wwww.example.com')
        .then(r => r.json())
        .then(r => action.asyncDispatch({ type: "fetch-response", value: r }))
      return state;

    case "fetch-response":
      return Object.assign({}, state, { whatever: action.value });;
  }
}

Using jQuery to compare two arrays of Javascript objects

My approach was quite different - I flattened out both collections using JSON.stringify and used a normal string compare to check for equality.

I.e.

var arr1 = [
             {Col: 'a', Val: 1}, 
             {Col: 'b', Val: 2}, 
             {Col: 'c', Val: 3}
           ];

var arr2 = [
             {Col: 'x', Val: 24}, 
             {Col: 'y', Val: 25}, 
             {Col: 'z', Val: 26}
           ];

if(JSON.stringify(arr1) == JSON.stringify(arr2)){
    alert('Collections are equal');
}else{
    alert('Collections are not equal');
}

NB: Please note that his method assumes that both Collections are sorted in a similar fashion, if not, it would give you a false result!

Create a rounded button / button with border-radius in Flutter

One of the simplest ways to create a rounded button is to use a FlatButton and then specify the roundness by setting its shape property. Follow the code below

_x000D_
_x000D_
FlatButton(
  padding: EdgeInsets.all(30.0),
  color: Colors.black,
  shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.circular(20.0)),
  child: child: Text(
    "Button",
    style: TextStyle(color: Colors.white),
  ),
  onPressed: () {
    print('Button pressed');
  },
),
_x000D_
_x000D_
_x000D_

Note: In order to change the roundness adjust the value inside BorderRadius.circular()

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

Java List.contains(Object with field value equal to x)

Binary Search

You can use Collections.binarySearch to search an element in your list (assuming the list is sorted):

Collections.binarySearch(list, new YourObject("a1", "b",
                "c"), new Comparator<YourObject>() {

            @Override
            public int compare(YourObject o1, YourObject o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

which will return a negative number if the object is not present in the collection or else it will return the index of the object. With this you can search for objects with different searching strategies.

How can I reverse a NSArray in Objective-C?

I don't know of any built in method. But, coding by hand is not too difficult. Assuming the elements of the array you are dealing with are NSNumber objects of integer type, and 'arr' is the NSMutableArray that you want to reverse.

int n = [arr count];
for (int i=0; i<n/2; ++i) {
  id c  = [[arr objectAtIndex:i] retain];
  [arr replaceObjectAtIndex:i withObject:[arr objectAtIndex:n-i-1]];
  [arr replaceObjectAtIndex:n-i-1 withObject:c];
}

Since you start with a NSArray then you have to create the mutable array first with the contents of the original NSArray ('origArray').

NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr setArray:origArray];

Edit: Fixed n -> n/2 in the loop count and changed NSNumber to the more generic id due to the suggestions in Brent's answer.

How to alter a column's data type in a PostgreSQL table?

If data already exists in the column you should do:

ALTER TABLE tbl_name ALTER COLUMN col_name TYPE integer USING col_name::integer;

As pointed out by @nobu and @jonathan-porter in comments to @derek-kromm's answer.

Change default icon

Go to the Project properties Build the project Locate the .exe file in your favorite file explorer.

Youtube - How to force 480p video quality in embed link / <iframe>

You can use the YouTube JavaScript player API, which has a feature on its own to set playback quality.

player.setPlaybackQuality(suggestedQuality:String):Void

This function sets the suggested video quality for the current video. The function causes the video to reload at its current position in the new quality. If the playback quality does change, it will only change for the video being played. Calling this function does not guarantee that the playback quality will actually change. However, if the playback quality does change, the onPlaybackQualityChange event will fire, and your code should respond to the event rather than the fact that it called the setPlaybackQuality function. [source]

The type or namespace name 'DbContext' could not be found

I had this problem, read the above answer and download the entityframework.ddl but found that it is alreadt referenced. So I added the namespace and problem was solved

using System.Data.Entity;

I am using Visual Studio 2010, SP1 installed

Xcode is not currently available from the Software Update server

Had the same issue and was getting the same error. When i ran xcode-select -p, it gave output as /Library/Developer/CommandLineTools. So that means xcode was already installed in my system. Then i ran steps as given on this answer. After which any command which required xcode ran successfully.

How do I convert array of Objects into one Object in JavaScript?

Using Underscore.js:

var myArray = [
  Object { key="11", value="1100", $$hashKey="00X"},
  Object { key="22", value="2200", $$hashKey="018"}
];
var myObj = _.object(_.pluck(myArray, 'key'), _.pluck(myArray, 'value'));

How do I scroll to an element using JavaScript?

The best, shortest answer that what works even with animation effects:

var scrollDiv = document.getElementById("myDiv").offsetTop;
window.scrollTo({ top: scrollDiv, behavior: 'smooth'});

If you have a fixed nav bar, just subtract its height from top value, so if your fixed bar height is 70px, line 2 will look like:

window.scrollTo({ top: scrollDiv-70, behavior: 'smooth'});

Explanation: Line 1 gets the element position Line 2 scroll to element position; behavior property adds a smooth animated effect

How to avoid reverse engineering of an APK file?

 1. How can I completely avoid reverse engineering of an Android APK? Is this possible?

Impossible

 2. How can I protect all the app's resources, assets and source code so that hackers can't hack the APK file in any way?

Impossible

 3. Is there a way to make hacking more tough or even impossible? What more can I do to protect the source code in my APK file?

More tough - possible, but in fact it will be more tough mostly for the average user, who is just googling for hacking guides. If somebody really wants to hack your app - it will be hacked, sooner or later.

Printing reverse of any String without using any predefined function?

This is the simplest solution:

System.out.print("egaugnal detatneiro tcejbo si avaj");

How to handle click event in Button Column in Datagridview?

just add ToList() method to end of your list, where bind to datagridview DataSource:

dataGridView1.DataSource = MyList.ToList();

setting the id attribute of an input element dynamically in IE: alternative for setAttribute method

I had the same issue! I was unable to change/set the ID attribute of elements. It worked in all other browsers but not IE. It probably isn't relevant to your problem but here is what I ended up doing:

Background

I was building an MVC site with jquery tabs. I wanted to create tabs dynamically and do an AJAX postback to the server saving the tab in the database. I wanted to use a unique identifier, in the form of an int, for the tabs so I wouldn't get in to trouble if a user created two tabs with the same name. I then used the unique ID to identify the tabs like:

<ul>
<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close'>Remove List</span></li>
<ul>

When I then implemented the remove functions on the tabs the callback uses the index, witch is 0 based. Then I had no way to sending back the unique ID to the server to trash the DB entry. The callback for the tabremove event gives the jquery event and ui parameters. With one line of code I could get the ID of the span:

var dbIndex = event.currentTarget.id;

The problem was that the span tag didn't have any ID. So in the create callback I tried to set the ID buy extracting the ID from the a href like this:

ui.tab.parentNode.id = ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6);

That worked fine in FireFox but not in IE. So I tried a few other:

//ui.tab.parentNode.setAttribute('id', ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6));
//$(ui.tab.parentNode).attr({'id':ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6)});
//ui.tab.parentNode.id.value = ui.tab.href.substring(ui.tab.href.indexOf('#list-') + 6);

None of them worked! So after a few hours of test and Googeling I gave up and draw the conclusion that IE cant set the ID attribute of an element dynamically.

As I sad this is probably not relevant to your issue but I thought I would share.

Solution

And for all of you who found this by Googleing on the tabs issue I had here is what I ended up doing in the tabsremove callback to solve the issue:

var dbIndex = event.currentTarget.offsetParent.childNodes[0].href.substring(event.currentTarget.offsetParent.childNodes[0].href.indexOf('#list-') + 6);

Probably not the sexiest solution but hey it solved the issue. If anyone have any input please share...

Convert HTML string to image

Thanks all for your responses. I used HtmlRenderer external dll (library) to achieve the same and found below code for the same.

Here is the code for this

public void ConvertHtmlToImage()
{
   Bitmap m_Bitmap = new Bitmap(400, 600);
   PointF point = new PointF(0, 0);
   SizeF maxSize = new System.Drawing.SizeF(500, 500);
   HtmlRenderer.HtmlRender.Render(Graphics.FromImage(m_Bitmap),
                                           "<html><body><p>This is some html code</p>"
                                           + "<p>This is another html line</p></body>",
                                            point, maxSize);

   m_Bitmap.Save(@"C:\Test.png", ImageFormat.Png);
}

Accessing last x characters of a string in Bash

Last three characters of string:

${string: -3}

or

${string:(-3)}

(mind the space between : and -3 in the first form).

Please refer to the Shell Parameter Expansion in the reference manual:

${parameter:offset}
${parameter:offset:length}

Expands to up to length characters of parameter starting at the character
specified by offset. If length is omitted, expands to the substring of parameter
starting at the character specified by offset. length and offset are arithmetic
expressions (see Shell Arithmetic). This is referred to as Substring Expansion.

If offset evaluates to a number less than zero, the value is used as an offset
from the end of the value of parameter. If length evaluates to a number less than
zero, and parameter is not ‘@’ and not an indexed or associative array, it is
interpreted as an offset from the end of the value of parameter rather than a
number of characters, and the expansion is the characters between the two
offsets. If parameter is ‘@’, the result is length positional parameters
beginning at offset. If parameter is an indexed array name subscripted by ‘@’ or
‘*’, the result is the length members of the array beginning with
${parameter[offset]}. A negative offset is taken relative to one greater than the
maximum index of the specified array. Substring expansion applied to an
associative array produces undefined results.

Note that a negative offset must be separated from the colon by at least one
space to avoid being confused with the ‘:-’ expansion. Substring indexing is
zero-based unless the positional parameters are used, in which case the indexing
starts at 1 by default. If offset is 0, and the positional parameters are used,
$@ is prefixed to the list.

Since this answer gets a few regular views, let me add a possibility to address John Rix's comment; as he mentions, if your string has length less than 3, ${string: -3} expands to the empty string. If, in this case, you want the expansion of string, you may use:

${string:${#string}<3?0:-3}

This uses the ?: ternary if operator, that may be used in Shell Arithmetic; since as documented, the offset is an arithmetic expression, this is valid.


Update for a POSIX-compliant solution

The previous part gives the best option when using Bash. If you want to target POSIX shells, here's an option (that doesn't use pipes or external tools like cut):

# New variable with 3 last characters removed
prefix=${string%???}
# The new string is obtained by removing the prefix a from string
newstring=${string#"$prefix"}

One of the main things to observe here is the use of quoting for prefix inside the parameter expansion. This is mentioned in the POSIX ref (at the end of the section):

The following four varieties of parameter expansion provide for substring processing. In each case, pattern matching notation (see Pattern Matching Notation), rather than regular expression notation, shall be used to evaluate the patterns. If parameter is '#', '*', or '@', the result of the expansion is unspecified. If parameter is unset and set -u is in effect, the expansion shall fail. Enclosing the full parameter expansion string in double-quotes shall not cause the following four varieties of pattern characters to be quoted, whereas quoting characters within the braces shall have this effect. In each variety, if word is omitted, the empty pattern shall be used.

This is important if your string contains special characters. E.g. (in dash),

$ string="hello*ext"
$ prefix=${string%???}
$ # Without quotes (WRONG)
$ echo "${string#$prefix}"
*ext
$ # With quotes (CORRECT)
$ echo "${string#"$prefix"}"
ext

Of course, this is usable only when then number of characters is known in advance, as you have to hardcode the number of ? in the parameter expansion; but when it's the case, it's a good portable solution.

How to get Wikipedia content using Wikipedia's API?

See Is there a clean wikipedia API just for retrieve content summary? for other proposed solutions. Here is one that I suggested:

There is actually a very nice prop called extracts that can be used with queries designed specifically for this purpose. Extracts allow you to get article extracts (truncated article text). There is a parameter called exintro that can be used to retrieve the text in the zeroth section (no additional assets like images or infoboxes). You can also retrieve extracts with finer granularity such as by a certain number of characters (exchars) or by a certain number of sentences(exsentences)

Here is a sample query http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=Stack%20Overflow and the API sandbox http://en.wikipedia.org/wiki/Special:ApiSandbox#action=query&prop=extracts&format=json&exintro=&titles=Stack%20Overflow to experiment more with this query.

Please note that if you want the first paragraph specifically you still need to get the first tag. However in this API call there are no additional assets like images to parse. If you are satisfied with this intro summary you can retrieve the text by running a function like php's strip_tag that remove the html tags.

How to replace specific values in a oracle database column?

In Oracle, there is the concept of schema name, so try using this

update schemname.tablename t
set t.columnname = replace(t.columnname, t.oldvalue, t.newvalue);

two divs the same line, one dynamic width, one fixed

So left div style depends on the presence of right div. I can't think of a CSS selector allowing that kind of behavior yet.

Thus it seems to me that you'll need to programmatically add a class server side (or in JS) on parent div or left div to do that.

<div id="parent twocols">
  <div class="left"></div>
  <div class="right"></div>
</div>

or

<div id="parent">
  <div class="left"></div>
</div>

So right style is always :

.right {
    float: right;
    width: 200px; /* or whatever value you need */
    /* margin and padding at your discretion */
}

and left style is :

.parent.twocols .left {
    margin-right: 200px; /* according to right div width + margin + padding*/
}

View more than one project/solution in Visual Studio

Just right click on the Visual Studio icon and then select "New Window" from the contextual toolbar that appears on the bottom in Windows 8. A new instance of Visual Studio will launch and then you can open your second project.

How to concat a string to xsl:value-of select="...?

The easiest way to concat a static text string to a selected value is to use element.

<a>
  <xsl:attribute name="href"> 
    <xsl:value-of select="/*/properties/property[@name='report']/@value" />
    <xsl:text>staticIconExample.png</xsl:text>
  </xsl:attribute>
</a>

What is the best collation to use for MySQL with PHP?

Actually, you probably want to use utf8_unicode_ci or utf8_general_ci.

  • utf8_general_ci sorts by stripping away all accents and sorting as if it were ASCII
  • utf8_unicode_ci uses the Unicode sort order, so it sorts correctly in more languages

However, if you are only using this to store English text, these shouldn't differ.

SSIS Connection not found in package

I determined that this problem was a corrupt connection manager by identifying the specific connection that was failing. I'm working in SQL Server 2016 and I have created the SSISDB catalog and I am deploying my projects there.

Here's the short answer. Delete the connection manager and then re-create it with the same name. Make sure the packages using that connection are still wired up correctly and you should be good to go. If you're not sure how to do that, I've included the detailed procedure below.

To identify the corrupt connection, I did the following. In SSMS, I opened the Integration Services Catalogs folder, then the SSISDB folder, then the folder for my solution, and on down until I found my list of packages for that project.

By right clicking the package that failed, going to reports>standard reports>all executions, selecting the last execution, and viewing the "All Messages" report I was able to isolate which connection was failing. In my case, the connection manager to my destination. I simply deleted the connection manager and then recreated a new connection manager with the same name.

Subsequently, I went into my package, opened the data flow, found that some of my destinations had lit up with the red X. I opened the destination, re-selected the correct connection name, re-selected the target table, and checked the mappings were still correct. I had six destinations and only three had the red X but I clicked all of them and made sure they were still configured correctly.

How to add dll in c# project

The DLL must be present at all times - as the name indicates, a reference only tells VS that you're trying to use stuff from the DLL. In the project file, VS stores the actual path and file name of the referenced DLL. If you move or delete it, VS is not able to find it anymore.

I usually create a libs folder within my project's folder where I copy DLLs that are not installed to the GAC. Then, I actually add this folder to my project in VS (show hidden files in VS, then right-click and "Include in project"). I then reference the DLLs from the folder, so when checking into source control, the library is also checked in. This makes it much easier when more than one developer will have to change the project.

(Please make sure to set the build type to "none" and "don't copy to output folder" for the DLL in your project.)

PS: I use a German Visual Studio, so the captions I quoted may not exactly match the English version...

adding 1 day to a DATETIME format value

There is a more concise and intuitive way to add days to php date. Don't get me wrong, those php expressions are great, but you always have to google how to treat them. I miss auto-completion facility for that.

Here is how I like to handle those cases:

(new Future(
    new DateTimeFromISO8601String('2014-11-21T06:04:31.321987+00:00'),
    new OneDay()
))
    ->value();

For me, it's way more intuitive and autocompletion works out of the box. No need to google for the solution each time.

As a nice bonus, you don't have to worry about formatting the resulting value, it's already is ISO8601 format.

This is meringue library, there are more examples here.

Facebook Open Graph not clearing cache

If you have many pages and don't want to refresh them manually - you can do it automatically.

Lets say you have user profile page with photo:

$url = 'http://'.$_SERVER['HTTP_HOST'].'/'.$user_profile;
$user_photo = 'http://'.$_SERVER['HTTP_HOST'].'/'.$user_photo;

<meta property="og:url" content="<?php echo $url; ?>"/>
<meta property="og:image" content="<?php echo $user_photo; ?>"

Just add this to your page:

// with jQuery
$.post(
    'https://graph.facebook.com',
    {
        id: '<?php echo $url; ?>',
        scrape: true
    },
    function(response){
        console.log(response);
    }
);

// with "vanilla" javascript
var fbxhr = new XMLHttpRequest();
fbxhr.open("POST", "https://graph.facebook.com", true);
fbxhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
fbxhr.send("id=<?php echo $url; ?>&scrape=true");

This will refresh Facebook cache. If you use the jQuery solution, have a look at "response" in console.log - you will find there "updated_time" field and other useful information.

How do I wait for an asynchronously dispatched block to finish?

In addition to the semaphore technique covered exhaustively in other answers, we can now use XCTest in Xcode 6 to perform asynchronous tests via XCTestExpectation. This eliminates the need for semaphores when testing asynchronous code. For example:

- (void)testDataTask
{
    XCTestExpectation *expectation = [self expectationWithDescription:@"asynchronous request"];

    NSURL *url = [NSURL URLWithString:@"http://www.apple.com"];
    NSURLSessionTask *task = [self.session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        XCTAssertNil(error, @"dataTaskWithURL error %@", error);

        if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSInteger statusCode = [(NSHTTPURLResponse *) response statusCode];
            XCTAssertEqual(statusCode, 200, @"status code was not 200; was %d", statusCode);
        }

        XCTAssert(data, @"data nil");

        // do additional tests on the contents of the `data` object here, if you want

        // when all done, Fulfill the expectation

        [expectation fulfill];
    }];
    [task resume];

    [self waitForExpectationsWithTimeout:10.0 handler:nil];
}

For the sake of future readers, while the dispatch semaphore technique is a wonderful technique when absolutely needed, I must confess that I see too many new developers, unfamiliar with good asynchronous programming patterns, gravitate too quickly to semaphores as a general mechanism for making asynchronous routines behave synchronously. Worse I've seen many of them use this semaphore technique from the main queue (and we should never block the main queue in production apps).

I know this isn't the case here (when this question was posted, there wasn't a nice tool like XCTestExpectation; also, in these testing suites, we must ensure the test does not finish until the asynchronous call is done). This is one of those rare situations where the semaphore technique for blocking the main thread might be necessary.

So with my apologies to the author of this original question, for whom the semaphore technique is sound, I write this warning to all of those new developers who see this semaphore technique and consider applying it in their code as a general approach for dealing with asynchronous methods: Be forewarned that nine times out of ten, the semaphore technique is not the best approach when encounting asynchronous operations. Instead, familiarize yourself with completion block/closure patterns, as well as delegate-protocol patterns and notifications. These are often much better ways of dealing with asynchronous tasks, rather than using semaphores to make them behave synchronously. Usually there are good reasons that asynchronous tasks were designed to behave asynchronously, so use the right asynchronous pattern rather than trying to make them behave synchronously.

Android M Permissions: onRequestPermissionsResult() not being called

Before you check everything according to above answers, make sure your request code is not 0!!!

check the code of onRequestPermissionsResult() in FragmentActivity.java:

public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
    int index = (requestCode>>16)&0xffff;
    if (index != 0) {
        index--;

        String who = mPendingFragmentActivityResults.get(index);
        mPendingFragmentActivityResults.remove(index);
        if (who == null) {
            Log.w(TAG, "Activity result delivered for unknown Fragment.");
            return;
        }
        Fragment frag = mFragments.findFragmentByWho(who);
        if (frag == null) {
            Log.w(TAG, "Activity result no fragment exists for who: " + who);
        } else {
            frag.onRequestPermissionsResult(requestCode&0xffff, permissions, grantResults);
        }
    }
}

How to select a radio button by default?

Use the checked attribute.

<input type="radio" name="imgsel"  value="" checked /> 

or

<input type="radio" name="imgsel"  value="" checked="checked" /> 

XML to CSV Using XSLT

This CsvEscape function is XSLT 1.0 and escapes column values ,, ", and newlines like RFC 4180 or Excel. It makes use of the fact that you can recursively call XSLT templates:

  • The template EscapeQuotes replaces all double quotes with 2 double quotes, recursively from the start of the string.
  • The template CsvEscape checks if the text contains a comma or double quote, and if so surrounds the whole string with a pair of double quotes and calls EscapeQuotes for the string.

Example usage: xsltproc xmltocsv.xslt file.xml > file.csv

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="UTF-8"/>

  <xsl:template name="EscapeQuotes">
    <xsl:param name="value"/>
    <xsl:choose>
      <xsl:when test="contains($value,'&quot;')">
    <xsl:value-of select="substring-before($value,'&quot;')"/>
    <xsl:text>&quot;&quot;</xsl:text>
    <xsl:call-template name="EscapeQuotes">
      <xsl:with-param name="value" select="substring-after($value,'&quot;')"/>
    </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
    <xsl:value-of select="$value"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template name="CsvEscape">
    <xsl:param name="value"/>
    <xsl:choose>
    <xsl:when test="contains($value,',')">
      <xsl:text>&quot;</xsl:text>
      <xsl:call-template name="EscapeQuotes">
    <xsl:with-param name="value" select="$value"/>
      </xsl:call-template>
      <xsl:text>&quot;</xsl:text>
    </xsl:when>
    <xsl:when test="contains($value,'&#xA;')">
      <xsl:text>&quot;</xsl:text>
      <xsl:call-template name="EscapeQuotes">
    <xsl:with-param name="value" select="$value"/>
      </xsl:call-template>
      <xsl:text>&quot;</xsl:text>
    </xsl:when>
    <xsl:when test="contains($value,'&quot;')">
      <xsl:text>&quot;</xsl:text>
      <xsl:call-template name="EscapeQuotes">
    <xsl:with-param name="value" select="$value"/>
      </xsl:call-template>
      <xsl:text>&quot;</xsl:text>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$value"/>
    </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="/">
    <xsl:text>project,name,language,owner,state,startDate</xsl:text>
    <xsl:text>&#xA;</xsl:text>
    <xsl:for-each select="projects/project">
      <xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(name)"/></xsl:call-template>
      <xsl:text>,</xsl:text>
      <xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(language)"/></xsl:call-template>
      <xsl:text>,</xsl:text>
      <xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(owner)"/></xsl:call-template>
      <xsl:text>,</xsl:text>
      <xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(state)"/></xsl:call-template>
      <xsl:text>,</xsl:text>
      <xsl:call-template name="CsvEscape"><xsl:with-param name="value" select="normalize-space(startDate)"/></xsl:call-template>
      <xsl:text>&#xA;</xsl:text>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

How to get values from IGrouping

foreach (var v in structure) 
{     
    var group = groups.Single(g => g.Key == v. ??? );
    v.ListOfSmth = group.ToList();
}

First you need to select the desired group. Then you can use the ToList method of on the group. The IGrouping is a IEnumerable of the values.

What does AngularJS do better than jQuery?

Data-Binding

You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

This is a good understanding of data-binding. I think you've got that down.

DOM Manipulation

For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.

I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.

I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.

This is the markup we want to use. I gave it an intuitive name.

<div rotate-on-click="45"></div>

First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.

Implementation with jQuery

live demo here (click).

function rotate(deg, elem) {
  $(elem).css({
    webkitTransform: 'rotate('+deg+'deg)', 
    mozTransform: 'rotate('+deg+'deg)', 
    msTransform: 'rotate('+deg+'deg)', 
    oTransform: 'rotate('+deg+'deg)', 
    transform: 'rotate('+deg+'deg)'    
  });
}

function addRotateOnClick($elems) {
  $elems.each(function(i, elem) {
    var deg = 0;
    $(elem).click(function() {
      deg+= parseInt($(this).attr('rotate-on-click'), 10);
      rotate(deg, this);
    });
  });
}

addRotateOnClick($('[rotate-on-click]'));

Implementation with Angular

live demo here (click).

app.directive('rotateOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var deg = 0;
      element.bind('click', function() {
        deg+= parseInt(attrs.rotateOnClick, 10);
        element.css({
          webkitTransform: 'rotate('+deg+'deg)', 
          mozTransform: 'rotate('+deg+'deg)', 
          msTransform: 'rotate('+deg+'deg)', 
          oTransform: 'rotate('+deg+'deg)', 
          transform: 'rotate('+deg+'deg)'    
        });
      });
    }
  };
});

Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link function (or compile function).

Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.

This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?

General differences.

The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.

Angular and jQuery can't reasonably be compared.

Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:

Why use a framework?

Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.

Here are some things that modern frameworks are providing:

  • Templating
  • Data-binding
  • routing (single page app)
  • clean, modular, reusable architecture
  • security
  • additional functions/features for convenience

Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.

If you need to destroy a planet and you have a Death Star, use the Death star.

Angular (revisited).

Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.

DOM reference.

In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:

<clock></clock>

Done.

Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.

MVW Architecure / Modules / Dependency Injection

Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.

It isn't easy to make things "work" in Angular.

THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.

Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.

Convert javascript object or array to json for ajax data

You can use JSON.stringify(object) with an object and I just wrote a function that'll recursively convert an array to an object, like this JSON.stringify(convArrToObj(array)), which is the following code (more detail can be found on this answer):

// Convert array to object
var convArrToObj = function(array){
    var thisEleObj = new Object();
    if(typeof array == "object"){
        for(var i in array){
            var thisEle = convArrToObj(array[i]);
            thisEleObj[i] = thisEle;
        }
    }else {
        thisEleObj = array;
    }
    return thisEleObj;
}

To make it more generic, you can override the JSON.stringify function and you won't have to worry about it again, to do this, just paste this at the top of your page:

// Modify JSON.stringify to allow recursive and single-level arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        return oldJSONStringify(convArrToObj(input));
    };
})();

And now JSON.stringify will accept arrays or objects! (link to jsFiddle with example)


Edit:

Here's another version that's a tad bit more efficient, although it may or may not be less reliable (not sure -- it depends on if JSON.stringify(array) always returns [], which I don't see much reason why it wouldn't, so this function should be better as it does a little less work when you use JSON.stringify with an object):

(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();

jsFiddle with example here

js Performance test here, via jsPerf

Draw in Canvas by finger, Android

tutorial to draw line use Bitmap, Canvas, and Paint class. draw-line-on-finger-touch and androiddraw

here one simple class to draw line using canvas as show below.

    public class TestLineView extends View {

    private Paint paint;
    private PointF startPoint, endPoint;
    private boolean isDrawing;

    public TestLineView(Context context)
    {
        super(context);
        init();
    }

    private void init()
    {
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStyle(Style.STROKE);
        paint.setStrokeWidth(2);
        paint.setAntiAlias(true);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        if(isDrawing)
        {
            canvas.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y, paint);
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                startPoint = new PointF(event.getX(), event.getY());
                endPoint = new PointF();
                isDrawing = true;
                break;
            case MotionEvent.ACTION_MOVE:
                if(isDrawing)
                {
                    endPoint.x = event.getX();
                    endPoint.y = event.getY();
                    invalidate();
                }
                break;
            case MotionEvent.ACTION_UP:
                if(isDrawing)
                {
                    endPoint.x = event.getX();
                    endPoint.y = event.getY();
                    isDrawing = false;
                    invalidate();
                }
                break;
            default:
                break;
        }
        return true;
    }
}

How to append strings using sprintf?

Using strcat(buffer,"Your new string...here"), as an option.

Android, How to create option Menu

Replace return super.onCreateOptionsMenu(menu); with return true; in your onCreateOptionsMenu method This will help

And you should also have the onCreate method in your activity

How to create a String with carriage returns?

Do this: Step 1: Your String

String str = ";;;;;;\n" +
            "Name, number, address;;;;;;\n" + 
             "01.01.12-16.02.12;;;;;;\n" + 
             ";;;;;;\n" + 
             ";;;;;;";

Step 2: Just replace all "\n" with "%n" the result looks like this

String str = ";;;;;;%n" +
             "Name, number, address;;;;;;%n" + 
             "01.01.12-16.02.12;;;;;;%n" + 
            ";;;;;;%n" + 
            ";;;;;;";

Notice I've just put "%n" in place of "\n"

Step 3: Now simply call format()

str=String.format(str);

That's all you have to do.

Ruby, remove last N characters from a string?

x = "my_test"
last_char = x.split('').last

Chrome hangs after certain amount of data transfered - waiting for available socket

Chrome is a Chromium-based browser and Chromium-based browsers only allow maximum 6 open socket connections at a time, when the 7th connection starts up it will just sit idle and wait for one of the 6 which are running to stop and then it will start running. Hence the error code ‘waiting for available sockets’, the 7th one will wait for one of those 6 sockets to become available and then it will start running.

You can either

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

How to use sha256 in php5.3.0

First of all, sha256 is a hashing algorithm, not a type of encryption. An encryption would require having a way to decrypt the information back to its original value (collisions aside).

Looking at your code, it seems it should work if you are providing the correct parameter.

  • Try using a literal string in your code first, and verify its validity instead of using the $_POST[] variable

  • Try moving the comparison from the database query to the code (get the hash for the given user and compare to the hash you have just calculated)

But most importantly before deploying this in any kind of public fashion, please remember to sanitize your inputs. Don't allow arbitrary SQL to be insert into the queries. The best idea here would be to use parameterized queries.

How to compare if two structs, slices or maps are equal?

You can use reflect.DeepEqual, or you can implement your own function (which performance wise would be better than using reflection):

http://play.golang.org/p/CPdfsYGNy_

m1 := map[string]int{   
    "a":1,
    "b":2,
}
m2 := map[string]int{   
    "a":1,
    "b":2,
}
fmt.Println(reflect.DeepEqual(m1, m2))

How to listen for a WebView finishing loading a URL?

I have simplified NeTeInStEiN's code to be like this:

mWebView.setWebViewClient(new WebViewClient() {
        private int       webViewPreviousState;
        private final int PAGE_STARTED    = 0x1;
        private final int PAGE_REDIRECTED = 0x2;

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
            webViewPreviousState = PAGE_REDIRECTED;
            mWebView.loadUrl(urlNewString);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            webViewPreviousState = PAGE_STARTED;
            if (dialog == null || !dialog.isShowing())
                dialog = ProgressDialog.show(WebViewActivity.this, "", getString(R.string.loadingMessege), true, true,
                        new OnCancelListener() {

                            @Override
                            public void onCancel(DialogInterface dialog) {
                                // do something
                            }
                        });
        }

        @Override
        public void onPageFinished(WebView view, String url) {

            if (webViewPreviousState == PAGE_STARTED) {
                dialog.dismiss();
                dialog = null;
            }

        }
 });

It is easy to understand, OnPageFinished if the previous callback is on onPageStarted, so the page is completely loaded.

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

To simplify Kirubaharan's answer a bit:

df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df = df.set_index('Datetime')

And to get rid of unwanted columns (as OP did but did not specify per se in the question):

df = df.drop(['date','time'], axis=1)

Install specific version using laravel installer

The direct way as mentioned in the documentation:

composer create-project --prefer-dist laravel/laravel blog "6.*"

https://laravel.com/docs/6.x/installation

Access localhost from the internet

Try with your IP Address , I think you can access it by internet.

Make an Installation program for C# applications and include .NET Framework installer into the setup

WiX is the way to go for new installers. If WiX alone is too complicated or not flexible enough on the GUI side consider using SharpSetup - it allows you to create installer GUI in WinForms of WPF and has other nice features like translations, autoupdater, built-in prerequisites, improved autocompletion in VS and more.

(Disclaimer: I am the author of SharpSetup.)

How to declare an array of objects in C#

With LINQ, you can transform the array of uninitialized elements into the new collection of created objects with one line of code.

var houses = new GameObject[200].Select(h => new GameObject()).ToArray();

Actually, you can use any other source for this, even generated sequence of integers:

var houses = Enumerable.Repeat(0, 200).Select(h => new GameObject()).ToArray();

However, the first case seems to me more readable, although the type of original sequence is not important.

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

Try this. The scope of local variables defined by "template" directive.

<table>
  <template ngFor let-group="$implicit" [ngForOf]="groups">
    <tr>
      <td>
        <h2>{{group.name}}</h2>
      </td>
    </tr>
    <tr *ngFor="let item of group.items">
                <td>{{item}}</td>
            </tr>
  </template>
</table>

Get month and year from a datetime in SQL Server 2005

The question is about SQL Server 2005, many of the answers here are for later version SQL Server.

select convert (varchar(7), getdate(),20)
--Typical output 2015-04

SQL Server 2005 does not have date function which was introduced in SQL Server 2008

grep exclude multiple strings

The greps can be chained. For example:

tail -f admin.log | grep -v "Nopaging the limit is" | grep -v "keyword to remove is"

Subset of rows containing NA (missing) values in a chosen column of a data frame

Prints all the rows with NA data:

tmp <- data.frame(c(1,2,3),c(4,NA,5));
tmp[round(which(is.na(tmp))/ncol(tmp)),]

Django TemplateDoesNotExist?

I'm embarrassed to admit this, but the problem for me was that a template had been specified as ….hml instead of ….html. Watch out!

Powershell import-module doesn't find modules

I had this problem, but only in Visual Studio Code, not in ISE. Turns out I was using an x86 session in VSCode. I displayed the PowerShell Session Menu and switched to the x64 session, and all the modules began working without full paths. I am using Version 1.17.2, architecture x64 of VSCode. My modules were stored in the C:\Windows\System32\WindowsPowerShell\v1.0\Modules directory.

Using a different font with twitter bootstrap

you can customize twitter bootstrap css file, open the bootstrap.css file on a text editor, and change the font-family with your font name and SAVE it.

OR got to http://getbootstrap.com/customize/ and make a customized twitter bootstrap

Composer - the requested PHP extension mbstring is missing from your system

  1. find your php.ini
  2. make sure the directive extension_dir=C:\path\to\server\php\ext is set and adjust the path (set your PHP extension dir)
  3. make sure the directive extension=php_mbstring.dll is set (uncommented)

If this doesn't work and the php_mbstring.dll file is missing, then the PHP installation of this stack is simply broken.

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

Show/hide image with JavaScript

It's pretty simple.

HTML:

<img id="theImage" src="yourImage.png">
<a id="showImage">Show image</a>

JavaScript:

document.getElementById("showImage").onclick = function() {
    document.getElementById("theImage").style.visibility = "visible";
}

CSS:

#theImage { visibility: hidden; }

How to find Current open Cursors in Oracle

Here's how to find open cursors that have been parsed. You need to be logged in as a user with access to v$open_cursor and v$session.

COLUMN USER_NAME FORMAT A15

SELECT s.machine, oc.user_name, oc.sql_text, count(1) 
FROM v$open_cursor oc, v$session s
WHERE oc.sid = s.sid
GROUP BY user_name, sql_text, machine
HAVING COUNT(1) > 2
ORDER BY count(1) DESC
;

If gives you part of the SQL text so it can be useful for identifying leaky applications. If a cursor has not been parsed, then it does not appear here. Note that Oralce will sometimes keep things open longer than you do.

Count distinct values

You can do a distinct count as follows:

SELECT COUNT(DISTINCT column_name) FROM table_name;

EDIT:

Following your clarification and update to the question, I see now that it's quite a different question than we'd originally thought. "DISTINCT" has special meaning in SQL. If I understand correctly, you want something like this:

  • 2 customers had 1 pets
  • 3 customers had 2 pets
  • 1 customers had 3 pets

Now you're probably going to want to use a subquery:

select COUNT(*) column_name FROM (SELECT DISTINCT column_name);

Let me know if this isn't quite what you're looking for.

How to Convert a Text File into a List in Python

Maybe:

crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]

Chart.js - Formatting Y axis

scaleLabel : "<%= Number(value).toFixed(2).replace('.', ',') + ' $'%>"

What does Html.HiddenFor do?

Like a lot of functions, this one can be used in many different ways to solve many different problems, I think of it as yet another tool in our toolbelts.

So far, the discussion has focused heavily on simply hiding an ID, but that is only one value, why not use it for lots of values! That is what I am doing, I use it to load up the values in a class only one view at a time, because html.beginform creates a new object and if your model object for that view already had some values passed to it, those values will be lost unless you provide a reference to those values in the beginform.

To see a great motivation for the html.hiddenfor, I recommend you see Passing data from a View to a Controller in .NET MVC - "@model" not highlighting

How to get the groups of a user in Active Directory? (c#, asp.net)

First of all, GetAuthorizationGroups() is a great function but unfortunately has 2 disadvantages:

  1. Performance is poor, especially in big company's with many users and groups. It fetches a lot more data then you actually need and does a server call for each loop iteration in the result
  2. It contains bugs which can cause your application to stop working 'some day' when groups and users are evolving. Microsoft recognized the issue and is related with some SID's. The error you'll get is "An error occurred while enumerating the groups"

Therefore, I've wrote a small function to replace GetAuthorizationGroups() with better performance and error-safe. It does only 1 LDAP call with a query using indexed fields. It can be easily extended if you need more properties than only the group names ("cn" property).

// Usage: GetAdGroupsForUser2("domain\user") or GetAdGroupsForUser2("user","domain")
public static List<string> GetAdGroupsForUser2(string userName, string domainName = null)
{
    var result = new List<string>();

    if (userName.Contains('\\') || userName.Contains('/'))
    {
        domainName = userName.Split(new char[] { '\\', '/' })[0];
        userName = userName.Split(new char[] { '\\', '/' })[1];
    }

    using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, domainName))
        using (UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, userName))
            using (var searcher = new DirectorySearcher(new DirectoryEntry("LDAP://" + domainContext.Name)))
            {
                searcher.Filter = String.Format("(&(objectCategory=group)(member={0}))", user.DistinguishedName);
                searcher.SearchScope = SearchScope.Subtree;
                searcher.PropertiesToLoad.Add("cn");

                foreach (SearchResult entry in searcher.FindAll())
                    if (entry.Properties.Contains("cn"))
                        result.Add(entry.Properties["cn"][0].ToString());
            }

    return result;
}

How can I remove text within parentheses with a regex?

>>> import re
>>> filename = "Example_file_(extra_descriptor).ext"
>>> p = re.compile(r'\([^)]*\)')
>>> re.sub(p, '', filename)
'Example_file_.ext'

Can you change what a symlink points to after it is created?

Just a warning to the correct answers above:

Using the -f / --force Method provides a risk to lose the file if you mix up source and target:

mbucher@server2:~/test$ ls -la
total 11448
drwxr-xr-x  2 mbucher www-data    4096 May 25 15:27 .
drwxr-xr-x 18 mbucher www-data    4096 May 25 15:13 ..
-rw-r--r--  1 mbucher www-data 4109466 May 25 15:26 data.tar.gz
-rw-r--r--  1 mbucher www-data 7582480 May 25 15:27 otherdata.tar.gz
lrwxrwxrwx  1 mbucher www-data      11 May 25 15:26 thesymlink -> data.tar.gz
mbucher@server2:~/test$ 
mbucher@server2:~/test$ ln -s -f thesymlink otherdata.tar.gz 
mbucher@server2:~/test$ 
mbucher@server2:~/test$ ls -la
total 4028
drwxr-xr-x  2 mbucher www-data    4096 May 25 15:28 .
drwxr-xr-x 18 mbucher www-data    4096 May 25 15:13 ..
-rw-r--r--  1 mbucher www-data 4109466 May 25 15:26 data.tar.gz
lrwxrwxrwx  1 mbucher www-data      10 May 25 15:28 otherdata.tar.gz -> thesymlink
lrwxrwxrwx  1 mbucher www-data      11 May 25 15:26 thesymlink -> data.tar.gz

Of course this is intended, but usually mistakes occur. So, deleting and rebuilding the symlink is a bit more work but also a bit saver:

mbucher@server2:~/test$ rm thesymlink && ln -s thesymlink otherdata.tar.gz 
ln: creating symbolic link `otherdata.tar.gz': File exists

which at least keeps my file.

Chrome & Safari Error::Not allowed to load local resource: file:///D:/CSS/Style.css

I know this post is old but here is what I found. It doesn't work when I link it this way(with / before css/style.csson the href attribute.

<link rel="stylesheet" media="all" href="/CSS/Style.css" type="text/css" />

However, when I removed / I'm able to link properly with the css file It should be like this(without /).

<link rel="stylesheet" media="all" href="CSS/Style.css" type="text/css" />

This was giving me trouble on my project. Hope it will help somebody else.

List all virtualenv

To list all the virtual environments (if using the anaconda distribution):

conda info --envs

Hope my answer helps someone...

Is there an opposite to display:none?

display: none doesn’t have a literal opposite like visibility:hidden does.

The visibility property decides whether an element is visible or not. It therefore has two states (visible and hidden), which are opposite to each other.

The display property, however, decides what layout rules an element will follow. There are several different kinds of rules for how elements will lay themselves out in CSS, so there are several different values (block, inline, inline-block etc — see the documentation for these values here ).

display:none removes an element from the page layout entirely, as if it wasn’t there.

All other values for display cause the element to be a part of the page, so in a sense they’re all opposite to display:none.

But there isn’t one value that’s the direct converse of display:none - just like there's no one hair style that's the opposite of "bald".

Access elements of parent window from iframe

You can access elements of parent window from within an iframe by using window.parent like this:

// using jquery    
window.parent.$("#element_id");

Which is the same as:

// pure javascript
window.parent.document.getElementById("element_id");

And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top like this:

// using jquery
window.top.$("#element_id");

Which is the same as:

// pure javascript
window.top.document.getElementById("element_id");

Why should we typedef a struct so often in C?

the name you (optionally) give the struct is called the tag name and, as has been noted, is not a type in itself. To get to the type requires the struct prefix.

GTK+ aside, I'm not sure the tagname is used anything like as commonly as a typedef to the struct type, so in C++ that is recognised and you can omit the struct keyword and use the tagname as the type name too:


    struct MyStruct
    {
      int i;
    };

    // The following is legal in C++:
    MyStruct obj;
    obj.i = 7;

Open another page in php

<?php
    header("Location: index.html");
?>

Just make sure nothing is actually written to the page prior to this code, or it won't work.

PHP refresh window? equivalent to F5 page reload?

PHP cannot force the client to do anything. It cannot refresh the page, let alone refresh the parent of a frame.

EDIT: You can of course, make PHP write JavaScript, but this is not PHP doing, it's actually JavaScript, and it will fail if JavaScript is disabled.

<?php
    echo '<script>parent.window.location.reload(true);</script>';
?>

On npm install: Unhandled rejection Error: EACCES: permission denied

sudo npm install --unsafe-perm=true --allow-root

This was the one that worked for me

How to get the row number from a datatable?

You have two options here.

  1. You can create your own index counter and increment it
  2. Rather than using a foreach loop, you can use a for loop

The individual row simply represents data, so it will not know what row it is located in.

Python: TypeError: object of type 'NoneType' has no len()

What is the purpose of this

 names = list;

? Also, no ; required in Python.

Do you want

 names = []

or

 names = list()

at the start of your program instead? Though given your particular code, there's no need for this statement to create this names variable since you do so later when you read data into it from your file.

@JBernardo has already pointed out the other (and more major) problem with the code.

Negation in Python

The negation operator in Python is not. Therefore just replace your ! with not.

For your example, do this:

if not os.path.exists("/usr/share/sounds/blues") :
    proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
    proc.wait()

For your specific example (as Neil said in the comments), you don't have to use the subprocess module, you can simply use os.mkdir() to get the result you need, with added exception handling goodness.

Example:

blues_sounds_path = "/usr/share/sounds/blues"
if not os.path.exists(blues_sounds_path):
    try:
        os.mkdir(blues_sounds_path)
    except OSError:
        # Handle the case where the directory could not be created.

"Line contains NULL byte" in CSV reader (Python)

This is long settled, but I ran across this answer because I was experiencing an unexpected error while reading a CSV to process as training data in Keras and TensorFlow.

In my case, the issue was much simpler, and is worth being conscious of. The data being produced into the CSV wasn't consistent, resulting in some columns being completely missing, which seems to end up throwing this error as well.

The lesson: If you're seeing this error, verify that your data looks the way that you think it does!

Running a CMD or BAT in silent mode

Include the phrase:

@echo off

Right at the top of your bat script.

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

Attribute 'nowrap' is considered outdated. A newer construct is recommended. What is it?

Although there's CSS defines a text-wrap property, it's not supported by any major browser, but maybe vastly supported white-space property solves your problem.

What is the difference between Views and Materialized Views in Oracle?

A view uses a query to pull data from the underlying tables.

A materialized view is a table on disk that contains the result set of a query.

Materialized views are primarily used to increase application performance when it isn't feasible or desirable to use a standard view with indexes applied to it. Materialized views can be updated on a regular basis either through triggers or by using the ON COMMIT REFRESH option. This does require a few extra permissions, but it's nothing complex. ON COMMIT REFRESH has been in place since at least Oracle 10.

add to array if it isn't there already

You should use the PHP function in_array (see http://php.net/manual/en/function.in-array.php).

if (!in_array($value, $array))
{
    $array[] = $value; 
}

This is what the documentation says about in_array:

Returns TRUE if needle is found in the array, FALSE otherwise.

What does "use strict" do in JavaScript, and what is the reasoning behind it?

Strict mode eliminates errors that would be ignored in non-strict mode, thus making javascript “more secured”.

Is it considered among best practices?

Yes, It's considered part of the best practices while working with javascript to include Strict mode. This is done by adding the below line of code in your JS file.

'use strict';

in your code.

What does it mean to user agents?

Indicating that code should be interpreted in strict mode specifies to user agents like browsers that they should treat code literally as written, and throw an error if the code doesn't make sense.

For example: Consider in your .js file you have the following code:

Scenario 1: [NO STRICT MODE]

var city = "Chicago"
console.log(city) // Prints the city name, i.e. Chicago

Scenario 2: [NO STRICT MODE]

city = "Chicago"
console.log(city) // Prints the city name, i.e. Chicago

So why does the variable name is being printed in both cases?

Without strict mode turned on, user agents often go through a series of modifications to problematic code in an attempt to get it to make sense. On the surface, this can seem like a fine thing, and indeed, working outside of strict mode makes it possible for people to get their feet wet with JavaScript code without having all the details quite nailed down. However, as a developer, I don't want to leave a bug in my code, because I know it could come back and bite me later on, and I also just want to write good code. And that's where strict mode helps out.

Scenario 3: [STRICT MODE]

'use strict';

city = "Chicago"
console.log(city) // Reference Error: asignment is undeclared variable city.

Additional tip: To maintain code quality using strict mode, you don't need to write this over and again especially if you have multiple .js file. You can enforce this rule globally in eslint rules as follows:

Filename: .eslintrc.js

module.exports = {
    env: {
        es6: true
    },
    rules : {
        strict: ['error', 'global'],
        },
    };
    

Okay, so what is prevented in strict mode?

  • Using a variable without declaring it will throw an error in strict mode. This is to prevent unintentionally creating global variables throughout your application. The example with printing Chicago covers this in particular.

  • Deleting a variable or a function or an argument is a no-no in strict mode.

    "use strict";
     function x(p1, p2) {}; 
     delete x; // This will cause an error
    
  • Duplicating a parameter name is not allowed in strict mode.

     "use strict";
     function x(p1, p1) {};   // This will cause an error
    
  • Reserved words in the Javascript language are not allowed in strict mode. The words are implements interface, let, packages, private, protected, public. static, and yield

For a more comprehensive list check out the MDN documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

Android : difference between invisible and gone?

  • View.INVISIBLE->The View is invisible but it will occupy some space in layout

  • View.GONE->The View is not visible and it will not occupy any space in layout

How to fill 100% of remaining height?

I know this is an old question, but nowadays there is a super easy form to do that, which is CCS Grid, so let me put the divs as example:

<div id="full">
  <div id="header">Contents of 1</div>
  <div id="someid">Contents of 2</div>
</div>

then the CSS code:

.full{
  width:/*the width you need*/;
  height:/*the height you need*/;
  display:grid;
  grid-template-rows: minmax(100px,auto) 1fr;
 }

And that's it, the second row, scilicet, the someide, will take the rest of the height because of the property 1fr, and the first div will have a min of 100px and a max of whatever it requires.

I must say CSS has advanced a lot to make easier programmers lives.

If else in stored procedure sql server

Instead of writing:

Select top 1 ParLngId from T_Param where ParStrNom = 'Extranet Client'

Write:

Select top 1 ParLngId from T_Param where ParStrNom IN 'Extranet Client'

i.e. replace '=' sign by 'IN'

How to check Network port access and display useful message?

boiled this down to a one liner sets the variable "$port389Open" to True or false - its fast and easy to replicate for a list of ports

try{$socket = New-Object Net.Sockets.TcpClient($ipAddress,389);if($socket -eq $null){$Port389Open = $false}else{Port389Open = $true;$socket.close()}}catch{Port389Open = $false}

If you want ot go really crazy you can return the an entire array-

Function StdPorts($ip){
    $rst = "" |  select IP,Port547Open,Port135Open,Port3389Open,Port389Open,Port53Open
    $rst.IP = $Ip
    try{$socket = New-Object Net.Sockets.TcpClient($ip,389);if($socket -eq $null){$rst.Port389Open = $false}else{$rst.Port389Open = $true;$socket.close();$ipscore++}}catch{$rst.Port389Open = $false}
    try{$socket = New-Object Net.Sockets.TcpClient($ip,53);if($socket -eq $null){$rst.Port53Open = $false}else{$rst.Port53Open = $true;$socket.close();$ipscore++}}catch{$rst.Port53Open = $false}
    try{$socket = New-Object Net.Sockets.TcpClient($ip,3389);if($socket -eq $null){$rst.Port3389Open = $false}else{$rst.Port3389Open = $true;$socket.close();$ipscore++}}catch{$rst.Port3389Open = $false}
    try{$socket = New-Object Net.Sockets.TcpClient($ip,547);if($socket -eq $null){$rst.Port547Open = $false}else{$rst.Port547Open = $true;$socket.close();$ipscore++}}catch{$rst.Port547Open = $false}
    try{$socket = New-Object Net.Sockets.TcpClient($ip,135);if($socket -eq $null){$rst.Port135Open = $false}else{$rst.Port135Open = $true;$socket.close();$SkipWMI = $False;$ipscore++}}catch{$rst.Port135Open = $false}
    Return $rst
}

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

I've fixed this issue using an entirely-Apache based solution. In my vhost / htaccess I put the following block:

# enable cross domain access control
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"

# force apache to return 200 without executing my scripts
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* / [R=200,L]

You may not need the latter part, depending on what happens when Apache executes your target script. Credit goes to the friendly ServerFault folk for the latter part.

Python Requests and persistent sessions

The documentation says that get takes in an optional cookies argument allowing you to specify cookies to use:

from the docs:

>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')

>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

http://docs.python-requests.org/en/latest/user/quickstart/#cookies

How do I cancel an HTTP fetch() request?

Let's polyfill:

if(!AbortController){
  class AbortController {
    constructor() {
      this.aborted = false;
      this.signal = this.signal.bind(this);
    }
    signal(abortFn, scope) {
      if (this.aborted) {
        abortFn.apply(scope, { name: 'AbortError' });
        this.aborted = false;
      } else {
        this.abortFn = abortFn.bind(scope);
      }
    }
    abort() {
      if (this.abortFn) {
        this.abortFn({ reason: 'canceled' });
        this.aborted = false;
      } else {
        this.aborted = true;
      }
    }
  }

  const originalFetch = window.fetch;

  const customFetch = (url, options) => {
    const { signal } = options || {};

    return new Promise((resolve, reject) => {
      if (signal) {
        signal(reject, this);
      }
      originalFetch(url, options)
        .then(resolve)
        .catch(reject);
    });
  };

  window.fetch = customFetch;
}

Please have in mind that the code is not tested! Let me know if you have tested it and something didn't work. It may give you warnings that you try to overwrite the 'fetch' function from the JavaScript official library.

Stop and Start a service via batch or cmd file?

Use the SC (service control) command, it gives you a lot more options than just start & stop.

  DESCRIPTION:
          SC is a command line program used for communicating with the
          NT Service Controller and services.
  USAGE:
      sc <server> [command] [service name]  ...

      The option <server> has the form "\\ServerName"
      Further help on commands can be obtained by typing: "sc [command]"
      Commands:
        query-----------Queries the status for a service, or
                        enumerates the status for types of services.
        queryex---------Queries the extended status for a service, or
                        enumerates the status for types of services.
        start-----------Starts a service.
        pause-----------Sends a PAUSE control request to a service.
        interrogate-----Sends an INTERROGATE control request to a service.
        continue--------Sends a CONTINUE control request to a service.
        stop------------Sends a STOP request to a service.
        config----------Changes the configuration of a service (persistant).
        description-----Changes the description of a service.
        failure---------Changes the actions taken by a service upon failure.
        qc--------------Queries the configuration information for a service.
        qdescription----Queries the description for a service.
        qfailure--------Queries the actions taken by a service upon failure.
        delete----------Deletes a service (from the registry).
        create----------Creates a service. (adds it to the registry).
        control---------Sends a control to a service.
        sdshow----------Displays a service's security descriptor.
        sdset-----------Sets a service's security descriptor.
        GetDisplayName--Gets the DisplayName for a service.
        GetKeyName------Gets the ServiceKeyName for a service.
        EnumDepend------Enumerates Service Dependencies.

      The following commands don't require a service name:
      sc <server> <command> <option>
        boot------------(ok | bad) Indicates whether the last boot should
                        be saved as the last-known-good boot configuration
        Lock------------Locks the Service Database
        QueryLock-------Queries the LockStatus for the SCManager Database
  EXAMPLE:
          sc start MyService

how to use json file in html code

use jQuery's $.getJSON

$.getJSON('mydata.json', function(data) {
    //do stuff with your data here
});

Background color not showing in print preview

Chrome will not render background-color, or several other styles, when printing if the background graphics setting is turned off.

This has nothing to do with css, @media, or specificity. You can probably hack your way around it, but the easiest way to get chrome to show the background-color and other graphics is to properly check this checkbox under More Settings.

enter image description here

SQL Server date format yyyymmdd

try this....

SELECT FORMAT(CAST(DOB AS DATE),'yyyyMMdd') FROM Employees;

How do you update a DateTime field in T-SQL?

Normally, it should work.

But can you try this? I don't have SQL on my home PC, I can't try myself

UPDATE table
SET EndDate = '2009-05-25 00:00:00.000'
WHERE Id = 1

How to convert char to integer in C?

In the old days, when we could assume that most computers used ASCII, we would just do

int i = c[0] - '0';

But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.

Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.

What is the Maximum Size that an Array can hold?

Per MSDN it is

By default, the maximum size of an Array is 2 gigabytes (GB).

In a 64-bit environment, you can avoid the size restriction by setting the enabled attribute of the gcAllowVeryLargeObjects configuration element to true in the run-time environment.

However, the array will still be limited to a total of 4 billion elements.

Refer Here http://msdn.microsoft.com/en-us/library/System.Array(v=vs.110).aspx

Note: Here I am focusing on the actual length of array by assuming that we will have enough hardware RAM.

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

Just adding here that [[ also is equipped for recursive indexing.

This was hinted at in the answer by @JijoMatthew but not explored.

As noted in ?"[[", syntax like x[[y]], where length(y) > 1, is interpreted as:

x[[ y[1] ]][[ y[2] ]][[ y[3] ]] ... [[ y[length(y)] ]]

Note that this doesn't change what should be your main takeaway on the difference between [ and [[ -- namely, that the former is used for subsetting, and the latter is used for extracting single list elements.

For example,

x <- list(list(list(1), 2), list(list(list(3), 4), 5), 6)
x
# [[1]]
# [[1]][[1]]
# [[1]][[1]][[1]]
# [1] 1
#
# [[1]][[2]]
# [1] 2
#
# [[2]]
# [[2]][[1]]
# [[2]][[1]][[1]]
# [[2]][[1]][[1]][[1]]
# [1] 3
#
# [[2]][[1]][[2]]
# [1] 4
#
# [[2]][[2]]
# [1] 5
#
# [[3]]
# [1] 6

To get the value 3, we can do:

x[[c(2, 1, 1, 1)]]
# [1] 3

Getting back to @JijoMatthew's answer above, recall r:

r <- list(1:10, foo=1, far=2)

In particular, this explains the errors we tend to get when mis-using [[, namely:

r[[1:3]]

Error in r[[1:3]] : recursive indexing failed at level 2

Since this code actually tried to evaluate r[[1]][[2]][[3]], and the nesting of r stops at level one, the attempt to extract through recursive indexing failed at [[2]], i.e., at level 2.

Error in r[[c("foo", "far")]] : subscript out of bounds

Here, R was looking for r[["foo"]][["far"]], which doesn't exist, so we get the subscript out of bounds error.

It probably would be a bit more helpful/consistent if both of these errors gave the same message.

is there any alternative for ng-disabled in angular2?

Yes You can either set [disabled]= "true" or if it is an radio button or checkbox then you can simply use disable

For radio button:

<md-radio-button disabled>Select color</md-radio-button>

For dropdown:

<ng-select (selected)="someFunction($event)" [disabled]="true"></ng-select>

Cannot find R.layout.activity_main

I used maven as build tool, after I build my project and dig a lot in the internet to solution. My problem resolved by adding to the main_activity.xml

tools:context=".MainActivity"

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

That very well may be a false positive. Like the warning message says, it is common for a capture to start in the middle of a tcp session. In those cases it does not have that information. If you are really missing acks then it is time to start looking upstream from your host for where they are disappearing. It is possible that tshark can not keep up with the data and so it is dropping some metrics. At the end of your capture it will tell you if the "kernel dropped packet" and how many. By default tshark disables dns lookup, tcpdump does not. If you use tcpdump you need to pass in the "-n" switch. If you are having a disk IO issue then you can do something like write to memory /dev/shm. BUT be careful because if your captures get very large then you can cause your machine to start swapping.

My bet is that you have some very long running tcp sessions and when you start your capture you are simply missing some parts of the tcp session due to that. Having said that, here are some of the things that I have seen cause duplicate/missing acks.

  1. Switches - (very unlikely but sometimes they get in a sick state)
  2. Routers - more likely than switches, but not much
  3. Firewall - More likely than routers. Things to look for here are resource exhaustion (license, cpu, etc)
  4. Client side filtering software - antivirus, malware detection etc.

ASP.NET Web API session or something?

in Global.asax add

public override void Init()
{
    this.PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
    base.Init();
}

void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
    System.Web.HttpContext.Current.SetSessionStateBehavior(
        SessionStateBehavior.Required);
}

give it a shot ;)

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.

How do check if a PHP session is empty?

Use isset, empty or array_key_exists (especially for array keys) before accessing a variable whose existence you are not sure of. So change the order in your second example:

if (!isset($_SESSION['something']) || $_SESSION['something'] == '')

What does this GCC error "... relocation truncated to fit..." mean?

On Cygwin -mcmodel=medium is already default and doesn't help. To me adding -Wl,--image-base -Wl,0x10000000 to GCC linker did fixed the error.

Setting up maven dependency for SQL Server

<dependency>
  <groupId>com.hynnet</groupId>
  <artifactId>sqljdbc4-chs</artifactId>
  <version>4.0.2206.100</version>
</dependency>

This worked for me(if you use maven)

https://search.maven.org/artifact/com.hynnet/sqljdbc4-chs/4.0.2206.100/jar

How to document Python code using Doxygen

Sphinx is mainly a tool for formatting docs written independently from the source code, as I understand it.

For generating API docs from Python docstrings, the leading tools are pdoc and pydoctor. Here's pydoctor's generated API docs for Twisted and Bazaar.

Of course, if you just want to have a look at the docstrings while you're working on stuff, there's the "pydoc" command line tool and as well as the help() function available in the interactive interpreter.

Selecting a row in DataGridView programmatically

You can use the Select method if you have a datasource: http://msdn.microsoft.com/en-us/library/b51xae2y%28v=vs.71%29.aspx

Or use linq if you have objects in you datasource

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

>>> re.split('(\W)', 'foo/bar spam\neggs')
['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs']

How to call a method in MainActivity from another class?

What I have done with no memory leaks or lint warnings is to use @f.trajkovski's method, but instead of using MainActivity, use WeakReference<MainActivity> instead.

public class MainActivity extends AppCompatActivity {
public static WeakReference<MainActivity> weakActivity;
// etc..
 public static MainActivity getmInstanceActivity() {
    return weakActivity.get();
}
}

Then in MainActivity OnCreate()

weakActivity = new WeakReference<>(MainActivity.this);

Then in another class

MainActivity.getmInstanceActivity().yourMethod();

Works like a charm

How do you overcome the HTML form nesting limitation?

Kind of an old topic, but this one might be useful for someone:

As someone mentioned above - you can use a dummy form. I had to overcome this issue some time ago. At first, I totally forgot about this HTML restriction and just added the nested forms. The result was interesting - I lost my first form from the nested. Then it turned out to be some kind of a "trick" to simply add a dummy form (that will be removed from the browser) before the actual nested forms.

In my case it looks like this:

<form id="Main">
  <form></form> <!--this is the dummy one-->
  <input...><form id="Nested 1> ... </form>
  <input...><form id="Nested 1> ... </form>
  <input...><form id="Nested 1> ... </form>
  <input...><form id="Nested 1> ... </form>
  ......
</form>

Works fine with Chrome, Firefox, and Safari. IE up to 9 (not sure about 10) and Opera does not detect parameters in the main form. The $_REQUEST global is empty, regardless of the inputs. Inner forms seem to work fine everywhere.

Haven't tested another suggestion described here - fieldset around nested forms.

EDIT: Frameset didn't work! I simply added the Main form after the others (no more nested forms) and used jQuery's "clone" to duplicate inputs in the form on button click. Added .hide() to each of the cloned inputs to keep layout unchanged and now it works like a charm.

Oracle JDBC intermittent Connection Issue

Just to clarify - at least from what we found on our side! It is an issue with the setup of the randomizer for Linux in the JDK distribution - and we found it in Java6, not sure about Java7. The syntax for linux for the randomizer is file:///dev/urandom, but the entry in the file is (probably left/copied from Windows) as file:/dev/urandom. So then Java probably falls back on the default, which happens to be /dev/random. And which doesn't work on a headless machine!!!

How can I run a php without a web server?

You can use these kind of programs to emulate an apache web server and run PHP on your computer:

http://www.wampserver.com/en/

http://www.apachefriends.org/en/xampp.html

How to get some values from a JSON string in C#?

Create a class like this:

public class Data
{
    public string Id {get; set;}
    public string Name {get; set;}
    public string First_Name {get; set;}
    public string Last_Name {get; set;}
    public string Username {get; set;}
    public string Gender {get; set;}
    public string Locale {get; set;}
}

(I'm not 100% sure, but if that doesn't work you'll need use [DataContract] and [DataMember] for DataContractJsonSerializer.)

Then create JSonSerializer:

private static readonly XmlObjectSerializer Serializer = new DataContractJsonSerializer(typeof(Data));

and deserialize object:

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
using(var stream = new MemoryStream(byteArray))
{
    (Data)Serializer.ReadObject(stream);
}

How to rename a component in Angular CLI?

Just rename the files and components as you normally would think, then restart ng serve. Easy peasy.

Rename the files, paths, and references. The key is that you have to close your running server and start it again after everything is renamed.

Update TextView Every Second

If you want to show time on textview then better use Chronometer or TextClock

Using Chronometer:This was added in API 1. It has lot of option to customize it.

Your xml

<Chronometer
    android:id="@+id/chronometer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="30sp" />

Your activity

Chronometer mChronometer=(Chronometer) findViewById(R.id.chronometer);
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();

Using TextClock: This widget is introduced in API level 17. I personally like Chronometer.

Your xml

<TextClock
    android:id="@+id/textClock"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:format12Hour="hh:mm:ss a"
    android:gravity="center_horizontal"
    android:textColor="#d41709"
    android:textSize="44sp"
    android:textStyle="bold" />

Thats it, you are done.

You can use any of these two widgets. This will make your life easy.

Convert byte[] to char[]

System.Text.Encoding.ChooseYourEncoding.GetString(bytes).ToCharArray();

Substitute the right encoding above: e.g.

System.Text.Encoding.UTF8.GetString(bytes).ToCharArray();

Removing a non empty directory programmatically in C or C++

If you are using a POSIX compliant OS, you could use nftw() for file tree traversal and remove (removes files or directories). If you are in C++ and your project uses boost, it is not a bad idea to use the Boost.Filesystem as suggested by Manuel.

In the code example below I decided not to traverse symbolic links and mount points (just to avoid a grand removal:) ):

#include <stdio.h>
#include <stdlib.h>
#include <ftw.h>

static int rmFiles(const char *pathname, const struct stat *sbuf, int type, struct FTW *ftwb)
{
    if(remove(pathname) < 0)
    {
        perror("ERROR: remove");
        return -1;
    }
    return 0;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr,"usage: %s path\n",argv[0]);
        exit(1);
    }

    // Delete the directory and its contents by traversing the tree in reverse order, without crossing mount boundaries and symbolic links

    if (nftw(argv[1], rmFiles,10, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) < 0)
    {
        perror("ERROR: ntfw");
        exit(1);
    }

    return 0;
}

Pass parameter to EventHandler

Timer.Elapsed expects method of specific signature (with arguments object and EventArgs). If you want to use your PlayMusicEvent method with additional argument evaluated during event registration, you can use lambda expression as an adapter:

myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));

Edit: you can also use shorter version:

myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);

CMake unable to determine linker language with C++

I also got the error you mention:

CMake Error: CMake can not determine linker language for target:helloworld
CMake Error: Cannot determine link language for target "helloworld".

In my case this was due to having C++ files with the .cc extension.

If CMake is unable to determine the language of the code correctly you can use the following:

set_target_properties(hello PROPERTIES LINKER_LANGUAGE CXX)

The accepted answer that suggests appending the language to the project() statement simply adds more strict checking for what language is used (according to the documentation), but it wasn't helpful to me:

Optionally you can specify which languages your project supports. Example languages are CXX (i.e. C++), C, Fortran, etc. By default C and CXX are enabled. E.g. if you do not have a C++ compiler, you can disable the check for it by explicitly listing the languages you want to support, e.g. C. By using the special language "NONE" all checks for any language can be disabled. If a variable exists called CMAKE_PROJECT__INCLUDE_FILE, the file pointed to by that variable will be included as the last step of the project command.

Does it make sense to use Require.js with Angular.js?

It makes sense to use requirejs with angularjs if you plan on lazy loading controllers and directives etc, while also combining multiple lazy dependencies into single script files for much faster lazy loading. RequireJS has an optimisation tool that makes the combining easy. See http://ify.io/using-requirejs-with-optimisation-for-lazy-loading-angularjs-artefacts/

Is it possible to use JS to open an HTML select to show its option list?

Unfortunately there's a simple answer to this question, and it's "No"

Javascript format date / time

Please do not reinvent the wheel. There are many open-source & COTS solutions that already exist to solve this problem.

Please take a look at the following JavaScript libraries:


Demo

I wrote a one-liner using Moment.js below. You can check out the demo here: JSFiddle.

moment('2014-08-20 15:30:00').format('MM/DD/YYYY h:mm a'); // 08/20/2014 3:30 pm

jQuery delete confirmation box

Update JQuery for version 1.9.1 link for deletion is here $("#div1").find('button').click(function(){...}

You need to use a Theme.AppCompat theme (or descendant) with this activity

In my case, i was inflating a view with ApplicationContext. When you use ApplicationContext, theme/style is not applied, so although there was Theme.Appcompat in my style, it was not applied and caused this exception. More details: Theme/Style is not applied when inflater used with ApplicationContext

Add custom message to thrown exception while maintaining stack trace in Java

There is an Exception constructor that takes also the cause argument: Exception(String message, Throwable t).

You can use it to propagate the stacktrace:

try{
    //...
}catch(Exception E){
    if(!transNbr.equals("")){
        throw new Exception("transaction: " + transNbr, E); 
    }
    //...
}

Iterating through a List Object in JSP

another example with just scriplets, when iterating through an ArrayList that contains Maps.

<%   
java.util.List<java.util.Map<String,String>> employees=(java.util.List<java.util.Map<String, String>>)request.getAttribute("employees");    

for (java.util.Map employee: employees) {
%>
<tr>
<td><input value="<%=employee.get("fullName") %>"/></td>    
</tr>
...
<%}%>

CodeIgniter 500 Internal Server Error

Try this to your .htaccess file:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule >

Accessing MP3 metadata with Python

The first answer that uses eyed3 is outdated so here is an updated version of it.

Reading tags from an mp3 file:

 import eyed3

 audiofile = eyed3.load("some/file.mp3")
 print(audiofile.tag.artist)
 print(audiofile.tag.album)
 print(audiofile.tag.album_artist)
 print(audiofile.tag.title)
 print(audiofile.tag.track_num)

An example from the website to modify tags:

 import eyed3

 audiofile = eyed3.load("some/file.mp3")
 audiofile.tag.artist = u"Integrity"
 audiofile.tag.album = u"Humanity Is The Devil"
 audiofile.tag.album_artist = u"Integrity"
 audiofile.tag.title = u"Hollow"
 audiofile.tag.track_num = 2

An issue I encountered while trying to use eyed3 for the first time had to do with an import error of libmagic even though it was installed. To fix this install the magic-bin whl from here

Enum to String C++

Kind of an anonymous lookup table rather than a long switch statement:

return (const char *[]) {
    "bananas & monkeys",
    "Round and orange", 
    "APPLE",
}[enumVal];

Making a <button> that's a link in HTML

You have three options:

  • Style links to look like buttons using CSS.

    Just look at the light blue "tags" under your question.

    It is possible, even to give them a depressed appearance when clicked (using pseudo-classes like :active), without any scripting. Lots of major sites, such as Google, are starting to make buttons out of CSS styles these days anyway, scripting or not.

  • Put a separate <form> element around each one.

    As you mentioned in the question. Easy and will definitely work without Javascript (or even CSS). But it adds a little extra code which may look untidy.

  • Rely on Javascript.

    Which is what you said you didn't want to do.

Installing python module within code

for installing multiple packages, i am using a setup.py file with following code:

import sys
import subprocess
import pkg_resources

required = {'numpy','pandas','<etc>'} 
installed = {pkg.key for pkg in pkg_resources.working_set}
missing = required - installed


if missing:
    # implement pip as a subprocess:
    subprocess.check_call([sys.executable, '-m', 'pip', 'install',*missing])

hidden field in php

You absolutely can, I use this approach a lot w/ both JavaScript and PHP.

Field definition:

<input type="hidden" name="foo" value="<?php echo $var;?>" />

Access w/ PHP:

$_GET['foo'] or $_POST['foo']

Also: Don't forget to sanitize your inputs if they are going into a database. Feel free to use my routine: https://github.com/niczak/PHP-Sanitize-Post/blob/master/sanitize.php

Cheers!

IntelliJ IDEA "cannot resolve symbol" and "cannot resolve method"

For me, IntelliJ could autocomplete packages, but never seemed to admit there were actual classes at any level of the hierarchy. Neither re-choosing the SDK nor re-creating the project seemed to fix it.

What did fix it was to delete the per-user IDEA directory ( in my case ~/.IntelliJIdea2017.1/) which meant losing all my other customizations... But at least it made the issue go away.

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

UPDATE  table
SET     columnx = CASE WHEN condition THEN 25 ELSE columnx END,
        columny = CASE WHEN condition THEN columny ELSE 25 END

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

NTFS performance and large volumes of files and directories

When you create a folder with N entries, you create a list of N items at file-system level. This list is a system-wide shared data structure. If you then start modifying this list continuously by adding/removing entries, I expect at least some lock contention over shared data. This contention - theoretically - can negatively affect performance.

For read-only scenarios I can't imagine any reason for performance degradation of directories with large number of entries.

Get Selected value from Multi-Value Select Boxes by jquery-select2?

Please, ckeck this simple example. You can get values in select2 multi.

var values = $('#id-select2-multi').val();
console.log(values);

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

How to set up file permissions for Laravel?

I decided to write my own script to ease some of the pain of setting up projects.

Run the following inside your project root:

wget -qO- https://raw.githubusercontent.com/defaye/bootstrap-laravel/master/bootstrap.sh | sh

Wait for the bootstrapping to complete and you're good to go.

Review the script before use.

Using VBA code, how to export Excel worksheets as image in Excel 2003?

Winand, Quality was also an issue for me so I did this:

For Each ws In ActiveWorkbook.Worksheets
    If ws.PageSetup.PrintArea <> "" Then
        'Reverse the effects of page zoom on the exported image
        zoom_coef = 100 / ws.Parent.Windows(1).Zoom
        areas = Split(ws.PageSetup.PrintArea, ",")
        areaNo = 0
        For Each a In areas
            Set area = ws.Range(a)
            ' Change xlPrinter to xlScreen to see zooming white space
            area.CopyPicture Appearance:=xlPrinter, Format:=xlPicture
            Set chartobj = ws.ChartObjects.Add(0, 0, area.Width * zoom_coef, area.Height * zoom_coef)
            chartobj.Chart.Paste
            'scale the image before export
            ws.Shapes(chartobj.Index).ScaleHeight 3, msoFalse, msoScaleFromTopLeft
            ws.Shapes(chartobj.Index).ScaleWidth 3, msoFalse, msoScaleFromTopLeft
            chartobj.Chart.Export ws.Name & "-" & areaNo & ".png", "png"
            chartobj.delete
            areaNo = areaNo + 1
        Next
    End If
Next

See here:https://robp30.wordpress.com/2012/01/11/improving-the-quality-of-excel-image-export/

Get value of div content using jquery

Try this to get value of div content using jquery.

_x000D_
_x000D_
    $(".showplaintext").click(function(){_x000D_
        alert($(".plain").text());_x000D_
    });_x000D_
    _x000D_
    // Show text content of formatted paragraph_x000D_
    $(".showformattedtext").click(function(){_x000D_
        alert($(".formatted").text());_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p class="plain">Exploring the zoo, we saw every kangaroo jump and quite a few carried babies. </p>_x000D_
    <p class="formatted">Exploring the zoo<strong>, we saw every kangaroo</strong> jump <em><sup> and quite a </sup></em>few carried <a href="#"> babies</a>.</p>_x000D_
    <button type="button" class="showplaintext">Get Plain Text</button>_x000D_
    <button type="button" class="showformattedtext">Get Formatted Text</button>
_x000D_
_x000D_
_x000D_

Taken from @ Get the text inside an element using jQuery

How to run .sh on Windows Command Prompt?

The error message indicates that you have not installed bash, or it is not in your PATH.

The top Google hit is http://win-bash.sourceforge.net/ but you also need to understand that most Bash scripts expect a Unix-like environment; so just installing Bash is probably unlikely to allow you to run a script you found on the net, unless it was specifically designed for this particular usage scenario. The usual solution to that is https://www.cygwin.com/ but there are many possible alternatives, depending on what exactly it is that you want to accomplish.

If Windows is not central to your usage scenario, installing a free OS (perhaps virtualized) might be the simplest way forward.

The second error message is due to the fact that Windows nominally accepts forward slash as a directory separator, but in this context, it is being interpreted as a switch separator. In other words, Windows parses your command line as app /build /build.sh (or, to paraphrase with Unix option conventions, app --build --build.sh). You could try app\build\build.sh but it is unlikely to work, because of the circumstances outlined above.

Access 2010 VBA query a table and iterate through results

Ahh. Because I missed the point of you initial post, here is an example which also ITERATES. The first example did not. In this case, I retreive an ADODB recordset, then load the data into a collection, which is returned by the function to client code:

EDIT: Not sure what I screwed up in pasting the code, but the formatting is a little screwball. Sorry!

Public Function StatesCollection() As Collection
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim colReturn As New Collection

Set colReturn = New Collection

Dim SQL As String
SQL = _
    "SELECT tblState.State, tblState.StateName " & _
    "FROM tblState"

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command

With cn
    .Provider = DataConnection.MyADOProvider
    .ConnectionString = DataConnection.MyADOConnectionString
    .Open
End With

With cmd
    .CommandText = SQL
    .ActiveConnection = cn
End With

Set rs = cmd.Execute

With rs
    If Not .EOF Then
    Do Until .EOF
        colReturn.Add Nz(!State, "")
        .MoveNext
    Loop
    End If
    .Close
End With
cn.Close

Set rs = Nothing
Set cn = Nothing

Set StatesCollection = colReturn

End Function

How to find children of nodes using BeautifulSoup

"How to find all a which are children of <li class=test> but not any others?"

Given the HTML below (I added another <a> to show te difference between select and select_one):

<div>
  <li class="test">
    <a>link1</a>
    <ul>
      <li>
        <a>link2</a>
      </li>
    </ul>
    <a>link3</a>
  </li>
</div>

The solution is to use child combinator (>) that is placed between two CSS selectors:

>>> soup.select('li.test > a')
[<a>link1</a>, <a>link3</a>]

In case you want to find only the first child:

>>> soup.select_one('li.test > a')
<a>link1</a>

How can I pad a String in Java?

Besides Apache Commons, also see String.format which should be able to take care of simple padding (e.g. with spaces).

How I can filter a Datatable?

You can use DataView.

DataView dv = new DataView(yourDatatable);
dv.RowFilter = "query"; // query example = "id = 10"


http://www.csharp-examples.net/dataview-rowfilter/

Access-Control-Allow-Origin Multiple Origin Domains?

For multiple domains, in your .htaccess:

<IfModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www\.)?(domain1.example|domain2.example)$" AccessControlAllowOrigin=$0$1
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header set Access-Control-Allow-Credentials true
</IfModule>

IE 8: background-size fix

I created jquery.backgroundSize.js: a 1.5K jquery plugin that can be used as a IE8 fallback for "cover" and "contain" values. Have a look at the demo.

Solving your problem could be as simple as:

$("h2#news").css({backgroundSize: "cover"});

What is the difference/usage of homebrew, macports or other package installation tools?

Homebrew and macports both solve the same problem - that is the installation of common libraries and utilities that are not bundled with osx.

Typically these are development related libraries and the most common use of these tools is for developers working on osx.

They both need the xcode command line tools installed (which you can download separately from https://developer.apple.com/), and for some specific packages you will need the entire xcode IDE installed.

xcode can be installed from the mac app store, its a free download but it takes a while since its around 5GB (if I remember correctly).

macports is an osx version of the port utility from BSD (as osx is derived from BSD, this was a natural choice). For anyone familiar with any of the BSD distributions, macports will feel right at home.

One major difference between homebrew and macports; and the reason I prefer homebrew is that it will not overwrite things that should be installed "natively" in osx. This means that if there is a native package available, homebrew will notify you instead of overwriting it and causing problems further down the line. It also installs libraries in the user space (thus, you don't need to use "sudo" to install things). This helps when getting rid of libraries as well since everything is in a path accessible to you.

homebrew also enjoys a more active user community and its packages (called formulas) are updated quite often.


macports does not overwrite native OSX packages - it supplies its own version - This is the main reason I prefer macports over home-brew, you need to be certain of what you are using and Apple's change at different times to the ports and have been know to be years behind updates in some projects

Can you give a reference showing that macports overwrites native OS X packages? As far as I can tell, all macports installation happens in /opt/local

Perhaps I should clarify - I did not say anywhere in my answer that macports overwrites OSX native packages. They both install items separately.

Homebrew will warn you when you should install things "natively" (using the library/tool's preferred installer) for better compatibility. This is what I meant. It will also use as many of the local libraries that are available in OS X. From the wiki:

We really don’t like dupes in Homebrew/homebrew

However, we do like dupes in the tap!

Stuff that comes with OS X or is a library that is provided by RubyGems, CPAN or PyPi should not be duped. There are good reasons for this:

  • Duplicate libraries regularly break builds
  • Subtle bugs emerge with duplicate libraries, and to a lesser extent, duplicate tools
  • We want you to try harder to make your formula work with what OS X comes with

You can optionally overwrite the macosx supplied versions of utilities with homebrew.

module.exports vs exports in Node.js

Initially,module.exports=exports , and the require function returns the object module.exports refers to.

if we add property to the object, say exports.a=1, then module.exports and exports still refer to the same object. So if we call require and assign the module to a variable, then the variable has a property a and its value is 1;

But if we override one of them, for example, exports=function(){}, then they are different now: exports refers to a new object and module.exports refer to the original object. And if we require the file, it will not return the new object, since module.exports is not refer to the new object.

For me, i will keep adding new property, or override both of them to a new object. Just override one is not right. And keep in mind that module.exports is the real boss.