Programs & Examples On #Tabindex

The [tabindex] is used to define a sequence that users follow when they use the Tab key to navigate through a page. By default, the natural tabbing order will match the source order in the markup.

What is the HTML tabindex attribute?

The HTML tabindex atribute is responsible for indicating if an element is reachable by keyboard navigation. When the user presses the Tab key the focus is shifted from one element to another. By using the tabindex atribute, the tab order flow is shifted.

How to ignore HTML element from tabindex?

Just add the attribute disabled to the element (or use jQuery to do it for you). Disabled prevents the input from being focused or selected at all.

Generate MD5 hash string with T-SQL

declare @hash nvarchar(50)
--declare @hash varchar(50)

set @hash = '1111111-2;20190110143334;001'  -- result a5cd84bfc56e245bbf81210f05b7f65f
declare @value varbinary(max);
set @value = convert(varbinary(max),@hash);


select  
 SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', '1111111-2;20190110143334;001')),3,32) as 'OK'
,SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', @hash)),3,32) as 'ERROR_01'
,SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5',convert(varbinary(max),@hash))),3,32) as 'ERROR_02'
,SUBSTRING(sys.fn_sqlvarbasetostr(sys.fn_repl_hash_binary(convert(varbinary(max),@hash))),3,32)
,SUBSTRING(sys.fn_sqlvarbasetostr(master.sys.fn_repl_hash_binary(@value)),3,32)

How to use struct timeval to get the execution time?

Change:

struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
                                          delcare a variable with
                                          no name. */

to:

struct timeval tvalBefore, tvalAfter;

It is less likely (IMO) to make this mistake if there is a single declaration per line:

struct timeval tvalBefore;
struct timeval tvalAfter;

It becomes more error prone when declaring pointers to types on a single line:

struct timeval* tvalBefore, tvalAfter;

tvalBefore is a struct timeval* but tvalAfter is a struct timeval.

Java integer list

To insert a sleep command you can use Thread.sleep(2000). So the code would be:

List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
Iterator<Integer> myListIterator = someList.iterator(); 
while (myListIterator.hasNext()) {
    Integer coord = myListIterator.next();    
    System.out.println(coord);
    Thread.Sleep(2000);
}

This would output: 10 20 30 40 50

If you want the numbers after each other you could use: System.out.print(coord +" " ); and if you want to repeat the section you can put it in another while loop.

List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
while(true)
    Iterator<Integer> myListIterator = someList.iterator(); 
    while (myListIterator.hasNext()) {
        Integer coord = myListIterator.next();    
        System.out.print(coord + " ");
        Thread.Sleep(2000);
    }
}

This would output: 10 20 30 40 50 10 20 30 40 50 ... and never stop until you kill the program.

Edit: You do have to put the sleep command in a try catch block

DB2 Date format

Current date is in yyyy-mm-dd format. You can convert it into yyyymmdd format using substring function:

select substr(current date,1,4)||substr(current date,6,2)||substr(currentdate,9,2)

How to sum up an array of integers in C#

In one of my apps I used :

public class ClassBlock
{
    public int[] p;
    public int Sum
    {
        get { int s = 0;  Array.ForEach(p, delegate (int i) { s += i; }); return s; }
    }
}

Javascript/DOM: How to remove all events of a DOM object?

Chrome only

As I'm trying to remove an EventListener within a Protractor test and do not have access to the Listener in the test, the following works to remove all event listeners of a single type:

function(eventType){
    getEventListeners(window).[eventType].forEach(
        function(e){
            window.removeEventListener(eventType, e.listener)
        }
    );
}

I hope this helps someone as previous answer were using the "remove" method which since then does not work anymore.

Pretty git branch graphs

Although sometimes I use gitg, always come back to command line:

[alias]
    #quick look at all repo
    loggsa = log --color --date-order --graph --oneline --decorate --simplify-by-decoration --all
    #quick look at active branch (or refs pointed)
    loggs  = log --color --date-order --graph --oneline --decorate --simplify-by-decoration
    #extend look at all repo
    logga  = log --color --date-order --graph --oneline --decorate --all
    #extend look at active branch
    logg   = log --color --date-order --graph --oneline --decorate
    #Look with date
    logda  = log --color --date-order --date=local --graph --format=\"%C(auto)%h%Creset %C(blue bold)%ad%Creset %C(auto)%d%Creset %s\" --all
    logd   = log --color --date-order --date=local --graph --format=\"%C(auto)%h%Creset %C(blue bold)%ad%Creset %C(auto)%d%Creset %s\"        
    #Look with relative date
    logdra = log --color --date-order --graph --format=\"%C(auto)%h%Creset %C(blue bold)%ar%Creset %C(auto)%d%Creset %s\" --all
    logdr = log --color --date-order --graph --format=\"%C(auto)%h%Creset %C(blue bold)%ar%Creset %C(auto)%d%Creset %s\"  

    loga   = log --graph --color --decorate --all

    # For repos without subject body commits (vim repo, git-svn clones)
    logt  = log --graph --color --format=\"%C(auto)%h %d %<|(100,trunc) %s\"
    logta  = log --graph --color --format=\"%C(auto)%h %d %<|(100,trunc) %s\" --all        
    logtsa = log --graph --color --format=\"%C(auto)%h %d %<|(100,trunc) %s\" --all --simplify-by-decoration 

As you can see is almost a keystroke saving aliases, based on:

  • --color: clear look
  • --graph: visualize parents
  • --date-order: most understandable look at repo
  • --decorate: who is who
  • --oneline: Many times all you need to know about a commit
  • --simplify-by-decoration: basic for a first look (just tags, relevant merges, branches)
  • --all: saving keystrokes with all alias with and without this option
  • --date=relative (%ar): Understand activity in repo (sometimes a branch is few commits near master but months ago from him)

See in recent version of git (1.8.5 and above) you can benefit from %C(auto) in decorate placeholder %d

From here all you need is a good understand of gitrevisions to filter whatever you need (something like master..develop, where --simplify-merges could help with long term branches)

The power behind command line is the quickly config based on your needs (understand a repo isn't a unique key log configuration, so adding --numstat, or --raw, or --name-status is sometimes needed. Here git log and aliases are fast, powerful and (with time) the prettiest graph you can achieved. Even more, with output showed by default through a pager (say less) you can always search quickly inside results. Not convinced? You can always parse the result with projects like gitgraph

Is it possible to open a Windows Explorer window from PowerShell?

I came across this question looking for a way to open an Explorer window from PowerShell and also select a file. I'm adding this answer in case others come across it for the same reason.

To launch Explorer and select a file, use Invoke-Expression:

Invoke-Expression "explorer '/select,$filePath'"

There are probably other ways to do this, but this worked for me.

JQuery Ajax - How to Detect Network Connection error when making Ajax call

USE

xhr.onerror = function(e){
    if (XMLHttpRequest.readyState == 4) {
        // HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
        selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
    }
    else if (XMLHttpRequest.readyState == 0) {
        // Network error (i.e. connection refused, access denied due to CORS, etc.)
        selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
    }
    else {
        selFoto.erroUploadFoto('Erro desconhecido.');
    }

};

(more code below - UPLOAD IMAGE EXAMPLE)

var selFoto = {
   foto: null,

   upload: function(){
        LoadMod.show();

        var arquivo = document.frmServico.fileupload.files[0];
        var formData = new FormData();

        if (arquivo.type.match('image.*')) {
            formData.append('upload', arquivo, arquivo.name);

            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'FotoViewServlet?acao=uploadFoto', true);
            xhr.responseType = 'blob';

            xhr.onload = function(e){
                if (this.status == 200) {
                    selFoto.foto = this.response;
                    var url = window.URL || window.webkitURL;
                    document.frmServico.fotoid.src = url.createObjectURL(this.response);
                    $('#foto-id').show();
                    $('#div_upload_foto').hide();           
                    $('#div_master_upload_foto').css('background-color','transparent');
                    $('#div_master_upload_foto').css('border','0');

                    Dados.foto = document.frmServico.fotoid;
                    LoadMod.hide();
                }
                else{
                    erroUploadFoto(XMLHttpRequest.statusText);
                }

                if (XMLHttpRequest.readyState == 4) {
                     selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
                }
                else if (XMLHttpRequest.readyState == 0) {
                     selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);                             
                }

            };

            xhr.onerror = function(e){
            if (XMLHttpRequest.readyState == 4) {
                // HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
                selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
            }
            else if (XMLHttpRequest.readyState == 0) {
                 // Network error (i.e. connection refused, access denied due to CORS, etc.)
                 selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
            }
            else {
                selFoto.erroUploadFoto('Erro desconhecido.');
            }
        };

        xhr.send(formData);
     }
     else{
        selFoto.erroUploadFoto('');                         
        MyCity.mensagens.push('Selecione uma imagem.');
        MyCity.showMensagensAlerta();
     }
  }, 

  erroUploadFoto : function(mensagem) {
        selFoto.foto = null;
        $('#file-upload').val('');
        LoadMod.hide();
        MyCity.mensagens.push('Erro ao atualizar a foto. '+mensagem);
        MyCity.showMensagensAlerta();
 }
 };

How to set the color of "placeholder" text?

Try this

textarea::-webkit-input-placeholder {  color: #999;}

Can I run HTML files directly from GitHub, instead of just viewing their source?

i wanted to edit html and js in github and have a preview. i wanted to do it in github to have instant commits and saves.

tried rawgithub.com but rawgithub.com was not realtime (it's cache refreshes once a minute).

so i quickly developed my own solution:

node.js solution for this: https://github.com/shimondoodkin/rawgithub

How to explicitly obtain post data in Spring MVC?

Spring MVC runs on top of the Servlet API. So, you can use HttpServletRequest#getParameter() for this:

String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");

The HttpServletRequest should already be available to you inside Spring MVC as one of the method arguments of the handleRequest() method.

Should I write script in the body or the head of the html?

I would answer this with multiple options actually, the some of which actually render in the body.

  • Place library script such as the jQuery library in the head section.
  • Place normal script in the head unless it becomes a performance/page load issue.
  • Place script associated with includes, within and at the end of that include. One example of this is .ascx user controls in asp.net pages - place the script at the end of that markup.
  • Place script that impacts the render of the page at the end of the body (before the body closure).
  • do NOT place script in the markup such as <input onclick="myfunction()"/> - better to put it in event handlers in your script body instead.
  • If you cannot decide, put it in the head until you have a reason not to such as page blocking issues.

Footnote: "When you need it and not prior" applies to the last item when page blocking (perceptual loading speed). The user's perception is their reality—if it is perceived to load faster, it does load faster (even though stuff might still be occurring in code).

EDIT: references:

Side note: IF you place script blocks within markup, it may effect layout in certain browsers by taking up space (ie7 and opera 9.2 are known to have this issue) so place them in a hidden div (use a css class like: .hide { display: none; visibility: hidden; } on the div)

Standards: Note that the standards allow placement of the script blocks virtually anywhere if that is in question: http://www.w3.org/TR/1999/REC-html401-19991224/sgml/dtd.html and http://www.w3.org/TR/xhtml11/xhtml11_dtd.html

EDIT2: Note that whenever possible (always?) you should put the actual Javascript in external files and reference those - this does not change the pertinent sequence validity.

How can I pass variable to ansible playbook in the command line?

ansible-playbook release.yml -e "version=1.23.45 other_variable=foo"

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

MySQL: View with Subquery in the FROM Clause Limitation

It appears to be a known issue.

http://dev.mysql.com/doc/refman/5.1/en/unnamed-views.html

http://bugs.mysql.com/bug.php?id=16757

Many IN queries can be re-written as (left outer) joins and an IS (NOT) NULL of some sort. for example

SELECT * FROM FOO WHERE ID IN (SELECT ID FROM FOO2)

can be re-written as

SELECT FOO.* FROM FOO JOIN FOO2 ON FOO.ID=FOO2.ID

or

SELECT * FROM FOO WHERE ID NOT IN (SELECT ID FROM FOO2)

can be

SELECT FOO.* FROM FOO 
LEFT OUTER JOIN FOO2 
ON FOO.ID=FOO2.ID WHERE FOO.ID IS NULL

Symbolicating iPhone App Crash Reports

The magical Xcode Organizer isn't that magical about symbolicating my app. I got no symbols at all for the crash reports that I got back from Apple from a failed app submission.

I tried using the command-line, putting the crash report in the same folder as the .app file (that I submitted to the store) and the .dSYM file:

$ symbolicatecrash "My App_date_blahblah-iPhone.crash" "My App.app"

This only provided symbols for my app and not the core foundation code, but it was better than the number dump that Organizer is giving me and was enough for me to find and fix the crash that my app had. If anyone knows how to extend this to get Foundation symbols it would be appreciated.

Bootstrap Navbar toggle button not working

If you will change the ID then Toggle will not working same problem was with me i just change

<div class="collapse navbar-collapse" id="defaultNavbar1">
    <ul class="nav navbar-nav">

id="defaultNavbar1" then toggle is working

How to read file from relative path in Java project? java.io.File cannot find the path specified

For me actually the problem is the File object's class path is from <project folder path> or ./src, so use File file = new File("./src/xxx.txt"); solved my problem

How to redirect user's browser URL to a different page in Nodejs?

In Express you can use

res.redirect('http://example.com');

to redirect user from server.

To include a status code 301 or 302 it can be used

res.redirect(301, 'http://example.com');

How to upgrade all Python packages with pip

From https://github.com/cakebread/yolk:

$ pip install -U `yolk -U | awk '{print $1}' | uniq`

However, you need to get yolk first:

$ sudo pip install -U yolk

Vuex - passing multiple parameters to mutation

Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

The easiest way to pass a number of parameters is to destruct them:

mutations: {
    authenticate(state, { token, expiration }) {
        localStorage.setItem('token', token);
        localStorage.setItem('expiration', expiration);
    }
}

Then later on in your actions you can simply

store.commit('authenticate', {
    token,
    expiration,
});

Maven error :Perhaps you are running on a JRE rather than a JDK?

Here's my automatic solution...

This will follow your javac executable's symlink (setup by yum and/or alternatives --config java) backwards to find the JAVA_HOME. (Toss this in your in your /etc/profile):

export JAVA_HOME=$(readlink -f /usr/bin/javac | sed 's:/bin/javac$::')

If you wanted a stable path (refreshed on boot) launch something like this:

export JAVA_HOME=$(readlink -f /usr/bin/javac | sed 's:/bin/javac$::')
ln -sfn "${JAVA_HOME}" /usr/lib/jvm/jdk-current

I'm kinda shocked the latter still isn't baked into alternatives.

pandas convert some columns into rows

I guess I found a simpler solution

temp1 = pd.melt(df1, id_vars=["location"], var_name='Date', value_name='Value')
temp2 = pd.melt(df1, id_vars=["name"], var_name='Date', value_name='Value')

Concat whole temp1 with temp2's column name

temp1['new_column'] = temp2['name']

You now have what you asked for.

The PowerShell -and conditional operator

You can simplify it to

if ($user_sam -and $user_case) {
  ...
}

because empty strings coerce to $false (and so does $null, for that matter).

sending mail from Batch file

PowerShell comes with a built in command for it. So running directly from a .bat file:

powershell -ExecutionPolicy ByPass -Command Send-MailMessage ^
    -SmtpServer server.address.name ^
    -To [email protected] ^
    -From [email protected] ^
    -Subject Testing ^
    -Body 123

NB -ExecutionPolicy ByPass is only needed if you haven't set up permissions for running PS from CMD

Also for those looking to call it from within powershell, drop everything before -Command [inclusive], and ` will be your escape character (not ^)

Docker - Container is not running

This happens with images for which the script does not launch a service awaiting requests, therefore the container exits at the end of the script.

This is typically the case with most base OS images (centos, debian, etc.), or also with the node images.

Your best bet is to run the image in interactive mode. Example below with the node image:

docker run -it node /bin/bash

Output is

root@cacc7897a20c:/# echo $SHELL
/bin/bash

Change the Right Margin of a View Programmatically?

Update: Android KTX

The Core KTX module provides extensions for common libraries that are part of the Android framework, androidx.core.view among them.

dependencies {
    implementation "androidx.core:core-ktx:{latest-version}"
}

The following extension functions are handy to deal with margins:

Note: they are all extension functions of MarginLayoutParams, so first you need to get and cast the layoutParams of your view:

val params = (myView.layoutParams as ViewGroup.MarginLayoutParams)

Sets the margins of all axes in the ViewGroup's MarginLayoutParams. (The dimension has to be provided in pixels, see the last section if you want to work with dp)

inline fun MarginLayoutParams.setMargins(@Px size: Int): Unit
// E.g. 16px margins
params.setMargins(16)

Updates the margins in the ViewGroup's ViewGroup.MarginLayoutParams.

inline fun MarginLayoutParams.updateMargins(
    @Px left: Int = leftMargin, 
    @Px top: Int = topMargin, 
    @Px right: Int = rightMargin, 
    @Px bottom: Int = bottomMargin
): Unit
// Example: 8px left margin 
params.updateMargins(left = 8)

Updates the relative margins in the ViewGroup's MarginLayoutParams (start/end instead of left/right).

inline fun MarginLayoutParams.updateMarginsRelative(
    @Px start: Int = marginStart, 
    @Px top: Int = topMargin, 
    @Px end: Int = marginEnd, 
    @Px bottom: Int = bottomMargin
): Unit
// E.g: 8px start margin 
params.updateMargins(start = 8)

The following extension properties are handy to get the current margins:

inline val View.marginBottom: Int
inline val View.marginEnd: Int
inline val View.marginLeft: Int
inline val View.marginRight: Int
inline val View.marginStart: Int
inline val View.marginTop: Int
// E.g: get margin bottom
val bottomPx = myView1.marginBottom
  • Using dp instead of px:

If you want to work with dp (density-independent pixels) instead of px, you will need to convert them first. You can easily do that with the following extension property:

val Int.px: Int
    get() = (this * Resources.getSystem().displayMetrics.density).toInt()

Then you can call the previous extension functions like:

params.updateMargins(start = 16.px, end = 16.px, top = 8.px, bottom = 8.px)
val bottomDp = myView1.marginBottom.dp

Old answer:

In Kotlin you can declare an extension function like:

fun View.setMargins(
    leftMarginDp: Int? = null,
    topMarginDp: Int? = null,
    rightMarginDp: Int? = null,
    bottomMarginDp: Int? = null
) {
    if (layoutParams is ViewGroup.MarginLayoutParams) {
        val params = layoutParams as ViewGroup.MarginLayoutParams
        leftMarginDp?.run { params.leftMargin = this.dpToPx(context) }
        topMarginDp?.run { params.topMargin = this.dpToPx(context) }
        rightMarginDp?.run { params.rightMargin = this.dpToPx(context) }
        bottomMarginDp?.run { params.bottomMargin = this.dpToPx(context) }
        requestLayout()
    }
}

fun Int.dpToPx(context: Context): Int {
    val metrics = context.resources.displayMetrics
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), metrics).toInt()
}

Then you can call it like:

myView1.setMargins(8, 16, 34, 42)

Or:

myView2.setMargins(topMarginDp = 8) 

Best way to check if a drop down list contains a value?

On C# this works:

        if (DDLAlmacen.Items.Count > 0)
        {
            if (DDLAlmacen.Items.FindByValue("AlmacenDefectoAndes").Value == "AlmacenDefectoAndes")
            {
                DDLAlmacen.SelectedValue = "AlmacenDefectoAndes";
            }
        }

Update:

Translating the code above to Visual Basic doesn't work. It throws "System.NullReferenceException: Object reference not set to an instance of an object.."

So. for this to work on Visual Basic, I had to change the code like this:

        If DDLAlmacen.Items.Count > 0 Then
            If DDLAlmacen.Items.Contains(New ListItem("AlmacenDefectoAndes")) Then
                DDLAlmacen.SelectedValue = "AlmacenDefectoAndes"
            End If
        End If

Python return statement error " 'return' outside function"

Use quit() in this context. break expects to be inside a loop, and return expects to be inside a function.

Jquery date picker z-index issue

I have a page where the datepicker was on top of a datatables.net tabletools button. The datatables buttons had a higher z-index than the individual datepicker date buttons. Thanks to Ronye's answer I was able to resolve this problem by using position: relative; and z-index: 10000. Thanks!

Git says remote ref does not exist when I delete remote branch

I followed the solution by poke with a minor adjustment in the end. My steps follow
- git fetch --prune;
- git branch -a printing the following
    master
    branch
    remotes/origin/HEAD -> origin/master
    remotes/origin/master
    remotes/origin/branch (remote branch to remove)
- git push origin --delete branch.
Here, the branch to remove is not named as remotes/origin/branch but simply branch. And the branch is removed.

Integer.valueOf() vs. Integer.parseInt()

Actually, valueOf uses parseInt internally. The difference is parseInt returns an int primitive while valueOf returns an Integer object. Consider from the Integer.class source:

public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s, 10);
}

public static Integer valueOf(String s, int radix) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, radix));
}

public static Integer valueOf(String s) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, 10));
}

As for parsing with a comma, I'm not familiar with one. I would sanitize them.

int million = Integer.parseInt("1,000,000".replace(",", ""));

Android - Back button in the title bar

Just sharing something that helped me and may be useful for others. Although most of the answers here are correct, by using the getActionBar().setDisplayHomeAsUpEnabled(true);, this wasn't working for me. The issue I had was that I was trying to create a second Activity manually, but there are more details involved.
What really solved my problem was following Android Developers tutorial (https://developer.android.com/training/basics/firstapp/starting-activity) for creating a second Activity using Android Studio own tools:

Create the second activity
1. In the Project window, right-click the app folder and select New > Activity > Empty Activity.
2. In the Configure Activity window, enter "DisplayMessageActivity" for Activity Name and click Finish (leave all other properties set to the defaults).
Android Studio automatically does three things:
- Creates the DisplayMessageActivity file.
- Creates the corresponding activity_display_message.xml layout file.
- Adds the required <activity> element in AndroidManifest.xml.

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

The easiest way to do this in my experience is with the Cloudmersive free native PHP library, just call convertDocumentDocxToPdf:

<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');



$apiInstance = new Swagger\Client\Api\ConvertDocumentApi(


    new GuzzleHttp\Client(),
    $config
);
$input_file = "/path/to/file.txt"; // \SplFileObject | Input file to perform the operation on.

try {
    $result = $apiInstance->convertDocumentDocxToPdf($input_file);
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling ConvertDocumentApi->convertDocumentDocxToPdf: ', $e->getMessage(), PHP_EOL;
}
?>

Be sure to replace $input_file with the appropriate file path. You can also configure it to use a byte array if you prefer to do it that way. The result will be the bytes of the converted PDF file.

Allow access permission to write in Program Files of Windows 7

Options I can think of:

  • Run entire app as full admin priv. using UAC
  • Run a sub-process as full admin for only those things needing access
  • Write temporary files elsewhere

What is stability in sorting algorithms and why is it important?

Stable sort will always return same solution (permutation) on same input.

For instance [2,1,2] will be sorted using stable sort as permutation [2,1,3] (first is index 2, then index 1 then index 3 in sorted output) That mean that output is always shuffled same way. Other non stable, but still correct permutation is [2,3,1].

Quick sort is not stable sort and permutation differences among same elements depends on algorithm for picking pivot. Some implementations pick up at random and that can make quick sort yielding different permutations on same input using same algorithm.

Stable sort algorithm is necessary deterministic.

Writing numerical values on the plot with Matplotlib

Use pyplot.text() (import matplotlib.pyplot as plt)

import matplotlib.pyplot as plt

x=[1,2,3]
y=[9,8,7]

plt.plot(x,y)
for a,b in zip(x, y): 
    plt.text(a, b, str(b))
plt.show()

Cannot read property length of undefined

perhaps, you can first determine if the DOM does really exists,

function walkmydog() {
    //when the user starts entering
    var dom = document.getElementById('WallSearch');
    if(dom == null){
        alert('sorry, WallSearch DOM cannot be found');
        return false;    
    }

    if(dom.value.length == 0){
        alert("nothing");
    }
}

if (document.addEventListener){
    document.addEventListener("DOMContentLoaded", walkmydog, false);
}

How to set image in circle in swift

imageView.layer.cornerRadius = imageView.frame.height/2
imageView.clipToBounds = true

C# how to change data in DataTable?

You should probably set the property dt.Columns["columnName"].ReadOnly = false; before.

jQuery: how to find first visible input/select/textarea excluding buttons?

This is an improvement over @Mottie's answer because as of jQuery 1.5.2 :text selects input elements that have no specified type attribute (in which case type="text" is implied):

$('form').find(':text,textarea,select').filter(':visible:first')

How do I create documentation with Pydoc?

Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for 'original' in 'original.py':

yourcode_dir$ pydoc -w original.py
no Python documentation found for 'original.py'

yourcode_dir$ pydoc -w original
wrote original.html

Run react-native application on iOS device directly from command line?

Just wanted to add something to Kamil's answer

After following the steps, I still got an error,

error Could not find device with the name: "....'s Xr"

After removing special characters from the device name (Go to Settings -> General -> About -> Name)

Eg: '

It Worked !

Hope this will help someone who faced similar issue.

Tested with - react-native-cli: 2.0.1 | react-native: 0.59.8 | VSCode 1.32 | Xcode 10.2.1 | iOS 12.3

HTML5 Video not working in IE 11

It was due to IE Document-mode version too low. Press 'F12' and using higher version( My case, above version 9 is OK)

Simple mediaplayer play mp3 from file path?

I use this class for Audio play. If your audio location is raw folder.

Call method for play:

new AudioPlayer().play(mContext, getResources().getIdentifier(alphabetItemList.get(mPosition)
                        .getDetail().get(0).getAudio(),"raw", getPackageName()));

AudioPlayer.java class:

public class AudioPlayer {

    private MediaPlayer mMediaPlayer;

    public void stop() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
    // mothod for raw folder (R.raw.fileName)
    public void play(Context context, int rid){
        stop();

        mMediaPlayer = MediaPlayer.create(context, rid);
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                stop();
            }
        });

        mMediaPlayer.start();
    }

    // mothod for other folder 
    public void play(Context context, String name) {
        stop();

        //mMediaPlayer = MediaPlayer.create(c, rid);
        mMediaPlayer = MediaPlayer.create(context, Uri.parse("android.resource://"+ context.getPackageName()+"/your_file/"+name+".mp3"));
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                stop();
            }
        });

        mMediaPlayer.start();
    }

}

What's the yield keyword in JavaScript?

Fibonacci sequence generator using the yield keyword.

function* fibbonaci(){
    var a = -1, b = 1, c;
    while(1){
        c = a + b;
        a = b;
        b = c;
        yield c;
    }   
}

var fibonacciGenerator = fibbonaci();
fibonacciGenerator.next().value; // 0 
fibonacciGenerator.next().value; // 1
fibonacciGenerator.next().value; // 1
fibonacciGenerator.next().value; // 2 

Expand Python Search Path to Other Source

You should also read about python packages here: http://docs.python.org/tutorial/modules.html.

From your example, I would guess that you really have a package at ~/codez/project. The file __init__.py in a python directory maps a directory into a namespace. If your subdirectories all have an __init__.py file, then you only need to add the base directory to your PYTHONPATH. For example:

PYTHONPATH=$PYTHONPATH:$HOME/adaifotis/project

In addition to testing your PYTHONPATH environment variable, as David explains, you can test it in python like this:

$ python
>>> import project                      # should work if PYTHONPATH set
>>> import sys
>>> for line in sys.path: print line    # print current python path

...

Windows equivalent of $export

To translate your *nix style command script to windows/command batch style it would go like this:

SET PROJ_HOME=%USERPROFILE%/proj/111
SET PROJECT_BASEDIR=%PROJ_HOME%/exercises/ex1
mkdir "%PROJ_HOME%"

mkdir on windows doens't have a -p parameter : from the MKDIR /? help:

MKDIR creates any intermediate directories in the path, if needed.

which basically is what mkdir -p (or --parents for purists) on *nix does, as taken from the man guide

How To Remove Outline Border From Input Button

Another alternative to restore outline when using the keyboard is to use :focus-visible. However, this doesn't work on IE :https://caniuse.com/?search=focus-visible.

How do I remove duplicate items from an array in Perl?

That last one was pretty good. I'd just tweak it a bit:

my @arr;
my @uniqarr;

foreach my $var ( @arr ){
  if ( ! grep( /$var/, @uniqarr ) ){
     push( @uniqarr, $var );
  }
}

I think this is probably the most readable way to do it.

Android Material Design Button Styles

Here is how I got what I wanted.

First, made a button (in styles.xml):

<style name="Button">
    <item name="android:textColor">@color/white</item>
    <item name="android:padding">0dp</item>
    <item name="android:minWidth">88dp</item>
    <item name="android:minHeight">36dp</item>
    <item name="android:layout_margin">3dp</item>
    <item name="android:elevation">1dp</item>
    <item name="android:translationZ">1dp</item>
    <item name="android:background">@drawable/primary_round</item>
</style>

The ripple and background for the button, as a drawable primary_round.xml:

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/primary_600">
  <item>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
        <corners android:radius="1dp" />
        <solid android:color="@color/primary" />
    </shape>
  </item>
</ripple>

This added the ripple effect I was looking for.

Are 2 dimensional Lists possible in c#?

Well you certainly can use a List<List<string>> where you'd then write:

List<string> track = new List<string>();
track.Add("2349");
track.Add("The Prime Time of Your Life");
// etc
matrix.Add(track);

But why would you do that instead of building your own class to represent a track, with Track ID, Name, Artist, Album, Play Count and Skip Count properties? Then just have a List<Track>.

SQL where datetime column equals today's date?

There might be another way, but this should work:

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest] 
FROM [dbo].[EXTRANET] 
WHERE day(Submission_date)=day(now) and 
     month(Submission_date)=month(now)
     and year(Submission_date)=year(now)

How to stop IIS asking authentication for default website on localhost

  1. Add Admin user with password
  2. Go to wwwroot props
  3. Give this user a full access to this folder and its children
  4. Change the user of the AppPool to the added user using this article http://technet.microsoft.com/en-us/library/cc771170(v=ws.10).aspx
  5. Change the User of the website using this article http://techblog.sunsetsurf.co.uk/2010/07/changing-the-user-iis-runs-as-windows-2008-iis-7-5/ Put the same username and password you have created at step (1).

It is working now congrats

How do I install Python 3 on an AWS EC2 instance?

Note: This may be obsolete for current versions of Amazon Linux 2 since late 2018 (see comments), you can now directly install it via yum install python3.

In Amazon Linux 2, there isn't a python3[4-6] in the default yum repos, instead there's the Amazon Extras Library.

sudo amazon-linux-extras install python3

If you want to set up isolated virtual environments with it; using yum install'd virtualenv tools don't seem to reliably work.

virtualenv --python=python3 my_venv

Calling the venv module/tool is less finicky, and you could double check it's what you want/expect with python3 --version beforehand.

python3 -m venv my_venv

Other things it can install (versions as of 18 Jan 18):

[ec2-user@x ~]$ amazon-linux-extras list
  0  ansible2   disabled  [ =2.4.2 ]
  1  emacs   disabled  [ =25.3 ]
  2  memcached1.5   disabled  [ =1.5.1 ]
  3  nginx1.12   disabled  [ =1.12.2 ]
  4  postgresql9.6   disabled  [ =9.6.6 ]
  5  python3=latest  enabled  [ =3.6.2 ]
  6  redis4.0   disabled  [ =4.0.5 ]
  7  R3.4   disabled  [ =3.4.3 ]
  8  rust1   disabled  [ =1.22.1 ]
  9  vim   disabled  [ =8.0 ]
 10  golang1.9   disabled  [ =1.9.2 ]
 11  ruby2.4   disabled  [ =2.4.2 ]
 12  nano   disabled  [ =2.9.1 ]
 13  php7.2   disabled  [ =7.2.0 ]
 14  lamp-mariadb10.2-php7.2   disabled  [ =10.2.10_7.2.0 ]

Generate SHA hash in C++ using OpenSSL library

Here is OpenSSL example of calculating sha-1 digest using BIO:

#include <openssl/bio.h>
#include <openssl/evp.h>

std::string sha1(const std::string &input)
{
    BIO * p_bio_md  = nullptr;
    BIO * p_bio_mem = nullptr;

    try
    {
        // make chain: p_bio_md <-> p_bio_mem
        p_bio_md = BIO_new(BIO_f_md());
        if (!p_bio_md) throw std::bad_alloc();
        BIO_set_md(p_bio_md, EVP_sha1());

        p_bio_mem = BIO_new_mem_buf((void*)input.c_str(), input.length());
        if (!p_bio_mem) throw std::bad_alloc();
        BIO_push(p_bio_md, p_bio_mem);

        // read through p_bio_md
        // read sequence: buf <<-- p_bio_md <<-- p_bio_mem
        std::vector<char> buf(input.size());
        for (;;)
        {
            auto nread = BIO_read(p_bio_md, buf.data(), buf.size());
            if (nread  < 0) { throw std::runtime_error("BIO_read failed"); }
            if (nread == 0) { break; } // eof
        }

        // get result
        char md_buf[EVP_MAX_MD_SIZE];
        auto md_len = BIO_gets(p_bio_md, md_buf, sizeof(md_buf));
        if (md_len <= 0) { throw std::runtime_error("BIO_gets failed"); }

        std::string result(md_buf, md_len);

        // clean
        BIO_free_all(p_bio_md);

        return result;
    }
    catch (...)
    {
        if (p_bio_md) { BIO_free_all(p_bio_md); }
        throw;
    }
}

Though it's longer than just calling SHA1 function from OpenSSL, but it's more universal and can be reworked for using with file streams (thus processing data of any length).

Does Spring Data JPA have any way to count entites using method name resolving?

@Autowired
private UserRepository userRepository;

@RequestMapping("/user/count")
private Long getNumberOfUsers(){
    return userRepository.count();
}

Rendering an array.map() in React

Using Stateless Functional Component We will not be using this.state. Like this

 {data1.map((item,key)=>
               { return
                <tr key={key}>
                <td>{item.heading}</td>
                <td>{item.date}</td>
                <td>{item.status}</td>
              </tr>
                
                })}

How to blur background images in Android

This might be a very late reply but I hope it helps someone.

  1. You can use third party libs such as RenderScript/Blurry/etc.
  2. If you do not want to use any third party libs, you can do the below using alpha(setting alpha to 0 means complete blur and 1 means same as existing).

Note(If you are using point 2) : While setting alpha to the background, it will blur the whole layout. To avoid this, create a new xml containing drawable and set alpha here to 0.5 (or value of your wish) and use this drawable name (name of file) as the background.

For example, use it as below (say file name is bgndblur.xml):

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shape="rectangle"
android:src="@drawable/registerscreenbackground" 
android:alpha="0.5">

Use the below in your layout :

<....
 android:background="@drawable/bgndblur">

Hope this helped.

Eclipse - java.lang.ClassNotFoundException

Carlos approach helped! Eclipse - java.lang.ClassNotFoundException

Try to check the classpath of the junit run configuration:

  1. Open your run configurations
  2. Click on the jUnit-Test you want to start
  3. go to the classpath tab
  4. Try to add a folder (click on user entries, click on advanced, click on add folders, click on ok and search the outputfolder for your test classes(those you find under projektproperties java build path, source))

works for me.

How does one target IE7 and IE8 with valid CSS?

I did it using Javascript. I add three css classes to the html element:

ie<version>
lte-ie<version>
lt-ie<version + 1>

So for IE7, it adds ie7, lte-ie7 ..., lt-ie8 ...

Here is the javascript code:

(function () {
    function getIEVersion() {
        var ua = window.navigator.userAgent;
        var msie = ua.indexOf('MSIE ');
        var trident = ua.indexOf('Trident/');

        if (msie > 0) {
            // IE 10 or older => return version number
            return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
        } else if (trident > 0) {
            // IE 11 (or newer) => return version number
            var rv = ua.indexOf('rv:');
            return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
        } else {
            return NaN;
        }
    };

    var ieVersion = getIEVersion();

    if (!isNaN(ieVersion)) { // if it is IE
        var minVersion = 6;
        var maxVersion = 13; // adjust this appropriately

        if (ieVersion >= minVersion && ieVersion <= maxVersion) {
            var htmlElem = document.getElementsByTagName('html').item(0);

            var addHtmlClass = function (className) { // define function to add class to 'html' element
                htmlElem.className += ' ' + className;
            };

            addHtmlClass('ie' + ieVersion); // add current version
            addHtmlClass('lte-ie' + ieVersion);

            if (ieVersion < maxVersion) {
                for (var i = ieVersion + 1; i <= maxVersion; ++i) {
                    addHtmlClass('lte-ie' + i);
                    addHtmlClass('lt-ie' + i);
                }
            }
        }
    }
})();

Thereafter, you use the .ie<version> css class in your stylesheet as described by potench.

(Used Mario's detectIE function in Check if user is using IE with jQuery)

The benefit of having lte-ie8 and lt-ie8 etc is that it you can target all browser less than or equal to IE9, that is IE7 - IE9.

EF Migrations: Rollback last applied migration?

Update-Database –TargetMigration:"Your migration name"

For this problem I suggest this link:

https://elegantcode.com/2012/04/12/entity-framework-migrations-tips/

Return JSON response from Flask view

Flask 1.1.x supports returning a JSON dict without calling jsonify. If you want to return something besides a dict, you still need to call jsonify.

@app.route("/")
def index():
    return {
        "api_stuff": "values",
    }

is equivalent to

@app.route("/")
def index():
    return jsonify({
        "api_stuff": "values",
    })

See the pull request that added this: https://github.com/pallets/flask/pull/3111

How to develop or migrate apps for iPhone 5 screen resolution?

Peter, you should really take a look at Canappi, it does all that for you, all you have to do is specify the layout as such:

button mySubmitButton 'Sumbit' (100,100,100,30 + 0,88,0,0) { ... }

From there Canappi will generate the correct objective-c code that detects the device the app is running on and will use:

(100,100,100,30) for iPhone4
(100,**188**,100,30) for iPhone 5

Canappi works like Interface Builder and Story Board combined, except that it is in a textual form. If you already have XIB files, you can convert them so you don't have to recreate the entire UI from scratch.

jquery - How to determine if a div changes its height or any css attribute?

For future sake I'll post this. If you do not need to support < IE11 then you should use MutationObserver.

Here is a link to the caniuse js MutationObserver

Simple usage with powerful results.

    var observer = new MutationObserver(function (mutations) {
        //your action here
    });

    //set up your configuration
    //this will watch to see if you insert or remove any children
    var config = { subtree: true, childList: true };

    //start observing
    observer.observe(elementTarget, config);

When you don't need to observe any longer just disconnect.

    observer.disconnect();

Check out the MDN documentation for more information

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

How to check for an active Internet connection on iOS or macOS?

First: Add CFNetwork.framework in framework

Code: ViewController.m

#import "Reachability.h"

- (void)viewWillAppear:(BOOL)animated
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus internetStatus = [r currentReachabilityStatus];

    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
    {
        /// Create an alert if connection doesn't work
        UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"No Internet Connection"   message:NSLocalizedString(@"InternetMessage", nil)delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [myAlert show];
        [myAlert release];
    }
    else
    {
         NSLog(@"INTERNET IS CONNECT");
    }
}

Is there a command to list all Unix group names?

If you want all groups known to the system, I would recommend using getent group instead of parsing /etc/group:

getent group

The reason is that on networked systems, groups may not only read from /etc/group file, but also obtained through LDAP or Yellow Pages (the list of known groups comes from the local group file plus groups received via LDAP or YP in these cases).

If you want just the group names you can use:

getent group | cut -d: -f1

In Visual Studio Code How do I merge between two local branches?

Update June 2017 (from VSCode 1.14)

The ability to merge local branches has been added through PR 25731 and commit 89cd05f: accessible through the "Git: merge branch" command.
And PR 27405 added handling the diff3-style merge correctly.

Vahid's answer mention 1.17, but that September release actually added nothing regarding merge.
Only the 1.18 October one added Git conflict markers

https://code.visualstudio.com/assets/updates/1_18/merge.png

From 1.18, with the combination of merge command (1.14) and merge markers (1.18), you truly can do local merges between branches.


Original answer 2016:

The Version Control doc does not mention merge commands, only merge status and conflict support.

Even the latest 1.3 June release does not bring anything new to the VCS front.

This is supported by issue 5770 which confirms you cannot use VS Code as a git mergetool, because:

Is this feature being included in the next iteration, by any chance?

Probably not, this is a big endeavour, since a merge UI needs to be implemented.

That leaves the actual merge to be initiated from command line only.

Git merge without auto commit

You're misunderstanding the meaning of the merge here.

The --no-commit prevents the MERGE COMMIT from occuring, and that only happens when you merge two divergent branch histories; in your example that's not the case since Git indicates that it was a "fast-forward" merge and then Git only applies the commits already present on the branch sequentially.

sql primary key and index

Primary keys are always indexed by default.

You can define a primary key in SQL Server 2012 by using SQL Server Management Studio or Transact-SQL. Creating a primary key automatically creates a corresponding unique, clustered or nonclustered index.

http://technet.microsoft.com/en-us/library/ms189039.aspx

PyCharm error: 'No Module' when trying to import own module (python script)

The answer that worked for me was indeed what OP mentions in his 2015 update: uncheck these two boxes in your Python run config:

  • "Add content roots to PYTHONPATH"
  • "Add source roots to PYTHONPATH"

I already had the run config set to use the proper venv, so PyCharm doing additional work to add things to the path was not necessary. Instead it was causing errors.

Convert pandas DataFrame into list of lists

There is a built in method which would be the fastest method also, calling tolist on the .values np array:

df.values.tolist()

[[0.0, 3.61, 380.0, 3.0],
 [1.0, 3.67, 660.0, 3.0],
 [1.0, 3.19, 640.0, 4.0],
 [0.0, 2.93, 520.0, 4.0]]

Why does z-index not work?

Make sure that this element you would like to control with z-index does not have a parent with z-index property, because element is in a lower stacking context due to its parent’s z-index level.

Here's an example:

<section class="content">            
    <div class="modal"></div>
</section>

<div class="side-tab"></div>

// CSS //
.content {
    position: relative;
    z-index: 1;
}

.modal {
    position: fixed;
    z-index: 100;
}

.side-tab {
    position: fixed;
    z-index: 5;
}

In the example above, the modal has a higher z-index than the content, although the content will appear on top of the modal because "content" is the parent with a z-index property.

Here's an article that explains 4 reasons why z-index might not work: https://coder-coder.com/z-index-isnt-working/

[INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]

13 September 2018 It worked for me when add more types and set universalApk with false to reduce apk size

splits {
    abi {
        enable true
        reset()
        include 'x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'mips', 'mips64', 'arm64-v8a'
        universalApk false
    }
}

Format datetime to YYYY-MM-DD HH:mm:ss in moment.js

Use different format or pattern to get the information from the date

_x000D_
_x000D_
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

For more info: https://momentjs.com/docs/#/parsing/string-format/

How to dynamically change header based on AngularJS partial view?

Mr Hash had the best answer so far, but the solution below makes it ideal (for me) by adding the following benefits:

  • Adds no watches, which can slow things down
  • Actually automates what I might have done in the controller, yet
  • Still gives me access from the controller if I still want it.
  • No extra injecting

In the router:

  .when '/proposals',
    title: 'Proposals',
    templateUrl: 'proposals/index.html'
    controller: 'ProposalListCtrl'
    resolve:
      pageTitle: [ '$rootScope', '$route', ($rootScope, $route) ->
        $rootScope.page.setTitle($route.current.params.filter + ' ' + $route.current.title)
      ]

In the run block:

.run(['$rootScope', ($rootScope) ->
  $rootScope.page =
    prefix: ''
    body: ' | ' + 'Online Group Consensus Tool'
    brand: ' | ' + 'Spokenvote'
    setTitle: (prefix, body) ->
      @prefix = if prefix then ' ' + prefix.charAt(0).toUpperCase() + prefix.substring(1) else @prifix
      @body = if body then ' | ' + body.charAt(0).toUpperCase() + body.substring(1) else @body
      @title = @prefix + @body + @brand
])

Find distance between two points on map using Google Map API V2

THIS IS THE EASY AND PERFECT CODE FOR DURATION AND DISTANCE FINDING

  • Step 1;(add this and sync in your gradle)

    compile 'com.android.volley:volley:1.0.0'  
    
  • Step 2:(write this in your trigger method)

    public void clicked(View view) throws JSONException {  
    
         JSONObject locationJsonObject = new JSONObject();
                locationJsonObject.put("origin", "54.406505,18.67708");
                locationJsonObject.put("destination", "54.446251,18.570993");
                LatlngCalc(locationJsonObject);
    }
    
  • Step 3:(Copy & Paste in your class)

    private void LatlngCalc(JSONObject locationJsonObject) throws JSONException {
    
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        String url = "http://maps.googleapis.com/maps/api/distancematrix/" +
                    "json?origins=" + locationJsonObject.getString("origin") + "&destinations=" + locationJsonObject.getString("destination") + "&mode=driving&" +
                    "language=en-EN&sensor=false";
    
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
    
                        mTextView.setText("Response is: " + response.substring(0, 500));
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mTextView.setText("That didn't work!");
            }
        });
        queue.add(stringRequest);  
    }
    

Python: Find in list

If you are going to check if value exist in the collectible once then using 'in' operator is fine. However, if you are going to check for more than once then I recommend using bisect module. Keep in mind that using bisect module data must be sorted. So you sort data once and then you can use bisect. Using bisect module on my machine is about 12 times faster than using 'in' operator.

Here is an example of code using Python 3.8 and above syntax:

import bisect
from timeit import timeit

def bisect_search(container, value):
    return (
      (index := bisect.bisect_left(container, value)) < len(container) 
      and container[index] == value
    )

data = list(range(1000))
# value to search
true_value = 666
false_value = 66666

# times to test
ttt = 1000

print(f"{bisect_search(data, true_value)=} {bisect_search(data, false_value)=}")

t1 = timeit(lambda: true_value in data, number=ttt)
t2 = timeit(lambda: bisect_search(data, true_value), number=ttt)

print("Performance:", f"{t1=:.4f}, {t2=:.4f}, diffs {t1/t2=:.2f}")

Output:

bisect_search(data, true_value)=True bisect_search(data, false_value)=False
Performance: t1=0.0220, t2=0.0019, diffs t1/t2=11.71

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

When a VS2013 C++ project is opened in VS2015, and there are warnings about "The build tools for v120... cannot be found", I simply need to edit the .vcxproj file and change <PlatformToolset>v120</PlatformToolset> to <PlatformToolset>v140</PlatformToolset>, and close and re-open the solution.

Efficient way to Handle ResultSet in Java

Here is the code little modified that i got it from google -

 List data_table = new ArrayList<>();
    Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.getConnection(conn_url, user_id, password);
            Statement stmt = con.createStatement();
            System.out.println("query_string: "+query_string);
            ResultSet rs = stmt.executeQuery(query_string);
            ResultSetMetaData rsmd = rs.getMetaData();


            int row_count = 0;
            while (rs.next()) {
                HashMap<String, String> data_map = new HashMap<>();
                if (row_count == 240001) {
                    break;
                }
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    data_map.put(rsmd.getColumnName(i), rs.getString(i));
                }
                data_table.add(data_map);
                row_count = row_count + 1;
            }
            rs.close();
            stmt.close();
            con.close();

How to change dataframe column names in pyspark?

There are many ways to do that:

  • Option 1. Using selectExpr.

    data = sqlContext.createDataFrame([("Alberto", 2), ("Dakota", 2)], 
                                      ["Name", "askdaosdka"])
    data.show()
    data.printSchema()
    
    # Output
    #+-------+----------+
    #|   Name|askdaosdka|
    #+-------+----------+
    #|Alberto|         2|
    #| Dakota|         2|
    #+-------+----------+
    
    #root
    # |-- Name: string (nullable = true)
    # |-- askdaosdka: long (nullable = true)
    
    df = data.selectExpr("Name as name", "askdaosdka as age")
    df.show()
    df.printSchema()
    
    # Output
    #+-------+---+
    #|   name|age|
    #+-------+---+
    #|Alberto|  2|
    #| Dakota|  2|
    #+-------+---+
    
    #root
    # |-- name: string (nullable = true)
    # |-- age: long (nullable = true)
    
  • Option 2. Using withColumnRenamed, notice that this method allows you to "overwrite" the same column. For Python3, replace xrange with range.

    from functools import reduce
    
    oldColumns = data.schema.names
    newColumns = ["name", "age"]
    
    df = reduce(lambda data, idx: data.withColumnRenamed(oldColumns[idx], newColumns[idx]), xrange(len(oldColumns)), data)
    df.printSchema()
    df.show()
    
  • Option 3. using alias, in Scala you can also use as.

    from pyspark.sql.functions import col
    
    data = data.select(col("Name").alias("name"), col("askdaosdka").alias("age"))
    data.show()
    
    # Output
    #+-------+---+
    #|   name|age|
    #+-------+---+
    #|Alberto|  2|
    #| Dakota|  2|
    #+-------+---+
    
  • Option 4. Using sqlContext.sql, which lets you use SQL queries on DataFrames registered as tables.

    sqlContext.registerDataFrameAsTable(data, "myTable")
    df2 = sqlContext.sql("SELECT Name AS name, askdaosdka as age from myTable")
    
    df2.show()
    
    # Output
    #+-------+---+
    #|   name|age|
    #+-------+---+
    #|Alberto|  2|
    #| Dakota|  2|
    #+-------+---+
    

Catching exceptions from Guzzle

Old question, but Guzzle adds the response within the exception object. So a simple try-catch on GuzzleHttp\Exception\ClientException and then using getResponse on that exception to see what 400-level error and continuing from there.

How to add a right button to a UINavigationController?

You can try

self.navigationBar.topItem.rightBarButtonItem = anotherButton;

I want to delete all bin and obj folders to force all projects to rebuild everything

This Works Fine For Me: start for /d /r . %%d in (bin,obj, ClientBin,Generated_Code) do @if exist "%%d" rd /s /q "%%d"

Vagrant error : Failed to mount folders in Linux guest

In configuration where windows is a host, and linux is a guest I found solution of the same problem in other place.

So again, the error message was "Failed to mount folders in Linux guest. This is usually because the "vboxsf" file system is not available." (...)

This was caused because I have made mistake by doing symlink inside the guest system from /vagrant into /home/vagrant/vagrant. The point is, that the directory /vagrant is a normal linux directory that has a symlink (so all ok), but when booting up by "vagrant up", it tries to mount windows directory on that place, and windows directory cannot work as a symlink. Windows host does not support linux symlinks.

So what You can do then, is to ssh into guest, remove the symlink wherever You have it, and reload machine.

In my configuration it was: Vagrant 1.7.2, VBoxGuestAdditions 4.3.28 and VBox 4.3.28.

Hibernate Error executing DDL via JDBC Statement

Dialects are removed in recent SQL so use

  <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL57Dialect"/>

Sublime Text 3, convert spaces to tabs

Here is a solution that will automatically convert to tabs whenever you open a file.

Create this file: .../Packages/User/on_file_load.py:

import sublime
import sublime_plugin

class OnFileLoadEventListener(sublime_plugin.EventListener):

    def on_load_async(self, view):
        view.run_command("unexpand_tabs")

NOTE. It causes the file to be in an unsaved state after opening it, even if no actual space-to-tab conversion took place... maybe some can help with a fix for that...

Can an XSLT insert the current date?

Late answer, but my solution works in Eclipse XSLT. Eclipse uses XSLT 1 at time of this writing. You can install an XSLT 2 engine like Saxon. Or you can use the XSLT 1 solution below to insert current date and time.

<xsl:value-of select="java:util.Date.new()"/>

This will call Java's Data class to output the date. It will not work unless you also put the following "java:" definition in your <xsl:stylesheet> tag.

<xsl:stylesheet [...snip...]
         xmlns:java="java"
         [...snip...]>

I hope that helps someone. This simple answer was difficult to find for me.

month name to month number and vice versa in python

You can use below as an alternative.

  1. Month to month number:

from time import strptime

strptime('Feb','%b').tm_mon

  1. Month number to month:

import calendar

calendar.month_abbr[2] or calendar.month[2]

what is the difference between ajax and jquery and which one is better?

They aren't comparable.

Ajax (Asynchronous Javascript and XML) is a subset of javascript. Ajax is way for the client-side browser to communicate with the server (for example: retrieve data from a database) without having to perform a page refresh.

jQuery is a javascript library that standardizes the javascript differences cross-browser. jQuery includes some ajax functions.

How to enable Auto Logon User Authentication for Google Chrome

In addition to setting the registry entry for AuthServerWhitelist you should also set AuthSchemes: "ntlm,negotiate" (or just "ntlm" as appropriate for your situation). Using the above templates the policy for that will be "Supported authentication schemes"

How to join two tables by multiple columns in SQL?

SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score
FROM Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND E.FileNum = V.FileNum AND E.ActivityNum = V.ActivityNum

Apply vs transform on a group object

As I felt similarly confused with .transform operation vs. .apply I found a few answers shedding some light on the issue. This answer for example was very helpful.

My takeout so far is that .transform will work (or deal) with Series (columns) in isolation from each other. What this means is that in your last two calls:

df.groupby('A').transform(lambda x: (x['C'] - x['D']))
df.groupby('A').transform(lambda x: (x['C'] - x['D']).mean())

You asked .transform to take values from two columns and 'it' actually does not 'see' both of them at the same time (so to speak). transform will look at the dataframe columns one by one and return back a series (or group of series) 'made' of scalars which are repeated len(input_column) times.

So this scalar, that should be used by .transform to make the Series is a result of some reduction function applied on an input Series (and only on ONE series/column at a time).

Consider this example (on your dataframe):

zscore = lambda x: (x - x.mean()) / x.std() # Note that it does not reference anything outside of 'x' and for transform 'x' is one column.
df.groupby('A').transform(zscore)

will yield:

       C      D
0  0.989  0.128
1 -0.478  0.489
2  0.889 -0.589
3 -0.671 -1.150
4  0.034 -0.285
5  1.149  0.662
6 -1.404 -0.907
7 -0.509  1.653

Which is exactly the same as if you would use it on only on one column at a time:

df.groupby('A')['C'].transform(zscore)

yielding:

0    0.989
1   -0.478
2    0.889
3   -0.671
4    0.034
5    1.149
6   -1.404
7   -0.509

Note that .apply in the last example (df.groupby('A')['C'].apply(zscore)) would work in exactly the same way, but it would fail if you tried using it on a dataframe:

df.groupby('A').apply(zscore)

gives error:

ValueError: operands could not be broadcast together with shapes (6,) (2,)

So where else is .transform useful? The simplest case is trying to assign results of reduction function back to original dataframe.

df['sum_C'] = df.groupby('A')['C'].transform(sum)
df.sort('A') # to clearly see the scalar ('sum') applies to the whole column of the group

yielding:

     A      B      C      D  sum_C
1  bar    one  1.998  0.593  3.973
3  bar  three  1.287 -0.639  3.973
5  bar    two  0.687 -1.027  3.973
4  foo    two  0.205  1.274  4.373
2  foo    two  0.128  0.924  4.373
6  foo    one  2.113 -0.516  4.373
7  foo  three  0.657 -1.179  4.373
0  foo    one  1.270  0.201  4.373

Trying the same with .apply would give NaNs in sum_C. Because .apply would return a reduced Series, which it does not know how to broadcast back:

df.groupby('A')['C'].apply(sum)

giving:

A
bar    3.973
foo    4.373

There are also cases when .transform is used to filter the data:

df[df.groupby(['B'])['D'].transform(sum) < -1]

     A      B      C      D
3  bar  three  1.287 -0.639
7  foo  three  0.657 -1.179

I hope this adds a bit more clarity.

Scraping: SSL: CERTIFICATE_VERIFY_FAILED error for http://en.wikipedia.org

For anyone who is using anaconda, you would install the certifi package, see more at:

https://anaconda.org/anaconda/certifi

To install, type this line in your terminal:

conda install -c anaconda certifi

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

Just a note. In case you want train, test, AND validation sets, you can do this:

from sklearn.cross_validation import train_test_split

X = get_my_X()
y = get_my_y()
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
x_test, x_val, y_test, y_val = train_test_split(x_test, y_test, test_size=0.5)

These parameters will give 70 % to training, and 15 % each to test and val sets. Hope this helps.

Android Saving created bitmap to directory on sd card

Hi You can write data to bytes and then create a file in sdcard folder with whatever name and extension you want and then write the bytes to that file. This will save bitmap to sdcard.

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
                        + File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());

// remember close de FileOutput
fo.close();

add image to uitableview cell

Swift 4 solution:

    cell.imageView?.image = UIImage(named: "yourImageName")

What does [object Object] mean?

Basics

You may not know it but, in JavaScript, whenever we interact with string, number or boolean primitives we enter a hidden world of object shadows and coercion.

string, number, boolean, null, undefined, and symbol.

In JavaScript there are 7 primitive types: undefined, null, boolean, string, number, bigint and symbol. Everything else is an object. The primitive types boolean, string and number can be wrapped by their object counterparts. These objects are instances of the Boolean, String and Number constructors respectively.

typeof true; //"boolean"
typeof new Boolean(true); //"object"

typeof "this is a string"; //"string"
typeof new String("this is a string"); //"object"

typeof 123; //"number"
typeof new Number(123); //"object"

If primitives have no properties, why does "this is a string".length return a value?

Because JavaScript will readily coerce between primitives and objects. In this case the string value is coerced to a string object in order to access the property length. The string object is only used for a fraction of second after which it is sacrificed to the Gods of garbage collection – but in the spirit of the TV discovery shows, we will trap the elusive creature and preserve it for further analysis…

To demonstrate this further consider the following example in which we are adding a new property to String constructor prototype.

String.prototype.sampleProperty = 5;
var str = "this is a string";
str.sampleProperty;            // 5

By this means primitives have access to all the properties (including methods) defined by their respective object constructors.

So we saw that primitive types will appropriately coerce to their respective Object counterpart when required.

Analysis of toString() method

Consider the following code

var myObj    = {lhs: 3, rhs: 2};
var myFunc   = function(){}
var myString = "This is a sample String";
var myNumber = 4;
var myArray  = [2, 3, 5];

myObj.toString();     // "[object Object]"
myFunc.toString();    // "function(){}"
myString.toString();  // "This is a sample String"
myNumber.toString();  // "4"
myArray.toString();   // "2,3,5"

As discussed above, what's really happening is when we call toString() method on a primitive type, it has to be coerced into its object counterpart before it can invoke the method.
i.e. myNumber.toString() is equivalent to Number.prototype.toString.call(myNumber) and similarly for other primitive types.

But what if instead of primitive type being passed into toString() method of its corresponding Object constructor function counterpart, we force the primitive type to be passed as parameter onto toString() method of Object function constructor (Object.prototype.toString.call(x))?

Closer look at Object.prototype.toString()

As per the documentation, When the toString method is called, the following steps are taken:

  1. If the this value is undefined, return "[object Undefined]".
  2. If the this value is null, return "[object Null]".
  3. If this value is none of the above, Let O be the result of calling toObject passing the this value as the argument.
  4. Let class be the value of the [[Class]] internal property of O.
  5. Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".

Understand this from the following example

var myObj       = {lhs: 3, rhs: 2};
var myFunc      = function(){}
var myString    = "This is a sample String";
var myNumber    = 4;
var myArray     = [2, 3, 5];
var myUndefined = undefined;
var myNull      = null;

Object.prototype.toString.call(myObj);        // "[object Object]"
Object.prototype.toString.call(myFunc);       // "[object Function]"
Object.prototype.toString.call(myString);     // "[object String]"
Object.prototype.toString.call(myNumber);     // "[object Number]"
Object.prototype.toString.call(myArray);      // "[object Array]"
Object.prototype.toString.call(myUndefined);  // "[object Undefined]"
Object.prototype.toString.call(myNull);       // "[object Null]"

References: https://es5.github.io/x15.2.html#x15.2.4.2 https://es5.github.io/x9.html#x9.9 https://javascriptweblog.wordpress.com/2010/09/27/the-secret-life-of-javascript-primitives/

Can I use tcpdump to get HTTP requests, response header and response body?

Here is another choice: Chaosreader

So I need to debug an application which posts xml to a 3rd party application. I found a brilliant little perl script which does all the hard work – you just chuck it a tcpdump output file, and it does all the manipulation and outputs everything you need...

The script is called chaosreader0.94. See http://www.darknet.org.uk/2007/11/chaosreader-trace-tcpudp-sessions-from-tcpdump/

It worked like a treat, I did the following:

tcpdump host www.blah.com -s 9000 -w outputfile; perl chaosreader0.94 outputfile

Draw path between two points using Google Maps Android API v2

in below code midpointsList is an ArrayList of waypoints

private String getMapsApiDirectionsUrl(GoogleMap googleMap, LatLng startLatLng, LatLng endLatLng, ArrayList<LatLng> midpointsList) {
    String origin = "origin=" + startLatLng.latitude + "," + startLatLng.longitude;

    String midpoints = "";
    for (int mid = 0; mid < midpointsList.size(); mid++) {
        midpoints += "|" + midpointsList.get(mid).latitude + "," + midpointsList.get(mid).longitude;
    }

    String waypoints = "waypoints=optimize:true" + midpoints + "|";

    String destination = "destination=" + endLatLng.latitude + "," + endLatLng.longitude;
    String key = "key=AIzaSyCV1sOa_7vASRBs6S3S6t1KofFvDhjohvI";

    String sensor = "sensor=false";
    String params = origin + "&" + waypoints + "&" + destination + "&" + sensor + "&" + key;
    String output = "json";
    String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + params;


    Log.e("url", url);
    parseDirectionApidata(url, googleMap);
    return url;
}

Then copy and paste this url in your browser to check And the below code is to parse the url

    private void parseDirectionApidata(String url, final GoogleMap googleMap) {

    final JSONObject jsonObject = new JSONObject();

    try {

        AppUtill.getJsonWithHTTPPost(ViewMapActivity.this, 1, new ServiceCallBack() {
            @Override
            public void serviceCallBack(int id, JSONObject jsonResult) throws JSONException {

                if (jsonResult != null) {

                    Log.e("jsonRes", jsonResult.toString());

                    String status = jsonResult.optString("status");

                    if (status.equalsIgnoreCase("ok")) {
                        drawPath(jsonResult, googleMap);
                    }

                } else {

                    Toast.makeText(ViewMapActivity.this, "Unable to parse Directions Data", Toast.LENGTH_LONG).show();
                }

            }
        }, url, jsonObject);

    } catch (Exception e) {
        e.printStackTrace();

    }
}

And then pass the result to the drawPath method

    public void drawPath(JSONObject jObject, GoogleMap googleMap) {

    List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
    JSONArray jRoutes = null;
    JSONArray jLegs = null;
    JSONArray jSteps = null;
    List<LatLng> list = null;
    try {

        Toast.makeText(ViewMapActivity.this, "Drawing Path...", Toast.LENGTH_SHORT).show();
        jRoutes = jObject.getJSONArray("routes");

        /** Traversing all routes */
        for (int i = 0; i < jRoutes.length(); i++) {
            jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
            List path = new ArrayList<HashMap<String, String>>();

            /** Traversing all legs */
            for (int j = 0; j < jLegs.length(); j++) {
                jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                /** Traversing all steps */
                for (int k = 0; k < jSteps.length(); k++) {
                    String polyline = "";
                    polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                    list = decodePoly(polyline);
                }
                Log.e("list", list.toString());
                routes.add(path);
                Log.e("routes", routes.toString());
                if (list != null) {
                    Polyline line = googleMap.addPolyline(new PolylineOptions()
                            .addAll(list)
                            .width(12)
                            .color(Color.parseColor("#FF0000"))//Google maps blue color #05b1fb
                            .geodesic(true)
                    );
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

  private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }

    return poly;
}

decode poly function is to decode the points(lat and long) provided by Directions API in encoded form

Simple function to sort an array of objects

_x000D_
_x000D_
var library = [_x000D_
        {name: 'Steve', course:'WAP', courseID: 'cs452'}, _x000D_
        {name: 'Rakesh', course:'WAA', courseID: 'cs545'},_x000D_
        {name: 'Asad', course:'SWE', courseID: 'cs542'},_x000D_
];_x000D_
_x000D_
const sorted_by_name = library.sort( (a,b) => a.name > b.name );_x000D_
_x000D_
for(let k in sorted_by_name){_x000D_
    console.log(sorted_by_name[k]);_x000D_
}
_x000D_
_x000D_
_x000D_

Convert to binary and keep leading zeros in Python

When using Python >= 3.6, the cleanest way is to use f-strings with string formatting:

>>> var = 23
>>> f"{var:#010b}"
'0b00010111'

Explanation:

  • var the variable to format
  • : everything after this is the format specifier
  • # use the alternative form (adds the 0b prefix)
  • 0 pad with zeros
  • 10 pad to a total length off 10 (this includes the 2 chars for 0b)
  • b use binary representation for the number

Get all Attributes from a HTML element with Javascript/jQuery

Imagine you've got an HTML element like below:

<a class="toc-item"
   href="/books/n/ukhta2333/s5/"
   id="book-link-29"
>
   Chapter 5. Conclusions and recommendations
</a>

One way you can get all attributes of it is to convert them into an array:

const el = document.getElementById("book-link-29")
const attrArray = Array.from(el.attributes)

// Now you can iterate all the attributes and do whatever you need.
const attributes = attrArray.reduce((attrs, attr) => {
    attrs !== '' && (attrs += ' ')
    attrs += `${attr.nodeName}="${attr.nodeValue}"`
    return attrs
}, '')
console.log(attributes)

And below is the string that what you'll get (from the example), which includes all attributes:

class="toc-item" href="/books/n/ukhta2333/s5/" id="book-link-29"

PHP filesize MB/KB conversion

Here is a sample:

<?php
// Snippet from PHP Share: http://www.phpshare.org

    function formatSizeUnits($bytes)
    {
        if ($bytes >= 1073741824)
        {
            $bytes = number_format($bytes / 1073741824, 2) . ' GB';
        }
        elseif ($bytes >= 1048576)
        {
            $bytes = number_format($bytes / 1048576, 2) . ' MB';
        }
        elseif ($bytes >= 1024)
        {
            $bytes = number_format($bytes / 1024, 2) . ' KB';
        }
        elseif ($bytes > 1)
        {
            $bytes = $bytes . ' bytes';
        }
        elseif ($bytes == 1)
        {
            $bytes = $bytes . ' byte';
        }
        else
        {
            $bytes = '0 bytes';
        }

        return $bytes;
}
?>

Select all DIV text with single mouse click

I found it useful to wrap this function as a jQuery plugin:

$.fn.selectText = function () {
    return $(this).each(function (index, el) {
        if (document.selection) {
            var range = document.body.createTextRange();
            range.moveToElementText(el);
            range.select();
        } else if (window.getSelection) {
            var range = document.createRange();
            range.selectNode(el);
            window.getSelection().addRange(range);
        }
    });
}

So, it becomes a reusable solution. Then you can do this:

<div onclick="$(this).selectText()">http://example.com/page.htm</div>

And it will selected test in the div.

Gets byte array from a ByteBuffer in java

If one does not know anything about the internal state of the given (Direct)ByteBuffer and wants to retrieve the whole content of the buffer, this can be used:

ByteBuffer byteBuffer = ...;
byte[] data = new byte[byteBuffer.capacity()];
((ByteBuffer) byteBuffer.duplicate().clear()).get(data);

Responsive image map

For responsive image maps you will need to use a plugin:

https://github.com/stowball/jQuery-rwdImageMaps (No longer maintained)

Or

https://github.com/davidjbradshaw/imagemap-resizer


No major browsers understand percentage coordinates correctly, and all interpret percentage coordinates as pixel coordinates.

http://www.howtocreate.co.uk/tutorials/html/imagemaps

And also this page for testing whether browsers implement

http://home.comcast.net/~urbanjost/IMG/resizeimg3.html

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

I was getting this error

Error:Execution failed for task ':app:preDebugAndroidTestBuild'. Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ. See https://d.android.com/r/tools/test-apk-dependency-conflicts.html for details.

I was having following dependencies in my build.gradle file under Gradle Scripts

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

So, I resolved it by commenting the following dependencies

testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

So my dependencies look like this

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
//testImplementation 'junit:junit:4.12'
//androidTestImplementation 'com.android.support.test:runner:1.0.2'
//androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Hope it helps!

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

I found the below stuff in ffmpeg Docs. Hope this helps! :)

Reference: http://ffmpeg.org/ffmpeg.html#toc-Generic-options

‘-report’ Dump full command line and console output to a file named program-YYYYMMDD-HHMMSS.log in the current directory. This file can be useful for bug reports. It also implies -loglevel verbose.

Note: setting the environment variable FFREPORT to any value has the same effect.

Merging dictionaries in C#

How about adding a params overload?

Also, you should type them as IDictionary for maximum flexibility.

public static IDictionary<TKey, TValue> Merge<TKey, TValue>(IEnumerable<IDictionary<TKey, TValue>> dictionaries)
{
    // ...
}

public static IDictionary<TKey, TValue> Merge<TKey, TValue>(params IDictionary<TKey, TValue>[] dictionaries)
{
    return Merge((IEnumerable<TKey, TValue>) dictionaries);
}

Why is using the JavaScript eval function a bad idea?

I know this discussion is old, but I really like this approach by Google and wanted to share that feeling with others ;)

The other thing is that the better You get the more You try to understand and finally You just don't believe that something is good or bad just because someone said so :) This is a very inspirational video that helped me to think more by myself :) GOOD PRACTICES are good, but don't use them mindelessly :)

What is "pom" packaging in maven?

Packaging an artifact as POM means that it has a very simple lifecycle

package -> install -> deploy

http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html

This is useful if you are deploying a pom.xml file or a project that doesn't fit with the other packaging types.

We use pom packaging for many of our projects and bind extra phases and goals as appropriate.

For example some of our applications use:

prepare-package -> test -> package -> install -> deploy

When you mvn install the application it should add it to your locally .m2 repository. To publish elsewhere you will need to set up correct distribution management information. You may also need to use the maven builder helper plugin, if artifacts aren't automatically attached to by Maven.

Initializing an Array of Structs in C#

Change const to static readonly and initialise it like this

static readonly MyStruct[] MyArray = new[] {
    new MyStruct { label = "a", id = 1 },
    new MyStruct { label = "b", id = 5 },
    new MyStruct { label = "q", id = 29 }
};

How can I get customer details from an order in WooCommerce?

I just dealt with this. Depending on what you really want, you can get the details from the order like this:

$field = get_post_meta($order->id, $field_name, true);

Where $field_name is '_billing_address_1' or '_shipping_address_1'or 'first_name'. You can google the other fields, but don't forget the "" at the beginning.

If you want to retrieve the customer for this order, and get its field directly, it works as in your solution, except you do not need to retrieve the full customer object:

$customer_id = (int)$order->user_id;

$field = get_user_meta($customer_id, $field_name, true);

Now in this case, the $field_name does not start with "_". For example: 'first_name' and 'billing_address_1'.

Escaping special characters in Java Regular Expressions

I wrote this pattern:

Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");

And use it in this method:

String escapeSpecialRegexChars(String str) {

    return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0");
}

Then you can use it like this, for example:

Pattern toSafePattern(String text)
{
    return Pattern.compile(".*" + escapeSpecialRegexChars(text) + ".*");
}

We needed to do that because, after escaping, we add some regex expressions. If not, you can simply use \Q and \E:

Pattern toSafePattern(String text)
{
    return Pattern.compile(".*\\Q" + text + "\\E.*")
}

How to execute raw SQL in Flask-SQLAlchemy app

Have you tried:

result = db.engine.execute("<sql here>")

or:

from sqlalchemy import text

sql = text('select name from penguins')
result = db.engine.execute(sql)
names = [row[0] for row in result]
print names

How can I set a UITableView to grouped style

Setting that is not that hard as mentioned in the question. Actually it's pretty simple. Try this on storyboard.

enter image description here

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

before start make sure of installation:

yum install -y xorg-x11-server-Xorg xorg-x11-xauth xorg-x11-apps
  1. start xming or cygwin
  2. make connection with X11 forwarding (in putty don't forget to set localhost:0.0 for X display location)
  3. edit sshd.cong and restart
     cat /etc/ssh/sshd_config | grep X
                             X11Forwarding yes
                             X11DisplayOffset 10
AddressFamily inet
  1. Without the X11 forwarding, you are subjected to the X11 SECURITY and then you must: authorize the remote server to make a connection with the local X Server using a method (for instance, the xhost command) set the display environment variable to redirect the output to the X server of your local computer. In this example: 192.168.2.223 is the IP of the server 192.168.2.2 is the IP of the local computer where the x server is installed. localhost can also be used.
blablaco@blablaco01 ~
$ xhost 192.168.2.223
192.168.2.223 being added to access control list

blablaco@blablaco01 ~
$ ssh -l root 192.168.2.223
[email protected] password:
Last login: Sat May 22 18:59:04 2010 from etcetc
[root@oel5u5 ~]# export DISPLAY=192.168.2.2:0.0
[root@oel5u5 ~]# echo $DISPLAY
192.168.2.2:0.0
[root@oel5u5 ~]# xclock&

Then the xclock application must launch.

Check it on putty or mobaxterm and don't check in remote desktop Manager software. Be careful for user that sudo in.

R: numeric 'envir' arg not of length one in predict()

There are several problems here:

  1. The newdata argument of predict() needs a predictor variable. You should thus pass it values for Coupon, instead of Total, which is the response variable in your model.

  2. The predictor variable needs to be passed in as a named column in a data frame, so that predict() knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).

  3. For this to work, your original call should pass df in through the data argument, rather than using it directly in your formula. (This way, the name of the column in newdata will be able to match the name on the RHS of the formula).

With those changes incorporated, this will work:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

SELECT  RIGHT(RTRIM(column), 3),
        LEFT(column, LEN(column) - 3)
FROM    table

Use RIGHT w/ RTRIM (to avoid complications with a fixed-length column), and LEFT coupled with LEN (to only grab what you need, exempt of the last 3 characters).

if there's ever a situation where the length is <= 3, then you're probably going to have to use a CASE statement so the LEFT call doesn't get greedy.

How to recover MySQL database from .myd, .myi, .frm files

I think .myi you can repair from inside mysql.

If you see these type of error messages from MySQL: Database failed to execute query (query) 1016: Can't open file: 'sometable.MYI'. (errno: 145) Error Msg: 1034: Incorrect key file for table: 'sometable'. Try to repair it thenb you probably have a crashed or corrupt table.

You can check and repair the table from a mysql prompt like this:

check table sometable;
+------------------+-------+----------+----------------------------+
| Table | Op | Msg_type | Msg_text | 
+------------------+-------+----------+----------------------------+ 
| yourdb.sometable | check | warning | Table is marked as crashed | 
| yourdb.sometable | check | status | OK | 
+------------------+-------+----------+----------------------------+ 

repair table sometable;
+------------------+--------+----------+----------+ 
| Table | Op | Msg_type | Msg_text | 
+------------------+--------+----------+----------+ 
| yourdb.sometable | repair | status | OK | 
+------------------+--------+----------+----------+

and now your table should be fine:

check table sometable;
+------------------+-------+----------+----------+ 
| Table | Op | Msg_type | Msg_text |
+------------------+-------+----------+----------+ 
| yourdb.sometable | check | status | OK |
+------------------+-------+----------+----------+

Xml serialization - Hide null values

In my case the nullable variables/elements were all String type. So, I simply performed a check and assigned them string.Empty in case of NULL. This way I got rid of the unnecessary nil and xmlns attributes (p3:nil="true" xmlns:p3="http://www.w3.org/2001/XMLSchema-instance)

// Example:

myNullableStringElement = varCarryingValue ?? string.Empty

// OR

myNullableStringElement = myNullableStringElement ?? string.Empty

How to update data in one table from corresponding data in another table in SQL Server 2005

UPDATE table1
SET column1 = (SELECT expression1
               FROM table2
               WHERE conditions)
[WHERE conditions];

How do I write out a text file in C# with a code page other than UTF-8?

using System.IO;
using System.Text;

using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant))
{    
    sw.WriteLine("my text...");     
}

An alternate way of getting your encoding:

using System.IO;
using System.Text;

using (var sw  = new StreamWriter(File.Open(@"c:\myfile.txt", FileMode.CreateNew), Encoding.GetEncoding("iso-8859-1"))) {
    sw.WriteLine("my text...");             
}

Check out the docs for the StreamWriter constructor.

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

This demo is returning correctly for me in Chrome 14, FF3 and FF5 (with Firebug):

var mytextvalue = document.getElementById("mytext").value;
console.log(mytextvalue == ''); // true
console.log(mytextvalue == null); // false

and changing the console.log to alert, I still get the desired output in IE6.

print highest value in dict with key

just :

 mydict = {'A':4,'B':10,'C':0,'D':87}
 max(mydict.items(), key=lambda x: x[1])

How to close the current fragment by using Button like the back button?

If you need to handle the action more specifically with the back button you can use the following method:

view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if( keyCode == KeyEvent.KEYCODE_BACK )
        {
            onCloseFragment();
            return true;
        } else {
            return false;
        }
    }
});

Convert array to JSON

I made it that way:

if I have:

var jsonArg1 = new Object();
    jsonArg1.name = 'calc this';
    jsonArg1.value = 3.1415;
var jsonArg2 = new Object();
    jsonArg2.name = 'calc this again';
    jsonArg2.value = 2.73;

var pluginArrayArg = new Array();
    pluginArrayArg.push(jsonArg1);
    pluginArrayArg.push(jsonArg2);

to convert pluginArrayArg (which is pure javascript array) into JSON array:

var jsonArray = JSON.parse(JSON.stringify(pluginArrayArg))

.gitignore after commit

If you have not pushed the changes already:

git rm -r --cached .
git add .
git commit -m 'clear git cache'
git push

C programming in Visual Studio

Short answer: Yes, you need to rename .cpp files to c, so you can write C: https://msdn.microsoft.com/en-us/library/bb384838.aspx?f=255&MSPPError=-2147217396

From the link above:

By default, the Visual C++ compiler treats all files that end in .c as C source code, and all files that end in .cpp as C++ source code. To force the compiler to treat all files as C regardless of file name extension, use the /Tc compiler option.

That being said, I do not recommend learning C language in Visual Studio, why VS? It does have lots of features you are not going to use while learning C

How does the "final" keyword in Java work? (I can still modify an object.)

First of all, the place in your code where you are initializing (i.e. assigning for the first time) foo is here:

foo = new ArrayList();

foo is an object (with type List) so it is a reference type, not a value type (like int). As such, it holds a reference to a memory location (e.g. 0xA7D2A834) where your List elements are stored. Lines like this

foo.add("foo"); // Modification-1

do not change the value of foo (which, again, is just a reference to a memory location). Instead, they just add elements into that referenced memory location. To violate the final keyword, you would have to try to re-assign foo as follows again:

foo = new ArrayList();

That would give you a compilation error.


Now, with that out of the way, think about what happens when you add the static keyword.

When you do NOT have the static keyword, each object that instantiates the class has its own copy of foo. Therefore, the constructor assigns a value to a blank, fresh copy of the foo variable, which is perfectly fine.

However, when you DO have the static keyword, only one foo exists in memory that is associated with the class. If you were to create two or more objects, the constructor would be attempting to re-assign that one foo each time, violating the final keyword.

Split string with string as delimiter

@ECHO OFF
SETLOCAL
SET "string=string1 by string2.txt"
SET "string=%string:* by =%"
ECHO +%string%+

GOTO :EOF

The above SET command will remove the unwanted data. Result shown between + to demonstrate absence of spaces.

Formula: set var=%somevar:*string1=string2%

will assign to var the value of somevar with all characters up to string1 replaced by string2. The enclosing quotes in a set command ensure that any stray trailing spaces on the line are not included in the value assigned.

Write bytes to file

If I understand you correctly, this should do the trick. You'll need add using System.IO at the top of your file if you don't already have it.

public bool ByteArrayToFile(string fileName, byte[] byteArray)
{
    try
    {
        using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
        {
            fs.Write(byteArray, 0, byteArray.Length);
            return true;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in process: {0}", ex);
        return false;
    }
}

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

Just install this package and your code will work:=> Install-Package Microsoft.Owin.Host.SystemWeb -Version 2.1.0

Run PHP function on html button click

If you want to make a server request you should use AJAX, so you can send your desired parameters to the server and it can run whatever php you want with these parameters.

Example with pure javascript:

<input type="text" id="name" value="..."/>
<input type="text" id="location" value="..."/>
<input type="button" onclick="ajaxFunction();" value="Submit" />
<div id="ajaxDiv"></div>
<script type="text/javascript">    
    function ajaxFunction(){
        var ajaxRequest;  // The variable that makes Ajax possible!

        try{
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
        } catch (e){
            // Internet Explorer Browsers
            try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try{
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                    // Something went wrong
                    alert("Your browser broke!");
                    return false;
                }
            }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                var ajaxDisplay = document.getElementById('ajaxDiv');
                ajaxDisplay.innerHTML = ajaxRequest.responseText;
            }
        }
        var name = document.getElementById('name').value;
        var location = document.getElementById('location').value;
        var queryString = "?name=" + name + "&location=" + location;
        ajaxRequest.open("POST", "some.php" + queryString, true);
        ajaxRequest.send(null); 
    }
</script>

Example with jQuery Ajax: http://api.jquery.com/jQuery.ajax/

$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

You can have one file with functions called for example functions.php

functions.php

<?php
  myFunction($Name, $Location) {
      // etc...
  }
  myFunction2() {
  }
  // ... many functions
?>

some.php

<?php include("functions.php");    
$Name = $_POST['name'];
$Location = $_POST['location'];

myFunction($Name, $Location);

// make what you want with these variables...?>

How do you follow an HTTP Redirect in Node.js?

Is there a wrapper module on top of the http to more easily handle processing http responses from a node application?

request

Redirection logic in request

How to set default value to all keys of a dict object in python?

You can replace your old dictionary with a defaultdict:

>>> from collections import defaultdict
>>> d = {'foo': 123, 'bar': 456}
>>> d['baz']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'baz'
>>> d = defaultdict(lambda: -1, d)
>>> d['baz']
-1

The "trick" here is that a defaultdict can be initialized with another dict. This means that you preserve the existing values in your normal dict:

>>> d['foo']
123

state provider and route provider in angularJS

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

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

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

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

$(this).serialize() -- How to add a value?

We can do like:

data = $form.serialize() + "&foo=bar";

For example:

var userData = localStorage.getItem("userFormSerializeData");
var userId = localStorage.getItem("userId");

$.ajax({
    type: "POST",
    url: postUrl,
    data: $(form).serialize() + "&" + userData + "&userId=" + userId,
    dataType: 'json',
    success: function (response) {
        //do something
    }
});

Closing Excel Application Process in C# after Data Access

Most of the methods works, but the excel process always stay until close the appliation.

When kill excel process once it can't be executed once again in the same thread - don't know why.

Change File Extension Using C#

Convert file format to png

string newfilename , 
 string filename = "~/Photo/"  + lbl_ImgPath.Text.ToString();/*get filename from specific path where we store image*/
 string newfilename = Path.ChangeExtension(filename, ".png");/*Convert file format from jpg to png*/

How do you reverse a string in place in C or C++?

In the interest of completeness, it should be pointed out that there are representations of strings on various platforms in which the number of bytes per character varies depending on the character. Old-school programmers would refer to this as DBCS (Double Byte Character Set). Modern programmers more commonly encounter this in UTF-8 (as well as UTF-16 and others). There are other such encodings as well.

In any of these variable-width encoding schemes, the simple algorithms posted here (evil, non-evil or otherwise) would not work correctly at all! In fact, they could even cause the string to become illegible or even an illegal string in that encoding scheme. See Juan Pablo Califano's answer for some good examples.

std::reverse() potentially would still work in this case, as long as your platform's implementation of the Standard C++ Library (in particular, string iterators) properly took this into account.

What are Unwind segues for and how do you use them?

Swift iOS:

Step 1: define this method into your MASTER controller view. in which you want to go back:

//pragma mark - Unwind Seques
@IBAction func goToSideMenu(segue: UIStoryboardSegue) {

    println("Called goToSideMenu: unwind action")

}

Step 2: (StoryBoard) Right click on you SLAVE/CHILD EXIT button and Select "goToSideMenu" As action to Connect you Button on which you will click to return back to you MASTER controller view:

enter image description here step 3: Build and Run ...

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

My problem went away after I shutdowned VirtualBox on my machine.

One thing I know is that Linux KVM can't get along with VirtualBox well.

SQL Server - An expression of non-boolean type specified in a context where a condition is expected, near 'RETURN'

An expression of non-boolean type specified in a context where a condition is expected

I also got this error when I forgot to add ON condition when specifying my join clause.

Truststore and Keystore Definitions

  1. First and major difference between trustStore and keyStore is that trustStore is used by TrustManager to determine whether remote connection should be trusted, keyStore is used from KeyManager deciding which authentication credentials should be sent to the remote host for authentication during SSL handshake.

  2. Another difference is that keyStore theoretically contains private keys required only if you are running a Server in SSL connection or you have enabled client authentication on server side and on the other hand trustStore stores public key or certificates from CA (Certificate Authorities) which are used to trust remote party or SSL connection.

    In fact you can store in the same file both private and public keys, given that the the tool to manage those file is the same (keytool), so you could use a single file for both the purposes, but you probably should not.

  3. At least on my Mac OSX the default keyStore is ${user.home}/.keystore, and the default trustStore is /System/Library/Java/Support/CoreDeploy.bundle/Contents/Home/lib/security/cacerts.

    If you want to override them you should add the JVM parameters -Djavax.net.ssl.keyStore /path/to/keyStore or -Djavax.net.ssl.trustStore /path/to/trustStore. You might also need to set the keyStore password in case of java.security.UnrecoverableKeyException: Password must not be null, using the parameter -Djavax.net.ssl.trustStorePassword=password or -Djavax.net.ssl.trustStorePassword=password

Main Source:

http://javarevisited.blogspot.co.uk/2012/09/difference-between-truststore-vs-keyStore-Java-SSL.html

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

Your URL should be jdbc:sqlserver://server:port;DatabaseName=dbname
and Class name should be like com.microsoft.sqlserver.jdbc.SQLServerDriver
Use MicrosoftSQL Server JDBC Driver 2.0

How to get share counts using graph API

There is a ruby gem for it - SocialShares

Currently it supports following social networks:

  • facebook
  • twitter
  • google plus
  • reddit
  • linkedin
  • pinterest
  • stumbleupon
  • vkontakte
  • mail.ru
  • odnoklassniki

Usage:

:000 > url = 'http://www.apple.com/'
  => "http://www.apple.com/"
:000 > SocialShares.facebook url
  => 394927
:000 > SocialShares.google url
  => 28289
:000 > SocialShares.twitter url
  => 1164675
:000 > SocialShares.all url
  => {:vkontakte=>44, :facebook=>399027, :google=>28346, :twitter=>1836, :mail_ru=>37, :odnoklassniki=>1, :reddit=>2361, :linkedin=>nil, :pinterest=>21011, :stumbleupon=>43035}
:000 > SocialShares.selected url, %w(facebook google linkedin)
  => {:facebook=>394927, :google=>28289, :linkedin=>nil}
:000 > SocialShares.total url, %w(facebook google)
  => 423216
:000 > SocialShares.has_any? url, %w(twitter linkedin)
  => true

No connection could be made because the target machine actively refused it 127.0.0.1:3446

I could not restart IIexpress. This is the solution that worked for me

  1. Cleaned the build
  2. Rebuild

Create dataframe from a matrix

You can use stack from the base package. But, you need first to coerce your matrix to a data.frame and to reorder the columns once the data is stacked.

mat <- as.data.frame(mat)
res <- data.frame(time= mat$time,stack(mat,select=-time))
res[,c(3,1,2)]

  ind time values
1 C_0  0.0    0.1
2 C_0  0.5    0.2
3 C_0  1.0    0.3
4 C_1  0.0    0.3
5 C_1  0.5    0.4
6 C_1  1.0    0.5

Note that stack is generally more efficient than the reshape2 package.

How to store a datetime in MySQL with timezone info

All the symptoms you describe suggest that you never tell MySQL what time zone to use so it defaults to system's zone. Think about it: if all it has is '2011-03-13 02:49:10', how can it guess that it's a local Tanzanian date?

As far as I know, MySQL doesn't provide any syntax to specify time zone information in dates. You have to change it a per-connection basis; something like:

SET time_zone = 'EAT';

If this doesn't work (to use named zones you need that the server has been configured to do so and it's often not the case) you can use UTC offsets because Tanzania does not observe daylight saving time at the time of writing but of course it isn't the best option:

SET time_zone = '+03:00';

Key Shortcut for Eclipse Imports

CTRL + 1 can also be used which will suggest to import.

How can I tell AngularJS to "refresh"

The solution was to call...

$scope.$apply();

...in my jQuery event callback.

How to implement OnFragmentInteractionListener

Instead of Activity use context.It works for me.

@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mListener = (OnFragmentInteractionListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
}

Uncaught TypeError: Cannot set property 'onclick' of null

Does document.getElementById("blue") exist? if it doesn't then blue_box will be equal to null. you can't set a onclick on something that's null

String Array object in Java

public static void main(String[] args) {

        public String[] name = {"Art", "Dan", "Jen"};
        public String[] country = {"Canada", "Germant", "USA"};
        // initialize your performance array here too.

        //Your constructor takes arrays as an argument so you need to be sure to pass in the arrays and not just objects.
        Athlete art = new Athlete(name, country, performance);   

}

Fetch: reject promise and catch the error if status is not OK?

Fetch promises only reject with a TypeError when a network error occurs. Since 4xx and 5xx responses aren't network errors, there's nothing to catch. You'll need to throw an error yourself to use Promise#catch.

A fetch Response conveniently supplies an ok , which tells you whether the request succeeded. Something like this should do the trick:

fetch(url).then((response) => {
  if (response.ok) {
    return response.json();
  } else {
    throw new Error('Something went wrong');
  }
})
.then((responseJson) => {
  // Do something with the response
})
.catch((error) => {
  console.log(error)
});

Filter element based on .data() key/value

your filter would work, but you need to return true on matching objects in the function passed to the filter for it to grab them.

var $previous = $('.navlink').filter(function() { 
  return $(this).data("selected") == true 
});

Environment Specific application.properties file in Spring Boot application

My Point , IN this arent way asking developer to create all environment related in single go, resulting in risk of exposing Production Configuration to end developer

as per 12-Factor, shouldnt be enviornment specific reside in Enviornment only .

How do we do for CI CD

  • Build Spring one time and promote to aother environment, in that case, if we have spring jar has all environment, it iwll security risk, having all environment variable in GIT

Python reshape list to ndim array

The answers above are good. Adding a case that I used. Just if you don't want to use numpy and keep it as list without changing the contents.

You can run a small loop and change the dimension from 1xN to Nx1.

    tmp=[]
    for b in bus:
        tmp.append([b])
    bus=tmp

It is maybe not efficient while in case of very large numbers. But it works for a small set of numbers. Thanks

python xlrd unsupported format, or corrupt file.

I met this problem too.I opened this file by excel and saved it as other formats such as excel 97-2003 and finally I solved this problem

Converting String To Float in C#

You can use parsing with double instead of float to get more precision value.

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Download Microsoft Drivers for PHP for SQL Server. Extract the files and use one of:

File                             Thread Safe         VC Bulid
php_sqlsrv_53_nts_vc6.dll           No                  VC6
php_sqlsrv_53_nts_vc9.dll           No                  VC9
php_sqlsrv_53_ts_vc6.dll            Yes                 VC6
php_sqlsrv_53_ts_vc9.dll            Yes                 VC9

You can see the Thread Safety status in phpinfo().

Add the correct file to your ext directory and the following line to your php.ini:

extension=php_sqlsrv_53_*_vc*.dll

Use the filename of the file you used.

As Gordon already posted this is the new Extension from Microsoft and uses the sqlsrv_* API instead of mssql_*

Update:
On Linux you do not have the requisite drivers and neither the SQLSERV Extension.
Look at Connect to MS SQL Server from PHP on Linux? for a discussion on this.

In short you need to install FreeTDS and YES you need to use mssql_* functions on linux. see update 2

To simplify things in the long run I would recommend creating a wrapper class with requisite functions which use the appropriate API (sqlsrv_* or mssql_*) based on which extension is loaded.

Update 2: You do not need to use mssql_* functions on linux. You can connect to an ms sql server using PDO + ODBC + FreeTDS. On windows, the best performing method to connect is via PDO + ODBC + SQL Native Client since the PDO + SQLSRV driver can be incredibly slow.

TextView - setting the text size programmatically doesn't seem to work

the method TextView.setTextSize(int unit , float size); takes two parameters .

Try this :

text.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);

refer this and this.

UPDATE: Now the setTextSize(float size) will set the text size automatically in "scaled pixel" units. no need to mention the COMPLEX_UNIT_SP manually. Refer to the documentation.

How do I ignore all files in a folder with a Git repository in Sourcetree?

Ignore full folder on source tree.

   Just Open Repository >Repository setting > Edit git ignore File and 
   you can rite some thing like this :

 *.pdb 
*.bak 
*.dll
*.lib 
.gitignore
packages/ 
*/bin/
*/obj/ 

For bin folder and obj folder just write : */bin/ */obj/

How to use responsive background image in css3 in bootstrap

You need to use background-size: 100% 100%;

Demo

Demo 2 (Won't stretch, this is what you are doing)

Explanation: You need to use 100% 100% as it sets for X AS WELL AS Y, you are setting 100% just for the X parameter, thus the background doesn't stretch vertically.


Still, the image will stretch out, it won't be responsive, if you want to stretch the background proportionately, you can look for background-size: cover; but IE will create trouble for you here as it's CSS3 property, but yes, you can use CSS3 Pie as a polyfill. Also, using cover will crop your image.

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

You get this message when you've used async in your template, but are referring to an object that isn't an Observable.

So for examples sake, lets' say I had these properties in my class:

job:Job
job$:Observable<Job>

Then in my template, I refer to it this way:

{{job | async }}

instead of:

{{job$ | async }}

You wouldn't need the job:Job property if you use the async pipe, but it serves to illustrate a cause of the error.

How do I convert a Django QuerySet into list of dicts?

You need DjangoJSONEncoder and list to make your Queryset to json, ref: Python JSON serialize a Decimal object

import json
from django.core.serializers.json import DjangoJSONEncoder


blog = Blog.objects.all().values()
json.dumps(list(blog), cls=DjangoJSONEncoder)

Changing the current working directory in Java?

The working directory is a operating system feature (set when the process starts). Why don't you just pass your own System property (-Dsomeprop=/my/path) and use that in your code as the parent of your File:

File f = new File ( System.getProperty("someprop"), myFilename)

Tesseract running error

Add this to your code :

instance.setDatapath("C:\\somepath\\tessdata");

instance.setLanguage("eng");

Measuring function execution time in R

A slightly nicer way of measuring execution time, is to use the rbenchmark package. This package (easily) allows you to specify how many times to replicate your test and would the relative benchmark should be.

See also a related question at stats.stackexchange

What are the rules about using an underscore in a C++ identifier?

The rules (which did not change in C++11):

  • Reserved in any scope, including for use as implementation macros:
    • identifiers beginning with an underscore followed immediately by an uppercase letter
    • identifiers containing adjacent underscores (or "double underscore")
  • Reserved in the global namespace:
    • identifiers beginning with an underscore
  • Also, everything in the std namespace is reserved. (You are allowed to add template specializations, though.)

From the 2003 C++ Standard:

17.4.3.1.2 Global names [lib.global.names]

Certain sets of names and function signatures are always reserved to the implementation:

  • Each name that contains a double underscore (__) or begins with an underscore followed by an uppercase letter (2.11) is reserved to the implementation for any use.
  • Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.165

165) Such names are also reserved in namespace ::std (17.4.3.1).

Because C++ is based on the C standard (1.1/2, C++03) and C99 is a normative reference (1.2/1, C++03) these also apply, from the 1999 C Standard:

7.1.3 Reserved identifiers

Each header declares or defines all identifiers listed in its associated subclause, and optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers.

  • All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
  • All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
  • Each macro name in any of the following subclauses (including the future library directions) is reserved for use as specified if any of its associated headers is included; unless explicitly stated otherwise (see 7.1.4).
  • All identifiers with external linkage in any of the following subclauses (including the future library directions) are always reserved for use as identifiers with external linkage.154
  • Each identifier with file scope listed in any of the following subclauses (including the future library directions) is reserved for use as a macro name and as an identifier with file scope in the same name space if any of its associated headers is included.

No other identifiers are reserved. If the program declares or defines an identifier in a context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved identifier as a macro name, the behavior is undefined.

If the program removes (with #undef) any macro definition of an identifier in the first group listed above, the behavior is undefined.

154) The list of reserved identifiers with external linkage includes errno, math_errhandling, setjmp, and va_end.

Other restrictions might apply. For example, the POSIX standard reserves a lot of identifiers that are likely to show up in normal code:

  • Names beginning with a capital E followed a digit or uppercase letter:
    • may be used for additional error code names.
  • Names that begin with either is or to followed by a lowercase letter
    • may be used for additional character testing and conversion functions.
  • Names that begin with LC_ followed by an uppercase letter
    • may be used for additional macros specifying locale attributes.
  • Names of all existing mathematics functions suffixed with f or l are reserved
    • for corresponding functions that operate on float and long double arguments, respectively.
  • Names that begin with SIG followed by an uppercase letter are reserved
    • for additional signal names.
  • Names that begin with SIG_ followed by an uppercase letter are reserved
    • for additional signal actions.
  • Names beginning with str, mem, or wcs followed by a lowercase letter are reserved
    • for additional string and array functions.
  • Names beginning with PRI or SCN followed by any lowercase letter or X are reserved
    • for additional format specifier macros
  • Names that end with _t are reserved
    • for additional type names.

While using these names for your own purposes right now might not cause a problem, they do raise the possibility of conflict with future versions of that standard.


Personally I just don't start identifiers with underscores. New addition to my rule: Don't use double underscores anywhere, which is easy as I rarely use underscore.

After doing research on this article I no longer end my identifiers with _t as this is reserved by the POSIX standard.

The rule about any identifier ending with _t surprised me a lot. I think that is a POSIX standard (not sure yet) looking for clarification and official chapter and verse. This is from the GNU libtool manual, listing reserved names.

CesarB provided the following link to the POSIX 2004 reserved symbols and notes 'that many other reserved prefixes and suffixes ... can be found there'. The POSIX 2008 reserved symbols are defined here. The restrictions are somewhat more nuanced than those above.

How to specify an element after which to wrap in css flexbox?

There is part of the spec that sure sounds like this... right in the "flex layout algorithm" and "main sizing" sections:

Otherwise, starting from the first uncollected item, collect consecutive items one by one until the first time that the next collected item would not fit into the flex container’s inner main size, or until a forced break is encountered. If the very first uncollected item wouldn’t fit, collect just it into the line. A break is forced wherever the CSS2.1 page-break-before/page-break-after [CSS21] or the CSS3 break-before/break-after [CSS3-BREAK] properties specify a fragmentation break.

From http://www.w3.org/TR/css-flexbox-1/#main-sizing

It sure sounds like (aside from the fact that page-breaks ought to be for printing), when laying out a potentially multi-line flex layout (which I take from another portion of the spec is one without flex-wrap: nowrap) a page-break-after: always or break-after: always should cause a break, or wrap to the next line.

.flex-container {
  display: flex;
  flex-flow: row wrap;
}

.child {
  flex-grow: 1;
}

.child.break-here {
  page-break-after: always;
  break-after: always;
}

However, I have tried this and it hasn't been implemented that way in...

  • Safari (up to 7)
  • Chrome (up to 43 dev)
  • Opera (up to 28 dev & 12.16)
  • IE (up to 11)

It does work the way it sounds (to me, at least) like in:

  • Firefox (28+)

Sample at http://codepen.io/morewry/pen/JoVmVj.

I didn't find any other requests in the bug tracker, so I reported it at https://code.google.com/p/chromium/issues/detail?id=473481.

But the topic took to the mailing list and, regardless of how it sounds, that's not what apparently they meant to imply, except I guess for pagination. So there's no way to wrap before or after a particular box in flex layout without nesting successive flex layouts inside flex children or fiddling with specific widths (e.g. flex-basis: 100%).

This is deeply annoying, of course, since working with the Firefox implementation confirms my suspicion that the functionality is incredibly useful. Aside from the improved vertical alignment, the lack obviates a good deal of the utility of flex layout in numerous scenarios. Having to add additional wrapping tags with nested flex layouts to control the point at which a row wraps increases the complexity of both the HTML and CSS and, sadly, frequently renders order useless. Similarly, forcing the width of an item to 100% reduces the "responsive" potential of the flex layout or requires a lot of highly specific queries or count selectors (e.g. the techniques that may accomplish the general result you need that are mentioned in the other answers).

At least floats had clear. Something may get added at some point or another for this, one hopes.

pass parameter by link_to ruby on rails

Try:

<%= link_to "Add to cart", {:controller => "car", :action => "add_to_cart", :car => car.id }%>

and then in your controller

@car = Car.find(params[:car])

which, will find in your 'cars' table (as with rails pluralization) in your DB a car with id == to car.id

hope it helps! happy coding

more than a year later, but if you see it or anyone does, i could use the points ;D

Automatically deleting related rows in Laravel (Eloquent ORM)

There are 3 approaches to solving this:

1. Using Eloquent Events On Model Boot (ref: https://laravel.com/docs/5.7/eloquent#events)

class User extends Eloquent
{
    public static function boot() {
        parent::boot();

        static::deleting(function($user) {
             $user->photos()->delete();
        });
    }
}

2. Using Eloquent Event Observers (ref: https://laravel.com/docs/5.7/eloquent#observers)

In your AppServiceProvider, register the observer like so:

public function boot()
{
    User::observe(UserObserver::class);
}

Next, add an Observer class like so:

class UserObserver
{
    public function deleting(User $user)
    {
         $user->photos()->delete();
    }
}

3. Using Foreign Key Constraints (ref: https://laravel.com/docs/5.7/migrations#foreign-key-constraints)

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

How to find the cumulative sum of numbers in a list?

lst = [4,6,12]

[sum(lst[:i+1]) for i in xrange(len(lst))]

If you are looking for a more efficient solution (bigger lists?) a generator could be a good call (or just use numpy if you really care about perf).

def gen(lst):
    acu = 0
    for num in lst:
        yield num + acu
        acu += num

print list(gen([4, 6, 12]))

How to pass a value from one Activity to another in Android?

Its simple If you are passing String X from A to B.
A--> B

In Activity A
1) Create Intent
2) Put data in intent using putExtra method of intent
3) Start activity

Intent i = new Intent(A.this, B.class);
i.putExtra("MY_kEY",X);

In Activity B
inside onCreate method
1) Get intent object
2) Get stored value using key(MY_KEY)

Intent intent = getIntent();
String result = intent.getStringExtra("MY_KEY");

This is the standard way to send data from A to B. you can send any data type, it could be int, boolean, ArrayList, String[]. Based on the datatype you stored in Activity as key, value pair retrieving method might differ like if you are passing int value then you will call

intent.getIntExtra("KEY");

You can even send Class objects too but for that, you have to make your class object implement the Serializable or Parceable interface.

TransactionTooLargeException

How much data you can send across size. If data exceeds a certain amount in size then you might get TransactionTooLargeException. Suppose you are trying to send bitmap across the activity and if the size exceeds certain data size then you might see this exception.

How to delete only the content of file in python

What could be easier than something like this:

import tempfile

for i in range(400):
    with tempfile.TemporaryFile() as tf:
        for j in range(1000):
            tf.write('Line {} of file {}'.format(j,i))

That creates 400 temp files and writes 1000 lines to each temp file. It executes in less than 1/2 second on my unremarkable machine. Each temp file of the total is created and deleted as the context manager opens and closes in this case. It is fast, secure, and cross platform.

Using tempfile is a lot better than trying to reinvent it.

How to set up devices for VS Code for a Flutter emulator

VS Code needs to know where Android SDK is installed on your system. On Windows, set "ANDROID_SDK_ROOT" environment variable to the Android SDK root folder.

Plus: Always check the "OUTPUT" and "DEBUG CONSOLE" tabs for errors and information.

Using querySelectorAll to retrieve direct children

I'd have gone with

var myFoo = document.querySelectorAll("#myDiv > .foo");
var myDiv = myFoo.parentNode;

Business logic in MVC

The term business logic is in my opinion not a precise definition. Evans talks in his book, Domain Driven Design, about two types of business logic:

  • Domain logic.
  • Application logic.

This separation is in my opinion a lot clearer. And with the realization that there are different types of business rules also comes the realization that they don't all necessarily go the same place.

Domain logic is logic that corresponds to the actual domain. So if you are creating an accounting application, then domain rules would be rules regarding accounts, postings, taxation, etc. In an agile software planning tool, the rules would be stuff like calculating release dates based on velocity and story points in the backlog, etc.

For both these types of application, CSV import/export could be relevant, but the rules of CSV import/export has nothing to do with the actual domain. This kind of logic is application logic.

Domain logic most certainly goes into the model layer. The model would also correspond to the domain layer in DDD.

Application logic however does not necessarily have to be placed in the model layer. That could be placed in the controllers directly, or you could create a separate application layer hosting those rules. What is most logical in this case would depend on the actual application.

%matplotlib line magic causes SyntaxError in Python script

The syntax '%' in %matplotlib inline is recognized by iPython (where it is set up to handle the magic methods), but not Python itself, which gives a SyntaxError. Here is given one solution.

No submodule mapping found in .gitmodule for a path that's not a submodule

No submodule mapping found in .gitmodules for path 'OtherLibrary/MKStore' when

$ git submodule update --init

I didn't know why the error occur. After spending a minute and found the answer in stackoverflow.

$ git rm --cached OtherLibrary/MKStore

and then update the submodule again. It's working fine.

http://en.saturngod.net/no-submodule-mapping-found-in-gitmodules

HTML Display Current date

I prefer to use

<input type='date' id='hasta' value='<?php echo date('Y-m-d');?>'>

that works well

How to check if all inputs are not empty with jQuery

Like this:

if ($('input[value=""]').length > 0) {
   console.log('some fields are empty!')
}

TypeError: 'NoneType' object is not iterable in Python

Code: for row in data:
Error message: TypeError: 'NoneType' object is not iterable

Which object is it complaining about? Choice of two, row and data. In for row in data, which needs to be iterable? Only data.

What's the problem with data? Its type is NoneType. Only None has type NoneType. So data is None.

You can verify this in an IDE, or by inserting e.g. print "data is", repr(data) before the for statement, and re-running.

Think about what you need to do next: How should "no data" be represented? Do we write an empty file? Do we raise an exception or log a warning or keep silent?

Best way to convert string to bytes in Python 3?

It's easier than it is thought:

my_str = "hello world"
my_str_as_bytes = str.encode(my_str)
type(my_str_as_bytes) # ensure it is byte representation
my_decoded_str = my_str_as_bytes.decode()
type(my_decoded_str) # ensure it is string representation

Error: Failed to lookup view in Express

It is solved by adding the following code in app.js file

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);

app.get('/', function(req, res){
    res.render("index");
});

CSS submit button weird rendering on iPad/iPhone

The above answer for webkit appearance worked, but the button still looked kind pale/dull compared to the browser on other devices/desktop. I also had to set opacity to full (ranges from 0 to 1)

-webkit-appearance:none;
opacity: 1

After setting the opacity, the button looked the same on all the different devices/emulator/desktop.

Is there a REAL performance difference between INT and VARCHAR primary keys?

For short codes, there's probably no difference. This is especially true as the table holding these codes are likely to be very small (a couple thousand rows at most) and not change often (when is the last time we added a new US State).

For larger tables with a wider variation among the key, this can be dangerous. Think about using e-mail address/user name from a User table, for example. What happens when you have a few million users and some of those users have long names or e-mail addresses. Now any time you need to join this table using that key it becomes much more expensive.

What's the "Content-Length" field in HTTP header?

From here:

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

   Content-Length    = "Content-Length" ":" 1*DIGIT

An example is

   Content-Length: 3495

Applications SHOULD use this field to indicate the transfer-length of the message-body, unless this is prohibited by the rules in section 4.4.

Any Content-Length greater than or equal to zero is a valid value. Section 4.4 describes how to determine the length of a message-body if a Content-Length is not given.

Note that the meaning of this field is significantly different from the corresponding definition in MIME, where it is an optional field used within the "message/external-body" content-type. In HTTP, it SHOULD be sent whenever the message's length can be determined prior to being transferred, unless this is prohibited by the rules in section 4.4.

My interpretation is that this means the length "on the wire", i.e. the length of the *encoded" content

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

I usually use float: left; and add overflow: auto; to solve the collapsing parent problem (as to why this works, overflow: auto will expand the parent instead of adding scrollbars if you do not give it explicit height, overflow: hidden works as well). Most of the vertical alignment needs I had are for one-line of text in menu bars, which can be solved using line-height property. If I really need to vertical align a block element, I'd set an explicit height on the parent and the vertically aligned item, position absolute, top 50%, and negative margin.

The reason I don't use display: table-cell is the way it overflows when you have more items than the site's width can handle. table-cell will force the user to scroll horizontally, while floats will wrap the overflow menu, making it still usable without the need for horizontal scrolling.

The best thing about float: left and overflow: auto is that it works all the way back to IE6 without hacks, probably even further.

enter image description here

Accessing localhost (xampp) from another computer over LAN network - how to?

If someone is still finding it hard, this simple thing worked for me:

  1. On you main system let's say Hosting PC... Go to Control Panel > Windows Defender Firewall > Allow an app or feature through Windows Defender Firewall > Change settings > Find "Apache HTTP Server" > Check both the check-boxes (under Private & Public). See Screenshot

    • In my case there were two "Apache HTTP Server" entries, so I checked both the check-boxes for both entries.
  2. On any another system connected over a same network... Open browser > type: your hosting pc's IP adress followed by your project name in the url bar. Example: 192.168.72.111/example.com/

Hope it helps! Thanks.