Programs & Examples On #Sharepoint api

Microsoft SharePoint API

How to write and save html file in python?

print('<tr><td>%04d</td>' % (i+1), file=Html_file)

How do I copy a version of a single file from one git branch to another?

What about using checkout command :

  git diff --stat "$branch"
  git checkout --merge "$branch" "$file"
  git diff --stat "$branch"

Remove all child nodes from a parent?

A other users suggested,

.empty()

is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.

If you wish to keep data, like event handlers for example, you should use

.detach()

as described on the JQuery's API detach documentation.

The method .remove() could be usefull for similar purposes.

correct PHP headers for pdf file download

There are some things to be considered in your code.

First, write those headers correctly. You will never see any server sending Content-type:application/pdf, the header is Content-Type: application/pdf, spaced, with capitalized first letters etc.

The file name in Content-Disposition is the file name only, not the full path to it, and altrough I don't know if its mandatory or not, this name comes wrapped in " not '. Also, your last ' is missing.

Content-Disposition: inline implies the file should be displayed, not downloaded. Use attachment instead.

In addition, make the file extension in upper case to make it compatible with some mobile devices. (Update: Pretty sure only Blackberries had this problem, but the world moved on from those so this may be no longer a concern)

All that being said, your code should look more like this:

<?php

    $filename = './pdf/jobs/pdffile.pdf';

    $fileinfo = pathinfo($filename);
    $sendname = $fileinfo['filename'] . '.' . strtoupper($fileinfo['extension']);

    header('Content-Type: application/pdf');
    header("Content-Disposition: attachment; filename=\"$sendname\"");
    header('Content-Length: ' . filesize($filename));
    readfile($filename);

Content-Length is optional but is also important if you want the user to be able to keep track of the download progress and detect if the download was interrupted. But when using it you have to make sure you won't be send anything along with the file data. Make sure there is absolutely nothing before <?php or after ?>, not even an empty line.

How to fix nginx throws 400 bad request headers on any header testing tools?

Yes changing the error_to debug level as Emmanuel Joubaud suggested worked out (edit /etc/nginx/sites-enabled/default ):

        error_log /var/log/nginx/error.log debug;

Then after restaring nginx I got in the error log with my Python application using uwsgi:

        2017/02/08 22:32:24 [debug] 1322#1322: *1 connect to unix:///run/uwsgi/app/socket, fd:20 #2
        2017/02/08 22:32:24 [debug] 1322#1322: *1 connected
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream connect: 0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 posix_memalign: 0000560E1F25A2A0:128 @16
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream send request
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream send request body
        2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer buf fl:0 s:454
        2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer in: 0000560E1F2A0928
        2017/02/08 22:32:24 [debug] 1322#1322: *1 writev: 454 of 454
        2017/02/08 22:32:24 [debug] 1322#1322: *1 chain writer out: 0000000000000000
        2017/02/08 22:32:24 [debug] 1322#1322: *1 event timer add: 20: 60000:1486593204249
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http finalize request: -4, "/?" a:1, c:2
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http request count:2 blk:0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 post event 0000560E1F2E5DE0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 post event 0000560E1F2E5E40
        2017/02/08 22:32:24 [debug] 1322#1322: *1 delete posted event 0000560E1F2E5DE0
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http run request: "/?"
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream check client, write event:1, "/"
        2017/02/08 22:32:24 [debug] 1322#1322: *1 http upstream recv(): -1 (11: Resource temporarily unavailable)

Then I took a look to my uwsgi log and found out that:

        Invalid HTTP_HOST header: 'www.mysite.local'. You may need to add u'www.mysite.local' to ALLOWED_HOSTS.
        [pid: 10903|app: 0|req: 2/4] 192.168.221.2 () {38 vars in 450 bytes} [Wed Feb  8 22:32:24 2017] GET / => generated 54098 bytes in 55 msecs (HTTP/1.1 400) 4 headers in 135 bytes (1 switches on core 0)

And adding www.mysite.local to the settings.py ALLOWED_HOSTS fixed the issue :)

        ALLOWED_HOSTS = ['www.mysite.local']

How to use QueryPerformanceCounter?

#include <windows.h>

double PCFreq = 0.0;
__int64 CounterStart = 0;

void StartCounter()
{
    LARGE_INTEGER li;
    if(!QueryPerformanceFrequency(&li))
    cout << "QueryPerformanceFrequency failed!\n";

    PCFreq = double(li.QuadPart)/1000.0;

    QueryPerformanceCounter(&li);
    CounterStart = li.QuadPart;
}
double GetCounter()
{
    LARGE_INTEGER li;
    QueryPerformanceCounter(&li);
    return double(li.QuadPart-CounterStart)/PCFreq;
}

int main()
{
    StartCounter();
    Sleep(1000);
    cout << GetCounter() <<"\n";
    return 0;
}

This program should output a number close to 1000 (windows sleep isn't that accurate, but it should be like 999).

The StartCounter() function records the number of ticks the performance counter has in the CounterStart variable. The GetCounter() function returns the number of milliseconds since StartCounter() was last called as a double, so if GetCounter() returns 0.001 then it has been about 1 microsecond since StartCounter() was called.

If you want to have the timer use seconds instead then change

PCFreq = double(li.QuadPart)/1000.0;

to

PCFreq = double(li.QuadPart);

or if you want microseconds then use

PCFreq = double(li.QuadPart)/1000000.0;

But really it's about convenience since it returns a double.

Warn user before leaving web page with unsaved changes

I made following code. It can compare changes in all fields (except those marked with .ignoreDirty class) or optionally for currently visible fields only. It can be reinitialized for new fields added by Javascript. From that reason I save not the form status but the status of each control.

/* Dirty warning for forms */
dirty = (skipHiddenOrNullToInit) => {
    /*  will return True if there are changes in form(s)
        for first initialization you can use both: .dirty(null) or .dirty() (ignore its result)
            .dirty(null) will (re)initialize all controls - in addititon use it after Save if you stay on same page
            .dirty() will initialize new controls - in addititon use it if you add new fields with JavaScript
        then
            .dirty() (or: .dirty(false)) says if data are changed without regard to hidden fields
            .dirty(true) says if data are changed with regard to hidden fields (ie. fields with .d-none or .hidden class)
        controls with .ignoreDirty class will be skipped always
        previous about .d-none, .hidden, .ignoreDirty applies to the control itself and all its ancestors
    */
    let isDirty = false;
    let skipSelectors = '.ignoreDirty';
    if (skipHiddenOrNullToInit) {
        skipSelectors += ', .d-none, .hidden'
    } else if (skipHiddenOrNullToInit === undefined) {
        skipHiddenOrNullToInit = false;
    }
    $('input, select').each(
    function(_idx, el) {
        if ($(el).prop('type') !== 'hidden') {
            let dirtyInit = $(el).data('dirty-init');
            if (skipHiddenOrNullToInit === null || dirtyInit === undefined) {
                try {
                    isChromeAutofillEl = $(el).is(":-webkit-autofill");
                } catch (error) {
                    isChromeAutofillEl = false;
                }
                if (isChromeAutofillEl && $(el).data('dirty-init') === undefined) {
                    setTimeout(function() {  // otherwise problem with Chrome autofilled controls
                        $(el).data('dirty-init', $(el).val());
                    }, 200)
                } else {
                    $(el).data('dirty-init', $(el).val());
                }
            } else if ($(el).closest(skipSelectors).length === 0 && dirtyInit !== $(el).val()) {
                isDirty = true;
                return false; // breaks jQuery .each
            }
        }
    }
    );
    return isDirty;
}

I have additional troubles with Chrome autofill values because it is difficult to initizialize and have them loaded already. So I do not initialize on page load but in any focusin event. (But: Maybe there is still problem with control values changed by JavaScript.) I use following code which I call at page load:

let init_dirty = (ifStayFunc) => {
    /*  ifStayFunc: optional callback when user decides to stay on page
    use .clearDirty class to avoid warning on some button, however:
        if the button fires JavaScript do't use .clearDirty class and instead
            use directly dirty(null) in code - to be sure it will run before window.location */
    $('input, select').on('focusin', function(evt) {
        if (!$('body').data('dirty_initialized')) {
            dirty();
            $('body').data('dirty_initialized', true);
        }
    });
    window.addEventListener('beforeunload', (evt) => {
        if (dirty(true)) {
            if (ifStayFunc) {
                ifStayFunc();
            }
            evt.preventDefault();
            evt.returnValue = '';  // at least Google Chrome requires this
        }
    });
    $('.clearDirty').on('click', function(evt) {
        dirty(null);
    });
};

So, I add the .clearDirty class to the buttons which provide Save and that way I prevent the warning in this case. Callback ifStayFunc allows me to do something if user will Stay on Page while he is warned. Typically I can show additional Save Button (if I have still visible only some default/primary button, which makes Safe+SomethingMore - and I want allow Save withou this "SomethingMore").

Looking for simple Java in-memory cache

Try this:

import java.util.*;

public class SimpleCacheManager {

    private static SimpleCacheManager instance;
    private static Object monitor = new Object();
    private Map<String, Object> cache = Collections.synchronizedMap(new HashMap<String, Object>());

    private SimpleCacheManager() {
    }

    public void put(String cacheKey, Object value) {
        cache.put(cacheKey, value);
    }

    public Object get(String cacheKey) {
        return cache.get(cacheKey);
    }

    public void clear(String cacheKey) {
        cache.put(cacheKey, null);
    }

    public void clear() {
        cache.clear();
    }

    public static SimpleCacheManager getInstance() {
        if (instance == null) {
            synchronized (monitor) {
                if (instance == null) {
                    instance = new SimpleCacheManager();
                }
            }
        }
        return instance;
    }

}

How to get the first column of a pandas DataFrame as a Series?

You can get the first column as a Series by following code:

x[x.columns[0]]

One liner for If string is not null or empty else

Old question, but thought I'd add this to help out,

#if DOTNET35
bool isTrulyEmpty = String.IsNullOrEmpty(s) || s.Trim().Length == 0;
#else
bool isTrulyEmpty = String.IsNullOrWhiteSpace(s) ;
#endif

for-in statement

edit 2018: This is outdated, js and typescript now have for..of loops.
http://www.typescriptlang.org/docs/handbook/iterators-and-generators.html


The book "TypeScript Revealed" says

"You can iterate through the items in an array by using either for or for..in loops as demonstrated here:

// standard for loop
for (var i = 0; i < actors.length; i++)
{
  console.log(actors[i]);
}

// for..in loop
for (var actor in actors)
{
  console.log(actor);
}

"

Turns out, the second loop does not pass the actors in the loop. So would say this is plain wrong. Sadly it is as above, loops are untouched by typescript.

map and forEach often help me and are due to typescripts enhancements on function definitions more approachable, lke at the very moment:

this.notes = arr.map(state => new Note(state));

My wish list to TypeScript;

  1. Generic collections
  2. Iterators (IEnumerable, IEnumerator interfaces would be best)

How to create a oracle sql script spool file

With spool:

  set heading off
  set arraysize 1
  set newpage 0
  set pages 0
  set feedback off
  set echo off
  set verify off

variable cd varchar2(10);
variable d number;

 declare
 ab varchar2(10) := 'Raj';
 a number := 10;
 c number;
 begin
 c := a+10;
 select ab,c into :cd,:d from dual;
 end;

 SPOOL 
 select :cd,:d from dual;
 SPOOL OFF
 EXIT;

Is it possible to set transparency in CSS3 box-shadow?

I suppose rgba() would work here. After all, browser support for both box-shadow and rgba() is roughly the same.

/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);

_x000D_
_x000D_
div {_x000D_
    width: 200px;_x000D_
    height: 50px;_x000D_
    line-height: 50px;_x000D_
    text-align: center;_x000D_
    color: white;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
  box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
_x000D_
_x000D_

How to get subarray from array?

The question is actually asking for a New array, so I believe a better solution would be to combine Abdennour TOUMI's answer with a clone function:

_x000D_
_x000D_
function clone(obj) {_x000D_
  if (null == obj || "object" != typeof obj) return obj;_x000D_
  const copy = obj.constructor();_x000D_
  for (const attr in obj) {_x000D_
    if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];_x000D_
  }_x000D_
  return copy;_x000D_
}_x000D_
_x000D_
// With the `clone()` function, you can now do the following:_x000D_
_x000D_
Array.prototype.subarray = function(start, end) {_x000D_
  if (!end) {_x000D_
    end = this.length;_x000D_
  } _x000D_
  const newArray = clone(this);_x000D_
  return newArray.slice(start, end);_x000D_
};_x000D_
_x000D_
// Without a copy you will lose your original array._x000D_
_x000D_
// **Example:**_x000D_
_x000D_
const array = [1, 2, 3, 4, 5];_x000D_
console.log(array.subarray(2)); // print the subarray [3, 4, 5, subarray: function]_x000D_
_x000D_
console.log(array); // print the original array [1, 2, 3, 4, 5, subarray: function]
_x000D_
_x000D_
_x000D_

[http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object]

Is there an easy way to reload css without reloading the page?

i now have this:

    function swapStyleSheet() {
        var old = $('#pagestyle').attr('href');
        var newCss = $('#changeCss').attr('href');
        var sheet = newCss +Math.random(0,10);
        $('#pagestyle').attr('href',sheet);
        $('#profile').attr('href',old);
        }
    $("#changeCss").on("click", function(event) { 
        swapStyleSheet();
    } );

make any element in your page with id changeCss with a href attribute with the new css url in it. and a link element with the starting css:

<link id="pagestyle" rel="stylesheet" type="text/css" href="css1.css?t=" />

<img src="click.jpg" id="changeCss" href="css2.css?t=">

How to convert string to boolean in typescript Angular 4

You can use that:

let s: string = "true";
let b: boolean = Boolean(s);

How to write character & in android strings.xml

To avoid the error, use extract string:

<string name="travels_tours_pvt_ltd"><![CDATA[Travels & Tours (Pvt) Ltd.]]></string>

Get week day name from a given month, day and year individually in SQL Server

select to_char(sysdate,'DAY') from dual; It's work try it

Default keystore file does not exist?

go to ~/.android if there is no debug.keystore copy it from your project and paste it here then run command again.

NodeJS w/Express Error: Cannot GET /

You need to define a root route.

app.get('/', function(req, res) {
  // do something here.
});

Oh and you cannot specify a file within the express.static. It needs to be a directory. The app.get('/'.... will be responsible to render that file accordingly. You can use express' render method, but your going to have to add some configuration options that will tell express where your views are, traditionally within the app/views/ folder.

Using a dictionary to count the items in a list

How about this:

src = [ 'one', 'two', 'three', 'two', 'three', 'three' ]
result_dict = dict( [ (i, src.count(i)) for i in set(src) ] )

This results in

{'one': 1, 'three': 3, 'two': 2}

Check if not nil and not empty in Rails shortcut?

There's a method that does this for you:

def show
  @city = @user.city.present?
end

The present? method tests for not-nil plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.

Since this pattern is so common there's even a shortcut in ActiveRecord:

def show
  @city = @user.city?
end

This is roughly equivalent.

As a note, testing vs nil is almost always redundant. There are only two logically false values in Ruby: nil and false. Unless it's possible for a variable to be literal false, this would be sufficient:

if (variable)
  # ...
end

This is preferable to the usual if (!variable.nil?) or if (variable != nil) stuff that shows up occasionally. Ruby tends to wards a more reductionist type of expression.

One reason you'd want to compare vs. nil is if you have a tri-state variable that can be true, false or nil and you need to distinguish between the last two states.

Ternary operators in JavaScript without an "else"

No, it needs three operands. That's why they're called ternary operators.

However, for what you have as your example, you can do this:

if(condition) x = true;

Although it's safer to have braces if you need to add more than one statement in the future:

if(condition) { x = true; }

Edit: Now that you mention the actual code in which your question applies to:

if(!defaults.slideshowWidth)
    { defaults.slideshowWidth = obj.find('img').width()+'px'; }

ERROR 2003 (HY000): Can't connect to MySQL server (111)

if the system you use is CentOS/RedHat, and rpm is the way you install MySQL, there is no my.cnf in /etc/ folder, you could use: #whereis mysql #cd /usr/share/mysql/ cp -f /usr/share/mysql/my-medium.cnf /etc/my.cnf

Check if element at position [x] exists in the list

if (list.Count > desiredIndex && list[desiredIndex] != null)
{
    // logic
}

When should I use curly braces for ES6 import?

The curly braces are used only for import when export is named. If the export is default then curly braces are not used for import.

Get MD5 hash of big files in Python

u can't get it's md5 without read full content. but u can use update function to read the files content block by block.
m.update(a); m.update(b) is equivalent to m.update(a+b)

How to insert &nbsp; in XSLT

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

<xsl:text> </xsl:text>

ValueError: math domain error

You are trying to do a logarithm of something that is not positive.

Logarithms figure out the base after being given a number and the power it was raised to. log(0) means that something raised to the power of 2 is 0. An exponent can never result in 0*, which means that log(0) has no answer, thus throwing the math domain error

*Note: 0^0 can result in 0, but can also result in 1 at the same time. This problem is heavily argued over.

Python: PIP install path, what is the correct location for this and other addons?

Since pip is an executable and which returns path of executables or filenames in environment. It is correct. Pip module is installed in site-packages but the executable is installed in bin.

How to remove unique key from mysql table

For those who don't know how to get index_name which mentioned in Devart's answer, or key_name which mentioned in Uday Sawant's answer, you can get it like this:

SHOW INDEX FROM table_name;

This will show all indexes for the given table, then you can pick name of the index or unique key that you want to remove.

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

Try this. It worked for me.

Go to RUN and type gpedit.msc then completely disable Onedrive. Have you noticed that the problem only existed after the last large download from Microsoft? It contained this package. I also removed it from the Start menu.

This appears to be the cause of the issue. Something to do with downloading temporary files, which of course an applet is.

Once done everything went back to normal.

Selenium WebDriver findElement(By.xpath()) not working for me

You missed the closing parenthesis at the end:

element = findElement(By.xpath("//[@test-id='test-username']"));

Get selected value of a dropdown's item using jQuery

If you have more than one dropdown try:

HTML:

<select id="dropdown1" onchange="myFunction(this)">
    <option value='...'>Option1
    <option value='...'>Option2
</select>
<select id="dropdown2" onchange="myFunction(this)">
    <option value='...'>Option1
    <option value='...'>Option2
</select>

JavaScript:

    function myFunction(sel) {
        var selected = sel.value;
    }

Combine GET and POST request methods in Spring

Below is one of the way by which you can achieve that, may not be an ideal way to do.

Have one method accepting both types of request, then check what type of request you received, is it of type "GET" or "POST", once you come to know that, do respective actions and the call one method which does common task for both request Methods ie GET and POST.

@RequestMapping(value = "/books")
public ModelAndView listBooks(HttpServletRequest request){
     //handle both get and post request here
     // first check request type and do respective actions needed for get and post.

    if(GET REQUEST){

     //WORK RELATED TO GET

    }else if(POST REQUEST){

      //WORK RELATED TO POST

    }

    commonMethod(param1, param2....);
}

Is there a list of Pytz Timezones?

Here, Python list of country codes, names, continents, capitals, and pytz timezones.

countries = [
{'timezones': ['Europe/Paris'], 'code': 'FR', 'continent': 'Europe', 'name': 'France', 'capital': 'Paris'}
{'timezones': ['Africa/Kampala'], 'code': 'UG', 'continent': 'Africa', 'name': 'Uganda', 'capital': 'Kampala'},
{'timezones': ['Asia/Colombo'], 'code': 'LK', 'continent': 'Asia', 'name': 'Sri Lanka', 'capital': 'Sri Jayewardenepura Kotte'},
{'timezones': ['Asia/Riyadh'], 'code': 'SA', 'continent': 'Asia', 'name': 'Saudi Arabia', 'capital': 'Riyadh'},
{'timezones': ['Africa/Luanda'], 'code': 'AO', 'continent': 'Africa', 'name': 'Angola', 'capital': 'Luanda'},    
{'timezones': ['Europe/Vienna'], 'code': 'AT', 'continent': 'Europe', 'name': 'Austria', 'capital': 'Vienna'},
{'timezones': ['Asia/Calcutta'], 'code': 'IN', 'continent': 'Asia', 'name': 'India', 'capital': 'New Delhi'},
{'timezones': ['Asia/Dubai'], 'code': 'AE', 'continent': 'Asia', 'name': 'United Arab Emirates', 'capital': 'Abu Dhabi'},
{'timezones': ['Europe/London'], 'code': 'GB', 'continent': 'Europe', 'name': 'United Kingdom', 'capital': 'London'},
]

For full list : Gist Github

Hope, It helps.

How do I select an element with its name attribute in jQuery?

You can use:

jQuery('[name="' + nameAttributeValue + '"]');

this will be an inefficient way to select elements though, so it would be best to also use the tag name or restrict the search to a specific element:

jQuery('div[name="' + nameAttributeValue + '"]'); // with tag name
jQuery('div[name="' + nameAttributeValue + '"]',
     document.getElementById('searcharea'));      // with a search base

Cannot make a static reference to the non-static method fxn(int) from the type Two

You cannot refer non-static members from a static method.

Non-Static members (like your fxn(int y)) can be called only from an instance of your class.

Example:

You can do this:

       public class A
       {
           public   int fxn(int y) {
              y = 5;
              return y;
          }
       }


  class Two {
public static void main(String[] args) {
    int x = 0;
    A a = new A();
    System.out.println("x = " + x);
    x = a.fxn(x);
    System.out.println("x = " + x);
}

or you can declare you method as static.

Add custom headers to WebView resource requests - android

This worked for me. Create WebViewClient like this below and set the webclient to your webview. I had to use webview.loadDataWithBaseURL as my urls (in my content) did not have the baseurl but only relative urls. You will get the url correctly only when there is a baseurl set using loadDataWithBaseURL.

public WebViewClient getWebViewClientWithCustomHeader(){
    return new WebViewClient() {
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            try {
                OkHttpClient httpClient = new OkHttpClient();
                com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
                        .url(url.trim())
                        .addHeader("<your-custom-header-name>", "<your-custom-header-value>")
                        .build();
                com.squareup.okhttp.Response response = httpClient.newCall(request).execute();

                return new WebResourceResponse(
                        response.header("content-type", response.body().contentType().type()), // You can set something other as default content-type
                        response.header("content-encoding", "utf-8"),  // Again, you can set another encoding as default
                        response.body().byteStream()
                );
            } catch (ClientProtocolException e) {
                //return null to tell WebView we failed to fetch it WebView should try again.
                return null;
            } catch (IOException e) {
                //return null to tell WebView we failed to fetch it WebView should try again.
                return null;
            }
        }
    };

}

JSON to PHP Array using file_get_contents

Check some typo ','

<?php
 //file_get_content(url);
$jsonD = '{
    "bpath":"http://www.sampledomain.com/",
    "clist":[{
            "cid":"11",
            "display_type":"grid",
            "ctitle":"abc",
            "acount":"71",
            "alist":[{
                    "aid":"6865",
                    "adate":"2 Hours ago",
                    "atitle":"test",
                    "adesc":"test desc",
                    "aimg":"",
                    "aurl":"?nid=6865",
                    "weburl":"news.php?nid=6865",
                    "cmtcount":"0"
                },
                {
                    "aid":"6857",
                    "adate":"20 Hours ago",
                    "atitle":"test1",
                    "adesc":"test desc1",
                    "aimg":"",
                    "aurl":"?nid=6857",
                    "weburl":"news.php?nid=6857",
                    "cmtcount":"0"
                }
            ]
        },
        {
            "cid":"1",
            "display_type":"grid",
            "ctitle":"test1",
            "acount":"2354",
            "alist":[{
                    "aid":"6851",
                    "adate":"1 Days ago",
                    "atitle":"test123",
                    "adesc":"test123 desc",
                    "aimg":"",
                    "aurl":"?nid=6851",
                    "weburl":"news.php?nid=6851",
                    "cmtcount":"7"
                },
                {
                    "aid":"6847",
                    "adate":"2 Days ago",
                    "atitle":"test12345",
                    "adesc":"test12345 desc",
                    "aimg":"",
                    "aurl":"?nid=6847",
                    "weburl":"news.php?nid=6847",
                    "cmtcount":"7"
                }
            ]
        }
    ]
}
';

$parseJ = json_decode($jsonD,true);

print_r($parseJ);
?>

jQuery: set selected value of dropdown list?

You need to select jQuery in the dropdown on the left and you have a syntax error because the $(document).ready should end with }); not )}; Check this link.

Most pythonic way to delete a file which may not exist

Matt's answer is the right one for older Pythons and Kevin's the right answer for newer ones.

If you wish not to copy the function for silentremove, this functionality is exposed in path.py as remove_p:

from path import Path
Path(filename).remove_p()

PostgreSQL naming conventions

There isn't really a formal manual, because there's no single style or standard.

So long as you understand the rules of identifier naming you can use whatever you like.

In practice, I find it easier to use lower_case_underscore_separated_identifiers because it isn't necessary to "Double Quote" them everywhere to preserve case, spaces, etc.

If you wanted to name your tables and functions "@MyA??! ""betty"" Shard$42" you'd be free to do that, though it'd be pain to type everywhere.

The main things to understand are:

  • Unless double-quoted, identifiers are case-folded to lower-case, so MyTable, MYTABLE and mytable are all the same thing, but "MYTABLE" and "MyTable" are different;

  • Unless double-quoted:

    SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($).

  • You must double-quote keywords if you wish to use them as identifiers.

In practice I strongly recommend that you do not use keywords as identifiers. At least avoid reserved words. Just because you can name a table "with" doesn't mean you should.

How can I compare two ordered lists in python?

If you want to just check if they are identical or not, a == b should give you true / false with ordering taken into account.

In case you want to compare elements, you can use numpy for comparison

c = (numpy.array(a) == numpy.array(b))

Here, c will contain an array with 3 elements all of which are true (for your example). In the event elements of a and b don't match, then the corresponding elements in c will be false.

How do I concatenate strings?

I think that concat method and + should be mentioned here as well:

assert_eq!(
  ("My".to_owned() + " " + "string"),
  ["My", " ", "string"].concat()
);

and there is also concat! macro but only for literals:

let s = concat!("test", 10, 'b', true);
assert_eq!(s, "test10btrue");

How to load html string in a webview?

You also can try out this

   final WebView webView = new WebView(this);
            webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);

Unable to call the built in mb_internal_encoding method?

mbstring is a "non-default" extension, that is not enabled by default ; see this page of the manual :

Installation

mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the configure option. See the Install section for details

So, you might have to enable that extension, modifying the php.ini file (and restarting Apache, so your modification is taken into account)


I don't use CentOS, but you may have to install the extension first, using something like this (see this page, for instance, which seems to give a solution) :

yum install php-mbstring

(The package name might be a bit different ; so, use yum search to get it :-) )

Convert int to a bit array in .NET

    public static bool[] Convert(int[] input, int length)
    {
        var ret = new bool[length];
        var siz = sizeof(int) * 8;
        var pow = 0;
        var cur = 0;

        for (var a = 0; a < input.Length && cur < length; ++a)
        {
            var inp = input[a];

            pow = 1;

            if (inp > 0)
            {
                for (var i = 0; i < siz && cur < length; ++i)
                {
                    ret[cur++] = (inp & pow) == pow;

                    pow *= 2;
                }
            }
            else
            {
                for (var i = 0; i < siz && cur < length; ++i)
                {
                    ret[cur++] = (inp & pow) != pow;

                    pow *= 2;
                }
            }
        }

        return ret;
    }

Microsoft Azure: How to create sub directory in a blob container

Got similar issue while trying Azure Sample first-serverless-app.
Here is the info of how i resolved by removing \ at front of $web.

Note: $web container was created automatically while enable static website. Never seen $root container anywhere.

//getting Invalid URI error while following tutorial as-is
az storage blob upload-batch -s . -d \$web --account-name firststgaccount01

//Remove "\" @destination param
az storage blob upload-batch -s . -d $web --account-name firststgaccount01

What is the purpose of global.asax in asp.net

The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level and session-level events raised by ASP.NET or by HTTP modules.

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

Escaping double quotes in JavaScript onClick event handler

Did you try

&quot; or \x22

instead of

\"

?

How to convert an object to JSON correctly in Angular 2 with TypeScript

You'll have to parse again if you want it in actual JSON:

JSON.parse(JSON.stringify(object))

How can I copy the content of a branch to a new local branch?

git branch copyOfMyBranch MyBranch

This avoids the potentially time-consuming and unnecessary act of checking out a branch. Recall that a checkout modifies the "working tree", which could take a long time if it is large or contains large files (images or videos, for example).

Equal height rows in CSS Grid Layout

Short Answer

If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:

  • Set the container to grid-auto-rows: 1fr

How it works

Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the fr unit. It is designed to distribute free space in the container and is somewhat analogous to the flex-grow property in flexbox.

If you set all rows in a grid container to 1fr, let's say like this:

grid-auto-rows: 1fr;

... then all rows will be equal height.

It doesn't really make sense off-the-bat because fr is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.

Except, buried deep in the grid spec is this little nugget:

7.2.3. Flexible Lengths: the fr unit

...

When the available space is infinite (which happens when the grid container’s width or height is indefinite), flex-sized (fr) grid tracks are sized to their contents while retaining their respective proportions.

The used size of each flex-sized grid track is computed by determining the max-content size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical 1fr size”.

The maximum of those is used as the resolved 1fr length (the flex fraction), which is then multiplied by each grid track’s flex factor to determine its final size.

So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.

The height of each row is determined by the tallest (max-content) grid item.

The maximum height of those rows becomes the length of 1fr.

That's how 1fr creates equal height rows in a grid container.


Why flexbox isn't an option

As noted in the question, equal height rows are not possible with flexbox.

Flex items can be equal height on the same row, but not across multiple rows.

This behavior is defined in the flexbox spec:

6. Flex Lines

In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.

In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.

How to extract HTTP response body from a Python requests call?

Your code is correct. I tested:

r = requests.get("http://www.google.com")
print(r.content)

And it returned plenty of content. Check the url, try "http://www.google.com". Cheers!

Read a HTML file into a string variable in memory

Use System.IO.File.ReadAllText(fileName)

When should I create a destructor?

Destructors provide an implicit way of freeing unmanaged resources encapsulated in your class, they get called when the GC gets around to it and they implicitly call the Finalize method of the base class. If you're using a lot of unmanaged resources it is better to provide an explicit way of freeing those resources via the IDisposable interface. See the C# programming guide: http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx

Using Linq to get the last N elements of a collection?

If you don't mind dipping into Rx as part of the monad, you can use TakeLast:

IEnumerable<int> source = Enumerable.Range(1, 10000);

IEnumerable<int> lastThree = source.AsObservable().TakeLast(3).AsEnumerable();

How do you pull first 100 characters of a string in PHP

try this function

function summary($str, $limit=100, $strip = false) {
    $str = ($strip == true)?strip_tags($str):$str;
    if (strlen ($str) > $limit) {
        $str = substr ($str, 0, $limit - 3);
        return (substr ($str, 0, strrpos ($str, ' ')).'...');
    }
    return trim($str);
}

Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain

In XCode 4.0 main workspace, at the top left side & just after the "Stop Button", there is scheme selector, click on it and change your scheme to IPhone Simulator. That's it

Sort arrays of primitive types in descending order

I think it would be best not to re-invent the wheel and use Arrays.sort().

Yes, I saw the "descending" part. The sorting is the hard part, and you want to benefit from the simplicity and speed of Java's library code. Once that's done, you simply reverse the array, which is a relatively cheap O(n) operation. Here's some code I found to do this in as little as 4 lines:

for (int left=0, right=b.length-1; left<right; left++, right--) {
    // exchange the first and last
    int temp = b[left]; b[left]  = b[right]; b[right] = temp;
}

excel formula to subtract number of days from a date

Here is what worked for me (Excel 14.0 - aka MS Office Pro Plus 2010):

=DATE(YEAR(A1), MONTH(A1), DAY(A1) - 16)

This takes the date (format mm/dd/yyyy) in cell A1 and subtracts 16 days with output in format of mm/dd/yyyy.

Create Pandas DataFrame from a string

Split Method

data = input_string
df = pd.DataFrame([x.split(';') for x in data.split('\n')])
print(df)

Adding machineKey to web.config on web-farm sites

If you are using IIS 7.5 or later you can generate the machine key from IIS and save it directly to your web.config, within the web farm you then just copy the new web.config to each server.

  1. Open IIS manager.
  2. If you need to generate and save the MachineKey for all your applications select the server name in the left pane, in that case you will be modifying the root web.config file (which is placed in the .NET framework folder). If your intention is to create MachineKey for a specific web site/application then select the web site / application from the left pane. In that case you will be modifying the web.config file of your application.
  3. Double-click the Machine Key icon in ASP.NET settings in the middle pane:
  4. MachineKey section will be read from your configuration file and be shown in the UI. If you did not configure a specific MachineKey and it is generated automatically you will see the following options:
  5. Now you can click Generate Keys on the right pane to generate random MachineKeys. When you click Apply, all settings will be saved in the web.config file.

Full Details can be seen @ Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS and .NET development…

see if two files have the same content in python

Yes, I think hashing the file would be the best way if you have to compare several files and store hashes for later comparison. As hash can clash, a byte-by-byte comparison may be done depending on the use case.

Generally byte-by-byte comparison would be sufficient and efficient, which filecmp module already does + other things too.

See http://docs.python.org/library/filecmp.html e.g.

>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False

Speed consideration: Usually if only two files have to be compared, hashing them and comparing them would be slower instead of simple byte-by-byte comparison if done efficiently. e.g. code below tries to time hash vs byte-by-byte

Disclaimer: this is not the best way of timing or comparing two algo. and there is need for improvements but it does give rough idea. If you think it should be improved do tell me I will change it.

import random
import string
import hashlib
import time

def getRandText(N):
    return  "".join([random.choice(string.printable) for i in xrange(N)])

N=1000000
randText1 = getRandText(N)
randText2 = getRandText(N)

def cmpHash(text1, text2):
    hash1 = hashlib.md5()
    hash1.update(text1)
    hash1 = hash1.hexdigest()

    hash2 = hashlib.md5()
    hash2.update(text2)
    hash2 = hash2.hexdigest()

    return  hash1 == hash2

def cmpByteByByte(text1, text2):
    return text1 == text2

for cmpFunc in (cmpHash, cmpByteByByte):
    st = time.time()
    for i in range(10):
        cmpFunc(randText1, randText2)
    print cmpFunc.func_name,time.time()-st

and the output is

cmpHash 0.234999895096
cmpByteByByte 0.0

Greater than and less than in one statement

Several third-party libraries have classes encapsulating the concept of a range, such as Apache commons-lang's Range (and subclasses).

Using classes such as this you could express your constraint similar to:

if (new IntRange(0, 5).contains(orderBean.getFiles().size())
// (though actually Apache's Range is INclusive, so it'd be new Range(1, 4) - meh

with the added bonus that the range object could be defined as a constant value elsewhere in the class.

However, without pulling in other libraries and using their classes, Java's strong syntax means you can't massage the language itself to provide this feature nicely. And (in my own opinion), pulling in a third party library just for this small amount of syntactic sugar isn't worth it.

With ' N ' no of nodes, how many different Binary and Binary Search Trees possible?

The number of binary trees can be calculated using the catalan number.

The number of binary search trees can be seen as a recursive solution. i.e., Number of binary search trees = (Number of Left binary search sub-trees) * (Number of Right binary search sub-trees) * (Ways to choose the root)

In a BST, only the relative ordering between the elements matter. So, without any loss on generality, we can assume the distinct elements in the tree are 1, 2, 3, 4, ...., n. Also, let the number of BST be represented by f(n) for n elements.

Now we have the multiple cases for choosing the root.

  1. choose 1 as root, no element can be inserted on the left sub-tree. n-1 elements will be inserted on the right sub-tree.
  2. Choose 2 as root, 1 element can be inserted on the left sub-tree. n-2 elements can be inserted on the right sub-tree.
  3. Choose 3 as root, 2 element can be inserted on the left sub-tree. n-3 elements can be inserted on the right sub-tree.

...... Similarly, for i-th element as the root, i-1 elements can be on the left and n-i on the right.

These sub-trees are itself BST, thus, we can summarize the formula as:

f(n) = f(0)f(n-1) + f(1)f(n-2) + .......... + f(n-1)f(0)

Base cases, f(0) = 1, as there is exactly 1 way to make a BST with 0 nodes. f(1) = 1, as there is exactly 1 way to make a BST with 1 node.

Final Formula

Local storage in Angular 2

How to store, retrieve & delete data from localStorage:

// General syntax for storing data
localStorage.setItem('key', 'value');
// Also note that both the key & the value has to be strings. So we stringify the value(if it's an object) before setting it.

// So, if you have an object as a value that you want to save, stringify it like this
localStorage.setItem('some-key', JSON.stringify(itemData));

// OR for individual key-value pairs
localStorage.setItem('some-key', JSON.stringify({ token: token, name: name }));

// To retrieve data from localstorage
const myData = JSON.parse(localStorage.getItem('some-key'));

// To remove a value/item from localStorage
localStorage.removeItem("some-key");


// see a note at the end of this answer for tips about 
// using an angular package for a cleaner & smoother storage usage.

A quick tip:
You can also use a package for your angular app, that is based on native localStorage API (that we are using above) to achieve this and you don't have to worry about stringify and parse. Check out this package for angular 5 and above. @ngx-pwa/local-storage

You can also do a quick google search for maybe ,angular local storage, & find a package that has even more Github stars etc.

Check out this page to know more about Web Storage API.

Maximum number of threads in a .NET app?

i did a test on a 64bit system with c# console, the exception is type of out of memory, using 2949 threads.

I realize we should be using threading pool, which I do, but this answer is in response to the main question ;)

new DateTime() vs default(DateTime)

No, they are identical.

default(), for any value type (DateTime is a value type) will always call the parameterless constructor.

Can you Run Xcode in Linux?

It was weird that no one suggested KVM.

It is gonna provide you almost native performance and it is built-in Linux. Go and check it out.

you will feel like u are using mac only and then install Xcode there u may even choose to directly boot into the OSX GUI instead of Linux one on startup

How do I iterate over a JSON structure?

With nested objects, it can be retrieve as by recursive function:

function inside(events)
  {
    for (i in events) {
      if (typeof events[i] === 'object')
        inside(events[i]);
      else
      alert(events[i]);
    }
  }
  inside(events);

where as events is json object.

Base64 decode snippet in C++

My version is a simple fast encoder (decoder) of Base64 for C++Builder.

// ---------------------------------------------------------------------------
UnicodeString __fastcall TExample::Base64Encode(void *data, int length)
{
    if (length <= 0)
        return L"";
    static const char set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    unsigned char *in = (unsigned char*)data;
    char *pos, *out = pos = new char[((length - 1) / 3 + 1) << 2];
    while ((length -= 3) >= 0)
    {
        pos[0] = set[in[0] >> 2];
        pos[1] = set[((in[0] & 0x03) << 4) | (in[1] >> 4)];
        pos[2] = set[((in[1] & 0x0F) << 2) | (in[2] >> 6)];
        pos[3] = set[in[2] & 0x3F];
        pos += 4;
        in += 3;
    };
    if ((length & 2) != 0)
    {
        pos[0] = set[in[0] >> 2];
        if ((length & 1) != 0)
        {
            pos[1] = set[((in[0] & 0x03) << 4) | (in[1] >> 4)];
            pos[2] = set[(in[1] & 0x0F) << 2];
        }
        else
        {
            pos[1] = set[(in[0] & 0x03) << 4];
            pos[2] = '=';
        };
        pos[3] = '=';
        pos += 4;
    };
    UnicodeString code = UnicodeString(out, pos - out);
    delete[] out;
    return code;
};

// ---------------------------------------------------------------------------
int __fastcall TExample::Base64Decode(const UnicodeString &code, unsigned char **data)
{
    int length;
    if (((length = code.Length()) == 0) || ((length & 3) != 0))
        return 0;
    wchar_t *str = code.c_str();
    unsigned char *pos, *out = pos = new unsigned char[(length >> 2) * 3];
    while (*str != 0)
    {
        length = -1;
        int shift = 18, bits = 0;
        do
        {
            wchar_t s = str[++length];
            if ((s >= L'A') && (s <= L'Z'))
                bits |= (s - L'A') << shift;
            else if ((s >= L'a') && (s <= L'z'))
                   bits |= (s - (L'a' - 26)) << shift;
            else if (((s >= L'0') && (s <= L'9')))
                   bits |= (s - (L'0' - 52)) << shift;
            else if (s == L'+')
                   bits |= 62 << shift;
            else if (s == L'/')
                   bits |= 63 << shift;
            else if (s == L'=')
            {
                length--;
                break;
            }
            else
            {
                delete[] out;
                return 0;
            };
        }
        while ((shift -= 6) >= 0);
        pos[0] = bits >> 16;
        pos[1] = bits >> 8;
        pos[2] = bits;
        pos += length;
        str += 4;
    };
    *data = out;
    return pos - out;
};
//---------------------------------------------------------------------------

Error when trying to access XAMPP from a network

In your xampppath\apache\conf\extra open file httpd-xampp.conf and find the below tag:

# Close XAMPP sites here
<LocationMatch "^/(?i:(?:xampp|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var
</LocationMatch>

and add

"Allow from all"

after Allow from ::1 127.0.0.0/8 {line}

Restart xampp, and you are done.

In later versions of Xampp

...you can simply remove this part

#
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
        Require local
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

from the same file and it should work over the local network.

How to import existing Android project into Eclipse?

It seems you cannot have your project root, with the AndroidManifest.xml deeper than one directory level below your workspace root. I struggled for an hour with this before I just gave up and rearranged my repo.

Standard Android Button with a different color

In <Button> use android:background="#33b5e5". or better android:background="@color/navig_button"

Sniff HTTP packets for GET and POST requests from an application

post in http
Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet

Difference Between $.getJSON() and $.ajax() in jQuery

There is lots of confusion in some of the function of jquery like $.ajax, $.get, $.post, $.getScript, $.getJSON that what is the difference among them which is the best, which is the fast, which to use and when so below is the description of them to make them clear and to get rid of this type of confusions.

$.getJSON() function is a shorthand Ajax function (internally use $.get() with data type script), which is equivalent to below expression, Uses some limited criteria like Request type is GET and data Type is json.

Read More .. jquery-post-vs-get-vs-ajax

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Have you tried using the stream_context_set_option() method ?

$context = stream_context_create();
$result = stream_context_set_option($context, 'ssl', 'local_cert', '/etc/ssl/certs/cacert.pem');
$fp = fsockopen($host, $port, $errno, $errstr, 20, $context);

In addition, try file_get_contents() for the pem file, to make sure you have permissions to access it, and make sure the host name matches the certificate.

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

just add your .jar file in applet tag as an attribute as shown below:

<applet
    code="file.class"
    archive="file.jar"
    height=550 
    width=1100>         
</applet>

How to empty the content of a div

If your div looks like this:

<div id="MyDiv">content in here</div>

Then this Javascript:

document.getElementById("MyDiv").innerHTML = "";

will make it look like this:

<div id="MyDiv"></div>

find vs find_by vs where

Model.find

1- Parameter: ID of the object to find.

2- If found: It returns the object (One object only).

3- If not found: raises an ActiveRecord::RecordNotFound exception.

Model.find_by

1- Parameter: key/value

Example:

User.find_by name: 'John', email: '[email protected]'

2- If found: It returns the object.

3- If not found: returns nil.

Note: If you want it to raise ActiveRecord::RecordNotFound use find_by!

Model.where

1- Parameter: same as find_by

2- If found: It returns ActiveRecord::Relation containing one or more records matching the parameters.

3- If not found: It return an Empty ActiveRecord::Relation.

Is there a command to list all Unix group names?

On Linux, macOS and Unix to display the groups to which you belong, use:

id -Gn

which is equivalent to groups utility which has been obsoleted on Unix (as per Unix manual).

On macOS and Unix, the command id -p is suggested for normal interactive.

Explanation of the parameters:

-G, --groups - print all group IDs

-n, --name - print a name instead of a number, for -ugG

-p - Make the output human-readable.

Passing variables in remote ssh command

As answered previously, you do not need to set the environment variable on the remote host. Instead, you can simply do the meta-expansion on the local host, and pass the value to the remote host.

ssh [email protected] '~/tools/run_pvt.pl $BUILD_NUMBER'

If you really want to set the environment variable on the remote host and use it, you can use the env program

ssh [email protected] "env BUILD_NUMBER=$BUILD_NUMBER ~/tools/run_pvt.pl \$BUILD_NUMBER"

In this case this is a bit of an overkill, and note

  • env BUILD_NUMBER=$BUILD_NUMBER does the meta expansion on the local host
  • the remote BUILD_NUMBER environment variable will be used by
    the remote shell

'module' has no attribute 'urlencode'

You use the Python 2 docs but write your program in Python 3.

Using the Web.Config to set up my SQL database connection string?

Web.config file

<connectionStrings>
  <add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS;    Initial Catalog=YourDatabaseName;Integrated Security=True;"/>
</connectionStrings>

.cs file

System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

Where can I find error log files?

On CentoS with cPanel installed my logs were in:

/usr/local/apache/logs/error_log

To watch: tail -f /usr/local/apache/logs/error_log

Adding a Button to a WPF DataGrid

First create a DataGridTemplateColumn to contain the button:

<DataGridTemplateColumn>
  <DataGridTemplateColumn.CellTemplate> 
    <DataTemplate> 
      <Button Click="ShowHideDetails">Details</Button> 
    </DataTemplate> 
  </DataGridTemplateColumn.CellTemplate> 
</DataGridTemplateColumn>

When the button is clicked, update the containing DataGridRow's DetailsVisibility:

void ShowHideDetails(object sender, RoutedEventArgs e)
{
    for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
    if (vis is DataGridRow)
    {
        var row = (DataGridRow)vis;
        row.DetailsVisibility = 
        row.DetailsVisibility == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
        break;
    }
}

How to run a program in Atom Editor?

You can try to use the runner in atom Hit Ctrl+R (Alt+R on Win/Linux) to launch the runner for the active window. Hit Ctrl+Shift+R (Alt+Shift+R on Win/Linux) to run the currently selected text in the active window. Hit Ctrl+Shift+C to kill a currently running process. Hit Escape to close the runner window

How can I find all the subsets of a set, with exactly n elements?

Here's some pseudocode - you can cut same recursive calls by storing the values for each call as you go and before recursive call checking if the call value is already present.

The following algorithm will have all the subsets excluding the empty set.

list * subsets(string s, list * v) {

    if(s.length() == 1) {
        list.add(s);    
        return v;
    }
    else
    {
        list * temp = subsets(s[1 to length-1], v);
        int length = temp->size();

        for(int i=0;i<length;i++) {
            temp.add(s[0]+temp[i]);
        }

        list.add(s[0]);
        return temp;
    }
}

So, for example if s = "123" then output is:

1
2
3
12
13
23
123

Is it possible to set a number to NaN or infinity?

Yes, you can use numpy for that.

import numpy as np
a = arange(3,dtype=float)

a[0] = np.nan
a[1] = np.inf
a[2] = -np.inf

a # is now [nan,inf,-inf]

np.isnan(a[0]) # True
np.isinf(a[1]) # True
np.isinf(a[2]) # True

How to make a .jar out from an Android Studio project

the way i found was to find the project compiler output (project structure > project). then find the complied folder of the module you wish to turn to a jar, compress it with zip and change the extension of the output from zip to jar.

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

I had a similar problem quite recently. In my case:

  1. I downloaded an artifact from some less popular Maven repo

  2. This repo dissappeared over this year

  3. Now builds fail, even if I have this artifact and its pom.xml in my local repo

Workaround:

delete _remote.repositories file in your local repo, where this artifact resides. Now the project builds.

Setting up redirect in web.config file

  1. Open web.config in the directory where the old pages reside
  2. Then add code for the old location path and new destination as follows:

    <configuration>
      <location path="services.htm">
        <system.webServer>
          <httpRedirect enabled="true" destination="http://domain.com/services" httpResponseStatus="Permanent" />
        </system.webServer>
      </location>
      <location path="products.htm">
        <system.webServer>
          <httpRedirect enabled="true" destination="http://domain.com/products" httpResponseStatus="Permanent" />
        </system.webServer>
      </location>
    </configuration>
    

You may add as many location paths as necessary.

How to decode encrypted wordpress admin password?

just edit wp_user table with your phpmyadmin, and choose MD5 on Function field then input your new password, save it (go button). enter image description here

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

maybe you forget to add parameter dataType:'json' in your $.ajax

$.ajax({
   type: "POST",
   dataType: "json",
   url: url,
   data: { get_member: id },
   success: function( response ) 
   { 
     //some action here
   },
   error: function( error )
   {
     alert( error );
   }
});

How to Copy Contents of One Canvas to Another Canvas Locally

Actually you don't have to create an image at all. drawImage() will accept a Canvas as well as an Image object.

//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');

//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);

Way faster than using an ImageData object or Image element.

Note that sourceCanvas can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. As mentioned by Dave in a comment below this answer, you cannot use a canvas drawing context as your source. If you have a canvas drawing context instead of the canvas element it was created from, there is a reference to the original canvas element on the context under context.canvas.

Here is a jsPerf to demonstrate why this is the only right way to clone a canvas: http://jsperf.com/copying-a-canvas-element

Input jQuery get old value before onchange and get value after on change

The simplest way is to save the original value using data() when the element gets focus. Here is a really basic example:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/

$('input').on('focusin', function(){
    console.log("Saving value " + $(this).val());
    $(this).data('val', $(this).val());
});

$('input').on('change', function(){
    var prev = $(this).data('val');
    var current = $(this).val();
    console.log("Prev value " + prev);
    console.log("New value " + current);
});

Better to use Delegated Event Handlers

Note: it is generally more efficient to use a delegated event handler when there can be multiple matching elements. This way only a single handler is added (smaller overhead and faster initialisation) and any speed difference at event time is negligible.

Here is the same example using delegated events connected to document:

$(document).on('focusin', 'input', function(){
    console.log("Saving value " + $(this).val());
    $(this).data('val', $(this).val());
}).on('change','input', function(){
    var prev = $(this).data('val');
    var current = $(this).val();
    console.log("Prev value " + prev);
    console.log("New value " + current);
});

JsFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/65/

Delegated events work by listening for an event (focusin, change etc) on an ancestor element (document* in this case), then applying the jQuery filter (input) to only the elements in the bubble chain then applying the function to only those matching elements that caused the event.

*Note: A a general rule, use document as the default for delegated events and not body. body has a bug, to do with styling, that can cause it to not get bubbled mouse events. Also document always exists so you can attach to it outside of a DOM ready handler :)

How can I share Jupyter notebooks with non-programmers?

Michael's suggestion of running your own nbviewer instance is a good one I used in the past with an Enterprise Github server.

Another lightweight alternative is to have a cell at the end of your notebook that does a shell call to nbconvert so that it's automatically refreshed after running the whole thing:

!ipython nbconvert <notebook name>.ipynb --to html

EDIT: With Jupyter/IPython's Big Split, you'll probably want to change this to !jupyter nbconvert <notebook name>.ipynb --to html now.

Execute a shell function with timeout

I have a slight modification of @Tiago Lopo's answer that can handle commands with multiple arguments. I've also tested TauPan's solution, but it does not work if you use it multiple times in a script, while Tiago's does.

function timeout_cmd { 
  local arr
  local cmd
  local timeout

  arr=( "$@" )

  # timeout: first arg
  # cmd: the other args
  timeout="${arr[0]}"
  cmd=( "${arr[@]:1}" )

  ( 
    eval "${cmd[@]}" &
    child=$!

    echo "child: $child"
    trap -- "" SIGTERM 
    (       
      sleep "$timeout"
      kill "$child" 2> /dev/null 
    ) &     
    wait "$child"
  )
}

Here's a fully functional script thant you can use to test the function above:

$ ./test_timeout.sh -h
Usage:
  test_timeout.sh [-n] [-r REPEAT] [-s SLEEP_TIME] [-t TIMEOUT]
  test_timeout.sh -h

Test timeout_cmd function.

Options:
  -n              Dry run, do not actually sleep. 
  -r REPEAT       Reapeat everything multiple times [default: 1].
  -s SLEEP_TIME   Sleep for SLEEP_TIME seconds [default: 5].
  -t TIMEOUT      Timeout after TIMEOUT seconds [default: no timeout].

For example you cnal launch like this:

$ ./test_timeout.sh -r 2 -s 5 -t 3
Try no: 1
  - Set timeout to: 3
child: 2540
    -> retval: 143
    -> The command timed out
Try no: 2
  - Set timeout to: 3
child: 2593
    -> retval: 143
    -> The command timed out
Done!
#!/usr/bin/env bash

#shellcheck disable=SC2128
SOURCED=false && [ "$0" = "$BASH_SOURCE" ] || SOURCED=true

if ! $SOURCED; then
  set -euo pipefail
  IFS=$'\n\t'
fi

#################### helpers
function check_posint() {
  local re='^[0-9]+$'
  local mynum="$1"
  local option="$2"

  if ! [[ "$mynum" =~ $re ]] ; then
     (echo -n "Error in option '$option': " >&2)
     (echo "must be a positive integer, got $mynum." >&2)
     exit 1
  fi

  if ! [ "$mynum" -gt 0 ] ; then
     (echo "Error in option '$option': must be positive, got $mynum." >&2)
     exit 1
  fi
}
#################### end: helpers

#################### usage
function short_usage() {
  (>&2 echo \
"Usage:
  test_timeout.sh [-n] [-r REPEAT] [-s SLEEP_TIME] [-t TIMEOUT]
  test_timeout.sh -h"
  )
}

function usage() {
  (>&2 short_usage )
  (>&2 echo \
"
Test timeout_cmd function.

Options:
  -n              Dry run, do not actually sleep. 
  -r REPEAT       Reapeat everything multiple times [default: 1].
  -s SLEEP_TIME   Sleep for SLEEP_TIME seconds [default: 5].
  -t TIMEOUT      Timeout after TIMEOUT seconds [default: no timeout].
")
}
#################### end: usage

help_flag=false
dryrun_flag=false
SLEEP_TIME=5
TIMEOUT=-1
REPEAT=1

while getopts ":hnr:s:t:" opt; do
  case $opt in
    h)
      help_flag=true
      ;;    
    n)
      dryrun_flag=true
      ;;
    r)
      check_posint "$OPTARG" '-r'

      REPEAT="$OPTARG"
      ;;
    s)
      check_posint "$OPTARG" '-s'

      SLEEP_TIME="$OPTARG"
      ;;
    t)
      check_posint "$OPTARG" '-t'

      TIMEOUT="$OPTARG"
      ;;
    \?)
      (>&2 echo "Error. Invalid option: -$OPTARG.")
      (>&2 echo "Try -h to get help")
      short_usage
      exit 1
      ;;
    :)
      (>&2 echo "Error.Option -$OPTARG requires an argument.")
      (>&2 echo "Try -h to get help")
      short_usage
      exit 1
      ;;
  esac
done

if $help_flag; then
  usage
  exit 0
fi

#################### utils
if $dryrun_flag; then
  function wrap_run() {
    ( echo -en "[dry run]\\t" )
    ( echo "$@" )
  }
else
  function wrap_run() { "$@"; }
fi

# Execute a shell function with timeout
# https://stackoverflow.com/a/24416732/2377454
function timeout_cmd { 
  local arr
  local cmd
  local timeout

  arr=( "$@" )

  # timeout: first arg
  # cmd: the other args
  timeout="${arr[0]}"
  cmd=( "${arr[@]:1}" )

  ( 
    eval "${cmd[@]}" &
    child=$!

    echo "child: $child"
    trap -- "" SIGTERM 
    (       
      sleep "$timeout"
      kill "$child" 2> /dev/null 
    ) &     
    wait "$child"
  )
}
####################

function sleep_func() {
  local secs
  local waitsec

  waitsec=1
  secs=$(($1))
  while [ "$secs" -gt 0 ]; do
   echo -ne "$secs\033[0K\r"
   sleep "$waitsec"
   secs=$((secs-waitsec))
  done

}

command=("wrap_run" \
         "sleep_func" "${SLEEP_TIME}"
         )

for i in $(seq 1 "$REPEAT"); do
  echo "Try no: $i"

  if [ "$TIMEOUT" -gt 0 ]; then
    echo "  - Set timeout to: $TIMEOUT"
    set +e
    timeout_cmd "$TIMEOUT" "${command[@]}"
    retval="$?"
    set -e

    echo "    -> retval: $retval"
    # check if (retval % 128) == SIGTERM (== 15)
    if [[ "$((retval % 128))" -eq 15 ]]; then
      echo "    -> The command timed out"
    fi
  else
    echo "  - No timeout"
    "${command[@]}"
    retval="$?"
  fi
done

echo "Done!"

exit 0

Using Get-childitem to get a list of files modified in the last 3 days

Here's a minor update to the solution provided by Dave Sexton. Many times you need multiple filters. The Filter parameter can only take a single string whereas the -Include parameter can take a string array. if you have a large file tree it also makes sense to only get the date to compare with once, not for each file. Here's my updated version:

$compareDate = (Get-Date).AddDays(-3)    
@(Get-ChildItem -Path c:\pstbak\*.* -Filter '*.pst','*.mdb' -Recurse | Where-Object { $_.LastWriteTime -gt $compareDate}).Count

Laravel - htmlspecialchars() expects parameter 1 to be string, object given

Laravel - htmlspecialchars() expects parameter 1 to be string, object given.

thank me latter.........................

when you send or get array from contrller or function but try to print as single value or single variable in laravel blade file so it throws an error

->use any think who convert array into string it work.

solution: 1)run the foreach loop and get single single value and print. 2)The implode() function returns a string from the elements of an array. {{ implode($your_variable,',') }}

implode is best way to do it and its 100% work.

Calling Objective-C method from C++ member function?

Sometimes renaming .cpp to .mm is not good idea, especially when project is crossplatform. In this case for xcode project I open xcode project file throught TextEdit, found string which contents interest file, it should be like:

/* OnlineManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = OnlineManager.cpp; sourceTree = "<group>"; };

and then change file type from sourcecode.cpp.cpp to sourcecode.cpp.objcpp

/* OnlineManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = **sourcecode.cpp.objcpp**; path = OnlineManager.cpp; sourceTree = "<group>"; };

It is equivalent to rename .cpp to .mm

How to add facebook share button on my website?

For Facebook share with an image without an API and using a # to deep link into a sub page, the trick was to share the image as picture=

The variable mainUrl would be http://yoururl.com/

var d1 = $('.targ .t1').text();
var d2 = $('.targ .t2').text();
var d3 = $('.targ .t3').text();
var d4 = $('.targ .t4').text();
var descript_ = d1 + ' ' + d2 + ' ' + d3 + ' ' + d4;
var descript = encodeURIComponent(descript_);

var imgUrl_ = 'path/to/mypic_'+id+'.jpg';
var imgUrl = mainUrl + encodeURIComponent(imgUrl_);

var shareLink = mainUrl + encodeURIComponent('mypage.html#' + id);

var fbShareLink = shareLink + '&picture=' + imgUrl + '&description=' + descript;
var twShareLink = 'text=' + descript + '&url=' + shareLink;

// facebook
$(".my-btn .facebook").off("tap click").on("tap click",function(){
  var fbpopup = window.open("https://www.facebook.com/sharer/sharer.php?u=" + fbShareLink, "pop", "width=600, height=400, scrollbars=no");
  return false;
});

// twitter
$(".my-btn .twitter").off("tap click").on("tap click",function(){
  var twpopup = window.open("http://twitter.com/intent/tweet?" + twShareLink , "pop", "width=600, height=400, scrollbars=no");
  return false;
});

How do I get the last word in each line with bash

You can do it easily with grep:

grep -oE '[^ ]+$' file

(-E use extended regex; -o output only the matched text instead of the full line)

Laravel Rule Validation for Numbers

Laravel min and max validation do not work properly with a numeric rule validation. Instead of numeric, min and max, Laravel provided a rule digits_between.

$this->validate($request,[
        'field_name'=>'digits_between:2,5',
       ]);

tsc is not recognized as internal or external command

For me, by running Visual Studio Code as Administrator, the problem is resolved.

"Sources directory is already netbeans project" error when opening a project from existing sources

  1. Go to the folder containing your project
  2. Delete the folder named nbproject
  3. Restart Netbeans
  4. Try creating your project again from the original folder

Formatting code snippets for blogging on Blogger

It looks like there have been some changes with SyntaxHighlighter 2.0 that make it easier to use with Blogger.

There are hosted versions of the styles and Javascripts at: http://alexgorbatchev.com/pub/sh/

Entity Framework - Generating Classes

1) First you need to generate EDMX model using your database. To do that you should add new item to your project:

  • Select ADO.NET Entity Data Model from the Templates list.
  • On the Choose Model Contents page, select the Generate from Database option and click Next.
  • Choose your database.
  • On the Choose Your Database Objects page, check the Tables. Choose Views or Stored Procedures if you need.

So now you have Model1.edmx file in your project.

2) To generate classes using your model:

  • Open your EDMX model designer.
  • On the design surface Right Click –> Add Code Generation Item…
  • Select Online templates.
  • Select EF 4.x DbContext Generator for C#.
  • Click ‘Add’.

Notice that two items are added to your project:

  • Model1.tt (This template generates very simple POCO classes for each entity in your model)
  • Model1.Context.tt (This template generates a derived DbContext to use for querying and persisting data)

3) Read/Write Data example:

 var dbContext = new YourModelClass(); //class derived from DbContext
 var contacts = from c in dbContext.Contacts select c; //read data
 contacts.FirstOrDefault().FirstName = "Alex"; //edit data
 dbContext.SaveChanges(); //save data to DB

Don't forget that you need 4.x version of EntityFramework. You can download EF 4.1 here: Entity Framework 4.1.

Django - "no module named django.core.management"

In case this is helpful to others... I had this issue because my virtualenv defaulted to python2.7 and I was calling Django using Python3 while using Ubuntu.

to check which python my virtualenv was using:

$ which python3
>> /usr/bin/python3

created new virtualenv with python3 specified (using virtualenv wrapper https://virtualenvwrapper.readthedocs.org/en/latest/):

$ mkvirtualenv --python=/usr/bin/python3 ENV_NAME

the python path should now point to the virtualenv python:

$ which python3
>> /home/user/.virtualenvs/ENV_NAME/bin/python3

Android RecyclerView addition & removal of items

To Method onBindViewHolder Write This Code

holder.remove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Cursor del=dbAdapter.ExecuteQ("delete from TblItem where Id="+values.get(position).getId());
                values.remove(position);
                notifyDataSetChanged();
            }
        });

How to convert a full date to a short date in javascript?

Built-in toLocaleDateString() does the job, but it will remove the leading 0s for the day and month, so we will get something like "1/9/1970", which is not perfect in my opinion. To get a proper format MM/DD/YYYY we can use something like:

new Date(dateString).toLocaleDateString('en-US', {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
})

Working with TIFFs (import, export) in Python using numpy

PyLibTiff worked better for me than PIL, which as of December 2020 still doesn't support color images with more than 8 bits per color.

from libtiff import TIFF

tif = TIFF.open('filename.tif') # open tiff file in read mode
# read an image in the currect TIFF directory as a numpy array
image = tif.read_image()

# read all images in a TIFF file:
for image in tif.iter_images(): 
    pass

tif = TIFF.open('filename.tif', mode='w')
tif.write_image(image)

You can install PyLibTiff with

pip3 install numpy libtiff

The readme of PyLibTiff also mentions the tifffile library but I haven't tried it.

How to use ADB to send touch events to device using sendevent command?

In order to do a particular action (for example to open the web browser), you need to first figure out where to tap. To do that, you can first run:

adb shell getevent -l

Once you press on the device, at the location that you want, you will see this output:

<...>
/dev/input/event3: EV_KEY       BTN_TOUCH            DOWN
/dev/input/event3: EV_ABS       ABS_MT_POSITION_X    000002f5
/dev/input/event3: EV_ABS       ABS_MT_POSITION_Y    0000069e

adb is telling you that a key was pressed (button down) at position 2f5, 69e in hex which is 757 and 1694 in decimal.

If you now want to generate the same event, you can use the input tap command at the same position:

adb shell input tap 757 1694

More info can be found at:

https://source.android.com/devices/input/touch-devices.html http://source.android.com/devices/input/getevent.html

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

I think that all the answers missed a crucial point:

If you use the Ajax form so that it needs to update itself (and NOT another div outside of the form) then you need to put the containing div OUTSIDE of the form. For example:

 <div id="target">
 @using (Ajax.BeginForm("MyAction", "MyController",
            new AjaxOptions
            {
                HttpMethod = "POST",
                InsertionMode = InsertionMode.Replace,
                UpdateTargetId = "target"
            }))
 {
      <!-- whatever -->
 }
 </div>

Otherwise you will end like @David where the result is displayed in a new page.

Close virtual keyboard on button press

This solution works perfect for me:

private void showKeyboard(EditText editText) {
    editText.requestFocus();
    editText.setFocusableInTouchMode(true);
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(editText, InputMethodManager.RESULT_UNCHANGED_SHOWN);
    editText.setSelection(editText.getText().length());
}

private void closeKeyboard() {
    InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
}

Multiple select in Visual Studio?

In Visual Studio 2019, you can put your caret on the right place and then press SHIFT ALT and . (dot). This will select the next occurrence.

Sending message through WhatsApp

private fun sendWhatsappMessage(phoneNumber:String, text:String) {        
  val url = if (Intent().setPackage("com.whatsapp").resolveActivity(packageManager) != null) {
        "whatsapp://send?text=Hello&phone=$phoneNumber"
    } else {
        "https://api.whatsapp.com/send?phone=$phoneNumber&text=$text"
    }

    val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
    startActivity(browserIntent)
}

This is a much easier way to achieve this. This code checks if whatsapp is installed on the device. If it is installed, it bypasses the system picker and goes to the contact on whatsapp and prefields the text in the chat. If not installed it opens whatsapp link on your web browser.

Need to get current timestamp in Java

java.time

As of Java 8+ you can use the java.time package. Specifically, use DateTimeFormatterBuilder and DateTimeFormatter to format the patterns and literals.

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendPattern("MM").appendLiteral("/")
        .appendPattern("dd").appendLiteral("/")
        .appendPattern("yyyy").appendLiteral(" ")
        .appendPattern("hh").appendLiteral(":")
        .appendPattern("mm").appendLiteral(":")
        .appendPattern("ss").appendLiteral(" ")
        .appendPattern("a")
        .toFormatter();
System.out.println(LocalDateTime.now().format(formatter));

The output ...

06/22/2015 11:59:14 AM

Or if you want different time zone

// system default
System.out.println(formatter.withZone(ZoneId.systemDefault()).format(Instant.now()));
// Chicago
System.out.println(formatter.withZone(ZoneId.of("America/Chicago")).format(Instant.now()));
// Kathmandu
System.out.println(formatter.withZone(ZoneId.of("Asia/Kathmandu")).format(Instant.now()));

The output ...

06/22/2015 12:38:42 PM
06/22/2015 02:08:42 AM
06/22/2015 12:53:42 PM

How can I link a photo in a Facebook album to a URL

You can only do this to you own photos. Due to recent upgrades, Facebook has made this more difficult. To do this, go to the album page where the photo is that you want to link to. You should see thumbnail images of the photos in the album. Hold down the "Control" or "Command" key while clicking the photo that you wish to link to. A new browser tab will open with the picture you clicked. Under the picture there is a URL that you can send to others to share the photo. You might have to have the privacy settings for that album set so that anyone can see the photos in that album. If you don't the person who clicks the link may have to be signed in and also be your "friend."

Here is an example of one of my photos: http://www.facebook.com/photo.php?pid=43764341&l=0d8a526a64&id=25502298 -it's my cat.

Update:

The link below the photo no longer appears. Once you open the photo in a new tab you can right click the photo (Control+click for Mac users) and click "Copy Image URL" or similar and then share this link. Based on my tests the person who clicks the link doesn't need to use Facebook. The photo will load without the Facebook interface. Like this - http://a1.sphotos.ak.fbcdn.net/hphotos-ak-ash4/189088_867367406856_25502298_43764341_1304758_n.jpg

How do I make a newline after a twitter bootstrap element?

You're using span6 and span2. Both of these classes are "float:left" meaning, if possible they will always try to sit next to each other. Twitter bootstrap is based on a 12 grid system. So you should generally always get the span**#** to add up to 12.

E.g.: span4 + span4 + span4 OR span6 + span6 OR span4 + span3 + span5.

To force a span down though, without listening to the previous float you can use twitter bootstraps clearfix class. To do this, your code should look like this:

<ul class="nav nav-tabs span2">
  <li><a href="./index.html"><i class="icon-black icon-music"></i></a></li>
  <li><a href="./about.html"><i class="icon-black icon-eye-open"></i></a></li>
  <li><a href="./team.html"><i class="icon-black icon-user"></i></a></li>
  <li><a href="./contact.html"><i class="icon-black icon-envelope"></i></a></li>
</ul>
<!-- Notice this following line -->
<div class="clearfix"></div>
<div class="well span6">
  <h3>I wish this appeared on the next line without having to gratuitously use BR!</h3>
</div>

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

Avoid browser popup blockers

My use case: In my react app, Upon user click there is an API call performed to the backend. Based on the response, new tab is opened with the api response added as params to the new tab URL (in same domain).

The only caveat in my use case is that it takes more for 1 second for the API response to be received. Hence pop-up blocker shows up (if it is active) when opening up URL in a new tab.

To circumvent the above described issue, here is the sample code,

var new_tab=window.open()
axios.get('http://backend-api').then(response=>{
    const url="http://someurl"+"?response"
    new_tab.location.href=url;
}).catch(error=>{
    //catch error
})

Summary: Create an empty tab (as above line 1) and when the API call is completed, you can fill up the tab with the url and skip the popup blocker.

How to delete multiple rows in SQL where id = (x to y)

Please try this:

DELETE FROM `table` WHERE id >=163 and id<= 265

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

if you want that not contains any of a-z and A-Z:

SELECT * FROM mytable WHERE NOT REGEXP_LIKE(column_1, '[A-Za-z]')

something like:

"98763045098" or "!%436%$7%$*#"

or other languages like persian, arabic and ... like this:

"???? ????"

XAMPP on Windows - Apache not starting

I encountered the same issue after XAMPP v3.2.1 installation. I do not have Skype as most people would believe, however as a Software Developer I assumed port 80 is already in use by my other apps. So I changed it by simply using the XAMPP Control Panel: enter image description here

Click on the 'Config' button corresponding to the APACHE service and choose the first option 'Apache (httpd.conf)'. In the document that opens (using any text editor - except MS Word!), locate the text:

Listen 12.34.56.78:80

Listen 80

And change this to:

Listen 12.34.56.78:83

Listen 83

This can be any non-used port number. Thanks.

Where does R store packages?

Thanks for the direction from the above two answerers. James Thompson's suggestion worked best for Windows users.

  1. Go to where your R program is installed. This is referred to as R_Home in the literature. Once you find it, go to the /etc subdirectory.

    C:\R\R-2.10.1\etc
    
  2. Select the file in this folder named Rprofile.site. I open it with VIM. You will find this is a bare-bones file with less than 20 lines of code. I inserted the following inside the code:

    # my custom library path
    .libPaths("C:/R/library")
    

    (The comment added to keep track of what I did to the file.)

  3. In R, typing the .libPaths() function yields the first target at C:/R/Library

NOTE: there is likely more than one way to achieve this, but other methods I tried didn't work for some reason.

How do I check in SQLite whether a table exists?

If you're using SQLite version 3.3+ you can easily create a table with:

create table if not exists TableName (col1 typ1, ..., colN typN)

In the same way, you can remove a table only if it exists by using:

drop table if exists TableName

Select first and last row from grouped data

I know the question specified dplyr. But, since others already posted solutions using other packages, I decided to have a go using other packages too:

Base package:

df <- df[with(df, order(id, stopSequence, stopId)), ]
merge(df[!duplicated(df$id), ], 
      df[!duplicated(df$id, fromLast = TRUE), ], 
      all = TRUE)

data.table:

df <-  setDT(df)
df[order(id, stopSequence)][, .SD[c(1,.N)], by=id]

sqldf:

library(sqldf)
min <- sqldf("SELECT id, stopId, min(stopSequence) AS StopSequence
      FROM df GROUP BY id 
      ORDER BY id, StopSequence, stopId")
max <- sqldf("SELECT id, stopId, max(stopSequence) AS StopSequence
      FROM df GROUP BY id 
      ORDER BY id, StopSequence, stopId")
sqldf("SELECT * FROM min
      UNION
      SELECT * FROM max")

In one query:

sqldf("SELECT * 
        FROM (SELECT id, stopId, min(stopSequence) AS StopSequence
              FROM df GROUP BY id 
              ORDER BY id, StopSequence, stopId)
        UNION
        SELECT *
        FROM (SELECT id, stopId, max(stopSequence) AS StopSequence
              FROM df GROUP BY id 
              ORDER BY id, StopSequence, stopId)")

Output:

  id stopId StopSequence
1  1      a            1
2  1      c            3
3  2      b            1
4  2      c            4
5  3      a            3
6  3      b            1

Calling dynamic function with dynamic number of parameters

Here's what you need:

function mainfunc (){
    window[Array.prototype.shift.call(arguments)].apply(null, arguments);
}

The first argument is used as the function name and all of the remaining ones are used as arguments to the called function...

We're able to use the shift method to return and then delete the first value from the arguments array. Note that we've called it from the Array prototype since, strictly speaking, 'arguments' is not a real array and so doesn't inherit the shift method like a regular array would.


You can also call the shift method like this:

[].shift.call(arguments);

PHP add elements to multidimensional array with array_push

I know the topic is old, but I just fell on it after a google search so... here is another solution:

$array_merged = array_merge($array_going_first, $array_going_second);

This one seems pretty clean to me, it works just fine!

Is there any "font smoothing" in Google Chrome?

I had the same problem, and I found the solution in this post of Sam Goddard,

The solution if to defined the call to the font twice. First as it is recommended, to be used for all the browsers, and after a particular call only for Chrome with a special media query:

@font-face {
  font-family: 'chunk-webfont';
  src: url('../../includes/fonts/chunk-webfont.eot');
  src: url('../../includes/fonts/chunk-webfont.eot?#iefix') format('eot'),
  url('../../includes/fonts/chunk-webfont.woff') format('woff'),
  url('../../includes/fonts/chunk-webfont.ttf') format('truetype'),
  url('../../includes/fonts/chunk-webfont.svg') format('svg');
  font-weight: normal;
  font-style: normal;
}

@media screen and (-webkit-min-device-pixel-ratio:0) {
  @font-face {
    font-family: 'chunk-webfont';
    src: url('../../includes/fonts/chunk-webfont.svg') format('svg');
  }
}

enter image description here

With this method the font will render good in all browsers. The only negative point that I found is that the font file is also downloaded twice.

You can find an spanish version of this article in my page

Using CRON jobs to visit url?

you can use this for url with parameters:

lynx -dump "http://vps-managed.com/tasks.php?code=23456"

lynx is available on all systems by default.

Aligning a button to the center

Here is what worked for me:

    <input type="submit" style="margin-left: 50%">

If you only add margin, without the left part, it will center the submit button into the middle of your entire page, making it difficult to find and rendering your form incomplete for people who don't have the patience to find a submit button lol. margin-left centers it within the same line, so it's not further down your page than you intended. You can also use pixels instead of percentage if you just want to indent the submit button a bit and not all the way halfway across the page.

Difference between IISRESET and IIS Stop-Start command

I know this is quite an old post, but I would like to point out the following for people who will read it in the future: As per MS:

Do not use the IISReset.exe tool to restart the IIS services. Instead, use the NET STOP and NET START commands. For example, to stop and start the World Wide Web Publishing Service, run the following commands:

  • NET STOP iisadmin /y
  • NET START w3svc

There are two benefits to using the NET STOP/NET START commands to restart the IIS Services as opposed to using the IISReset.exe tool. First, it is possible for IIS configuration changes that are in the process of being saved when the IISReset.exe command is run to be lost. Second, using IISReset.exe can make it difficult to identify which dependent service or services failed to stop when this problem occurs. Using the NET STOP commands to stop each individual dependent service will allow you to identify which service fails to stop, so you can then troubleshoot its failure accordingly.

KB:https://support.microsoft.com/en-ca/help/969864/using-iisreset-exe-to-restart-internet-information-services-iis-result

How to send only one UDP packet with netcat?

Netcat sends one packet per newline. So you're fine. If you do anything more complex then you might need something else.

I was fooling around with Wireshark when I realized this. Don't know if it helps.

Creating a simple XML file using python

For such a simple XML structure, you may not want to involve a full blown XML module. Consider a string template for the simplest structures, or Jinja for something a little more complex. Jinja can handle looping over a list of data to produce the inner xml of your document list. That is a bit trickier with raw python string templates

For a Jinja example, see my answer to a similar question.

Here is an example of generating your xml with string templates.

import string
from xml.sax.saxutils import escape

inner_template = string.Template('    <field${id} name="${name}">${value}</field${id}>')

outer_template = string.Template("""<root>
 <doc>
${document_list}
 </doc>
</root>
 """)

data = [
    (1, 'foo', 'The value for the foo document'),
    (2, 'bar', 'The <value> for the <bar> document'),
]

inner_contents = [inner_template.substitute(id=id, name=name, value=escape(value)) for (id, name, value) in data]
result = outer_template.substitute(document_list='\n'.join(inner_contents))
print result

Output:

<root>
 <doc>
    <field1 name="foo">The value for the foo document</field1>
    <field2 name="bar">The &lt;value&gt; for the &lt;bar&gt; document</field2>
 </doc>
</root>

The downer of the template approach is that you won't get escaping of < and > for free. I danced around that problem by pulling in a util from xml.sax

Is there an "if -then - else " statement in XPath?

How about using fn:replace(string,pattern,replace) instead?

XPATH is very often used in XSLTs and if you are in that situation and does not have XPATH 2.0 you could use:

  <xsl:choose>
    <xsl:when test="condition1">
      condition1-statements
    </xsl:when>
    <xsl:when test="condition2">
      condition2-statements
    </xsl:when>
    <xsl:otherwise>
      otherwise-statements
    </xsl:otherwise>
  </xsl:choose>

remove item from array using its name / value

Maybe this is helpful, too.

for (var i = countries.length - 1; i--;) {
    if (countries[i]['id'] === 'AF' || countries[i]['name'] === 'Algeria'{
        countries.splice(i, 1);
    }
}

phpmailer error "Could not instantiate mail function"

Try using SMTP to send email:-

$mail->IsSMTP();
$mail->Host = "smtp.example.com";

// optional
// used only when SMTP requires authentication  
$mail->SMTPAuth = true;
$mail->Username = 'smtp_username';
$mail->Password = 'smtp_password';

Redirecting a request using servlets and the "setHeader" method not working

As you can see, the response is still HTTP/1.1 200 OK. To indicate a redirect, you need to send back a 302 status code:

response.setStatus(HttpServletResponse.SC_FOUND); // SC_FOUND = 302

How to handle button clicks using the XML onClick within Fragments

You could just do this:

Activity:

Fragment someFragment;    

//...onCreate etc instantiating your fragments

public void myClickMethod(View v) {
    someFragment.myClickMethod(v);
}

Fragment:

public void myClickMethod(View v) {
    switch(v.getId()) {
        // Just like you were doing
    }
}    

In response to @Ameen who wanted less coupling so Fragments are reuseable

Interface:

public interface XmlClickable {
    void myClickMethod(View v);
}

Activity:

XmlClickable someFragment;    

//...onCreate, etc. instantiating your fragments casting to your interface.
public void myClickMethod(View v) {
    someFragment.myClickMethod(v);
}

Fragment:

public class SomeFragment implements XmlClickable {

//...onCreateView, etc.

@Override
public void myClickMethod(View v) {
    switch(v.getId()){
        // Just like you were doing
    }
}    

How to communicate between Docker containers via "hostname"

The new networking feature allows you to connect to containers by their name, so if you create a new network, any container connected to that network can reach other containers by their name. Example:

1) Create new network

$ docker network create <network-name>       

2) Connect containers to network

$ docker run --net=<network-name> ...

or

$ docker network connect <network-name> <container-name>

3) Ping container by name

docker exec -ti <container-name-A> ping <container-name-B> 

64 bytes from c1 (172.18.0.4): icmp_seq=1 ttl=64 time=0.137 ms
64 bytes from c1 (172.18.0.4): icmp_seq=2 ttl=64 time=0.073 ms
64 bytes from c1 (172.18.0.4): icmp_seq=3 ttl=64 time=0.074 ms
64 bytes from c1 (172.18.0.4): icmp_seq=4 ttl=64 time=0.074 ms

See this section of the documentation;

Note: Unlike legacy links the new networking will not create environment variables, nor share environment variables with other containers.

This feature currently doesn't support aliases

Converting string to title case

Try this:

using System.Globalization;
using System.Threading;
public void ToTitleCase(TextBox TextBoxName)
        {
            int TextLength = TextBoxName.Text.Length;
            if (TextLength == 1)
            {
                CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                TextInfo textInfo = cultureInfo.TextInfo;
                TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text);
                TextBoxName.SelectionStart = 1;
            }
            else if (TextLength > 1 && TextBoxName.SelectionStart < TextLength)
            {
                int x = TextBoxName.SelectionStart;
                CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                TextInfo textInfo = cultureInfo.TextInfo;
                TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text);
                TextBoxName.SelectionStart = x;
            }
            else if (TextLength > 1 && TextBoxName.SelectionStart >= TextLength)
            {
                CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
                TextInfo textInfo = cultureInfo.TextInfo;
                TextBoxName.Text = textInfo.ToTitleCase(TextBoxName.Text);
                TextBoxName.SelectionStart = TextLength;
            }
        }


Call this method in the TextChanged event of the TextBox.

Cannot open include file: 'unistd.h': No such file or directory

If you're using ZLib in your project, then you need to find :

#if 1

in zconf.h and replace(uncomment) it with :

#if HAVE_UNISTD_H /* ...the rest of the line

If it isn't ZLib I guess you should find some alternative way to do this. GL.

How to convert DateTime to VarChar

Try the following:

CONVERT(varchar(10), [MyDateTimecolumn], 20)

For a full date time and not just date do:

CONVERT(varchar(23), [MyDateTimecolumn], 121)

See this page for convert styles:

http://msdn.microsoft.com/en-us/library/ms187928.aspx
OR
SQL Server CONVERT() Function

Is it possible to cherry-pick a commit from another git repository?

See How to create and apply a patch with Git. (From the wording of your question, I assumed that this other repository is for an entirely different codebase. If it's a repository for the same code base, you should add it as a remote as suggested by @CharlesB. Even if it is for another code base, I guess you could still add it as a remote, but you might not want to get the entire branch into your repository...)

Prevent Android activity dialog from closing on outside touch

What you actually have is an Activity (even if it looks like a Dialog), therefore you should call setFinishOnTouchOutside(false) from your activity if you want to keep it open when the background activity is clicked.

EDIT: This only works with android API level 11 or greater

pip install from git repo branch

Just to add an extra, if you want to install it in your pip file it can be added like this:

-e git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6#egg=django-oscar-paypal

It will be saved as an egg though.

Convert Long into Integer

In addition to @Thilo's accepted answer, Math.toIntExact works also great in Optional method chaining, despite it accepts only an int as an argument

Long coolLong = null;
Integer coolInt = Optional.ofNullable(coolLong).map(Math::toIntExact).orElse(0); //yields 0

wordpress contactform7 textarea cols and rows change in smaller screens

Add it after Placeholder attribute.

[textarea* message id:message class:form-control 40x7 placeholder "Message"]

c#: getter/setter

This means that the compiler defines a backing field at runtime. This is the syntax for auto-implemented properties.

More Information: Auto-Implemented Properties

How can I convert JSON to a HashMap using Gson?

JSONObject typically uses HashMap internally to store the data. So, you can use it as Map in your code.

Example,

JSONObject obj = JSONObject.fromObject(strRepresentation);
Iterator i = obj.entrySet().iterator();
while (i.hasNext()) {
   Map.Entry e = (Map.Entry)i.next();
   System.out.println("Key: " + e.getKey());
   System.out.println("Value: " + e.getValue());
}

How to limit file upload type file size in PHP?

Something that your code doesn't account for is displaying multiple errors. As you have noted above it is possible for the user to upload a file >2MB of the wrong type, but your code can only report one of the issues. Try something like:

if(isset($_FILES['uploaded_file'])) {
    $errors     = array();
    $maxsize    = 2097152;
    $acceptable = array(
        'application/pdf',
        'image/jpeg',
        'image/jpg',
        'image/gif',
        'image/png'
    );

    if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
        $errors[] = 'File too large. File must be less than 2 megabytes.';
    }

    if((!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) {
        $errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
    }

    if(count($errors) === 0) {
        move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
    } else {
        foreach($errors as $error) {
            echo '<script>alert("'.$error.'");</script>';
        }

        die(); //Ensure no more processing is done
    }
}

Look into the docs for move_uploaded_file() (it's called move not store) for more.

How to _really_ programmatically change primary and accent color in Android Lollipop?

I read the comments about contacts app and how it use a theme for each contact.

Probably, contacts app has some predefine themes (for each material primary color from here: http://www.google.com/design/spec/style/color.html).

You can apply a theme before a the setContentView method inside onCreate method.

Then the contacts app can apply a theme randomly to each user.

This method is:

setTheme(R.style.MyRandomTheme);

But this method has a problem, for example it can change the toolbar color, the scroll effect color, the ripple color, etc, but it cant change the status bar color and the navigation bar color (if you want to change it too).

Then for solve this problem, you can use the method before and:

if (Build.VERSION.SDK_INT >= 21) {
        getWindow().setNavigationBarColor(getResources().getColor(R.color.md_red_500));
        getWindow().setStatusBarColor(getResources().getColor(R.color.md_red_700));
    }

This two method change the navigation and status bar color. Remember, if you set your navigation bar translucent, you can't change its color.

This should be the final code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(R.style.MyRandomTheme);
    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().setNavigationBarColor(getResources().getColor(R.color.myrandomcolor1));
        getWindow().setStatusBarColor(getResources().getColor(R.color.myrandomcolor2));
    }
    setContentView(R.layout.activity_main);

}

You can use a switch and generate random number to use random themes, or, like in contacts app, each contact probably has a predefine number associated.

A sample of theme:

<style name="MyRandomTheme" parent="Theme.AppCompat.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/myrandomcolor1</item>
    <item name="colorPrimaryDark">@color/myrandomcolor2</item>
    <item name="android:navigationBarColor">@color/myrandomcolor1</item>
</style>

Sorry for my english.

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

combining two data frames of different lengths

Hope this will work for you!

You can use library(qpcR) for combining two matrix with unequal size.

resultant_matrix <- qpcR:::cbind.na(matrix1, matrix2)

NOTE:- The resultant matrix will be of size of matrix2.

SQL LEFT JOIN Subquery Alias

I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.

SELECT wpoi.order_id As No_Commande
FROM  wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id 
                            AND wpp.meta_key = '_shipping_first_name'
WHERE  wpoi.order_id =2198 

How can I get the content of CKEditor using JQuery?

First of all you should include ckeditor and jquery connector script in your page,

then create a textarea

<textarea name="content" class="editor" id="ms_editor"></textarea>

attach ckeditor to the text area, in my project I use something like this:

$('textarea.editor').ckeditor(function() {
        }, { toolbar : [
            ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
            ['Undo','Redo'],
            ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
            ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
            ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
            ['Link','Unlink','Anchor', 'Image', 'Smiley'],
            ['Table','HorizontalRule','SpecialChar'],
            ['Styles','BGColor']
        ], toolbarCanCollapse:false, height: '300px', scayt_sLang: 'pt_PT', uiColor : '#EBEBEB' } );

on submit get the content using:

var content = $( 'textarea.editor' ).val();

That's it! :)

Export pictures from excel file into jpg using VBA

Dim filepath as string
Sheets("Sheet 1").ChartObjects("Chart 1").Chart.Export filepath & "Name.jpg"

Slimmed down the code to the absolute minimum if needed.

Equivalent of LIMIT for DB2

There are 2 solutions to paginate efficiently on a DB2 table :

1 - the technique using the function row_number() and the clause OVER which has been presented on another post ("SELECT row_number() OVER ( ORDER BY ... )"). On some big tables, I noticed sometimes a degradation of performances.

2 - the technique using a scrollable cursor. The implementation depends of the language used. That technique seems more robust on big tables.

I presented the 2 techniques implemented in PHP during a seminar next year. The slide is available on this link : http://gregphplab.com/serendipity/uploads/slides/DB2_PHP_Best_practices.pdf

Sorry but this document is only in french.

Does java.util.List.isEmpty() check if the list itself is null?

Invoking any method on any null reference will always result in an exception. Test if the object is null first:

List<Object> test = null;
if (test != null && !test.isEmpty()) {
    // ...
}

Alternatively, write a method to encapsulate this logic:

public static <T> boolean IsNullOrEmpty(Collection<T> list) {
    return list == null || list.isEmpty();
}

Then you can do:

List<Object> test = null;
if (!IsNullOrEmpty(test)) {
    // ...
}

How to frame two for loops in list comprehension python

tags = [u'man', u'you', u'are', u'awesome']
entries = [[u'man', u'thats'],[ u'right',u'awesome']]

result = []
[result.extend(entry) for tag in tags for entry in entries if tag in entry]

print(result)

Output:

['man', 'thats', 'right', 'awesome']

Monad in plain English? (For the OOP programmer with no FP background)

If you've ever used Powershell, the patterns Eric described should sound familiar. Powershell cmdlets are monads; functional composition is represented by a pipeline.

Jeffrey Snover's interview with Erik Meijer goes into more detail.

Extension methods must be defined in a non-generic static class

Try changing it to static class and back. That might resolve visual studio complaining when it's a false positive.

What are sessions? How do they work?

Because HTTP is stateless, in order to associate a request to any other request, you need a way to store user data between HTTP requests.

Cookies or URL parameters ( for ex. like http://example.com/myPage?asd=lol&boo=no ) are both suitable ways to transport data between 2 or more request. However they are not good in case you don't want that data to be readable/editable on client side.

The solution is to store that data server side, give it an "id", and let the client only know (and pass back at every http request) that id. There you go, sessions implemented. Or you can use the client as a convenient remote storage, but you would encrypt the data and keep the secret server-side.

Of course there are other aspects to consider, like you don't want people to hijack other's sessions, you want sessions to not last forever but to expire, and so on.

In your specific example, the user id (could be username or another unique ID in your user database) is stored in the session data, server-side, after successful identification. Then for every HTTP request you get from the client, the session id (given by the client) will point you to the correct session data (stored by the server) that contains the authenticated user id - that way your code will know what user it is talking to.

How do I import a .bak file into Microsoft SQL Server 2012?

You can use the following script if you don't wish to use Wizard;

RESTORE DATABASE myDB
FROM  DISK = N'C:\BackupDB.bak' 
WITH  REPLACE,RECOVERY,  
MOVE N'HRNET' TO N'C:\MSSQL\Data\myDB.mdf',  
MOVE N'HRNET_LOG' TO N'C:\MSSQL\Data\myDB.ldf'

How to make a button redirect to another page using jQuery or just Javascript

You can use:

  location.href = "newpage.html"

in the button's onclick event.

Rolling or sliding window iterator?

Multiple iterators!

def window(seq, size, step=1):
    # initialize iterators
    iters = [iter(seq) for i in range(size)]
    # stagger iterators (without yielding)
    [next(iters[i]) for j in range(size) for i in range(-1, -j-1, -1)]
    while(True):
        yield [next(i) for i in iters]
        # next line does nothing for step = 1 (skips iterations for step > 1)
        [next(i) for i in iters for j in range(step-1)]

next(it) raises StopIteration when the sequence is finished, and for some cool reason that's beyond me, the yield statement here excepts it and the function returns, ignoring the leftover values that don't form a full window.

Anyway, this is the least-lines solution yet whose only requirement is that seq implement either __iter__ or __getitem__ and doesn't rely on itertools or collections besides @dansalmo's solution :)

CSS float right not working correctly

LIke this

final answer

css

h2 {
    border-bottom-width: 1px;
    border-bottom-style: solid;
    margin: 0;
    padding: 0;
}
.edit_button {
    float: right;
}

demo1

css

h2 {
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: gray;
    float: left;
    margin: 0;
    padding: 0;
}
.edit_button {
    float: right;
}

html

<h2>
Contact Details</h2>
<button type="button" class="edit_button" >My Button</button>

demo

html

<div style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: gray; float:left;">
Contact Details



</div>
<button type="button" class="edit_button" style="float: right;">My Button</button>

How can I match on an attribute that contains a certain string?

To add onto bobince's answer... If whatever tool/library you using uses Xpath 2.0, you can also do this:

//*[count(index-of(tokenize(@class, '\s+' ), $classname)) = 1]

count() is apparently needed because index-of() returns a sequence of each index it has a match at in the string.

PHPmailer sending HTML CODE

do like this-paste your html code inside your separate html file using GET method.

$mail->IsHTML(true);                                 
    $mail->WordWrap = 70;                                 
    $mail->addAttachment= $_GET['addattachment']; $mail->AltBody   
    =$_GET['AltBody'];  $mail->Subject = $_GET['subject']; $mail->Body = $_GET['body'];

How do I manage conflicts with git submodules?

Got help from this discussion. In my case the

git reset HEAD subby
git commit

worked for me :)

What is perm space?

Perm Gen stands for permanent generation which holds the meta-data information about the classes.

  1. Suppose if you create a class name A, it's instance variable will be stored in heap memory and class A along with static classloaders will be stored in permanent generation.
  2. Garbage collectors will find it difficult to clear or free the memory space stored in permanent generation memory. Hence it is always recommended to keep the permgen memory settings to the advisable limit.
  3. JAVA8 has introduced the concept called meta-space generation, hence permgen is no longer needed when you use jdk 1.8 versions.

Unsetting array values in a foreach loop

You can use the index of the array element to remove it from the array, the next time you use the $list variable, you will see that the array is changed.

Try something like this

foreach($list as $itemIndex => &$item) {

   if($item['status'] === false) {
      unset($list[$itemIndex]);
   }

}

android layout with visibility GONE

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/activity_register_header"
    android:minHeight="50dp"
    android:orientation="vertical"
    android:visibility="gone" />

Try this piece of code..For me this code worked..

How to convert a DataFrame back to normal RDD in pyspark?

@dapangmao's answer works, but it doesn't give the regular spark RDD, it returns a Row object. If you want to have the regular RDD format.

Try this:

rdd = df.rdd.map(tuple)

or

rdd = df.rdd.map(list)

Targeting only Firefox with CSS

First of all, a disclaimer. I don't really advocate for the solution I present below. The only browser specific CSS I write is for IE (especially IE6), although I wish it wasn't the case.

Now, the solution. You asked it to be elegant so I don't know how elegant is it but it's sure going to target Gecko platforms only.

The trick is only working when JavaScript is enabled and makes use of Mozilla bindings (XBL), which are heavily used internally in Firefox and all other Gecko-based products. For a comparison, this is like the behavior CSS property in IE, but much more powerful.

Three files are involved in my solution:

  1. ff.html: the file to style
  2. ff.xml: the file containg the Gecko bindings
  3. ff.css: Firefox specific styling

ff.html

<!DOCTYPE html>

<html>
<head>
<style type="text/css">
body {
 -moz-binding: url(ff.xml#load-mozilla-css);
}
</style>
</head>
<body>

<h1>This should be red in FF</h1>

</body>
</html>

ff.xml

<?xml version="1.0"?>

<bindings xmlns="http://www.mozilla.org/xbl">
    <binding id="load-mozilla-css">
        <implementation>
            <constructor>
            <![CDATA[
                var link = document.createElement("link");
                    link.setAttribute("rel", "stylesheet");
                    link.setAttribute("type", "text/css");
                    link.setAttribute("href", "ff.css");

                document.getElementsByTagName("head")[0]
                        .appendChild(link);
            ]]>
            </constructor>
        </implementation>
    </binding>
</bindings>

ff.css

h1 {
 color: red;
}

Update: The above solution is not that good. It would be better if instead of appending a new LINK element it will add that "firefox" class on the BODY element. And it's possible, just by replacing the above JS with the following:

this.className += " firefox";

The solution is inspired by Dean Edwards' moz-behaviors.

live output from subprocess command

Similar to previous answers but the following solution worked for for me on windows using Python3 to provide a common method to print and log in realtime (getting-realtime-output-using-python):

def print_and_log(command, logFile):
    with open(logFile, 'wb') as f:
        command = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)

        while True:
            output = command.stdout.readline()
            if not output and command.poll() is not None:
                f.close()
                break
            if output:
                f.write(output)
                print(str(output.strip(), 'utf-8'), flush=True)
        return command.poll()

jQuery datepicker to prevent past date

I used the min attribute: min="' + (new Date()).toISOString().substring(0,10) + '"

Here's my code and it worked.

<input type="date" min="' + (new Date()).toISOString().substring(0,10) + '" id="' + invdateId + '" value="' + d.Invoice.Invoice_Date__c + '"/>

enter image description here

Best way to alphanumeric check in JavaScript

    // On keypress event call the following method
    function AlphaNumCheck(e) {
        var charCode = (e.which) ? e.which : e.keyCode;
        if (charCode == 8) return true;

        var keynum;
        var keychar;
        var charcheck = /[a-zA-Z0-9]/;
        if (window.event) // IE
        {
            keynum = e.keyCode;
        }
        else {
            if (e.which) // Netscape/Firefox/Opera
            {
                keynum = e.which;
            }
            else return true;
        }

        keychar = String.fromCharCode(keynum);
        return charcheck.test(keychar);
    }

Further, this article also helps to understand JavaScript alphanumeric validation.

How to copy file from host to container using Dockerfile

If you want to copy the current dir's contents, you can run:

docker build  -t <imagename:tag> -f- ./ < Dockerfile

How to set environment variables in Python?

I have been trying to add environment variables. My goal was to store some user information to system variables such that I can use those variables for future solutions, as an alternative to config files. However, the method described in the code below did not help me at all.

import os
os.environ["variable_1"] = "value_1"
os.environ["variable_2"] = "value_2"
# To Verify above code
os.environ.get("variable_1")
os.environ.get("variable_2")

This simple code block works well, however, these variables exist inside the respective processes such that you will not find them in the environment variables tab of windows system settings. Pretty much above code did not serve my purpose. This problem is discussed here: variable save problem

os.environ.putenv(key, value)

Another unsuccessful attempt. So, finally, I managed to save variable successfully inside the window environment register by mimicking the windows shell commands wrapped inside the system class of os package. The following code describes this successful attempt.

os.system("SETX {0} {1} /M".format(key, value))

I hope this will be helpful for some of you.

How do I create ColorStateList programmatically?

Here's an example of how to create a ColorList programmatically in Kotlin:

val colorList = ColorStateList(
        arrayOf(
                intArrayOf(-android.R.attr.state_enabled),  // Disabled
                intArrayOf(android.R.attr.state_enabled)    // Enabled
        ),
        intArrayOf(
                Color.BLACK,     // The color for the Disabled state
                Color.RED        // The color for the Enabled state
        )
)

How do you install Boost on MacOS?

Install Xcode from the mac app store. Then use the command:

  /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

the above will install homebrew and allow you to use brew in terminal

then just use command :

brew install boost

which would then install the boost libraries to <your macusername>/usr/local/Cellar/boost

Restore DB — Error RESTORE HEADERONLY is terminating abnormally.

This type of error will come when you try to upload backup data from a higher version to lower version. Like you have backup of SQL server 2008 and you trying to upload data into SQL server 2005 then you will get this kind of error. Please try to upload in a higher version.

What is the difference between new/delete and malloc/free?

In C++ new/delete call the Constructor/Destructor accordingly.

malloc/free simply allocate memory from the heap. new/delete allocate memory as well.

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

The issue is that you're not saving the mysqli connection. Change your connect to:

$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');

And then include it in your query:

$query1 = mysqli_query($aVar, "SELECT name1 FROM users
    ORDER BY RAND()
    LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];

Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.

How to create a video from images with FFmpeg?

cat *.png | ffmpeg -f image2pipe -i - output.mp4

from wiki

Force table column widths to always be fixed regardless of contents

You can add a div to the td, then style that. It should work as you expected.

<td><div>AAAAAAAAAAAAAAAAAAA</div></td>

Then the css.

td div { width: 50px; overflow: hidden; }

Getting full URL of action in ASP.NET MVC

This question is specific to ASP .NET however I am sure some of you will benefit of system agnostic javascript which is beneficial in many situations.

UPDATE: The way to get url formed outside of the page itself is well described in answers above.

Or you could do a oneliner like following:

new UrlHelper(actionExecutingContext.RequestContext).Action(
    "SessionTimeout", "Home", 
    new {area = string.Empty}, 
    actionExecutingContext.Request.Url!= null? 
    actionExecutingContext.Request.Url.Scheme : "http"
);

from filter or:

new UrlHelper(this.Request.RequestContext).Action(
    "Details", 
    "Journey", 
    new { area = productType }, 
    this.Request.Url!= null? this.Request.Url.Scheme : "http"
);

However quite often one needs to get the url of current page, for those cases using Html.Action and putting he name and controller of page you are in to me feels awkward. My preference in such cases is to use JavaScript instead. This is especially good in systems that are half re-written MVT half web-forms half vb-script half God knows what - and to get URL of current page one needs to use different method every time.

One way is to use JavaScript to get URL is window.location.href another - document.URL

Going through a text file line by line in C

So many problems in so few lines. I probably forget some:

  • argv[0] is the program name, not the first argument;
  • if you want to read in a variable, you have to allocate its memory
  • one never loops on feof, one loops on an IO function until it fails, feof then serves to determinate the reason of failure,
  • sscanf is there to parse a line, if you want to parse a file, use fscanf,
  • "%s" will stop at the first space as a format for the ?scanf family
  • to read a line, the standard function is fgets,
  • returning 1 from main means failure

So

#include <stdio.h>

int main(int argc, char* argv[])
{
    char const* const fileName = argv[1]; /* should check that argc > 1 */
    FILE* file = fopen(fileName, "r"); /* should check the result */
    char line[256];

    while (fgets(line, sizeof(line), file)) {
        /* note that fgets don't strip the terminating \n, checking its
           presence would allow to handle lines longer that sizeof(line) */
        printf("%s", line); 
    }
    /* may check feof here to make a difference between eof and io failure -- network
       timeout for instance */

    fclose(file);

    return 0;
}

How To Run PHP From Windows Command Line in WAMPServer

The problem you are describing sounds like your version of PHP might be missing the readline PHP module, causing the interactive shell to not work. I base this on this PHP bug submission.

Try running

php -m

And see if "readline" appears in the output.

There might be good reasons for omitting readline from the distribution. PHP is typically executed by a web server; so it is not really need for most use cases. I am sure you can execute PHP code in a file from the command prompt, using:

php file.php

There is also the phpsh project which provides a (better) interactive shell for PHP. However, some people have had trouble running it under Windows (I did not try this myself).

Edit: According to the documentation here, readline is not supported under Windows:

Note: This extension is not available on Windows platforms.

So, if that is correct, your options are:

  • Avoid the interactive shell, and just execute PHP code in files from the command line - this should work well
  • Try getting phpsh to work under Windows

What is the difference between Cloud, Grid and Cluster?

Cloud is a marketing term, with the bare minimum feature relating to fast automated provisioning of new servers. HA, utility billing, etc are all features people can lump on top to define it to their own liking.

Grid [Computing] is an extension of clusters where multiple loosely coupled systems are used to solve a single problem. They tend to be multi-tenant, sharing some likeness to Clouds, but tend to rely heavily upon custom frameworks that manage the interop between grid nodes.

Cluster hosting is a specialization of clusters where a load balancer is used to direct incoming traffic to one of many worker nodes. It predates grid computing and doesn't rely on a homogenous abstraction of the underlying nodes as much as Grid computing. A web farm tends to have very specialized machines dedicated to each component type and is far more optimized for that specific task.

For pure hosting, Grid computing is the wrong tool. If you have no idea what your traffic shape is, then a Cloud would be useful. For predictable usage that changes at a reasonable pace, then a traditional cluster is fine and the most efficient.