Programs & Examples On #Er diagrams

An Entity Relationship Diagram (ERD) is a snapshot of data structures. ERDs show entities in a database and relationships between tables within that database. It is essential to have one of these if you want to create a good database design.

Generate ER Diagram from existing MySQL database, created for CakePHP

CakePHP was intended to be used as Ruby on Rails framework clone, done in PHP, so any reverse-engineering of underlying database is pointless. EER diagrams should be reverse-engineered from Model layer.

Such tools do exist for Ruby Here you can see Redmine database EER diagrams reverse-engineered from Models. Not from database. http://redminecookbook.com/Redmine-erd-diagrams.html

With following tools: http://rails-erd.rubyforge.org/ http://railroady.prestonlee.com/

How to fix a collation conflict in a SQL Server query?

Adding to the accepted answer, you can used DATABASE_DEFAULT as encoding.

This allows database to make choice for you and your code becomes more portable.

SELECT MyColumn
FROM 
    FirstTable a
        INNER JOIN SecondTable b
            ON a.MyID COLLATE DATABASE_DEFAULT = b.YourID COLLATE DATABASE_DEFAULT

Cross-browser custom styling for file upload button

The best example is this one, No hiding, No jQuery, It's completely pure CSS

http://css-tricks.com/snippets/css/custom-file-input-styling-webkitblink/

_x000D_
_x000D_
.custom-file-input::-webkit-file-upload-button {_x000D_
    visibility: hidden;_x000D_
}_x000D_
_x000D_
.custom-file-input::before {_x000D_
    content: 'Select some files';_x000D_
    display: inline-block;_x000D_
    background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);_x000D_
    border: 1px solid #999;_x000D_
    border-radius: 3px;_x000D_
    padding: 5px 8px;_x000D_
    outline: none;_x000D_
    white-space: nowrap;_x000D_
    -webkit-user-select: none;_x000D_
    cursor: pointer;_x000D_
    text-shadow: 1px 1px #fff;_x000D_
    font-weight: 700;_x000D_
    font-size: 10pt;_x000D_
}_x000D_
_x000D_
.custom-file-input:hover::before {_x000D_
    border-color: black;_x000D_
}_x000D_
_x000D_
.custom-file-input:active::before {_x000D_
    background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);_x000D_
}
_x000D_
<input type="file" class="custom-file-input">
_x000D_
_x000D_
_x000D_

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

According to scikit-learn documentation,

http://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html#sklearn.metrics.confusion_matrix

By definition a confusion matrix C is such that C[i, j] is equal to the number of observations known to be in group i but predicted to be in group j.

Thus in binary classification, the count of true negatives is C[0,0], false negatives is C[1,0], true positives is C[1,1] and false positives is C[0,1].

CM = confusion_matrix(y_true, y_pred)

TN = CM[0][0]
FN = CM[1][0]
TP = CM[1][1]
FP = CM[0][1]

Android canvas draw rectangle

Try paint.setStyle(Paint.Style.STROKE)?

How to convert vector to array

We can do this using data() method. C++11 provides this method.

Code Snippet

#include<bits/stdc++.h>
using namespace std;


int main()
{
  ios::sync_with_stdio(false);

  vector<int>v = {7, 8, 9, 10, 11};
  int *arr = v.data();

  for(int i=0; i<v.size(); i++)
  {
    cout<<arr[i]<<" ";
  }

  return 0;
}

Remove lines that contain certain string

I have used this to remove unwanted words from text files:

bad_words = ['abc', 'def', 'ghi', 'jkl']

with open('List of words.txt') as badfile, open('Clean list of words.txt', 'w') as cleanfile:
    for line in badfile:
        clean = True
        for word in bad_words:
            if word in line:
                clean = False
        if clean == True:
            cleanfile.write(line)

Or to do the same for all files in a directory:

import os

bad_words = ['abc', 'def', 'ghi', 'jkl']

for root, dirs, files in os.walk(".", topdown = True):
    for file in files:
        if '.txt' in file:
            with open(file) as filename, open('clean '+file, 'w') as cleanfile:
                for line in filename:
                    clean = True
                    for word in bad_words:
                        if word in line:
                            clean = False
                    if clean == True:
                        cleanfile.write(line)

I'm sure there must be a more elegant way to do it, but this did what I wanted it to.

Eliminating duplicate values based on only one column of the table

This is where the window function row_number() comes in handy:

SELECT s.siteName, s.siteIP, h.date
FROM sites s INNER JOIN
     (select h.*, row_number() over (partition by siteName order by date desc) as seqnum
      from history h
     ) h
    ON s.siteName = h.siteName and seqnum = 1
ORDER BY s.siteName, h.date

How to add fonts to create-react-app based projects?

There are two options:

Using Imports

This is the suggested option. It ensures your fonts go through the build pipeline, get hashes during compilation so that browser caching works correctly, and that you get compilation errors if the files are missing.

As described in “Adding Images, Fonts, and Files”, you need to have a CSS file imported from JS. For example, by default src/index.js imports src/index.css:

import './index.css';

A CSS file like this goes through the build pipeline, and can reference fonts and images. For example, if you put a font in src/fonts/MyFont.woff, your index.css might include this:

@font-face {
  font-family: 'MyFont';
  src: local('MyFont'), url(./fonts/MyFont.woff) format('woff');
}

Notice how we’re using a relative path starting with ./. This is a special notation that helps the build pipeline (powered by Webpack) discover this file.

Normally this should be enough.

Using public Folder

If for some reason you prefer not to use the build pipeline, and instead do it the “classic way”, you can use the public folder and put your fonts there.

The downside of this approach is that the files don’t get hashes when you compile for production so you’ll have to update their names every time you change them, or browsers will cache the old versions.

If you want to do it this way, put the fonts somewhere into the public folder, for example, into public/fonts/MyFont.woff. If you follow this approach, you should put CSS files into public folder as well and not import them from JS because mixing these approaches is going to be very confusing. So, if you still want to do it, you’d have a file like public/index.css. You would have to manually add <link> to this stylesheet from public/index.html:

<link rel="stylesheet" href="%PUBLIC_URL%/index.css">

And inside of it, you would use the regular CSS notation:

@font-face {
  font-family: 'MyFont';
  src: local('MyFont'), url(fonts/MyFont.woff) format('woff');
}

Notice how I’m using fonts/MyFont.woff as the path. This is because index.css is in the public folder so it will be served from the public path (usually it’s the server root, but if you deploy to GitHub Pages and set your homepage field to http://myuser.github.io/myproject, it will be served from /myproject). However fonts are also in the public folder, so they will be served from fonts relatively (either http://mywebsite.com/fonts or http://myuser.github.io/myproject/fonts). Therefore we use the relative path.

Note that since we’re avoiding the build pipeline in this example, it doesn’t verify that the file actually exists. This is why I don’t recommend this approach. Another problem is that our index.css file doesn’t get minified and doesn’t get a hash. So it’s going to be slower for the end users, and you risk the browsers caching old versions of the file.

 Which Way to Use?

Go with the first method (“Using Imports”). I only described the second one since that’s what you attempted to do (judging by your comment), but it has many problems and should only be the last resort when you’re working around some issue.

Create a date time with month and day only, no year

Anyway you need 'Year'.

In some engineering fields, you have fixed day and month and year can be variable. But that day and month are important for beginning calculation without considering which year you are. Your user, for example, only should select a day and a month and providing year is up to you.

You can create a custom combobox using this: Customizable ComboBox Drop-Down.

1- In VS create a user control.

2- See the code in the link above for impelemnting that control.

3- Create another user control and place in it 31 button or label and above them place a label to show months.

4- Place the control in step 3 in your custom combobox.

5- Place the control in setp 4 in step 1.

You now have a control with only days and months. You can use any year that you have in your database or ....

Can we have multiple "WITH AS" in single sql - Oracle SQL

You can do this as:

WITH abc AS( select
             FROM ...)
, XYZ AS(select
         From abc ....) /*This one uses "abc" multiple times*/
  Select 
  From XYZ....   /*using abc, XYZ multiple times*/

load csv into 2D matrix with numpy for plotting

You can read a CSV file with headers into a NumPy structured array with np.genfromtxt. For example:

import numpy as np

csv_fname = 'file.csv'
with open(csv_fname, 'w') as fp:
    fp.write("""\
"A","B","C","D","E","F","timestamp"
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12
""")

# Read the CSV file into a Numpy record array
r = np.genfromtxt(csv_fname, delimiter=',', names=True, case_sensitive=True)
print(repr(r))

which looks like this:

array([(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111196e+12),
       (611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111311e+12),
       (611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29112065e+12)],
      dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ('D', '<f8'), ('E', '<f8'), ('F', '<f8'), ('timestamp', '<f8')])

You can access a named column like this r['E']:

array([1715.37476, 1715.37476, 1715.37476])

Note: this answer previously used np.recfromcsv to read the data into a NumPy record array. While there was nothing wrong with that method, structured arrays are generally better than record arrays for speed and compatibility.

How can I make all images of different height and width the same via CSS?

For those using Bootstrap and not wanting to lose the responsivness just do not set the width of the container. The following code is based on gillytech post.

index.hmtl

<div id="image_preview" class="row">  
    <div class='crop col-xs-12 col-sm-6 col-md-6 '>
         <img class="col-xs-12 col-sm-6 col-md-6" 
          id="preview0" src='img/preview_default.jpg'/>
    </div>
    <div class="col-xs-12 col-sm-6 col-md-6">
         more stuff
    </div>

</div> <!-- end image preview -->

style.css

/*images with the same width*/
.crop {
    height: 300px;
    /*width: 400px;*/
    overflow: hidden;
}
.crop img {
    height: auto;
    width: 100%;
}

OR style.css

/*images with the same height*/
.crop {
    height: 300px;
    /*width: 400px;*/
    overflow: hidden;
}
.crop img {
    height: 100%;
    width: auto;
}

How to get row data by clicking a button in a row in an ASP.NET gridview

<ItemTemplate>
     <asp:Button ID="Button1" runat="server" Text="Button" 
            OnClick="MyButtonClick" />
</ItemTemplate>

and your method

 protected void MyButtonClick(object sender, System.EventArgs e)
{
     //Get the button that raised the event
Button btn = (Button)sender;

    //Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}

How can I find where Python is installed on Windows?

if you still stuck or you get this

C:\\\Users\\\name of your\\\AppData\\\Local\\\Programs\\\Python\\\Python36

simply do this replace 2 \ with one

C:\Users\akshay\AppData\Local\Programs\Python\Python36

How to export datagridview to excel using vb.net?

another easy way and more flexible , after loading data into Datagrid

Private Sub Button_Export_Click(sender As Object, e As EventArgs) Handles Button_Export.Click
    Dim file As System.IO.StreamWriter
    file = My.Computer.FileSystem.OpenTextFileWriter("c:\1\Myfile.csv", True)
    If DataGridView1.Rows.Count = 0 Then GoTo loopend

    ' collect the header's names 
    Dim Headerline As String
    For k = 0 To DataGridView1.Columns.Count - 1
        If k = DataGridView1.Columns.Count - 1 Then ' last column dont put , separate 
            Headerline = Headerline & DataGridView1.Columns(k).HeaderText
        Else
            Headerline = Headerline & DataGridView1.Columns(k).HeaderText & ","
        End If
    Next
    file.WriteLine(Headerline)  ' this will write header names at the first line 
    ' collect the data 

    For i = 0 To DataGridView1.Rows.Count - 1
        Dim DataRow As String
        For k = 0 To DataGridView1.Columns.Count - 1
            If k = DataGridView1.Columns.Count - 1 Then
                DataRow = DataRow & DataGridView1.Rows(i).Cells(k).Value ' last column dont put , separate 
            End If
            DataRow = DataRow & DataGridView1.Rows(i).Cells(k).Value & ","
        Next

        file.WriteLine(DataRow)
        DataRow = ""
    Next



loopend:
        file.Close()
End Sub

Drop data frame columns by name

I keep thinking there must be a better idiom, but for subtraction of columns by name, I tend to do the following:

df <- data.frame(a=1:10, b=1:10, c=1:10, d=1:10)

# return everything except a and c
df <- df[,-match(c("a","c"),names(df))]
df

Launch a shell command with in a python script, wait for the termination and return to the script

this worked for me fine!

shell_command = "ls -l" subprocess.call(shell_command.split())

Sending private messages to user

In order for a bot to send a message, you need <client>.send() , the client is where the bot will send a message to(A channel, everywhere in the server, or a PM). Since you want the bot to PM a certain user, you can use message.author as your client. (you can replace author as mentioned user in a message or something, etc)

Hence, the answer is: message.author.send("Your message here.")

I recommend looking up the Discord.js documentation about a certain object's properties whenever you get stuck, you might find a particular function that may serve as your solution.

How to return multiple values in one column (T-SQL)?

group_concat() sounds like what you're looking for.

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

since you're on mssql, i just googled "group_concat mssql" and found a bunch of hits to recreate group_concat functionality. here's one of the hits i found:

http://www.stevenmapes.com/index.php?/archives/23-Recreating-MySQL-GROUP_CONCAT-In-MSSQL-Cross-Tab-Query.html

How to add a downloaded .box file to Vagrant?

Solution for Windows:

  • Open the cmd or powershell as admin
  • CD into the folder containing the .box file
  • vagrant box add --name name_of_my_box 'name_of_my_box.box'
  • vagrant box list should show the new box in the list

Solution for MAC:

  • Open terminal
  • CD into the folder containing the .box file
  • vagrant box add --name name_of_my_box "./name_of_my_box.box"
  • vagrant box list should show the new box in the list

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

There is a new spec called the Native File System API that allows you to do this properly like this:

const result = await window.chooseFileSystemEntries({ type: "save-file" });

There is a demo here, but I believe it is using an origin trial so it may not work in your own website unless you sign up or enable a config flag, and it obviously only works in Chrome. If you're making an Electron app this might be an option though.

C#, Looping through dataset and show each record from a dataset column

I believe you intended it more this way:

foreach (DataTable table in ds.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
        DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
        TaskStart.ToString("dd-MMMM-yyyy");
        rpt.SetParameterValue("TaskStartDate", TaskStart);
    }
}

You always accessed your first row in your dataset.

Combine hover and click functions (jQuery)?

Use basic programming composition: create a method and pass the same function to click and hover as a callback.

var hoverOrClick = function () {
    // do something common
}
$('#target').click(hoverOrClick).hover(hoverOrClick);

Second way: use bindon:

$('#target').on('click mouseover', function () {
    // Do something for both
});

jQuery('#target').bind('click mouseover', function () {
    // Do something for both
});

Difference between `Optional.orElse()` and `Optional.orElseGet()`

I reached here for the problem Kudo mentioned.

I'm sharing my experience for others.

orElse, or orElseGet, that is the question:

static String B() {
    System.out.println("B()...");
    return "B";
}

public static void main(final String... args) {
    System.out.println(Optional.of("A").orElse(B()));
    System.out.println(Optional.of("A").orElseGet(() -> B()));
}

prints

B()...
A
A

orElse evaluates the value of B() interdependently of the value of the optional. Thus, orElseGet is lazy.

How to blur background images in Android

you can use Glide for load and transform into blur image, 1) for only one view,

val requestOptions = RequestOptions()
                requestOptions.transform(BlurTransformation(50)) // 0-100
Glide.with(applicationContext).setDefaultRequestOptions(requestOptions)
                        .load(imageUrl).into(view)

2) if you are using the adapter to load an image in the item, you should write your code in the if-else block, otherwise, it will make all your images blurry.

 if(isBlure){
  val requestOptions = RequestOptions()
                requestOptions.transform(BlurTransformation(50))
                Glide.with(applicationContext).setDefaultRequestOptions(requestOptions)
                        .load(imageUrl).into(view )
}else{
 val requestOptions = RequestOptions()
            Glide.with(applicationContext).setDefaultRequestOptions(requestOptions).load(imageUrl).into(view)
}

Eclipse: Set maximum line length for auto formatting?

Take a look of following image:

Java->Code style->Formatter-> Edit

enter image description here

Is there a way to make npm install (the command) to work behind proxy?

Try to find .npmrc in C:\Users\.npmrc

then open (notepad), write, and save inside :

proxy=http://<username>:<pass>@<proxyhost>:<port>

PS : remove "<" and ">" please !!

Getting msbuild.exe without installing Visual Studio

It used to be installed with the .NET framework. MsBuild v12.0 (2013) is now bundled as a stand-alone utility and has it's own installer.

http://www.microsoft.com/en-us/download/confirmation.aspx?id=40760

To reference the location of MsBuild.exe from within an MsBuild script, use the default $(MsBuildToolsPath) property.

How to check command line parameter in ".bat" file?

You are comparing strings. If an arguments are omitted, %1 expands to a blank so the commands become IF =="-b" GOTO SPECIFIC for example (which is a syntax error). Wrap your strings in quotes (or square brackets).

REM this is ok
IF [%1]==[/?] GOTO BLANK

REM I'd recommend using quotes exclusively
IF "%1"=="-b" GOTO SPECIFIC

IF NOT "%1"=="-b" GOTO UNKNOWN

Finding first and last index of some value in a list in Python

s.index(x[, i[, j]])

index of the first occurrence of x in s (at or after index i and before index j)

How to insert element as a first child?

Required here

<div class="outer">Outer Text <div class="inner"> Inner Text</div> </div>

added by

$(document).ready(function(){ $('.inner').prepend('<div class="middle">New Text Middle</div>'); });

How to enable file sharing for my app?

If you find by alphabet in plist, it should be "Application supports iTunes file sharing".

PHP Function with Optional Parameters

What I have done in this case is pass an array, where the key is the parameter name, and the value is the value.

$optional = array(
  "param" => $param1,
  "param2" => $param2
);

function func($required, $requiredTwo, $optional) {
  if(isset($optional["param2"])) {
    doWork();
  }
}

Is there a keyboard shortcut (hotkey) to open Terminal in macOS?

I tested the following procedure under macOS Mojave 10.14.6 (18G3020).

Launch Automator. Create a document of type “Quick Action”:

quick action template

(In older versions of macOS, use the “Service” template.)

In the new Automator document, add a “Run AppleScript” action. (You can type “run applescript” into the search field at the top of the action list to find it.) Here's the AppleScript to paste into the action:

on run {input, parameters}
    tell application "Terminal"
        if it is running then
            do script ""
        end if
        activate
    end tell
end run

Set the “Workflow receives” popup to “no input”. It should look like this overall:

workflow with applescript

Save the document with the name “New Terminal”. Then go to the Automator menu (or the app menu in any running application) and open the Services submenu. You should now see the “New Terminal” quick action:

New Terminal service menu item

If you click the “New Terminal” menu item, you'll get a dialog box:

permission dialog

Click OK to allow the action to run. You'll see this dialog once in each application that's frontmost when you use the action. In other words, the first time you use the action while Finder is frontmost, you'll see the dialog. And the first time you use the action while Safari is frontmost, you'll see the dialog. And so on.

After you click OK in the dialog, Terminal should open a new window.

To assign a keyboard shortcut to the quick action, choose the “Services Preferences…” item from the Services menu. (Or launch System Preferences, choose the Keyboard pane, then choose the Shortcuts tab, then choose Services from the left-hand list.) Scroll to the bottom of the right-hand list and find the New Terminal service. Click it and you should see an “Add Shortcut” button:

add shortcut button

Click the button and press your preferred keyboard shortcut. Then, scratch your head, because (when I tried it) the Add Shortcut button reappears. But click the button again and you should see your shortcut:

keyboard shortcut set

Now you should be able to press your keyboard shortcut in most circumstances to get a new terminal window.

Powershell 2 copy-item which creates a folder if doesn't exist

In PowerShell 3 and above I use the Copy-Item with New-Item.

copy-item -Path $file -Destination (new-item -type directory -force ("C:\Folder\sub\sub\" + $newSub)) -force -ea 0

I haven't tried it in ver 2.

PHP CURL DELETE request

I finally solved this myself. If anyone else is having this problem, here is my solution:

I created a new method:

public function curl_del($path)
{
    $url = $this->__url.$path;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $result;
}

Update 2

Since this seems to help some people, here is my final curl DELETE method, which returns the HTTP response in JSON decoded object:

  /**
 * @desc    Do a DELETE request with cURL
 *
 * @param   string $path   path that goes after the URL fx. "/user/login"
 * @param   array  $json   If you need to send some json with your request.
 *                         For me delete requests are always blank
 * @return  Obj    $result HTTP response from REST interface in JSON decoded.
 */
public function curl_del($path, $json = '')
{
    $url = $this->__url.$path;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    $result = json_decode($result);
    curl_close($ch);

    return $result;
}

How do I suspend painting for a control and its children?

Or just use Control.SuspendLayout() and Control.ResumeLayout().

Warning about `$HTTP_RAW_POST_DATA` being deprecated

I just got the solution to this problem from a friend. he said: Add ob_start(); under your session code. You can add exit(); under the header. I tried it and it worked. Hope this helps

This is for those on a rented Hosting sever who do not have access to php.init file.

How to prevent Browser cache on Angular 2 site?

angular-cli resolves this by providing an --output-hashing flag for the build command (versions 6/7, for later versions see here). Example usage:

ng build --output-hashing=all

Bundling & Tree-Shaking provides some details and context. Running ng help build, documents the flag:

--output-hashing=none|all|media|bundles (String)

Define the output filename cache-busting hashing mode.
aliases: -oh <value>, --outputHashing <value>

Although this is only applicable to users of angular-cli, it works brilliantly and doesn't require any code changes or additional tooling.

Update

A number of comments have helpfully and correctly pointed out that this answer adds a hash to the .js files but does nothing for index.html. It is therefore entirely possible that index.html remains cached after ng build cache busts the .js files.

At this point I'll defer to How do we control web page caching, across all browsers?

Turning off auto indent when pasting text into vim

The following vim plugin handles that automatically through its "Bracketed Paste" mode: https://github.com/wincent/terminus

Sets up "Bracketed Paste" mode, which means you can forget about manually setting the 'paste' option and simply go ahead and paste in any mode.

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

Get screenshot on Windows with Python?

Another approach that is really fast is the MSS module. It is different from other solutions in the way that it uses only the ctypes standard module, so it does not require big dependencies. It is OS independant and its use is made easy:

from mss import mss

with mss() as sct:
    sct.shot()

And just find the screenshot.png file containing the screen shot of the first monitor. There are a lot of possibile customizations, you can play with ScreenShot objects and OpenCV/Numpy/PIL/etc..

Why is String immutable in Java?

I read this post Why String is Immutable or Final in Java and suppose that following may be the most important reason:

String is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all another client.

Android device does not show up in adb list

adb was not detecting connected nexus 5 device. Switched on the phone, enabled developer options, Enabled USB debugging mode, Now visible with adb. Also, USB configuration is still MTP. Hope this helps.

display data from SQL database into php/ html table

Look in the manual http://www.php.net/manual/en/mysqli.query.php

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
    printf("Table myCity successfully created.\n");
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
    printf("Select returned %d rows.\n", $result->num_rows);

    /* free result set */
    $result->close();
}

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {

    /* Note, that we can't execute any functions which interact with the
       server until result set was closed. All calls will return an
       'out of sync' error */
    if (!$mysqli->query("SET @a:='this will not work'")) {
        printf("Error: %s\n", $mysqli->error);
    }
    $result->close();
}

$mysqli->close();
?>

How do I get the backtrace for all the threads in GDB?

Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.

thread apply all bt

Hidden TextArea

Set CSS display to none for textarea

<textarea name="hide" style="display:none;"></textarea>

What does "Object reference not set to an instance of an object" mean?

In a nutshell it means.. You are trying to access an object without instantiating it.. You might need to use the "new" keyword to instantiate it first i.e create an instance of it.

For eg:

public class MyClass
{
   public int Id {get; set;}
}

MyClass myClass;

myClass.Id = 0; <----------- An error will be thrown here.. because myClass is null here...

You will have to use:

myClass = new MyClass();
myClass.Id = 0;

Hope I made it clear..

How to let an ASMX file output JSON

Alternative: Use a generic HTTP handler (.ashx) and use your favorite json library to manually serialize and deserialize your JSON.

I've found that complete control over the handling of a request and generating a response beats anything else .NET offers for simple, RESTful web services.

Android intent for playing video?

Use setDataAndType on the Intent

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(newVideoPath), "video/mp4");
startActivity(intent);

Use "video/mp4" as MIME or use "video/*" if you don't know the type.

How to ignore conflicts in rpm installs

From the context, the conflict was caused by the version of the package.
Let's take a look the manual about rpm:

--force
    Same as using --replacepkgs, --replacefiles, and --oldpackage.

--oldpackage
    Allow an upgrade to replace a newer package with an older one.

So, you can execute the command rpm -Uvh info-4.13a-2.rpm --force to solve your issue.

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

Ensure that all dependencies of your own dll are present near the dll, or in System32.

Creating a "Hello World" WebSocket example

Issue

Since you are using WebSocket, spender is correct. After recieving the initial data from the WebSocket, you need to send the handshake message from the C# server before any further information can flow.

HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: websocket
Connection: Upgrade
WebSocket-Origin: example
WebSocket-Location: something.here
WebSocket-Protocol: 13

Something along those lines.

You can do some more research into how WebSocket works on w3 or google.

Links and Resources

Here is a protocol specifcation: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76#section-1.3

List of working examples:

CSS @media print issues with background-color;

Found this issue, because I had a similar problem when trying to generate a PDF from a html output in Google Apps Script where background-colors are also not "printed".

The -webkit-print-color-adjust:exact; and !important solutions of course did not work, but the box-shadow: inset 0 0 0 1000px gold; did... great hack, thank you very much :)

Debugging with Android Studio stuck at "Waiting For Debugger" forever

Android studio 3.0 and Above

Disable the instant Run

enter image description here

Declare multiple module.exports in Node.js

You can do something like:

module.exports = {
    method: function() {},
    otherMethod: function() {},
};

Or just:

exports.method = function() {};
exports.otherMethod = function() {};

Then in the calling script:

const myModule = require('./myModule.js');
const method = myModule.method;
const otherMethod = myModule.otherMethod;
// OR:
const {method, otherMethod} = require('./myModule.js');

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

For future readers, this should help:

public void show() {
    if(mContext instanceof Activity) {
        Activity activity = (Activity) mContext;
        if (!activity.isFinishing() && !activity.isDestroyed()) {
            dialog.show();
        }
    }
}

How to convert ISO8859-15 to UTF8?

Could it be that your file is not ISO-8859-15 encoded? You should be able to check with the file command:

file YourFile.txt

Also, you can use iconv without providing the encoding of the original file:

iconv -t UTF-8 YourFile.txt

No restricted globals

/* eslint no-restricted-globals:0 */

is another alternate approach

How do I get the HTTP status code with jQuery?

I encapsulate the jQuery Ajax to a method:

var http_util = function (type, url, params, success_handler, error_handler, base_url) {

    if(base_url) {
        url = base_url + url;
    }

    var success = arguments[3]?arguments[3]:function(){};
    var error = arguments[4]?arguments[4]:function(){};



    $.ajax({
        type: type,
        url: url,
        dataType: 'json',
        data: params,
        success: function (data, textStatus, xhr) {

            if(textStatus === 'success'){
                success(xhr.code, data);   // there returns the status code
            }
        },
        error: function (xhr, error_text, statusText) {

            error(xhr.code, xhr);  // there returns the status code
        }
    })

}

Usage:

http_util('get', 'http://localhost:8000/user/list/', null, function (status_code, data) {
    console(status_code, data)
}, function(status_code, err){
    console(status_code, err)
})

Serializing PHP object to JSON

In the simplest cases type hinting should work:

$json = json_encode( (array)$object );

What is the difference between a .cpp file and a .h file?

A good rule of thumb is ".h files should have declarations [potentially] used by multiple source files, but no code that gets run."

MySQL Select Date Equal to Today

This query will use index if you have it for signup_date field

SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d') 
    FROM users 
    WHERE signup_date >= CURDATE() && signup_date < (CURDATE() + INTERVAL 1 DAY)

UIImage resize (Scale proportion)

That's ok not a big problem . thing is u got to find the proportional width and height

like if size is 2048.0 x 1360.0 which has to be resized to 320 x 480 resolution then the resulting image size should be 722.0 x 480.0

here is the formulae to do that . if w,h is original and x,y are resulting image.
w/h=x/y 
=> 
x=(w/h)*y;  

submitting w=2048,h=1360,y=480 => x=722.0 ( here width>height. if height>width then consider x to be 320 and calculate y)

U can submit in this web page . ARC

Confused ? alright , here is category for UIImage which will do the thing for you.

@interface UIImage (UIImageFunctions)
    - (UIImage *) scaleToSize: (CGSize)size;
    - (UIImage *) scaleProportionalToSize: (CGSize)size;
@end
@implementation UIImage (UIImageFunctions)

- (UIImage *) scaleToSize: (CGSize)size
{
    // Scalling selected image to targeted size
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, size.width, size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
    CGContextClearRect(context, CGRectMake(0, 0, size.width, size.height));

    if(self.imageOrientation == UIImageOrientationRight)
    {
        CGContextRotateCTM(context, -M_PI_2);
        CGContextTranslateCTM(context, -size.height, 0.0f);
        CGContextDrawImage(context, CGRectMake(0, 0, size.height, size.width), self.CGImage);
    }
    else
        CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), self.CGImage);

    CGImageRef scaledImage=CGBitmapContextCreateImage(context);

    CGColorSpaceRelease(colorSpace);
    CGContextRelease(context);

    UIImage *image = [UIImage imageWithCGImage: scaledImage];

    CGImageRelease(scaledImage);

    return image;
}

- (UIImage *) scaleProportionalToSize: (CGSize)size1
{
    if(self.size.width>self.size.height)
    {
        NSLog(@"LandScape");
        size1=CGSizeMake((self.size.width/self.size.height)*size1.height,size1.height);
    }
    else
    {
        NSLog(@"Potrait");
        size1=CGSizeMake(size1.width,(self.size.height/self.size.width)*size1.width);
    }

    return [self scaleToSize:size1];
}

@end

-- the following is appropriate call to do this if img is the UIImage instance.

img=[img scaleProportionalToSize:CGSizeMake(320, 480)];

Clear variable in python

  • If want to totally delete it use del:

    del your_variable
    
  • Or otherwise, to make the value None:

    your_variable = None
    
  • If it's a mutable iterable (lists, sets, dictionaries, etc, but not tuples because they're immutable), you can make it empty like:

    your_variable.clear()
    

Then your_variable will be empty

Import Package Error - Cannot Convert between Unicode and Non Unicode String Data Type

At some point, you're trying to convert an nvarchar column to a varchar column (or vice-versa).

Moreover, why is everything (supposedly) nvarchar(max)? That's a code smell if I ever saw one. Are you aware of how SQL Server stores those columns? They use pointers to where the column is stored from the actual rows, since they don't fit within the 8k pages.

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

Yes, that is a good question. I don't understand it fully yet, but:

I understand that ENTRYPOINT is the binary that is being executed. You can overide entrypoint by --entrypoint="".

docker run -t -i --entrypoint="/bin/bash" ubuntu

CMD is the default argument to container. Without entrypoint, default argument is command that is executed. With entrypoint, cmd is passed to entrypoint as argument. You can emulate a command with entrypoint.

# no entrypoint
docker run ubuntu /bin/cat /etc/passwd

# with entry point, emulating cat command
docker run --entrypoint="/bin/cat" ubuntu /etc/passwd

So, main advantage is that with entrypoint you can pass arguments (cmd) to your container. To accomplish this, you need to use both:

# Dockerfile
FROM ubuntu
ENTRYPOINT ["/bin/cat"]

and

docker build -t=cat .

then you can use:

docker run cat /etc/passwd
#              ^^^^^^^^^^^
#                   CMD
#          ^^^      
#          image (tag)- using the default ENTRYPOINT

How to create a HTML Table from a PHP array?

It would be better to just fetch the data into array like this:

<?php
$shop = array( array("title"=>"rose", "price"=>1.25 , "number"=>15),
               array("title"=>"daisy", "price"=>0.75 , "number"=>25),
               array("title"=>"orchid", "price"=>1.15 , "number"=>7) 
             ); 
?>

And then do something like this, which should work well even when you add more columns to your table in the database later.

<?php if (count($shop) > 0): ?>
<table>
  <thead>
    <tr>
      <th><?php echo implode('</th><th>', array_keys(current($shop))); ?></th>
    </tr>
  </thead>
  <tbody>
<?php foreach ($shop as $row): array_map('htmlentities', $row); ?>
    <tr>
      <td><?php echo implode('</td><td>', $row); ?></td>
    </tr>
<?php endforeach; ?>
  </tbody>
</table>
<?php endif; ?>

How do I add a .click() event to an image?

You can't bind an event to the element before it exists, so you should do it in the onload event:

<html>
<head>
<script type="text/javascript">

window.onload = function() {

  document.getElementById('foo').addEventListener('click', function (e) {
    var img = document.createElement('img');
    img.setAttribute('src', 'http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png');
    e.target.appendChild(img);
  });

};

</script>
</head>
<body>
<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
</body>
</html>

How to apply CSS to iframe?

use can try this:

$('iframe').load( function() {
     $('iframe').contents().find("head")
     .append($("<style type='text/css'>  .my-class{display:none;}  </style>"));
  });

PHP Multiple Checkbox Array

You need to use the square brackets notation to have values sent as an array:

<form method='post' id='userform' action='thisform.php'>
<tr>
    <td>Trouble Type</td>
    <td>
    <input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Three'>3
    </td>
</tr>
</table>
<input type='submit' class='buttons'>
</form>

Please note though, that only the values of only checked checkboxes will be sent.

Why are unnamed namespaces used and what are their benefits?

Unnamed namespaces are a utility to make an identifier translation unit local. They behave as if you would choose a unique name per translation unit for a namespace:

namespace unique { /* empty */ }
using namespace unique;
namespace unique { /* namespace body. stuff in here */ }

The extra step using the empty body is important, so you can already refer within the namespace body to identifiers like ::name that are defined in that namespace, since the using directive already took place.

This means you can have free functions called (for example) help that can exist in multiple translation units, and they won't clash at link time. The effect is almost identical to using the static keyword used in C which you can put in in the declaration of identifiers. Unnamed namespaces are a superior alternative, being able to even make a type translation unit local.

namespace { int a1; }
static int a2;

Both a's are translation unit local and won't clash at link time. But the difference is that the a1 in the anonymous namespace gets a unique name.

Read the excellent article at comeau-computing Why is an unnamed namespace used instead of static? (Archive.org mirror).

Load local HTML file in a C# WebBrowser

  1. Place it in the Applications setup folder or in a separte folder beneath
  2. Reference it relative to the current directory when your app runs.

Style bottom Line in Android

I think you do not need to use shape if I understood you.

If you are looking as shown in following image then use following layout.

enter image description here

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:background="#1bd4f6"
    android:paddingBottom="4dp" >

    <TextView
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:background="#ababb2"
        android:padding="5dp"
        android:text="Hello Android" />
 </RelativeLayout>

 </RelativeLayout>

EDIT

play with these properties you will get result

    android:top="dimension"
    android:right="dimension"
    android:bottom="dimension"
    android:left="dimension"

try like this

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item>
    <shape android:shape="rectangle" >
        <solid android:color="#1bd4f6" />
    </shape>
</item>

<item android:top="20px"
    android:left="0px">
    <shape android:shape="line"  >
        <padding android:bottom="1dp" />

        <stroke
            android:dashGap="10px"
            android:dashWidth="10px"
            android:width="1dp"
            android:color="#ababb2" />
    </shape>
</item>

</layer-list>

Unix command to find lines common in two files

To easily apply the comm command to unsorted files, use Bash's process substitution:

$ bash --version
GNU bash, version 3.2.51(1)-release
Copyright (C) 2007 Free Software Foundation, Inc.
$ cat > abc
123
567
132
$ cat > def
132
777
321

So the files abc and def have one line in common, the one with "132". Using comm on unsorted files:

$ comm abc def
123
    132
567
132
    777
    321
$ comm -12 abc def # No output! The common line is not found
$

The last line produced no output, the common line was not discovered.

Now use comm on sorted files, sorting the files with process substitution:

$ comm <( sort abc ) <( sort def )
123
            132
    321
567
    777
$ comm -12 <( sort abc ) <( sort def )
132

Now we got the 132 line!

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

When I tried to include the JSTL Core Library in my JSP:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

I got the following error in Eclipse (Indigo):

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I went to the Project Properties -> Targeted Runtimes, and then checked the Server I was using (Geronimo 3.0). Most people would be using Tomcat. This solved my problem. Hope it helps!

E: Unable to locate package mongodb-org

I had the same issue in 14.04, but I fixed it by these steps:

  1. sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
  2. echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb- org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list
  3. sudo apt-get update
  4. sudo apt-get install -y mongodb

It worked like charm :)

Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies

I had this same problem - some users could pull from git and everything ran fine. Some would pull and get a very similar exception:

Could not load file or assembly '..., Version=..., Culture=neutral, PublicKeyToken=...' or one of its dependencies. The system cannot find the file specified.

In my particular case it was AjaxMin, so the actual error looked like this but the details don't matter:

Could not load file or assembly 'AjaxMin, Version=4.95.4924.12383, Culture=neutral, PublicKeyToken=21ef50ce11b5d80f' or one of its dependencies. The system cannot find the file specified.

It turned out to be a result of the following actions on a Solution:

  1. NuGet Package Restore was turned on for the Solution.

  2. A Project was added, and a Nuget package was installed into it (AjaxMin in this case).

  3. The Project was moved to different folder in the Solution.

  4. The Nuget package was updated to a newer version.

And slowly but surely this bug started showing up for some users.

The reason was the Solution-level packages/respositories.config kept the old Project reference, and now had a new, second entry for the moved Project. In other words it had this before the reorg:

  <repository path="..\Old\packages.config" />

And this after the reorg:

  <repository path="..\Old\packages.config" />
  <repository path="..\New\packages.config" />

So the first line now refers to a Project that, while on disk, is no longer part of my Solution.

With Nuget Package Restore on, both packages.config files were being read, which each pointed to their own list of Nuget packages and package versions. Until a Nuget package was updated to a newer version however, there weren't any conflicts.

Once a Nuget package was updated, however, only active Projects had their repositories listings updated. NuGet Package Restore chose to download just one version of the library - the first one it encountered in repositories.config, which was the older one. The compiler and IDE proceeded as though it chose the newer one. The result was a run-time exception saying the DLL was missing.

The answer obviously is to delete any lines from this file that referenced Projects that aren't in your Solution.

How to select a schema in postgres when using psql?

if playing with psql inside docker exec it like this:

docker exec -e "PGOPTIONS=--search_path=<your_schema>" -it docker_pg psql -U user db_name

Can't find @Nullable inside javax.annotation.*

The artifact has been moved from net.sourceforge.findbugs to

<dependency>
    <groupId>com.google.code.findbugs</groupId>
    <artifactId>jsr305</artifactId>
    <version>3.0.0</version>
</dependency>

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

A word of caution, all you hard-charging programmers: applying "use strict" to existing code can be hazardous! This thing is not some feel-good, happy-face sticker that you can slap on the code to make it 'better'. With the "use strict" pragma, the browser will suddenly THROW exceptions in random places that it never threw before just because at that spot you are doing something that default/loose JavaScript happily allows but strict JavaScript abhors! You may have strictness violations hiding in seldom used calls in your code that will only throw an exception when they do eventually get run - say, in the production environment that your paying customers use!

If you are going to take the plunge, it is a good idea to apply "use strict" alongside comprehensive unit tests and a strictly configured JSHint build task that will give you some confidence that there is no dark corner of your module that will blow up horribly just because you've turned on Strict Mode. Or, hey, here's another option: just don't add "use strict" to any of your legacy code, it's probably safer that way, honestly. DEFINITELY DO NOT add "use strict" to any modules you do not own or maintain, like third party modules.

I think even though it is a deadly caged animal, "use strict" can be good stuff, but you have to do it right. The best time to go strict is when your project is greenfield and you are starting from scratch. Configure JSHint/JSLint with all the warnings and options cranked up as tight as your team can stomach, get a good build/test/assert system du jour rigged like Grunt+Karma+Chai, and only THEN start marking all your new modules as "use strict". Be prepared to cure lots of niggly errors and warnings. Make sure everyone understands the gravity by configuring the build to FAIL if JSHint/JSLint produces any violations.

My project was not a greenfield project when I adopted "use strict". As a result, my IDE is full of red marks because I don't have "use strict" on half my modules, and JSHint complains about that. It's a reminder to me about what refactoring I should do in the future. My goal is to be red mark free due to all of my missing "use strict" statements, but that is years away now.

What does the 'u' symbol mean in front of string values?

This is a feature, not a bug.

See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

Changing my listening port from 3000 to (process.env.PORT || 5000) solved the problem.

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:

# sending manually set cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));

# sending cookies from file
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);

In this case curl will send your defined cookie along with the cookies from the file.

If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).

The utma utmc, utmz are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.

Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. /var/dir/cookie.txt) instead of relative one.

Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.

curl_setopt($ch, CURLOPT_VERBOSE, true);

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

Starting from support library version 24.0.0 you can call FragmentTransaction.commitNow() method which commits this transaction synchronously instead of calling commit() followed by executePendingTransactions()

Android Emulator: Installation error: INSTALL_FAILED_VERSION_DOWNGRADE

First uninstall your application from the emulator:

adb -e uninstall your.application.package.name

Then try to install the application again.

What is the difference between float and double?

If one works with embedded processing, eventually the underlying hardware (e.g. FPGA or some specific processor / microcontroller model) will have float implemented optimally in hardware whereas double will use software routines. So if the precision of a float is enough to handle the needs, the program will execute some times faster with float then double. As noted on other answers, beware of accumulation errors.

Can we execute a java program without a main() method?

Yes You can compile and execute without main method By using static block. But after static block executed (printed) you will get an error saying no main method found.

And Latest INFO --> YOU cant Do this with JAVA 7 version. IT will not execute.

{
    static
    {
        System.out.println("Hello World!");
        System.exit(0); // prevents “main method not found” error
    }
}

But this will not execute with JAVA 7 version.

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

First, all collections in .NET implement IEnumerable.

Second, a lot of the collections are duplicates because generics were added in version 2.0 of the framework.

So, although the generic collections likely add features, for the most part:

  • List is a generic implementation of ArrayList.
  • Dictionary is a generic implementation of Hashtable

Arrays are a fixed size collection that you can change the value stored at a given index.

SortedDictionary is an IDictionary that is sorted based on the keys. SortedList is an IDictionary that is sorted based on a required IComparer.

So, the IDictionary implementations (those supporting KeyValuePairs) are: * Hashtable * Dictionary * SortedList * SortedDictionary

Another collection that was added in .NET 3.5 is the Hashset. It is a collection that supports set operations.

Also, the LinkedList is a standard linked-list implementation (the List is an array-list for faster retrieval).

How do I enable/disable log levels in Android?

https://limxtop.blogspot.com/2019/05/app-log.html

Read this article please, where provides complete implement:

  1. For debug version, all the logs will be output;
  2. For release version, only the logs whose level is above DEBUG (exclude) will be output by default. In the meanwhile, the DEBUG and VERBOSE log can be enable through setprop log.tag.<YOUR_LOG_TAG> <LEVEL> in running time.

Float and double datatype in Java

Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. For example, calculations such as square root, or transcendentals such as sine and cosine, result in a value whose precision requires a floating-point type. Java implements the standard (IEEE–754) set of floatingpoint types and operators. There are two kinds of floating-point types, float and double, which represent single- and double-precision numbers, respectively. Their width and ranges are shown here:


   Name     Width in Bits   Range 
    double  64              1 .7e–308 to 1.7e+308
    float   32              3 .4e–038 to 3.4e+038


float

The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some processors and takes half as much space as double precision, but will become imprecise when the values are either very large or very small. Variables of type float are useful when you need a fractional component, but don't require a large degree of precision.

Here are some example float variable declarations:

float hightemp, lowtemp;


double

Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values. When you need to maintain accuracy over many iterative calculations, or are manipulating large-valued numbers, double is the best choice.

Checking whether a variable is an integer or not

A more general approach that will attempt to check for both integers and integers given as strings will be

def isInt(anyNumberOrString):
    try:
        int(anyNumberOrString) #to check float and int use "float(anyNumberOrString)"
        return True
    except ValueError :
        return False

isInt("A") #False
isInt("5") #True
isInt(8) #True
isInt("5.88") #False *see comment above on how to make this True

Reverse colormap in matplotlib

In matplotlib a color map isn't a list, but it contains the list of its colors as colormap.colors. And the module matplotlib.colors provides a function ListedColormap() to generate a color map from a list. So you can reverse any color map by doing

colormap_r = ListedColormap(colormap.colors[::-1])

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

Add this is work for me

<repositories>
    <!-- Repository for ORACLE JDBC Driver -->
    <repository>
        <id>codelds</id>
        <url>https://code.lds.org/nexus/content/groups/main-repo</url>
    </repository>
</repositories>

How does origin/HEAD get set?

Remember there are two independent git repos we are talking about. Your local repo with your code and the remote running somewhere else.

Your are right, when you change a branch, HEAD points to your current branch. All of this is happening on your local git repo. Not the remote repo, which could be owned by another developer, or siting on a sever in your office, or github, or another directory on the filesystem, or etc...

Your computer (local repo) has no business changing the HEAD pointer on the remote git repo. It could be owned by a different developer for example.

One more thing, what your computer calls origin/XXX is your computer's understanding of the state of the remote at the time of the last fetch.

So what would "organically" update origin/HEAD? It would be activity on the remote git repo. Not your local repo.

People have mentioned

git symbolic-ref HEAD refs/head/my_other_branch

Normally, that is used when there is a shared central git repo on a server for use by the development team. It would be a command executed on the remote computer. You would see this as activity on the remote git repo.

How to run a Command Prompt command with Visual Basic code?

Or, you could do it the really simple way.

Dim OpenCMD 
OpenCMD = CreateObject("wscript.shell")
OpenCMD.run("Command Goes Here")

Create zip file and ignore directory structure

Just use the -jrm option to remove the file and directory structures

zip -jrm /path/to/file.zip /path/to/file

Script not served by static file handler on IIS7.5

For other people reading this:

This can happen is if the .Net version that you have registered isn't the one selected under the 'Basic Settings' of the application pool attached to your website. For instance, your sites application pool has .Net v2.0 selected but you registered v4.0

PHP check if file is an image

The getimagesize() should be the most definite way of working out whether the file is an image:

if(@is_array(getimagesize($mediapath))){
    $image = true;
} else {
    $image = false;
}

because this is a sample getimagesize() output:

Array (
[0] => 800
[1] => 450
[2] => 2
[3] => width="800" height="450"
[bits] => 8
[channels] => 3
[mime] => image/jpeg)

Why is my CSS style not being applied?

There could be an error earlier in the CSS file that is causing your (correct) CSS to not work.

Creating a script for a Telnet session?

Couple of questions:

  1. Can you put stuff on the device that you're telnetting into?
  2. Are the commands executed by the script the same or do they vary by machine/user?
  3. Do you want the person clicking the icon to have to provide a userid and/or password?

That said, I wrote some Java a while ago to talk to a couple of IP-enabled power strips (BayTech RPC3s) which might be of use to you. If you're interested I'll see if I can dig it up and post it someplace.

COPYing a file in a Dockerfile, no such file or directory?

For following error,

COPY failed: stat /<**path**> :no such file or directory

I got it around by restarting docker service.

sudo service docker restart

Check if a div exists with jquery

The first is the most concise, I would go with that. The first two are the same, but the first is just that little bit shorter, so you'll save on bytes. The third is plain wrong, because that condition will always evaluate true because the object will never be null or falsy for that matter.

Android runOnUiThread explanation

If you already have the data "for (Parcelable currentHeadline : allHeadlines)," then why are you doing that in a separate thread?

You should poll the data in a separate thread, and when it's finished gathering it, then call your populateTables method on the UI thread:

private void populateTable() {
    runOnUiThread(new Runnable(){
        public void run() {
            //If there are stories, add them to the table
            for (Parcelable currentHeadline : allHeadlines) {
                addHeadlineToTable(currentHeadline);
            }
            try {
                dialog.dismiss();
            } catch (final Exception ex) {
                Log.i("---","Exception in thread");
            }
        }
    });
}

Count the number of all words in a string

require(stringr)

Define a very simple function

str_words <- function(sentence) {

  str_count(sentence, " ") + 1

}

Check

str_words(This is a sentence with six words)

JavaScript - document.getElementByID with onClick

In JavaScript functions are objects.

document.getElementById('foo').onclick = function(){
    prompt('Hello world');
}

Run local python script on remote server

I've had to do this before using Paramiko in a case where I wanted to run a dynamic, local PyQt4 script on a host running an ssh server that has connected my OpenVPN server and ask for their routing preference (split tunneling).

So long as the ssh server you are connecting to has all of the required dependencies of your script (PyQt4 in my case), you can easily encapsulate the data by encoding it in base64 and use the exec() built-in function on the decoded message. If I remember correctly my one-liner for this was:

stdout = client.exec_command('python -c "exec(\\"' + open('hello.py','r').read().encode('base64').strip('\n') + '\\".decode(\\"base64\\"))"' )[1]

It is hard to read and you have to escape the escape sequences because they are interpreted twice (once by the sender and then again by the receiver). It also may need some debugging, I've packed up my server to PCS or I'd just reference my OpenVPN routing script.

The difference in doing it this way as opposed to sending a file is that it never touches the disk on the server and is run straight from memory (unless of course they log the command). You'll find that encapsulating information this way (although inefficient) can help you package data into a single file.

For instance, you can use this method to include raw data from external dependencies (i.e. an image) in your main script.

Sharing url link does not show thumbnail image on facebook

Your meta tag should look like this:

<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>

And it has to be placed on the page you want to share (this is unclear in your question).

If you have shared the page before the image (or the meta tag) was present, then it is possible, that facebook has the page in its "memory" without an image. In this case simply enter the URL of your page in the debug tool http://developers.facebook.com/tools/debug. After that, the image should be present when the page is shared the next time.

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

The behavior you're trying to produce is not really best done using AJAX. AJAX would be best used if you wanted to only update a portion of the page, not completely redirect to some other page. That defeats the whole purpose of AJAX really.

I would suggest to just not use AJAX with the behavior you're describing.

Alternatively, you could try using jquery Ajax, which would submit the request and then you specify a callback when the request completes. In the callback you could determine if it failed or succeeded, and redirect to another page on success. I've found jquery Ajax to be much easier to use, especially since I'm already using the library for other things anyway.

You can find documentation about jquery ajax here, but the syntax is as follows:

jQuery.ajax( options )  

jQuery.get( url, data, callback, type)

jQuery.getJSON( url, data, callback )

jQuery.getScript( url, callback )

jQuery.post( url, data, callback, type)

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support

Another possibility, is the machine has an older version of xlrd installed separately, and it's not in the "..:\Python27\Scripts.." folder.

In another word, there are 2 different versions of xlrd in the machine.

enter image description here

when you check the version below, it reads the one not in the "..:\Python27\Scripts.." folder, no matter how updated you done with pip.

print xlrd.__version__

Delete the whole redundant sub-folder, and it works. (in addition to xlrd, I had another library encountered the same)

How to append new data onto a new line

All answers seem to work fine. If you need to do this many times, be aware that writing

hs.write(name + "\n")

constructs a new string in memory and appends that to the file.

More efficient would be

hs.write(name)
hs.write("\n")

which does not create a new string, just appends to the file.

Adding a library/JAR to an Eclipse Android project

If you are using the ADT version 22, you need to check the android dependencies and android private libraries in the order&Export tab in the project build path

What integer hash function are good that accepts an integer hash key?

Fast and good hash functions can be composed from fast permutations with lesser qualities, like

  • multiplication with an uneven integer
  • binary rotations
  • xorshift

To yield a hashing function with superior qualities, like demonstrated with PCG for random number generation.

This is in fact also the recipe rrxmrrxmsx_0 and murmur hash are using, knowingly or unknowingly.

I personally found

uint64_t xorshift(const uint64_t& n,int i){
  return n^(n>>i);
}
uint64_t hash(const uint64_t& n){
  uint64_t p = 0x5555555555555555ull; // pattern of alternating 0 and 1
  uint64_t c = 17316035218449499591ull;// random uneven integer constant; 
  return c*xorshift(p*xorshift(n,32),32);
}

to be good enough.

A good hash function should

  1. be bijective to not loose information, if possible and have the least collisions
  2. cascade as much and as evenly as possible, i.e. each input bit should flip every output bit with probability 0.5.

Let's first look at the identity function. It satisfies 1. but not 2. :

identity function

Input bit n determines output bit n with a correlation of 100% (red) and no others, they are therefore blue, giving a perfect red line across.

A xorshift(n,32) is not much better, yielding one and half a line. Still satisfying 1., because it is invertible with a second application.

xorshift

A multiplication with an unsigned integer ("Knuth's multiplicative method") is much better, cascading more strongly and flipping more output bits with a probability of 0.5, which is what you want, in green. It satisfies 1. as for each uneven integer there is a multiplicative inverse.

knuth

Combining the two gives the following output, still satisfying 1. as the composition of two bijective functions yields another bijective function.

knuth•xorshift

A second application of multiplication and xorshift will yield the following:

proposed hash

Or you can use Galois field multiplications like GHash, they have become reasonably fast on modern CPUs and have superior qualities in one step.

   uint64_t const inline gfmul(const uint64_t& i,const uint64_t& j){           
     __m128i I{};I[0]^=i;                                                          
     __m128i J{};J[0]^=j;                                                          
     __m128i M{};M[0]^=0xb000000000000000ull;                                      
     __m128i X = _mm_clmulepi64_si128(I,J,0);                                      
     __m128i A = _mm_clmulepi64_si128(X,M,0);                                      
     __m128i B = _mm_clmulepi64_si128(A,M,0);                                      
     return A[0]^A[1]^B[1]^X[0]^X[1];                                              
   }

"And" and "Or" troubles within an IF statement

I like assylias' answer, however I would refactor it as follows:

Sub test()

Dim origNum As String
Dim creditOrDebit As String

origNum = "30062600006"
creditOrDebit = "D"

If creditOrDebit = "D" Then
  If origNum = "006260006" Then
    MsgBox "OK"
  ElseIf origNum = "30062600006" Then
    MsgBox "OK"
  End If
End If

End Sub

This might save you some CPU cycles since if creditOrDebit is <> "D" there is no point in checking the value of origNum.

Update:

I used the following procedure to test my theory that my procedure is faster:

Public Declare Function timeGetTime Lib "winmm.dll" () As Long

Sub DoTests2()

  Dim startTime1 As Long
  Dim endTime1 As Long
  Dim startTime2 As Long
  Dim endTime2 As Long
  Dim i As Long
  Dim msg As String

  Const numberOfLoops As Long = 10000
  Const origNum As String = "006260006"
  Const creditOrDebit As String = "D"

  startTime1 = timeGetTime
  For i = 1 To numberOfLoops
    If creditOrDebit = "D" Then
      If origNum = "006260006" Then
        ' do something here
        Debug.Print "OK"
      ElseIf origNum = "30062600006" Then
        ' do something here
        Debug.Print "OK"
      End If
    End If
  Next i
  endTime1 = timeGetTime

  startTime2 = timeGetTime
  For i = 1 To numberOfLoops
    If (origNum = "006260006" Or origNum = "30062600006") And _
      creditOrDebit = "D" Then
      ' do something here
      Debug.Print "OK"
    End If
  Next i
  endTime2 = timeGetTime

  msg = "number of iterations: " & numberOfLoops & vbNewLine
  msg = msg & "JP proc: " & Format$((endTime1 - startTime1), "#,###") & _
       " ms" & vbNewLine
  msg = msg & "assylias proc: " & Format$((endTime2 - startTime2), "#,###") & _
       " ms"

  MsgBox msg

End Sub

I must have a slow computer because 1,000,000 iterations took nowhere near ~200 ms as with assylias' test. I had to limit the iterations to 10,000 -- hey, I have other things to do :)

After running the above procedure 10 times, my procedure is faster only 20% of the time. However, when it is slower it is only superficially slower. As assylias pointed out, however, when creditOrDebit is <>"D", my procedure is at least twice as fast. I was able to reasonably test it at 100 million iterations.

And that is why I refactored it - to short-circuit the logic so that origNum doesn't need to be evaluated when creditOrDebit <> "D".

At this point, the rest depends on the OP's spreadsheet. If creditOrDebit is likely to equal D, then use assylias' procedure, because it will usually run faster. But if creditOrDebit has a wide range of possible values, and D is not any more likely to be the target value, my procedure will leverage that to prevent needlessly evaluating the other variable.

How to call Base Class's __init__ method from the child class?

As Mingyu pointed out, there is a problem in formatting. Other than that, I would strongly recommend not using the Derived class's name while calling super() since it makes your code inflexible (code maintenance and inheritance issues). In Python 3, Use super().__init__ instead. Here is the code after incorporating these changes :

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):

    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super().__init__(model, color, mpg)

Thanks to Erwin Mayer for pointing out the issue in using __class__ with super()

How to window.scrollTo() with a smooth effect

2018 Update

Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
btn.addEventListener('click', () => window.scrollTo({_x000D_
  top: 400,_x000D_
  behavior: 'smooth',_x000D_
}));
_x000D_
#x {_x000D_
  height: 1000px;_x000D_
  background: lightblue;_x000D_
}
_x000D_
<div id='x'>_x000D_
  <button id='elem'>Click to scroll</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Older solutions

You can do something like this:

_x000D_
_x000D_
var btn = document.getElementById('x');_x000D_
_x000D_
btn.addEventListener("click", function() {_x000D_
  var i = 10;_x000D_
  var int = setInterval(function() {_x000D_
    window.scrollTo(0, i);_x000D_
    i += 10;_x000D_
    if (i >= 200) clearInterval(int);_x000D_
  }, 20);_x000D_
})
_x000D_
body {_x000D_
  background: #3a2613;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='x'>click</button>
_x000D_
_x000D_
_x000D_

ES6 recursive approach:

_x000D_
_x000D_
const btn = document.getElementById('elem');_x000D_
_x000D_
const smoothScroll = (h) => {_x000D_
  let i = h || 0;_x000D_
  if (i < 200) {_x000D_
    setTimeout(() => {_x000D_
      window.scrollTo(0, i);_x000D_
      smoothScroll(i + 10);_x000D_
    }, 10);_x000D_
  }_x000D_
}_x000D_
_x000D_
btn.addEventListener('click', () => smoothScroll());
_x000D_
body {_x000D_
  background: #9a6432;_x000D_
  height: 600px;_x000D_
}
_x000D_
<button id='elem'>click</button>
_x000D_
_x000D_
_x000D_

Can you put two conditions in an xslt test attribute?

Maybe this is a no-brainer for the xslt-professional, but for me at beginner/intermediate level, this got me puzzled. I wanted to do exactly the same thing, but I had to test a responsetime value from an xml instead of a plain number. Following this thread, I tried this:

<xsl:when test="responsetime/@value &gt;= 5000 and responsetime/@value &lt;= 8999"> 

which generated an error. This works:

<xsl:when test="number(responsetime/@value) &gt;= 5000 and number(responsetime/@value) &lt;= 8999">

Don't really understand why it doesn't work without number(), though. Could it be that without number() the value is treated as a string and you can't compare numbers with a string?

Anyway, hope this saves someone a lot of searching...

Best way in asp.net to force https for an entire site?

For @Joe above, "This is giving me a redirect loop. Before I added the code it worked fine. Any suggestions? – Joe Nov 8 '11 at 4:13"

This was happening to me as well and what I believe was happening is that there was a load balancer terminating the SSL request in front of the Web server. So, my Web site was always thinking the request was "http", even if the original browser requested it to be "https".

I admit this is a bit hacky, but what worked for me was to implement a "JustRedirected" property that I could leverage to figure out the person was already redirected once. So, I test for specific conditions that warrant the redirect and, if they are met, I set this property (value stored in session) prior to the redirection. Even if the http/https conditions for redirection are met the second time, I bypass the redirection logic and reset the "JustRedirected" session value to false. You'll need your own conditional test logic, but here's a simple implementation of the property:

    public bool JustRedirected
    {
        get
        {
            if (Session[RosadaConst.JUSTREDIRECTED] == null)
                return false;

            return (bool)Session[RosadaConst.JUSTREDIRECTED];
        }
        set
        {
            Session[RosadaConst.JUSTREDIRECTED] = value;
        }
    }

Hide/Show Action Bar Option Menu Item for different fragments

Try this...

You don't need to override onCreateOptionsMenu() in your Fragment class again. Menu items visibility can be changed by overriding onPrepareOptionsMenu() method available in Fragment class.

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
    menu.findItem(R.id.action_search).setVisible(false);
    super.onPrepareOptionsMenu(menu);
}

Floating Div Over An Image

Change your positioning a bit:

.container {
    border: 1px solid #DDDDDD;
    width: 200px;
    height: 200px;
    position:relative;
}
.tag {
    float: left;
    position: absolute;
    left: 0px;
    top: 0px;
    background-color: green;
}

jsFiddle example

You need to set relative positioning on the container and then absolute on the inner tag div. The inner tag's absolute positioning will be with respect to the outer relatively positioned div. You don't even need the z-index rule on the tag div.

Format date with Moment.js

May be this helps some one who are looking for multiple date formats one after the other by willingly or unexpectedly. Please find the code: I am using moment.js format function on a current date as (today is 29-06-2020) var startDate = moment(new Date()).format('MM/DD/YY'); Result: 06/28/20

what happening is it retains only the year part :20 as "06/28/20", after If I run the statement : new Date(startDate) The result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)",

Then, when I use another format on "06/28/20": startDate = moment(startDate ).format('MM-DD-YYYY'); Result: 06-28-1920, in google chrome and firefox browsers it gives correct date on second attempt as: 06-28-2020. But in IE it is having issues, from this I understood we can apply one dateformat on the given date, If we want second date format, it should be apply on the fresh date not on the first date format result. And also observe that for first time applying 'MM-DD-YYYY' and next 'MM-DD-YY' is working in IE. For clear understanding please find my question in the link: Date went wrong when using Momentjs date format in IE 11

How do you properly use WideCharToMultiByte

Here's a couple of functions (based on Brian Bondy's example) that use WideCharToMultiByte and MultiByteToWideChar to convert between std::wstring and std::string using utf8 to not lose any data.

// Convert a wide Unicode string to an UTF8 string
std::string utf8_encode(const std::wstring &wstr)
{
    if( wstr.empty() ) return std::string();
    int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
    std::string strTo( size_needed, 0 );
    WideCharToMultiByte                  (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
    return strTo;
}

// Convert an UTF8 string to a wide Unicode String
std::wstring utf8_decode(const std::string &str)
{
    if( str.empty() ) return std::wstring();
    int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
    std::wstring wstrTo( size_needed, 0 );
    MultiByteToWideChar                  (CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
    return wstrTo;
}

Get the index of a certain value in an array in PHP

Here is a function that will work for numeric or string indices. Pass the array as first parameter, then the index to the element that needs to be moved and finally set the direction to -1 to move the element up and to 1 to move it down. Example: Move(['first'=>'Peter','second'=>'Paul','third'=>'Kate'],'second',-1) will move Paul up and Peter down.

function Move($a,$element,$direction)
{

$temp = [];
$index = 0;

foreach($a as $key=>$value)
{
    $temp[$index++] = $key;
}

$index = array_search($element,$temp);

$newpos = $index+$direction;

if(isset($temp[$newpos]))
{
        $value2 = $temp[$newpos];
        $temp[$newpos]=$element;
        $temp[$index]=$value2;
}
else
{
    # move is not possible
    return $a; # returns the array unchanged
}   

$final = [];

foreach($temp as $next)
{
    $final[$next]=$a[$next];
}

return $final;

}

Difference between Python's Generators and Iterators

Adding an answer because none of the existing answers specifically address the confusion in the official literature.

Generator functions are ordinary functions defined using yield instead of return. When called, a generator function returns a generator object, which is a kind of iterator - it has a next() method. When you call next(), the next value yielded by the generator function is returned.

Either the function or the object may be called the "generator" depending on which Python source document you read. The Python glossary says generator functions, while the Python wiki implies generator objects. The Python tutorial remarkably manages to imply both usages in the space of three sentences:

Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield statement whenever they want to return data. Each time next() is called on it, the generator resumes where it left off (it remembers all the data values and which statement was last executed).

The first two sentences identify generators with generator functions, while the third sentence identifies them with generator objects.

Despite all this confusion, one can seek out the Python language reference for the clear and final word:

The yield expression is only used when defining a generator function, and can only be used in the body of a function definition. Using a yield expression in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.

When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of a generator function.

So, in formal and precise usage, "generator" unqualified means generator object, not generator function.

The above references are for Python 2 but Python 3 language reference says the same thing. However, the Python 3 glossary states that

generator ... Usually refers to a generator function, but may refer to a generator iterator in some contexts. In cases where the intended meaning isn’t clear, using the full terms avoids ambiguity.

Notice: Undefined offset: 0 in

If you leave out the brackets then PHP will assign the keys by default.

Try this:

$votes = $row['votes_up']; 
$votes = $row['votes_down']; 

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

Steps I have followed to fix the issue as follows,

Analyze -> Code Cleanup

File -> Project Structures -> Select project from the list and update the gradle version to latest.

Build -> Clean Project

Build -> Make Project

Now the issue related to the build may get reported like using compile instead of implementation etc.

Please fix those and hopefully it should fix the issue.

A Space between Inline-Block List Items

Even if its not inline-block based, this solution might worth consideration (allows nearly same formatting control from upper levels).

ul {
  display: table;
}
ul li {
  display: table-cell;
}

Creating an R dataframe row-by-row

Dirk Eddelbuettel's answer is the best; here I just note that you can get away with not pre-specifying the dataframe dimensions or data types, which is sometimes useful if you have multiple data types and lots of columns:

row1<-list("a",1,FALSE) #use 'list', not 'c' or 'cbind'!
row2<-list("b",2,TRUE)  

df<-data.frame(row1,stringsAsFactors = F) #first row
df<-rbind(df,row2) #now this works as you'd expect.

Convert number to month name in PHP

If you just want an array of month names from the beginning of the year to the end e.g. to populate a drop-down select, I would just use the following;

for ($i = 0; $i < 12; ++$i) {
  $months[$m] = $m = date("F", strtotime("January +$i months"));
}

How to set a:link height/width with css?

Thanks to RandomUs 1r for this observation:

changing it to display:inline-block; solves that issue. – RandomUs1r May 14 '13 at 21:59

I tried it myself for a top navigation menu bar, as follows:

First style the "li" element as follows:

display: inline-block;
width: 7em;
text-align: center;

Then style the "a"> element as follows:

width: 100%;

Now the navigation links are all equal width with text centered in each link.

Check if a Bash array contains a value

I came up with this one, which turns out to work only in zsh, but I think the general approach is nice.

arr=( "hello world" "find me" "what?" )
if [[ "${arr[@]/#%find me/}" != "${arr[@]}" ]]; then
    echo "found!"
else
    echo "not found!"
fi

You take out your pattern from each element only if it starts ${arr[@]/#pattern/} or ends ${arr[@]/%pattern/} with it. These two substitutions work in bash, but both at the same time ${arr[@]/#%pattern/} only works in zsh.

If the modified array is equal to the original, then it doesn't contain the element.

Edit:

This one works in bash:

 function contains () {
        local arr=(${@:2})
        local el=$1
        local marr=(${arr[@]/#$el/})
        [[ "${#arr[@]}" != "${#marr[@]}" ]]
    }

After the substitution it compares the length of both arrays. Obly if the array contains the element the substitution will completely delete it, and the count will differ.

How do I detect if a user is already logged in Firebase?

There's no need to use onAuthStateChanged() function in this scenario.

You can easily detect if the user is logged or not by executing:

var user = firebase.auth().currentUser;

For those who face the "returning null" issue, it's just because you are not waiting for the firebase call to complete.

Let's suppose you perform the login action on Page A and then you invoke Page B, on Page B you can call the following JS code to test the expected behavior:

  var config = {
    apiKey: "....",
    authDomain: "...",
    databaseURL: "...",
    projectId: "..",
    storageBucket: "..",
    messagingSenderId: ".."
  };
  firebase.initializeApp(config);

    $( document ).ready(function() {
        console.log( "testing.." );
        var user = firebase.auth().currentUser;
        console.log(user);
    });

If the user is logged then "var user" will contain the expected JSON payload, if not, then it will be just "null"

And that's all you need.

Regards

Map and Reduce in .NET

The classes of problem that are well suited for a mapreduce style solution are problems of aggregation. Of extracting data from a dataset. In C#, one could take advantage of LINQ to program in this style.

From the following article: http://codecube.net/2009/02/mapreduce-in-c-using-linq/

the GroupBy method is acting as the map, while the Select method does the job of reducing the intermediate results into the final list of results.

var wordOccurrences = words
                .GroupBy(w => w)
                .Select(intermediate => new
                {
                    Word = intermediate.Key,
                    Frequency = intermediate.Sum(w => 1)
                })
                .Where(w => w.Frequency > 10)
                .OrderBy(w => w.Frequency);

For the distributed portion, you could check out DryadLINQ: http://research.microsoft.com/en-us/projects/dryadlinq/default.aspx

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

You can also use forEach:

_x000D_
_x000D_
var maximum = Number.MIN_SAFE_INTEGER;_x000D_
_x000D_
var array = [-3, -2, 217, 9, -8, 46];_x000D_
array.forEach(function(value){_x000D_
  if(value > maximum) {_x000D_
    maximum = value;_x000D_
  }_x000D_
});_x000D_
_x000D_
console.log(maximum); // 217
_x000D_
_x000D_
_x000D_

Change color and appearance of drop down arrow

You can acheive this with CSS but you are not techinically changing the arrow itself.

In this example I am actually hiding the default arrow and displaying my own arrow instead.

_x000D_
_x000D_
.styleSelect select {_x000D_
  background: transparent;_x000D_
  width: 168px;_x000D_
  padding: 5px;_x000D_
  font-size: 16px;_x000D_
  line-height: 1;_x000D_
  border: 0;_x000D_
  border-radius: 0;_x000D_
  height: 34px;_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  appearance: none;_x000D_
  color: #000;_x000D_
}_x000D_
_x000D_
.styleSelect {_x000D_
  width: 140px;_x000D_
  height: 34px;_x000D_
  overflow: hidden;_x000D_
  background: url("images/downArrow.png") no-repeat right #fff;_x000D_
  border: 2px solid #000;_x000D_
}
_x000D_
<div class="styleSelect">_x000D_
  <select class="units">_x000D_
    <option value="Metres">Metres</option>_x000D_
    <option value="Feet">Feet</option>_x000D_
    <option value="Fathoms">Fathoms</option>_x000D_
  </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Angular 2 router no base href set

I had faced similar issue with Angular4 and Jasmine unit tests; below given solution worked for me

Add below import statement

import { APP_BASE_HREF } from '@angular/common';

Add below statement for TestBed configuration:

TestBed.configureTestingModule({
    providers: [
        { provide: APP_BASE_HREF, useValue : '/' }
    ]
})

How to get the first and last date of the current year?

For start date of current year:

SELECT DATEADD(DD,-DATEPART(DY,GETDATE())+1,GETDATE())

For end date of current year:

SELECT DATEADD(DD,-1,DATEADD(YY,DATEDIFF(YY,0,GETDATE())+1,0))

How to install Openpyxl with pip

  1. Go to https://pypi.org/project/openpyxl/#files
  2. Download the file and unzip in your pc in the main folder, there's a file call setup.py
  3. Install with this command: python setup.py install

overlay a smaller image on a larger image python OpenCv

A simple function that blits an image front onto an image back and returns the result. It works with both 3 and 4-channel images and deals with the alpha channel. Overlaps are handled as well.

The output image has the same size as back, but always 4 channels.
The output alpha channel is given by (u+v)/(1+uv) where u,v are the alpha channels of the front and back image and -1 <= u,v <= 1. Where there is no overlap with front, the alpha value from back is taken.

import cv2

def merge_image(back, front, x,y):
    # convert to rgba
    if back.shape[2] == 3:
        back = cv2.cvtColor(back, cv2.COLOR_BGR2BGRA)
    if front.shape[2] == 3:
        front = cv2.cvtColor(front, cv2.COLOR_BGR2BGRA)

    # crop the overlay from both images
    bh,bw = back.shape[:2]
    fh,fw = front.shape[:2]
    x1, x2 = max(x, 0), min(x+fw, bw)
    y1, y2 = max(y, 0), min(y+fh, bh)
    front_cropped = front[y1-y:y2-y, x1-x:x2-x]
    back_cropped = back[y1:y2, x1:x2]

    alpha_front = front_cropped[:,:,3:4] / 255
    alpha_back = back_cropped[:,:,3:4] / 255
    
    # replace an area in result with overlay
    result = back.copy()
    print(f'af: {alpha_front.shape}\nab: {alpha_back.shape}\nfront_cropped: {front_cropped.shape}\nback_cropped: {back_cropped.shape}')
    result[y1:y2, x1:x2, :3] = alpha_front * front_cropped[:,:,:3] + alpha_back * back_cropped[:,:,:3]
    result[y1:y2, x1:x2, 3:4] = (alpha_front + alpha_back) / (1 + alpha_front*alpha_back) * 255

    return result

Do I commit the package-lock.json file created by npm 5?

Yes, it's a standard practice to commit package-lock.json.

The main reason for committing package-lock.json is that everyone in the project is on the same package version.

Pros:

  • If you follow strict versioning and don't allow updating to major versions automatically to save yourself from backward-incompatible changes in third-party packages committing package-lock helps a lot.
  • If you update a particular package, it gets updated in package-lock.json and everyone using the repository gets updated to that particular version when they take the pull of your changes.

Cons:

  • It can make your pull requests look ugly :)

npm install won't make sure that everyone in the project is on the same package version. npm ci will help with this.

What is the T-SQL syntax to connect to another SQL Server?

In SQL Server Management Studio, turn on SQLCMD mode from the Query menu. Then at the top of your script, type in the command below

:Connect server_name[\instance_name] [-l timeout] [-U user_name [-P password]

If you are connecting to multiple servers, be sure to insert GO between connections; otherwise your T-SQL won't execute on the server you're thinking it will.

Numpy first occurrence of value greater than existing value

I would go with

i = np.min(np.where(V >= x))

where V is vector (1d array), x is the value and i is the resulting index.

Test if remote TCP port is open from a shell script

I needed a more flexible solution for working on multiple git repositories so I wrote the following sh code based on 1 and 2. You can use your server address instead of gitlab.com and your port in replace of 22.

SERVER=gitlab.com
PORT=22
nc -z -v -w5 $SERVER $PORT
result1=$?

#Do whatever you want

if [  "$result1" != 0 ]; then
  echo  'port 22 is closed'
else
  echo 'port 22 is open'
fi

Can I set subject/content of email using mailto:?

The mailto: URL scheme is defined in RFC 2368. Also, the convention for encoding information into URLs and URIs is defined in RFC 1738 and then RFC 3986. These prescribe how to include the body and subject headers into a URL (URI):

mailto:[email protected]?subject=current-issue&body=send%20current-issue

Specifically, you must percent-encode the email address, subject, and body and put them into the format above. Percent-encoded text is legal for use in HTML, however this URL must be entity encoded for use in an href attribute, according to the HTML4 standard:

<a href="mailto:[email protected]?subject=current-issue&amp;body=send%20current-issue">Send email</a>

And most generally, here is a simple PHP script that encodes per the above.

<?php
$encodedTo = rawurlencode($message->to);
$encodedSubject = rawurlencode($message->subject);
$encodedBody = rawurlencode($message->body);
$uri = "mailto:$encodedTo?subject=$encodedSubject&body=$encodedBody";
$encodedUri = htmlspecialchars($uri);
echo "<a href=\"$encodedUri\">Send email</a>";
?>

MVC 5 Access Claims Identity User Data

Try this:

[Authorize]
public ActionResult SomeAction()
{
    var identity = (ClaimsIdentity)User.Identity;
    IEnumerable<Claim> claims = identity.Claims;
    ...
}

Get distance between two points in canvas

i tend to use this calculation a lot in things i make, so i like to add it to the Math object:

Math.dist=function(x1,y1,x2,y2){ 
  if(!x2) x2=0; 
  if(!y2) y2=0;
  return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); 
}
Math.dist(0,0, 3,4); //the output will be 5
Math.dist(1,1, 4,5); //the output will be 5
Math.dist(3,4); //the output will be 5

Update:

this approach is especially happy making when you end up in situations something akin to this (i often do):

varName.dist=Math.sqrt( ( (varName.paramX-varX)/2-cx )*( (varName.paramX-varX)/2-cx ) + ( (varName.paramY-varY)/2-cy )*( (varName.paramY-varY)/2-cy ) );

that horrid thing becomes the much more manageable:

varName.dist=Math.dist((varName.paramX-varX)/2, (varName.paramY-varY)/2, cx, cy);

How to activate JMX on my JVM for access with jconsole?

along with below command line parameters ,

-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

Sometimes in the linux servers , imx connection doesn't get succeeded. that is because , in cloud linux host, in /etc/hosts so that the hostname resolves to the host address.

the best way to fix it is, ping the particular linux server from other machine in network and use that host IP address in the

-Djava.rmi.server.hostname=IP address that obtained when you ping that linux server.

But never rely on the ipaddress that you get from linux server using ifconfig.me. the ip that you get there is masked one which is present in the host file.

How do I copy directories recursively with gulp?

So - the solution of providing a base works given that all of the paths have the same base path. But if you want to provide different base paths, this still won't work.

One way I solved this problem was by making the beginning of the path relative. For your case:

gulp.src([
    'index.php',
    '*css/**/*',
    '*js/**/*',
    '*src/**/*',
])
.pipe(gulp.dest('/var/www/'));

The reason this works is that Gulp sets the base to be the end of the first explicit chunk - the leading * causes it to set the base at the cwd (which is the result that we all want!)

This only works if you can ensure your folder structure won't have certain paths that could match twice. For example, if you had randomjs/ at the same level as js, you would end up matching both.

This is the only way that I have found to include these as part of a top-level gulp.src function. It would likely be simple to create a plugin/function that could separate out each of those globs so you could specify the base directory for them, however.

Make Adobe fonts work with CSS3 @font-face in IE9

Try this, add this lines in the web.config.

<system.webServer>
  <staticContent>
     <mimeMap fileExtension=".woff" mimeType="application/octet-stream" />
  </staticContent>
</system.webServer>

How can I add reflection to a C++ application?

I would like to advertise the existence of the automatic introspection/reflection toolkit "IDK". It uses a meta-compiler like Qt's and adds meta information directly into object files. It is claimed to be easy to use. No external dependencies. It even allows you to automatically reflect std::string and then use it in scripts. Please look at IDK

Kubernetes service external ip pending

Check kube-controller logs. I was able to solve this issue by setting the clusterID tags to the ec2 instance I deployed the cluster on.

Maven compile: package does not exist

the issue happened with me, I resolved by removing the scope tag only and built successfully.

Counting repeated elements in an integer array

public class ArrayDuplicate {
private static Scanner sc;
static int totalCount = 0;

    public static void main(String[] args) {
        int n, num;
        sc = new Scanner(System.in);
        System.out.print("Enter the size of array: ");
        n =sc.nextInt();
        int[] a = new int[n];
        for(int i=0;i<n;i++){
            System.out.print("Enter the element at position "+i+": ");
            num = sc.nextInt();
            a[enter image description here][1][i]=num;
        }
        System.out.print("Elements in array are: ");
        for(int i=0;i<a.length;i++)
            System.out.print(a[i]+" ");
        System.out.println();
        duplicate(a);
        System.out.println("There are "+totalCount+" repeated numbers:");
    }

    public static void duplicate(int[] a){
        int j = 0,count, recount, temp;
        for(int i=0; i<a.length;i++){
            count = 0;
            recount = 0;
            j=i+1;
            while(j<a.length){
                if(a[i]==a[j])
                    count++;
                j++;
            }
            if(count>0){
                temp = a[i];
                for(int x=0;x<i;x++){
                    if(a[x]==temp)
                        recount++;
                }
                if(recount==0){                 
                    totalCount++;
                    System.out.println(+a[i]+" : "+count+" times");
                }   
            }

        }
    }

}

How to get address of a pointer in c/c++?

To get the address of p do:

int **pp = &p;

and you can go on:

int ***ppp = &pp;
int ****pppp = &ppp;
...

or, only in C++11, you can do:

auto pp = std::addressof(p);

To print the address in C, most compilers support %p, so you can simply do:

printf("addr: %p", pp);

otherwise you need to cast it (assuming a 32 bit platform)

printf("addr: 0x%u", (unsigned)pp);

In C++ you can do:

cout << "addr: " << pp;

Ng-model does not update controller value

For me the problem was solved by stocking my datas into an object (here "datas").

_x000D_
_x000D_
NgApp.controller('MyController', function($scope) {_x000D_
_x000D_
   $scope.my_title = ""; // This don't work in ng-click function called_x000D_
_x000D_
   $scope.datas = {_x000D_
      'my_title' : "",_x000D_
   };_x000D_
_x000D_
   $scope.doAction = function() {_x000D_
         console.log($scope.my_title); // bad value_x000D_
         console.log($scope.datas.my_title); // Good Value binded by'ng-model'_x000D_
   }_x000D_
   _x000D_
_x000D_
});
_x000D_
_x000D_
_x000D_

I Hop it will help

The application was unable to start correctly (0xc000007b)

Also download and unzip "Dependencies" into same folder where you put the wget.exe from

http://gnuwin32.sourceforge.net/packages/wget.htm

You will then have some lib*.dll files as well as wget.exe in the same folder and it should work fine.

(I also answered here https://superuser.com/a/873531/146668 which I originally found.)

Javascript onload not working

Try this one:

<body onload="imageRefreshBig();">

Also you might want to check Javascript console for errors (in Chrome it's under Shift + Ctrl + J).

General error: 1364 Field 'user_id' doesn't have a default value

Use database column nullble() in Laravel. You can choose the default value or nullable value in database.

How to dismiss notification after action has been clicked

I found that when you use the action buttons in expanded notifications, you have to write extra code and you are more constrained.

You have to manually cancel your notification when the user clicks an action button. The notification is only cancelled automatically for the default action.

Also if you start a broadcast receiver from the button, the notification drawer doesn't close.

I ended up creating a new NotificationActivity to address these issues. This intermediary activity without any UI cancels the notification and then starts the activity I really wanted to start from the notification.

I've posted sample code in a related post Clicking Android Notification Actions does not close Notification drawer.

Passing dynamic javascript values using Url.action()

The @Url.Action() method is proccess on the server-side, so you cannot pass a client-side value to this function as a parameter. You can concat the client-side variables with the server-side url generated by this method, which is a string on the output. Try something like this:

var firstname = "abc";
var username = "abcd";
location.href = '@Url.Action("Display", "Customer")?uname=' + firstname + '&name=' + username;

The @Url.Action("Display", "Customer") is processed on the server-side and the rest of the string is processed on the client-side, concatenating the result of the server-side method with the client-side.

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

Getting a list of all subdirectories in the current directory

Implemented this using python-os-walk. (http://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk/)

import os

print("root prints out directories only from what you specified")
print("dirs prints out sub-directories from root")
print("files prints out all files from root and directories")
print("*" * 20)

for root, dirs, files in os.walk("/var/log"):
    print(root)
    print(dirs)
    print(files)

How to fill color in a cell in VBA?

Non VBA Solution:

Use Conditional Formatting rule with formula: =ISNA(A1) (to highlight cells with all errors - not only #N/A, use =ISERROR(A1))

enter image description here

VBA Solution:

Your code loops through 50 mln cells. To reduce number of cells, I use .SpecialCells(xlCellTypeFormulas, 16) and .SpecialCells(xlCellTypeConstants, 16)to return only cells with errors (note, I'm using If cell.Text = "#N/A" Then)

Sub ColorCells()
    Dim Data As Range, Data2 As Range, cell As Range
    Dim currentsheet As Worksheet

    Set currentsheet = ActiveWorkbook.Sheets("Comparison")

    With currentsheet.Range("A2:AW" & Rows.Count)
        .Interior.Color = xlNone
        On Error Resume Next
        'select only cells with errors
        Set Data = .SpecialCells(xlCellTypeFormulas, 16)
        Set Data2 = .SpecialCells(xlCellTypeConstants, 16)
        On Error GoTo 0
    End With

    If Not Data2 Is Nothing Then
        If Not Data Is Nothing Then
            Set Data = Union(Data, Data2)
        Else
            Set Data = Data2
        End If
    End If

    If Not Data Is Nothing Then
        For Each cell In Data
            If cell.Text = "#N/A" Then
               cell.Interior.ColorIndex = 4
            End If
        Next
    End If
End Sub

Note, to highlight cells witn any error (not only "#N/A"), replace following code

If Not Data Is Nothing Then
   For Each cell In Data
       If cell.Text = "#N/A" Then
          cell.Interior.ColorIndex = 3
       End If
   Next
End If

with

If Not Data Is Nothing Then Data.Interior.ColorIndex = 3

UPD: (how to add CF rule through VBA)

Sub test()
    With ActiveWorkbook.Sheets("Comparison").Range("A2:AW" & Rows.Count).FormatConditions
        .Delete
        .Add Type:=xlExpression, Formula1:="=ISNA(A1)"
        .Item(1).Interior.ColorIndex = 3
    End With
End Sub

Bulk Insertion in Laravel using eloquent ORM

$start_date = date('Y-m-d h:m:s');        
        $end_date = date('Y-m-d h:m:s', strtotime($start_date . "+".$userSubscription['duration']." months") );
        $user_subscription_array = array(
          array(
            'user_id' => $request->input('user_id'),
            'user_subscription_plan_id' => $request->input('subscription_plan_id'),
            'name' => $userSubscription['name'],
            'description' => $userSubscription['description'],
            'duration' => $userSubscription['duration'],
            'start_datetime' => $start_date,
            'end_datetime' => $end_date,
            'amount' => $userSubscription['amount'],
            'invoice_id' => '',
            'transection_datetime' => '',
            'created_by' => '1',
            'status_id' => '1', ),
array(
            'user_id' => $request->input('user_id'),
            'user_subscription_plan_id' => $request->input('subscription_plan_id'),
            'name' => $userSubscription['name'],
            'description' => $userSubscription['description'],
            'duration' => $userSubscription['duration'],
            'start_datetime' => $start_date,
            'end_datetime' => $end_date,
            'amount' => $userSubscription['amount'],
            'invoice_id' => '',
            'transection_datetime' => '',
            'created_by' => '1',
            'status_id' => '1', )
        );
        dd(UserSubscription::insert($user_subscription_array));

UserSubscription is my model name. This will return "true" if insert successfully else "false".

How to Free Inode Usage?

you could see this info

for i in /var/run/*;do echo -n "$i "; find $i| wc -l;done | column -t

Lists in ConfigParser

I landed here seeking to consume this...

[global]
spys = [email protected], [email protected]

The answer is to split it on the comma and strip the spaces:

SPYS = [e.strip() for e in parser.get('global', 'spys').split(',')]

To get a list result:

['[email protected]', '[email protected]']

It may not answer the OP's question exactly but might be the simple answer some people are looking for.

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

How to convert String to Date value in SAS?

input(char_val,current_date_format);

You can specify any date format at display time, like set char_val=date9.;

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

How to post object and List using postman

Try this one,

{
  "address": "colombo",
  "username": "hesh",
  "password": "123",
  "registetedDate": "2015-4-3",
  "firstname": "hesh",
  "contactNo": "07762",
  "accountNo": "16161",
  "lastName": "jay",
  "skill":[1436517454492,1436517476993]
}

Checking on a thread / remove from list

you need to call thread.isAlive()to find out if the thread is still running

Best way to store a key=>value array in JavaScript?

You can use Map.

  • A new data structure introduced in JavaScript ES6.
  • Alternative to JavaScript Object for storing key/value pairs.
  • Has useful methods for iteration over the key/value pairs.
var map = new Map();
map.set('name', 'John');
map.set('id', 11);

// Get the full content of the Map
console.log(map); // Map { 'name' => 'John', 'id' => 11 }

Get value of the Map using key

console.log(map.get('name')); // John 
console.log(map.get('id')); // 11

Get size of the Map

console.log(map.size); // 2

Check key exists in Map

console.log(map.has('name')); // true
console.log(map.has('age')); // false

Get keys

console.log(map.keys()); // MapIterator { 'name', 'id' }

Get values

console.log(map.values()); // MapIterator { 'John', 11 }

Get elements of the Map

for (let element of map) {
  console.log(element);
}

// Output:
// [ 'name', 'John' ]
// [ 'id', 11 ]

Print key value pairs

for (let [key, value] of map) {
  console.log(key + " - " + value);
}

// Output: 
// name - John
// id - 11

Print only keys of the Map

for (let key of map.keys()) {
  console.log(key);
}

// Output:
// name
// id

Print only values of the Map

for (let value of map.values()) {
  console.log(value);
}

// Output:
// John
// 11

A reference to the dll could not be added

Normally in Visual Studio 2015 you should create the dll project as a C++ -> CLR project from Visual Studio's templates, but you can technically enable it after the fact:

The critical property is called Common Language Runtime Support set in your project's configuration. It's found under Configuration Properties > General > Common Language Runtime Support.

When doing this, VS will probably not update the 'Target .NET Framework' option (like it should). You can manually add this by unloading your project, editing the your_project.xxproj file, and adding/updating the Target .NET framework Version XML tag.

For a sample, I suggest creating a new solution as a C++ CLR project and examining the XML there, perhaps even diffing it to make sure there's nothing very important that's out of the ordinary.

How to handle Pop-up in Selenium WebDriver using Java

I found the solution for the above program, which had the goal of signing in to http://rediff.com

public class Handle_popupNAlert
{
    public static void main(String[] args ) throws InterruptedException
    {
        WebDriver driver= new FirefoxDriver(); 
        driver.get("http://www.rediff.com/");
        WebElement sign = driver.findElement(By.xpath("//html/body/div[3]/div[3]/span[4]/span/a"));
        sign.click();

        Set<String> windowId = driver.getWindowHandles();    // get  window id of current window
        Iterator<String> itererator = windowId.iterator();   

        String mainWinID = itererator.next();
        String  newAdwinID = itererator.next();

        driver.switchTo().window(newAdwinID);
        System.out.println(driver.getTitle());
        Thread.sleep(3000);
        driver.close();

        driver.switchTo().window(mainWinID);
        System.out.println(driver.getTitle());
        Thread.sleep(2000);

        WebElement email_id= driver.findElement(By.xpath("//*[@id='c_uname']"));
        email_id.sendKeys("hi");
        Thread.sleep(5000);

        driver.close();
        driver.quit();
    }  
}

How to get the Display Name Attribute of an Enum member via MVC Razor code?

I'm sorry to do this, but I couldn't use any of the other answers as-is and haven't time to duke it out in the comments.

Uses C# 6 syntax.

static class EnumExtensions
{
    /// returns the localized Name, if a [Display(Name="Localised Name")] attribute is applied to the enum member
    /// returns null if there isnt an attribute
    public static string DisplayNameOrEnumName(this Enum value)
    // => value.DisplayNameOrDefault() ?? value.ToString()
    {
        // More efficient form of ^ based on http://stackoverflow.com/a/17034624/11635
        var enumType = value.GetType();
        var enumMemberName = Enum.GetName(enumType, value);
        return enumType
            .GetEnumMemberAttribute<DisplayAttribute>(enumMemberName)
            ?.GetName() // Potentially localized
            ?? enumMemberName; // Or fall back to the enum name
    }

    /// returns the localized Name, if a [Display] attribute is applied to the enum member
    /// returns null if there is no attribute
    public static string DisplayNameOrDefault(this Enum value) =>
        value.GetEnumMemberAttribute<DisplayAttribute>()?.GetName();

    static TAttribute GetEnumMemberAttribute<TAttribute>(this Enum value) where TAttribute : Attribute =>
        value.GetType().GetEnumMemberAttribute<TAttribute>(value.ToString());

    static TAttribute GetEnumMemberAttribute<TAttribute>(this Type enumType, string enumMemberName) where TAttribute : Attribute =>
        enumType.GetMember(enumMemberName).Single().GetCustomAttribute<TAttribute>();
}

Git: copy all files in a directory from another branch

If there are no spaces in paths, and you are interested, like I was, in files of specific extension only, you can use

git checkout otherBranch -- $(git ls-tree --name-only -r otherBranch | egrep '*.java')

How can I search for a multiline pattern in a file?

Here is a more useful example:

pcregrep -Mi "<title>(.*\n){0,5}</title>" afile.html

It searches the title tag in a html file even if it spans up to 5 lines.

Here is an example of unlimited lines:

pcregrep -Mi "(?s)<title>.*</title>" example.html 

C# How to determine if a number is a multiple of another?

Use the modulus (%) operator:

6 % 3 == 0
7 % 3 == 1

Cmake is not able to find Python-libraries

You can fix the errors by appending to the cmake command the -DPYTHON_LIBRARY and -DPYTHON_INCLUDE_DIR flags filled with the respective folders.

Thus, the trick is to fill those parameters with the returned information from the python interpreter, which is the most reliable. This may work independently of your python location/version (also for Anaconda users):

$ cmake .. \
-DPYTHON_INCLUDE_DIR=$(python -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())")  \
-DPYTHON_LIBRARY=$(python -c "import distutils.sysconfig as sysconfig; print(sysconfig.get_config_var('LIBDIR'))")

If the version of python that you want to link against cmake is Python3.X and the default python symlink points to Python2.X, python3 -c ... can be used instead of python -c ....

In case that the error persists, you may need to update the cmake to a higher version as stated by @pdpcosta and repeat the process again.

Get Maven artifact version at runtime

You should not need to access Maven-specific files to get the version information of any given library/class.

You can simply use getClass().getPackage().getImplementationVersion() to get the version information that is stored in a .jar-files MANIFEST.MF. Luckily Maven is smart enough Unfortunately Maven does not write the correct information to the manifest as well by default!

Instead one has to modify the <archive> configuration element of the maven-jar-plugin to set addDefaultImplementationEntries and addDefaultSpecificationEntries to true, like this:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
        <archive>                   
            <manifest>
                <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
            </manifest>
        </archive>
    </configuration>
</plugin>

Ideally this configuration should be put into the company pom or another base-pom.

Detailed documentation of the <archive> element can be found in the Maven Archive documentation.

Unlink of file Failed. Should I try again?

I encountered this issue while doing a git pull.

I tried git gc and it resolved my problem.

How to align center the text in html table row?

HTML in line styling example:

<td style='text-align:center; vertical-align:middle'></td> 

CSS file example:

td {
    text-align: center;
    vertical-align: middle;
}

Convert XML to JSON (and back) using Javascript

https://github.com/abdmob/x2js - my own library (updated URL from http://code.google.com/p/x2js/):

This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions. The library is very small and doesn't require any other additional libraries.

API functions

  • new X2JS() - to create your instance to access all library functionality. Also you could specify optional configuration options here
  • X2JS.xml2json - Convert XML specified as DOM Object to JSON
  • X2JS.json2xml - Convert JSON to XML DOM Object
  • X2JS.xml_str2json - Convert XML specified as string to JSON
  • X2JS.json2xml_str - Convert JSON to XML string

Online Demo on http://jsfiddle.net/abdmob/gkxucxrj/1/

var x2js = new X2JS();
function convertXml2JSon() {
    $("#jsonArea").val(JSON.stringify(x2js.xml_str2json($("#xmlArea").val())));
}

function convertJSon2XML() {
    $("#xmlArea").val(x2js.json2xml_str($.parseJSON($("#jsonArea").val())));
}

convertXml2JSon();
convertJSon2XML();
$("#convertToJsonBtn").click(convertXml2JSon);
$("#convertToXmlBtn").click(convertJSon2XML);

The action or event has been blocked by Disabled Mode

I solved this with Access options.

Go to the Office Button --> Access Options --> Trust Center --> Trust Center Settings Button --> Message Bar

In the right hand pane I selected the radio button "Show the message bar in all applications when content has been blocked."

Closed Access, reopened the database and got the warning for blocked content again.

Nested JSON objects - do I have to use arrays for everything?

You don't need to use arrays.

JSON values can be arrays, objects, or primitives (numbers or strings).

You can write JSON like this:

{ 
    "stuff": {
        "onetype": [
            {"id":1,"name":"John Doe"},
            {"id":2,"name":"Don Joeh"}
        ],
        "othertype": {"id":2,"company":"ACME"}
    }, 
    "otherstuff": {
        "thing": [[1,42],[2,2]]
     }
}

You can use it like this:

obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1]  //thing is a nested array or a 2-by-2 matrix.
                            //I'm not sure whether you intended to do that.

How do I call a non-static method from a static method in C#?

You just need to provide object reference . Please provide your class name in the position.

private static void data2()
{
    <classname> c1 = new <classname>();
    c1. data1();
}

How should I unit test multithreaded code?

It's not perfect, but I wrote this helper for my tests in C#:

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace Proto.Promises.Tests.Threading
{
    public class ThreadHelper
    {
        public static readonly int multiThreadCount = Environment.ProcessorCount * 100;
        private static readonly int[] offsets = new int[] { 0, 10, 100, 1000 };

        private readonly Stack<Task> _executingTasks = new Stack<Task>(multiThreadCount);
        private readonly Barrier _barrier = new Barrier(1);
        private int _currentParticipants = 0;
        private readonly TimeSpan _timeout;

        public ThreadHelper() : this(TimeSpan.FromSeconds(10)) { } // 10 second timeout should be enough for most cases.

        public ThreadHelper(TimeSpan timeout)
        {
            _timeout = timeout;
        }

        /// <summary>
        /// Execute the action multiple times in parallel threads.
        /// </summary>
        public void ExecuteMultiActionParallel(Action action)
        {
            for (int i = 0; i < multiThreadCount; ++i)
            {
                AddParallelAction(action);
            }
            ExecutePendingParallelActions();
        }

        /// <summary>
        /// Execute the action once in a separate thread.
        /// </summary>
        public void ExecuteSingleAction(Action action)
        {
            AddParallelAction(action);
            ExecutePendingParallelActions();
        }

        /// <summary>
        /// Add an action to be run in parallel.
        /// </summary>
        public void AddParallelAction(Action action)
        {
            var taskSource = new TaskCompletionSource<bool>();
            lock (_executingTasks)
            {
                ++_currentParticipants;
                _barrier.AddParticipant();
                _executingTasks.Push(taskSource.Task);
            }
            new Thread(() =>
            {
                try
                {
                    _barrier.SignalAndWait(); // Try to make actions run in lock-step to increase likelihood of breaking race conditions.
                    action.Invoke();
                    taskSource.SetResult(true);
                }
                catch (Exception e)
                {
                    taskSource.SetException(e);
                }
            }).Start();
        }

        /// <summary>
        /// Runs the pending actions in parallel, attempting to run them in lock-step.
        /// </summary>
        public void ExecutePendingParallelActions()
        {
            Task[] tasks;
            lock (_executingTasks)
            {
                _barrier.SignalAndWait();
                _barrier.RemoveParticipants(_currentParticipants);
                _currentParticipants = 0;
                tasks = _executingTasks.ToArray();
                _executingTasks.Clear();
            }
            try
            {
                if (!Task.WaitAll(tasks, _timeout))
                {
                    throw new TimeoutException($"Action(s) timed out after {_timeout}, there may be a deadlock.");
                }
            }
            catch (AggregateException e)
            {
                // Only throw one exception instead of aggregate to try to avoid overloading the test error output.
                throw e.Flatten().InnerException;
            }
        }

        /// <summary>
        /// Run each action in parallel multiple times with differing offsets for each run.
        /// <para/>The number of runs is 4^actions.Length, so be careful if you don't want the test to run too long.
        /// </summary>
        /// <param name="expandToProcessorCount">If true, copies each action on additional threads up to the processor count. This can help test more without increasing the time it takes to complete.
        /// <para/>Example: 2 actions with 6 processors, runs each action 3 times in parallel.</param>
        /// <param name="setup">The action to run before each parallel run.</param>
        /// <param name="teardown">The action to run after each parallel run.</param>
        /// <param name="actions">The actions to run in parallel.</param>
        public void ExecuteParallelActionsWithOffsets(bool expandToProcessorCount, Action setup, Action teardown, params Action[] actions)
        {
            setup += () => { };
            teardown += () => { };
            int actionCount = actions.Length;
            int expandCount = expandToProcessorCount ? Math.Max(Environment.ProcessorCount / actionCount, 1) : 1;
            foreach (var combo in GenerateCombinations(offsets, actionCount))
            {
                setup.Invoke();
                for (int k = 0; k < expandCount; ++k)
                {
                    for (int i = 0; i < actionCount; ++i)
                    {
                        int offset = combo[i];
                        Action action = actions[i];
                        AddParallelAction(() =>
                        {
                            for (int j = offset; j > 0; --j) { } // Just spin in a loop for the offset.
                            action.Invoke();
                        });
                    }
                }
                ExecutePendingParallelActions();
                teardown.Invoke();
            }
        }

        // Input: [1, 2, 3], 3
        // Ouput: [
        //          [1, 1, 1],
        //          [2, 1, 1],
        //          [3, 1, 1],
        //          [1, 2, 1],
        //          [2, 2, 1],
        //          [3, 2, 1],
        //          [1, 3, 1],
        //          [2, 3, 1],
        //          [3, 3, 1],
        //          [1, 1, 2],
        //          [2, 1, 2],
        //          [3, 1, 2],
        //          [1, 2, 2],
        //          [2, 2, 2],
        //          [3, 2, 2],
        //          [1, 3, 2],
        //          [2, 3, 2],
        //          [3, 3, 2],
        //          [1, 1, 3],
        //          [2, 1, 3],
        //          [3, 1, 3],
        //          [1, 2, 3],
        //          [2, 2, 3],
        //          [3, 2, 3],
        //          [1, 3, 3],
        //          [2, 3, 3],
        //          [3, 3, 3]
        //        ]
        private static IEnumerable<int[]> GenerateCombinations(int[] options, int count)
        {
            int[] indexTracker = new int[count];
            int[] combo = new int[count];
            for (int i = 0; i < count; ++i)
            {
                combo[i] = options[0];
            }
            // Same algorithm as picking a combination lock.
            int rollovers = 0;
            while (rollovers < count)
            {
                yield return combo; // No need to duplicate the array since we're just reading it.
                for (int i = 0; i < count; ++i)
                {
                    int index = ++indexTracker[i];
                    if (index == options.Length)
                    {
                        indexTracker[i] = 0;
                        combo[i] = options[0];
                        if (i == rollovers)
                        {
                            ++rollovers;
                        }
                    }
                    else
                    {
                        combo[i] = options[index];
                        break;
                    }
                }
            }
        }
    }
}

Example usage:

[Test]
public void DeferredMayBeBeResolvedAndPromiseAwaitedConcurrently_void0()
{
    Promise.Deferred deferred = default(Promise.Deferred);
    Promise promise = default(Promise);

    int invokedCount = 0;

    var threadHelper = new ThreadHelper();
    threadHelper.ExecuteParallelActionsWithOffsets(false,
        // Setup
        () =>
        {
            invokedCount = 0;
            deferred = Promise.NewDeferred();
            promise = deferred.Promise;
        },
        // Teardown
        () => Assert.AreEqual(1, invokedCount),
        // Parallel Actions
        () => deferred.Resolve(),
        () => promise.Then(() => { Interlocked.Increment(ref invokedCount); }).Forget()
    );
}

How do I clear my local working directory in Git?

To reset a specific file as git status suggests:

git checkout <filename>

To reset a folder

git checkout <foldername>/*

Python lookup hostname from IP with 1 second timeout

>>> import socket
>>> socket.gethostbyaddr("69.59.196.211")
('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211'])

For implementing the timeout on the function, this stackoverflow thread has answers on that.

Variably modified array at file scope

Imho this is a flaw in many c compilers. I know for a fact that the compilers i worked with do not store a "static const"variable at an adress but replace the use in the code by the very constant. This can be verified as you will get the same checksum for the produced code when you use a preprocessors #define directive and when you use a static const variable.

Either way you should use static const variables instead of #defines whenever possible as the static const is type safe.

Can I apply multiple background colors with CSS3?

You can only use one color but as many images as you want, here is the format:

background: [ <bg-layer> , ]* <final-bg-layer>

<bg-layer> = <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2}

<final-bg-layer> = <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2} || <background-color>

or background: url(image1.png) center bottom no-repeat, url(image2.png) left top no-repeat;

If you need more colors, make an image of a solid color and use it. I know it’s not what you want to hear, but I hope it helps.

The format is from http://www.css3.info/preview/multiple-backgrounds/

How do I remove  from the beginning of a file?

I don't know PHP, so I don't know if this is possible, but the best solution would be to read the file as UTF-8 rather than some other encoding. The BOM is actually a ZERO WIDTH NO BREAK SPACE. This is whitespace, so if the file were being read in the correct encoding (UTF-8), then the BOM would be interpreted as whitespace and it would be ignored in the resulting CSS file.

Also, another advantage of reading the file in the correct encoding is that you don't have to worry about characters being misinterpreted. Your editor is telling you that the code page you want to save it in won't do all the characters that you need. If PHP is then reading the file in the incorrect encoding, then it is very likely that other characters besides the BOM are being silently misinterpreted. Use UTF-8 everywhere, and these problems disappear.

disable horizontal scroll on mobile web

I know this is an old question but it's worth noting that BlackBerry doesn't support overflow-x or overflow-y.

See my post here

Migration: Cannot add foreign key constraint

In my case, the issue was that the main table already had records in it and I was forcing the new column to not be NULL. So adding a ->nullable() to the new column did the trick. In the question's example would be something like this:

$table->integer('user_id')->unsigned()->nullable();

or:

$table->unsignedInteger('user_id')->nullable();

Hope this helps somebody!

c++ custom compare function for std::sort()

Your comparison function is not even wrong.

Its arguments should be the type stored in the range, i.e. std::pair<K,V>, not const void*.

It should return bool not a positive or negative value. Both (bool)1 and (bool)-1 are true so your function says every object is ordered before every other object, which is clearly impossible.

You need to model the less-than operator, not strcmp or memcmp style comparisons.

See StrictWeakOrdering which describes the properties the function must meet.