Programs & Examples On #Multi gpu

This refers to one application's using multiple graphics-processing units, either in traditional (graphical) or general-purpose (GPGPU) applications.

Using Java with Nvidia GPUs (CUDA)

I'd start by using one of the projects out there for Java and CUDA: http://www.jcuda.org/

Making a Windows shortcut start relative to where the folder is?

I tried %~dp0 in the Start in field and it is working fine in Windows 10 x64

How to define the basic HTTP authentication using cURL correctly?

as header

AUTH=$(echo -ne "$BASIC_AUTH_USER:$BASIC_AUTH_PASSWORD" | base64 --wrap 0)

curl \
  --header "Content-Type: application/json" \
  --header "Authorization: Basic $AUTH" \
  --request POST \
  --data  '{"key1":"value1", "key2":"value2"}' \
  https://example.com/

How to squash commits in git after they have been pushed?

On a branch I was able to do it like this (for the last 4 commits)

git checkout my_branch
git reset --soft HEAD~4
git commit
git push --force origin my_branch

How can I debug javascript on Android?

You could try https://github.com/fullpipe/screen-log. Tried to make it clean and simple.

3 column layout HTML/CSS

CSS:

     .container div{
 width: 33.33%;
 float: left;
 height: 100px ;} 

Clear floats after the columns

 .container:after {
 content: "";
 display: table;
 clear: both;}

How to use the 'main' parameter in package.json?

For OpenShift, you only get one PORT and IP pair to bind to (per application). It sounds like you should be able to serve both services from a single nodejs instance by adding internal routes for each service endpoint.

I have some info on how OpenShift uses your project's package.json to start your application here: https://www.openshift.com/blogs/run-your-nodejs-projects-on-openshift-in-two-simple-steps#package_json

Remove part of a string

Maybe the most intuitive solution is probably to use the stringr function str_remove which is even easier than str_replace as it has only 1 argument instead of 2.

The only tricky part in your example is that you want to keep the underscore but its possible: You must match the regular expression until it finds the specified string pattern (?=pattern).

See example:

strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121")
strings %>% stringr::str_remove(".+?(?=_)")

[1] "_1121" "_1432" "_1121"

How do you check if a JavaScript Object is a DOM Object?

var isElement = function(e){
    try{
        // if e is an element attached to the DOM, we trace its lineage and use native functions to confirm its pedigree
        var a = [e], t, s, l = 0, h = document.getElementsByTagName('HEAD')[0], ht = document.getElementsByTagName('HTML')[0];
        while(l!=document.body&&l!=h&&l.parentNode) l = a[a.push(l.parentNode)-1];
        t = a[a.length-1];
        s = document.createElement('SCRIPT');   // safe to place anywhere and it won't show up
        while(a.length>1){  // assume the top node is an element for now...
            var p = a.pop(),n = a[a.length-1];
            p.insertBefore(s,n);
        }
        if(s.parentNode)s.parentNode.removeChild(s);
        if(t!=document.body&&t!=h&&t!=ht)
            // the top node is not attached to the document, so we don't have to worry about it resetting any dynamic media
            // test the top node
            document.createElement('DIV').appendChild(t).parentNode.removeChild(t);
        return e;
    }
    catch(e){}
    return null;
}

I tested this on Firefox, Safari, Chrome, Opera and IE9. I couldn't find a way to hack it.
In theory, it tests every ancestor of the proposed element, as well as the element itself, by inserting a script tag before it.
If its first ancestor traces back to a known element, such as <html>, <head> or <body>, and it hasn't thrown an error along the way, we have an element.
If the first ancestor is not attached to the document, we create an element and attempt to place the proposed element inside of it, (and then remove it from the new element).
So it either traces back to a known element, successfully attaches to a known element or fails.
It returns the element or null if it is not an element.

html select option separator

This is an old thread, but since no one posted a similar response, I'll add this as it's my preferred way of separation.

I find using dashes and such to be somewhat of an eyesore since it could fall short of the width of the selection box. So, I prefer to use CSS to create my separators.. a simple background coloring.

_x000D_
_x000D_
<select>_x000D_
  <option style="background-color: #cccccc;" disabled selected>Select An Option</option>_x000D_
  <option>First Option</option>_x000D_
  <option>Second</option>_x000D_
  <option style="font-size: 1pt; background-color: #000000;" disabled>&nbsp;</option>_x000D_
  <option>Third</option>_x000D_
  <option>Fourth</option>_x000D_
  <option style="font-size: 1pt; background-color: #000000;" disabled>&nbsp;</option>_x000D_
  <option>Fifth</option>_x000D_
  <option>Sixth</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to coerce a list object to type 'double'

In this case a loop will also do the job (and is usually sufficiently fast).

a <- array(0, dim=dim(X))
for (i in 1:ncol(X)) {a[,i] <- X[,i]}

What is SOA "in plain english"?

SOA is a buzzword that was invented by technology vendors to help sell their Enterprise Service Bus related technologies. The idea is that you make your little island applications in the enterprise (eg: accounting system, stock control system, etc) all expose services, so that they can be orchestrated flexibly into 'applications', or rather become parts of aggregate enterprise scoped business logic.

Basically a load of old bollocks that nearly never works, because it misses the point that the reasons why technology is the way it is in an organisation is down to culture, evolution, history of the firm, and the lock in is so high that any attempt to restructure the technology is bound to fail.

Converting string to number in javascript/jQuery

It sounds like this in your code is not referring to your .btn element. Try referencing it explicitly with a selector:

var votevalue = parseInt($(".btn").data('votevalue'), 10);

Also, don't forget the radix.

Test if a string contains a word in PHP?

_x000D_
_x000D_
use _x000D_
_x000D_
if(stripos($str,'job')){_x000D_
   // do your work_x000D_
}
_x000D_
_x000D_
_x000D_

Check/Uncheck checkbox with JavaScript

function setCheckboxValue(checkbox,value) {
    if (checkbox.checked!=value)
        checkbox.click();
}

How do I count columns of a table

I have a more general answer; but I believe it is useful for counting the columns for all tables in a DB:

SELECT table_name, count(*)
FROM information_schema.columns
GROUP BY table_name;

Reload an iframe with jQuery

Just reciprocating Alex's answer but with jQuery

var currSrc = $("#currentElement").attr("src");
$("#currentElement").attr("src", currSrc);

mysql_config not found when installing mysqldb python interface

sudo apt-get install python-mysqldb

Python 2.5? Sounds like you are using a very old version of Ubuntu Server (Hardy 8.04?) - please confirm which Linux version the server uses.

python-mysql search on ubuntu package database

Some additional info:

From the README of mysql-python -

Red Hat Linux .............

MySQL-python is pre-packaged in Red Hat Linux 7.x and newer. This includes Fedora Core and Red Hat Enterprise Linux. You can also build your own RPM packages as described above.

Debian GNU/Linux ................

Packaged as python-mysqldb_::

# apt-get install python-mysqldb

Or use Synaptic.

.. _python-mysqldb: http://packages.debian.org/python-mysqldb

Ubuntu ......

Same as with Debian.

Footnote: If you really are using a server distribution older than Ubuntu 10.04 then you are out of official support, and should upgrade sooner rather than later.

How do you set the max number of characters for an EditText in Android?

it doesn't work from XML with maxLenght I used this code, you can limit the number of characters

String editorName = mEditorNameNd.getText().toString().substring(0, Math.min(mEditorNameNd.length(), 15));

ios simulator: how to close an app

You can use this command to quit an app in iOS Simulator

xcrun simctl terminate booted com.apple.mobilesafari

You will need to know the bundle id of the app you have installed in the simulator. You can refer to this link

How to use group by with union in t-sql

with UnionTable as  
(
    SELECT a.id, a.time FROM dbo.a
    UNION
    SELECT b.id, b.time FROM dbo.b
) SELECT id FROM UnionTable GROUP BY id

How to check if directory exist using C++ and winAPI

If linking to the shell Lightweight API (shlwapi.dll) is ok for you, you can use the PathIsDirectory function

Getting the encoding of a Postgres database

tl;dr

SELECT character_set_name 
FROM information_schema.character_sets 
;

Standard way: information_schema

From the SQL-standard schema information_schema present in every database/catalog, use the defined view named character_sets. This approach should be portable across all standard database systems.

SELECT * 
FROM information_schema.character_sets 
;

Despite the name being plural, it shows only a single row, reporting on the current database/catalog.

screenshot of pgAdmin 4 with results of query shown above

The third column is character_set_name:

Name of the character set, currently implemented as showing the name of the database encoding

No such keg: /usr/local/Cellar/git

Had a similar issue while installing "Lua" in OS X using homebrew. I guess it could be useful for other users facing similar issue in homebrew.

On running the command:

$ brew install lua

The command returned an error:

Error: /usr/local/opt/lua is not a valid keg
(in general the error can be of /usr/local/opt/ is not a valid keg

FIXED it by deleting the file/directory it is referring to, i.e., deleting the "/usr/local/opt/lua" file.

root-user # rm -rf /usr/local/opt/lua

And then running the brew install command returned success.

How and when to use ‘async’ and ‘await’

public static void Main(string[] args)
{
    string result = DownloadContentAsync().Result;
    Console.ReadKey();
}

// You use the async keyword to mark a method for asynchronous operations.
// The "async" modifier simply starts synchronously the current thread. 
// What it does is enable the method to be split into multiple pieces.
// The boundaries of these pieces are marked with the await keyword.
public static async Task<string> DownloadContentAsync()// By convention, the method name ends with "Async
{
    using (HttpClient client = new HttpClient())
    {
        // When you use the await keyword, the compiler generates the code that checks if the asynchronous operation is finished.
        // If it is already finished, the method continues to run synchronously.
        // If not completed, the state machine will connect a continuation method that must be executed WHEN the Task is completed.


        // Http request example. 
        // (In this example I can set the milliseconds after "sleep=")
        String result = await client.GetStringAsync("http://httpstat.us/200?sleep=1000");

        Console.WriteLine(result);

        // After completing the result response, the state machine will continue to synchronously execute the other processes.


        return result;
    }
}

When should I use the new keyword in C++?

Are you passing myClass out of a function, or expecting it to exist outside that function? As some others said, it is all about scope when you aren't allocating on the heap. When you leave the function, it goes away (eventually). One of the classic mistakes made by beginners is the attempt to create a local object of some class in a function and return it without allocating it on the heap. I can remember debugging this kind of thing back in my earlier days doing c++.

jQuery - add additional parameters on submit (NOT ajax)

This one did it for me:

var input = $("<input>")
               .attr("type", "hidden")
               .attr("name", "mydata").val("bla");
$('#form1').append(input);

is based on the Daff's answer, but added the NAME attribute to let it show in the form collection and changed VALUE to VAL Also checked the ID of the FORM (form1 in my case)

used the Firefox firebug to check whether the element was inserted.

Hidden elements do get posted back in the form collection, only read-only fields are discarded.

Michel

Export SQL query data to Excel

For anyone coming here looking for how to do this in C#, I have tried the following method and had success in dotnet core 2.0.3 and entity framework core 2.0.3

First create your model class.

public class User
{  
    public string Name { get; set; }  
    public int Address { get; set; }  
    public int ZIP { get; set; }  
    public string Gender { get; set; }  
} 

Then install EPPlus Nuget package. (I used version 4.0.5, probably will work for other versions as well.)

Install-Package EPPlus -Version 4.0.5

The create ExcelExportHelper class, which will contain the logic to convert dataset to Excel rows. This class do not have dependencies with your model class or dataset.

public class ExcelExportHelper
    {
        public static string ExcelContentType
        {
            get
            { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; }
        }

        public static DataTable ListToDataTable<T>(List<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable dataTable = new DataTable();

            for (int i = 0; i < properties.Count; i++)
            {
                PropertyDescriptor property = properties[i];
                dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
            }

            object[] values = new object[properties.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = properties[i].GetValue(item);
                }

                dataTable.Rows.Add(values);
            }
            return dataTable;
        }

        public static byte[] ExportExcel(DataTable dataTable, string heading = "", bool showSrNo = false, params string[] columnsToTake)
        {

            byte[] result = null;
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(String.Format("{0} Data", heading));
                int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3;

                if (showSrNo)
                {
                    DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
                    dataColumn.SetOrdinal(0);
                    int index = 1;
                    foreach (DataRow item in dataTable.Rows)
                    {
                        item[0] = index;
                        index++;
                    }
                }


                // add the content into the Excel file  
                workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);

                // autofit width of cells with small content  
                int columnIndex = 1;
                foreach (DataColumn column in dataTable.Columns)
                {
                    int maxLength;
                    ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
                    try
                    {
                        maxLength = columnCells.Max(cell => cell.Value.ToString().Count());
                    }
                    catch (Exception) //nishanc
                    {
                        maxLength = columnCells.Max(cell => (cell.Value +"").ToString().Length);
                    }

                    //workSheet.Column(columnIndex).AutoFit();
                    if (maxLength < 150)
                    {
                        //workSheet.Column(columnIndex).AutoFit();
                    }


                    columnIndex++;
                }

                // format header - bold, yellow on black  
                using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])
                {
                    r.Style.Font.Color.SetColor(System.Drawing.Color.White);
                    r.Style.Font.Bold = true;
                    r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    r.Style.Fill.BackgroundColor.SetColor(Color.Brown);
                }

                // format cells - add borders  
                using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
                {
                    r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
                    r.Style.Border.Right.Style = ExcelBorderStyle.Thin;

                    r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
                    r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
                }

                // removed ignored columns  
                for (int i = dataTable.Columns.Count - 1; i >= 0; i--)
                {
                    if (i == 0 && showSrNo)
                    {
                        continue;
                    }
                    if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))
                    {
                        workSheet.DeleteColumn(i + 1);
                    }
                }

                if (!String.IsNullOrEmpty(heading))
                {
                    workSheet.Cells["A1"].Value = heading;
                   // workSheet.Cells["A1"].Style.Font.Size = 20;

                    workSheet.InsertColumn(1, 1);
                    workSheet.InsertRow(1, 1);
                    workSheet.Column(1).Width = 10;
                }

                result = package.GetAsByteArray();
            }

            return result;
        }

        public static byte[] ExportExcel<T>(List<T> data, string Heading = "", bool showSlno = false, params string[] ColumnsToTake)
        {
            return ExportExcel(ListToDataTable<T>(data), Heading, showSlno, ColumnsToTake);
        }
    }

Now add this method where you want to generate the excel file, probably for a method in the controller. You can pass parameters for your stored procedure as well. Note that the return type of the method is FileContentResult. Whatever query you execute, important thing is you must have the results in a List.

[HttpPost]
public async Task<FileContentResult> Create([Bind("Id,StartDate,EndDate")] GetReport getReport)
{
    DateTime startDate = getReport.StartDate;
    DateTime endDate = getReport.EndDate;

    // call the stored procedure and store dataset in a List.
    List<User> users = _context.Reports.FromSql("exec dbo.SP_GetEmpReport @start={0}, @end={1}", startDate, endDate).ToList();
    //set custome column names
    string[] columns = { "Name", "Address", "ZIP", "Gender"};
    byte[] filecontent = ExcelExportHelper.ExportExcel(users, "Users", true, columns);
    // set file name.
    return File(filecontent, ExcelExportHelper.ExcelContentType, "Report.xlsx"); 
}

More details can be found here

Can I remove the URL from my print css, so the web address doesn't print?

Now we can do this with:

<style type="text/css" media="print">
@page {
    size: auto;   /* auto is the initial value */
    margin: 0;  /* this affects the margin in the printer settings */
}
</style>

Source: https://stackoverflow.com/a/14975912/1760939

Android Eclipse - Could not find *.apk

remove -- R.java -- Clean the project and run again.. this worked for me ..

How do I generate a random number between two variables that I have stored?

If you have a C++11 compiler you can prepare yourself for the future by using c++'s pseudo random number faculties:

//make sure to include the random number generators and such
#include <random>
//the random device that will seed the generator
std::random_device seeder;
//then make a mersenne twister engine
std::mt19937 engine(seeder());
//then the easy part... the distribution
std::uniform_int_distribution<int> dist(min, max);
//then just generate the integer like this:
int compGuess = dist(engine);

That might be slightly easier to grasp, being you don't have to do anything involving modulos and crap... although it requires more code, it's always nice to know some new C++ stuff...

Hope this helps - Luke

How to store Query Result in variable using mysql

Surround that select with parentheses.

SET @v1 := (SELECT COUNT(*) FROM user_rating);
SELECT @v1;

Can you put two conditions in an xslt test attribute?

Not quite, the AND has to be lower-case.

<xsl:when test="4 &lt; 5 and 1 &lt; 2">
<!-- do something -->
</xsl:when>

How to sort Counter by value? - python

A rather nice addition to @MartijnPieters answer is to get back a dictionary sorted by occurrence since Collections.most_common only returns a tuple. I often couple this with a json output for handy log files:

from collections import Counter, OrderedDict

x = Counter({'a':5, 'b':3, 'c':7})
y = OrderedDict(x.most_common())

With the output:

OrderedDict([('c', 7), ('a', 5), ('b', 3)])
{
  "c": 7, 
  "a": 5, 
  "b": 3
}

Best way to create unique token in Rails?

you can user has_secure_token https://github.com/robertomiranda/has_secure_token

is really simple to use

class User
  has_secure_token :token1, :token2
end

user = User.create
user.token1 => "44539a6a59835a4ee9d7b112b48cd76e"
user.token2 => "226dd46af6be78953bde1641622497a8"

How to get distinct values from an array of objects in JavaScript?

Using ES6 features, you could do something like:

const uniqueAges = [...new Set( array.map(obj => obj.age)) ];

Concrete Javascript Regex for Accented Characters (Diacritics)

How about this?

/^[a-zA-ZÀ-ÖØ-öø-ÿ]+$/

How do I get column datatype in Oracle with PL-SQL with low privileges?

You can use the desc command.

desc MY_TABLE

This will give you the column names, whether null is valid, and the datatype (and length if applicable)

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

try staring jboss with ./standalone.sh -c standalone-full.xml or any other alternative that allows you to start with the full profile

Linux bash script to extract IP address

A slight modification to one of the previous ip route ... solutions, which eliminates the need for a grep:

ip route get 8.8.8.8 | sed -n 's|^.*src \(.*\)$|\1|gp'

disabling spring security in spring boot app

The accepted answer didn't work for me.

If you have a multi configuration, adding the following to your WebSecurityConfig class worked for me (ensure that your Order(1) is lower than all of your other Order annotations in the class):

/* UNCOMMENT TO DISABLE SPRING SECURITY */
    /*@Configuration
    @Order(1)
    public static class DisableSecurityConfigurationAdapater extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/**").authorizeRequests().anyRequest().permitAll();
        }
    }*/

open existing java project in eclipse

The typical pattern is to check out the root project folder (=the one containing a file called ".project") from SVN using eclipse's svn integration (SVN repository exploring perspective). The project is then recognized automatically.

How do I kill a process using Vb.NET or C#?

Here is an easy example of how to kill all Word Processes.

Process[] procs = Process.GetProcessesByName("winword");

foreach (Process proc in procs)
    proc.Kill();

Check if program is running with bash shell script?

If you want to execute that command, you should probably change:

PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'

to:

PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)

How do I add a margin between bootstrap columns without wrapping

I was facing the same issue; and the following worked well for me. Hope this helps someone landing here:

<div class="row">
    <div class="col-md-6">
        <div class="col-md-12">
            Set room heater temperature
        </div>
    </div>
    <div class="col-md-6">
        <div class="col-md-12">
            Set room heater temperature
        </div>
    </div>
</div>

This will automatically render some space between the 2 divs. enter image description here

async for loop in node.js

I've reduced your code sample to the following lines to make it easier to understand the explanation of the concept.

var results = [];
var config = JSON.parse(queries);
for (var key in config) {
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
    });
}
res.writeHead( ... );
res.end(results);

The problem with the previous code is that the search function is asynchronous, so when the loop has ended, none of the callback functions have been called. Consequently, the list of results is empty.

To fix the problem, you have to put the code after the loop in the callback function.

    search(query, function(result) {
        results.push(result);
        // Put res.writeHead( ... ) and res.end(results) here
    });

However, since the callback function is called multiple times (once for every iteration), you need to somehow know that all callbacks have been called. To do that, you need to count the number of callbacks, and check whether the number is equal to the number of asynchronous function calls.

To get a list of all keys, use Object.keys. Then, to iterate through this list, I use .forEach (you can also use for (var i = 0, key = keys[i]; i < keys.length; ++i) { .. }, but that could give problems, see JavaScript closure inside loops – simple practical example).

Here's a complete example:

var results = [];
var config = JSON.parse(queries);
var onComplete = function() {
    res.writeHead( ... );
    res.end(results);
};
var keys = Object.keys(config);
var tasksToGo = keys.length;
if (tasksToGo === 0) {
   onComplete();
} else {
    // There is at least one element, so the callback will be called.
    keys.forEach(function(key) {
        var query = config[key].query;
        search(query, function(result) {
            results.push(result);
            if (--tasksToGo === 0) {
                // No tasks left, good to go
                onComplete();
            }
        });
    });
}

Note: The asynchronous code in the previous example are executed in parallel. If the functions need to be called in a specific order, then you can use recursion to get the desired effect:

var results = [];
var config = JSON.parse(queries);
var keys = Object.keys(config);
(function next(index) {
    if (index === keys.length) { // No items left
        res.writeHead( ... );
        res.end(results);
        return;
    }
    var key = keys[index];
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
        next(index + 1);
    });
})(0);

What I've shown are the concepts, you could use one of the many (third-party) NodeJS modules in your implementation, such as async.

Count textarea characters

For those wanting a simple solution without jQuery, here's a way.

textarea and message container to put in your form:

<textarea onKeyUp="count_it()" id="text" name="text"></textarea>
Length <span id="counter"></span>

JavaScript:

<script>
function count_it() {
    document.getElementById('counter').innerHTML = document.getElementById('text').value.length;
}
count_it();
</script>

The script counts the characters initially and then for every keystroke and puts the number in the counter span.

Martin

Bootstrap Carousel image doesn't align properly

I am facing the same problem with you. Based on the hint of @thuliha, the following codes has solved my issues.

In the html file, modify as the following sample:

<img class="img-responsive center-block" src=".....png" alt="Third slide">

In the carousel.css, modify the class:

.carousel .item {
  text-align: center;
  height: 470px;
  background-color: #777;
}

How to get cell value from DataGridView in VB.Net?

The line would be as shown below:

Dim x As Integer    
x = dgvName.Rows(yourRowIndex).Cells(yourColumnIndex).Value

What's the difference between using "let" and "var"?

Here is an example for the difference between the two (support just started for chrome):
enter image description here

As you can see the var j variable is still having a value outside of the for loop scope (Block Scope), but the let i variable is undefined outside of the for loop scope.

_x000D_
_x000D_
"use strict";_x000D_
console.log("var:");_x000D_
for (var j = 0; j < 2; j++) {_x000D_
  console.log(j);_x000D_
}_x000D_
_x000D_
console.log(j);_x000D_
_x000D_
console.log("let:");_x000D_
for (let i = 0; i < 2; i++) {_x000D_
  console.log(i);_x000D_
}_x000D_
_x000D_
console.log(i);
_x000D_
_x000D_
_x000D_

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

JavaScript data grid for millions of rows

dojox.grid.DataGrid offers a JS abstraction for data so you can hook it up to various backends with provided dojo.data stores or write your own. You'll obviously need one that supports random access for this many records. DataGrid also provides full accessibility.

Edit so here's a link to Matthew Russell's article that should provide the example you need, viewing millions of records with dojox.grid. Note that it uses the old version of the grid, but the concepts are the same, there were just some incompatible API improvements.

Oh, and it's totally free open source.

Generate unique random numbers between 1 and 100

Another approach is to generate an 100 items array with ascending numbers and sort it randomly. This leads actually to a really short and (in my opinion) simple snippet.

_x000D_
_x000D_
const numbers = Array(100).fill().map((_, index) => index + 1);_x000D_
numbers.sort(() => Math.random() - 0.5);_x000D_
console.log(numbers.slice(0, 8));
_x000D_
_x000D_
_x000D_

Add / Change parameter of URL and redirect to the new URL

I need help to adjust my script below or to find a script that could be used on my wordpress site to grab the url suffix parameters from a forward url, then to be added at the button click url for tracking the proper forward ads id.

REASON: parameters are used for advertisement tracking to find out from which ad the user has been forward, even if the user hops from optin page to the sales page by using button click.

Here the goal to reach: 1. An FB ad points to an optin page with tracking code: https://ownsite.com/optin-page/?tid=fbad1 2. At the optin-page there is a button with a setup URL to forward to the sales page, but if clicked then only the URL is forward, but the parameter "?tid=fbad1" is missing. 3. The auto-forward script below (which is working properly) can be used to change for button click forward, but has a limitation as it grab only "tid" parameters instead also utm parameters.

Therefore a script code shall be implemented to establish click buttons (also to style them or use images instead) and while clicking the button to forward to a different sales page with grabbing the suffix parameter form the current optin-page to forward then to sales-page https://ownsite.com/sales-page/?tid=fbad1 also including UTM parameters

Currently, I could have solved this by using an auto-redirect script, but A.) I do not want to use an autoredirect at this page. Better is an event click button used to let the user himself click to forward with the URL parameter included. B.) The tracking ID parameter in this script is limited to "?tid=..." instead I do also want to track the UTM code on button click also i.e. Grab from current page the paramater of URL https://www.optin-page.com/?tid=facebookad1?utm_campaign=blogpost then on button click grab parameters and add to button set URL https://www.sales-page.com/?tid=facebookad1?utm_campaign=blogpost

Please now find here the Code below in use for auto-redirect and grabbing the URL parameters. This code shall be changed now to be able to create a button with a click-event to be redirect then to the forward URL with parameter grabbing of current URL if the button is clicked (as stated above).

    <p><!-- Modify this according to your requirement - core script from https://gist.github.com/Joel-James/62d98e8cb3a1b6b05102 and suffix grabbing </p>
    <h3 style="text-align: center;"><span style="color: #ffffff; background-color: #039e00;">?Auto-redirecting after <span id="countdown">35</span> seconds?</span></h3>
    <p><!-- JavaScript part --><br /><script type="text/javascript">

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    location.search
        .substr(1)
        .split("&")
        .forEach(function (item) {
          tmp = item.split("=");
          if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
        });
    return result;
}


    // Total seconds to wait
    var seconds = 45;

    function countdown() {
        seconds = seconds - 1;
        if (seconds < 0) {
            // Chnage your redirection link here
var tid = findGetParameter('tid');
window.location = "https://www.2share.info/ql-cb2/" + '?tid='+tid;
        } else {
            // Update remaining seconds
            document.getElementById("countdown").innerHTML = seconds;
            // Count down using javascript
            window.setTimeout("countdown()", 1000);
        }
    }

    // Run countdown function
    countdown();

</script></p>

Elasticsearch difference between MUST and SHOULD bool query

must means: The clause (query) must appear in matching documents. These clauses must match, like logical AND.

should means: At least one of these clauses must match, like logical OR.

Basically they are used like logical operators AND and OR. See this.

Now in a bool query:

must means: Clauses that must match for the document to be included.

should means: If these clauses match, they increase the _score; otherwise, they have no effect. They are simply used to refine the relevance score for each document.


Yes you can use multiple filters inside must.

How to set $_GET variable

For the form, use:

<form name="form1" action="<?=$_SERVER['PHP_SELF'];?>" method="get">

and for getting the value, use the get method as follows:

$value = $_GET['name_to_send_using_get'];

Auto-redirect to another HTML page

If you want to redirect your webpage to another HTML FILE, just use as followed:

<meta http-equiv="refresh" content"2;otherpage.html">

2 being the seconds you want the client to wait before redirecting. Use "url=" only when it's an URL, to redirect to an HTML file just write the name after the ';'

Rails Active Record find(:all, :order => ) issue

Make sure to check the schema at the database level directly. I've gotten burned by this before, where, for example, a migration was initially written to create a :datetime column, and I ran it locally, then tweaked the migration to a :date before actually deploying. Thus everyone's database looks good except for mine, and the bugs are subtle.

Apply style to cells of first row

This should do the work:

.category_table tr:first-child td {
    vertical-align: top;
}

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

What about this:

ListItem match = ddlCustomerNumber.Items.FindByText(
    GetCustomerNumberCookie().ToString());
if (match == null)
    ddlCustomerNumber.SelectedIndex = 0;
//else
//    match.Selected = true; // you'll probably select that cookie value

How to disassemble a memory range with GDB?

gdb disassemble has a /m to include source code alongside the instructions. This is equivalent of objdump -S, with the extra benefit of confining to just the one function (or address-range) of interest.

What's the difference between a web site and a web application?

Websites are primarily informational. In this sense, http://cnn.com and http://php.net are websites, not web applications.

Web applications primarily allow the user to perform actions. Google Analytics, gmail, and jslint are web applications.

They are not entirely exclusive. A university website likely gives information such as location, tuition rates, programs available, etc; it will likely have web applications that allow teachers to manage grades and course materials, applications for students to register for and withdraw from courses, etc.

What are the differences among grep, awk & sed?

Short definition:

grep: search for specific terms in a file

#usage
$ grep This file.txt
Every line containing "This"
Every line containing "This"
Every line containing "This"
Every line containing "This"

$ cat file.txt
Every line containing "This"
Every line containing "This"
Every line containing "That"
Every line containing "This"
Every line containing "This"

Now awk and sed are completly different than grep. awk and sed are text processors. Not only do they have the ability to find what you are looking for in text, they have the ability to remove, add and modify the text as well (and much more).

awk is mostly used for data extraction and reporting. sed is a stream editor
Each one of them has its own functionality and specialties.

Example
Sed

$ sed -i 's/cat/dog/' file.txt
# this will replace any occurrence of the characters 'cat' by 'dog'

Awk

$ awk '{print $2}' file.txt
# this will print the second column of file.txt

Basic awk usage:
Compute sum/average/max/min/etc. what ever you may need.

$ cat file.txt
A 10
B 20
C 60
$ awk 'BEGIN {sum=0; count=0; OFS="\t"} {sum+=$2; count++} END {print "Average:", sum/count}' file.txt
Average:    30

I recommend that you read this book: Sed & Awk: 2nd Ed.

It will help you become a proficient sed/awk user on any unix-like environment.

Given final block not properly padded

If you try to decrypt PKCS5-padded data with the wrong key, and then unpad it (which is done by the Cipher class automatically), you most likely will get the BadPaddingException (with probably of slightly less than 255/256, around 99.61%), because the padding has a special structure which is validated during unpad and very few keys would produce a valid padding.

So, if you get this exception, catch it and treat it as "wrong key".

This also can happen when you provide a wrong password, which then is used to get the key from a keystore, or which is converted into a key using a key generation function.

Of course, bad padding can also happen if your data is corrupted in transport.

That said, there are some security remarks about your scheme:

  • For password-based encryption, you should use a SecretKeyFactory and PBEKeySpec instead of using a SecureRandom with KeyGenerator. The reason is that the SecureRandom could be a different algorithm on each Java implementation, giving you a different key. The SecretKeyFactory does the key derivation in a defined manner (and a manner which is deemed secure, if you select the right algorithm).

  • Don't use ECB-mode. It encrypts each block independently, which means that identical plain text blocks also give always identical ciphertext blocks.

    Preferably use a secure mode of operation, like CBC (Cipher block chaining) or CTR (Counter). Alternatively, use a mode which also includes authentication, like GCM (Galois-Counter mode) or CCM (Counter with CBC-MAC), see next point.

  • You normally don't want only confidentiality, but also authentication, which makes sure the message is not tampered with. (This also prevents chosen-ciphertext attacks on your cipher, i.e. helps for confidentiality.) So, add a MAC (message authentication code) to your message, or use a cipher mode which includes authentication (see previous point).

  • DES has an effective key size of only 56 bits. This key space is quite small, it can be brute-forced in some hours by a dedicated attacker. If you generate your key by a password, this will get even faster. Also, DES has a block size of only 64 bits, which adds some more weaknesses in chaining modes. Use a modern algorithm like AES instead, which has a block size of 128 bits, and a key size of 128 bits (for the standard variant).

Shell script to send email

Yes it works fine and is commonly used:

$ echo "hello world" | mail -s "a subject" [email protected]

CSS rule to apply only if element has BOTH classes

Below applies to all tags with the following two classes

.abc.xyz {  
  width: 200px !important;
}

applies to div tags with the following two classes

div.abc.xyz {  
  width: 200px !important;
}

If you wanted to modify this using jQuery

$(document).ready(function() {
  $("div.abc.xyz").width("200px");
});

iOS: How to store username/password within an app?

But, now you can go for NURLCredential instead of keychain wrapper. It does what we need to do.

Hibernate dialect for Oracle Database 11g?

According to supported databases, Oracle 11g is not officially supported. Although, I believe you shouldn't have any problems using org.hibernate.dialect.OracleDialect.

API pagination best practices

I think currently your api's actually responding the way it should. The first 100 records on the page in the overall order of objects you are maintaining. Your explanation tells that you are using some kind of ordering ids to define the order of your objects for pagination.

Now, in case you want that page 2 should always start from 101 and end at 200, then you must make the number of entries on the page as variable, since they are subject to deletion.

You should do something like the below pseudocode:

page_max = 100
def get_page_results(page_no) :

    start = (page_no - 1) * page_max + 1
    end = page_no * page_max

    return fetch_results_by_id_between(start, end)

How to declare a constant map in Golang?

You can create constants in many different ways:

const myString = "hello"
const pi = 3.14 // untyped constant
const life int = 42 // typed constant (can use only with ints)

You can also create a enum constant:

const ( 
   First = 1
   Second = 2
   Third = 4
)

You can not create constants of maps, arrays and it is written in effective go:

Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.

Setting format and value in input type="date"

new Date().toISOString().split('T')[0];

Create request with POST, which response codes 200 or 201 and content

In a few words:

  • 200 when an object is created and returned
  • 201 when an object is created but only its reference is returned (such as an ID or a link)

How to use paths in tsconfig.json?

Solution for 2021.

Note: CRA. Initially the idea of ??using a third party library or ejecting app for alias seemed crazy to me. However, after 8 hours of searching (and trying variant with eject), it turned out that this option is the least painful.

Step 1.

yarn add --dev react-app-rewired react-app-rewire-alias

Step 2. Create config-overrides.js file in your project's root and fill it with :

const {alias} = require('react-app-rewire-alias')

module.exports = function override(config) {
  return alias({
    assets: './src/assets',
    '@components': './src/components',
  })(config)
}

Step 3. Fix your package.json file:

  "scripts": {
-   "start": "react-scripts start",
+   "start": "react-app-rewired start",
-   "build": "react-scripts build",
+   "build": "react-app-rewired build",
-   "test": "react-scripts test",
+   "test": "react-app-rewired test",
    "eject": "react-scripts eject"
}

If @declarations don't work, add them to the d.ts file. For example: '@constants': './src/constants', => add in react-app-env.d.ts declare module '@constants';

That is all. Now you can continue to use yarn or npm start/build/test commands as usual.

Full version in docs.

Note: The 'Using with ts / js config' part in docs did not work for me. The error "aliased imports are not supported" when building the project remained. So I used an easier way. Luckily it works.

Verifying that a string contains only letters in C#

Recently, I made performance improvements for a function that checks letters in a string with the help of this page.

I figured out that the Solutions with regex are 30 times slower than the ones with the Char.IsLetterOrDigit check.

We were not sure that those Letters or Digits include and we were in need of only Latin characters so implemented our function based on the decompiled version of Char.IsLetterOrDigit function.

Here is our solution:

internal static bool CheckAllowedChars(char uc)
    {
        switch (uc)
        {
            case '-':
            case '.':
            case 'A':
            case 'B':
            case 'C':
            case 'D':
            case 'E':
            case 'F':
            case 'G':
            case 'H':
            case 'I':
            case 'J':
            case 'K':
            case 'L':
            case 'M':
            case 'N':
            case 'O':
            case 'P':
            case 'Q':
            case 'R':
            case 'S':
            case 'T':
            case 'U':
            case 'V':
            case 'W':
            case 'X':
            case 'Y':
            case 'Z':
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                return true;
            default:
                return false;
        }
    }

And the usage is like this:

 if( logicalId.All(c => CheckAllowedChars(c)))
 { // Do your stuff here.. }

makefiles - compile all c files at once

You need to take out your suffix rule (%.o: %.c) in favour of a big-bang rule. Something like this:

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

OBJ = 64bitmath.o    \
      monotone.o     \
      node_sort.o    \
      planesweep.o   \
      triangulate.o  \
      prim_combine.o \
      welding.o      \
      test.o         \
      main.o

SRCS = $(OBJ:%.o=%.c)

test: $(SRCS)
    gcc -o $@  $(CFLAGS) $(LIBS) $(SRCS)

If you're going to experiment with GCC's whole-program optimization, make sure that you add the appropriate flag to CFLAGS, above.

On reading through the docs for those flags, I see notes about link-time optimization as well; you should investigate those too.

Garbage collector in Android

Quick note for Xamarin developers.

If you would like to call System.gc() in Xamarin.Android apps you should call Java.Lang.JavaSystem.Gc()

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

What are the advantages of NumPy over regular Python lists?

Alex mentioned memory efficiency, and Roberto mentions convenience, and these are both good points. For a few more ideas, I'll mention speed and functionality.

Functionality: You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc. And really, who can live without FFTs?

Speed: Here's a test on doing a sum over a list and a NumPy array, showing that the sum on the NumPy array is 10x faster (in this test -- mileage may vary).

from numpy import arange
from timeit import Timer

Nelements = 10000
Ntimeits = 10000

x = arange(Nelements)
y = range(Nelements)

t_numpy = Timer("x.sum()", "from __main__ import x")
t_list = Timer("sum(y)", "from __main__ import y")
print("numpy: %.3e" % (t_numpy.timeit(Ntimeits)/Ntimeits,))
print("list:  %.3e" % (t_list.timeit(Ntimeits)/Ntimeits,))

which on my systems (while I'm running a backup) gives:

numpy: 3.004e-05
list:  5.363e-04

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

Simple and easy :

_x000D_
_x000D_
<form onSubmit="return confirm('Do you want to submit?') ">_x000D_
  <input type="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to add default value for html <textarea>?

Placeholder cannot set the default value for text area. You can use

<textarea rows="10" cols="55" name="description"> /*Enter default value here to display content</textarea>

This is the tag if you are using it for database connection. You may use different syntax if you are using other languages than php.For php :

e.g.:

<textarea rows="10" cols="55" name="description" required><?php echo $description; ?></textarea>

required command minimizes efforts needed to check empty fields using php.

How do I list all the files in a directory and subdirectories in reverse chronological order?

If the number of files you want to view fits within the maximum argument limit you can use globbing to get what you want, with recursion if you have globstar support.

For exactly 2 layers deep use: ls -d * */*

With globstar, for recursion use: ls -d **/*

The -d argument to ls tells it not to recurse directories passed as arguments (since you are using the shell globbing to do the recursion). This prevents ls using its recursion formatting.

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

The question "what the Context is" is one of the most difficult questions in the Android universe.

Context defines methods that access system resources, retrieve application's static assets, check permissions, perform UI manipulations and many more. In essence, Context is an example of God Object anti-pattern in production.

When it comes to which kind of Context should we use, it becomes very complicated because except for being God Object, the hierarchy tree of Context subclasses violates Liskov Substitution Principle brutally.

This blog post (now from Wayback Machine) attempts to summarize Context classes applicability in different situations.

Let me copy the main table from that post for completeness:

+----------------------------+-------------+----------+---------+-----------------+-------------------+
|                            | Application | Activity | Service | ContentProvider | BroadcastReceiver |
+----------------------------+-------------+----------+---------+-----------------+-------------------+
| Show a Dialog              | NO          | YES      | NO      | NO              | NO                |
| Start an Activity          | NO¹         | YES      | NO¹     | NO¹             | NO¹               |
| Layout Inflation           | NO²         | YES      | NO²     | NO²             | NO²               |
| Start a Service            | YES         | YES      | YES     | YES             | YES               |
| Bind to a Service          | YES         | YES      | YES     | YES             | NO                |
| Send a Broadcast           | YES         | YES      | YES     | YES             | YES               |
| Register BroadcastReceiver | YES         | YES      | YES     | YES             | NO³               |
| Load Resource Values       | YES         | YES      | YES     | YES             | YES               |
+----------------------------+-------------+----------+---------+-----------------+-------------------+
  1. An application CAN start an Activity from here, but it requires that a new task be created. This may fit specific use cases, but can create non-standard back stack behaviors in your application and is generally not recommended or considered good practice.
  2. This is legal, but inflation will be done with the default theme for the system on which you are running, not what’s defined in your application.
  3. Allowed if the receiver is null, which is used for obtaining the current value of a sticky broadcast, on Android 4.2 and above.

screenshot

SQL query for finding records where count > 1

Try this query:

SELECT column_name
  FROM table_name
 GROUP BY column_name
HAVING COUNT(column_name) = 1;

Using Django time/date widgets in custom form

My head code for 1.4 version(some new and some removed)

{% block extrahead %}

<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/forms.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/base.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/global.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}admin/css/widgets.css"/>

<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/core.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/admin/RelatedObjectLookups.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/jquery.init.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/actions.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/calendar.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}admin/js/admin/DateTimeShortcuts.js"></script>

{% endblock %}

Should each and every table have a primary key?

In short, no. However, you need to keep in mind that certain client access CRUD operations require it. For future proofing, I tend to always utilize primary keys.

How to skip "are you sure Y/N" when deleting files in batch files

You have the following options on Windows command line:

net use [DeviceName [/home[{Password | *}] [/delete:{yes | no}]]

Try like:

net use H: /delete /y

How do I print out the contents of a vector?

I am going to add another answer here, because I have come up with a different approach to my previous one, and that is to use locale facets.

The basics are here

Essentially what you do is:

  1. Create a class that derives from std::locale::facet. The slight downside is that you will need a compilation unit somewhere to hold its id. Let's call it MyPrettyVectorPrinter. You'd probably give it a better name, and also create ones for pair and map.
  2. In your stream function, you check std::has_facet< MyPrettyVectorPrinter >
  3. If that returns true, extract it with std::use_facet< MyPrettyVectorPrinter >( os.getloc() )
  4. Your facet objects will have values for the delimiters and you can read them. If the facet isn't found, your print function (operator<<) provides default ones. Note you can do the same thing for reading a vector.

I like this method because you can use a default print whilst still being able to use a custom override.

The downsides are needing a library for your facet if used in multiple projects (so can't just be headers-only) and also the fact that you need to beware about the expense of creating a new locale object.

I have written this as a new solution rather than modify my other one because I believe both approaches can be correct and you take your pick.

WAMP shows error 'MSVCR100.dll' is missing when install

Some times you have to install all versions or a bunch of them.

Anyone who has not found above answers useful , take a look at here

How do you create a temporary table in an Oracle database?

CREATE GLOBAL TEMPORARY TABLE Table_name
    (startdate DATE,
     enddate DATE,
     class CHAR(20))
  ON COMMIT DELETE ROWS;

Import pandas dataframe column as string not int

Since pandas 1.0 it became much more straightforward. This will read column 'ID' as dtype 'string':

pd.read_csv('sample.csv',dtype={'ID':'string'})

As we can see in this Getting started guide, 'string' dtype has been introduced (before strings were treated as dtype 'object').

Creating and throwing new exception

To call a specific exception such as FileNotFoundException use this format

if (-not (Test-Path $file)) 
{
    throw [System.IO.FileNotFoundException] "$file not found."
}

To throw a general exception use the throw command followed by a string.

throw "Error trying to do a task"

When used inside a catch, you can provide additional information about what triggered the error

What is the difference between == and equals() in Java?

The difference between == and equals confused me for sometime until I decided to have a closer look at it. Many of them say that for comparing string you should use equals and not ==. Hope in this answer I will be able to say the difference.

The best way to answer this question will be by asking a few questions to yourself. so let's start:

What is the output for the below program:

String mango = "mango";
String mango2 = "mango";
System.out.println(mango != mango2);
System.out.println(mango == mango2);

if you say,

false
true

I will say you are right but why did you say that? and If you say the output is,

true
false

I will say you are wrong but I will still ask you, why you think that is right?

Ok, Let's try to answer this one:

What is the output for the below program:

String mango = "mango";
String mango3 = new String("mango");
System.out.println(mango != mango3);
System.out.println(mango == mango3);

Now If you say,

false
true

I will say you are wrong but why is it wrong now? the correct output for this program is

true
false

Please compare the above program and try to think about it.

Ok. Now this might help (please read this : print the address of object - not possible but still we can use it.)

String mango = "mango";
String mango2 = "mango";
String mango3 = new String("mango");
System.out.println(mango != mango2);
System.out.println(mango == mango2);
System.out.println(mango3 != mango2);
System.out.println(mango3 == mango2);
// mango2 = "mang";
System.out.println(mango+" "+ mango2);
System.out.println(mango != mango2);
System.out.println(mango == mango2);

System.out.println(System.identityHashCode(mango));
System.out.println(System.identityHashCode(mango2));
System.out.println(System.identityHashCode(mango3));

can you just try to think about the output of the last three lines in the code above: for me ideone printed this out (you can check the code here):

false
true
true
false
mango mango
false
true
17225372
17225372
5433634

Oh! Now you see the identityHashCode(mango) is equal to identityHashCode(mango2) But it is not equal to identityHashCode(mango3)

Even though all the string variables - mango, mango2 and mango3 - have the same value, which is "mango", identityHashCode() is still not the same for all.

Now try to uncomment this line // mango2 = "mang"; and run it again this time you will see all three identityHashCode() are different. Hmm that is a helpful hint

we know that if hashcode(x)=N and hashcode(y)=N => x is equal to y

I am not sure how java works internally but I assume this is what happened when I said:

mango = "mango";

java created a string "mango" which was pointed(referenced) by the variable mango something like this

mango ----> "mango"

Now in the next line when I said:

mango2 = "mango";

It actually reused the same string "mango" which looks something like this

mango ----> "mango" <---- mango2

Both mango and mango2 pointing to the same reference Now when I said

mango3 = new String("mango")

It actually created a completely new reference(string) for "mango". which looks something like this,

mango -----> "mango" <------ mango2

mango3 ------> "mango"

and that's why when I put out the values for mango == mango2, it put out true. and when I put out the value for mango3 == mango2, it put out false (even when the values were the same).

and when you uncommented the line // mango2 = "mang"; It actually created a string "mang" which turned our graph like this:

mango ---->"mango"
mango2 ----> "mang"
mango3 -----> "mango"

This is why the identityHashCode is not the same for all.

Hope this helps you guys. Actually, I wanted to generate a test case where == fails and equals() pass. Please feel free to comment and let me know If I am wrong.

How can two strings be concatenated?

Alternatively, if your objective is to output directly to a file or stdout, you can use cat:

cat(s1, s2, sep=", ")

jQuery - getting custom attribute from selected option

Here is the entire script with an AJAX call to target a single list within a page with multiple lists. None of the other stuff above worked for me until I used the "id" attribute even though my attribute name is "ItemKey". By using the debugger

Chrome Debug

I was able to see that the selected option had attributes: with a map to the JQuery "id" and the value.

<html>
<head>
<script type="text/JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<select id="List1"></select>
<select id="List2">
<option id="40000">List item #1</option>
<option id="27888">List item #2</option>
</select>

<div></div>
</body>
<script type="text/JavaScript">
//get a reference to the select element
$select = $('#List1');

//request the JSON data and parse into the select element
$.ajax({
url: 'list.json',
dataType:'JSON',
success:function(data){

//clear the current content of the select
$select.html('');

//iterate over the data and append a select option
$.each(data.List, function(key, val){
$select.append('<option id="' + val.ItemKey + '">' + val.ItemText + '</option>');
})
},

error:function(){

//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
});

$( "#List1" ).change(function () {
var optionSelected = $('#List1 option:selected').attr('id');
$( "div" ).text( optionSelected );
});
</script>
</html>

Here is the JSON File to create...

{  
"List":[  
{  
"Sort":1,
"parentID":0,
"ItemKey":100,
"ItemText":"ListItem-#1"
},
{  
"Sort":2,
"parentID":0,
"ItemKey":200,
"ItemText":"ListItem-#2"
},
{  
"Sort":3,
"parentID":0,
"ItemKey":300,
"ItemText":"ListItem-#3"
},
{  
"Sort":4,
"parentID":0,
"ItemKey":400,
"ItemText":"ListItem-#4"
}
]
}

Hope this helps, thank you all above for getting me this far.

iOS: Compare two dates

I don't know exactly if you have asked this but if you only want to compare the date component of a NSDate you have to use NSCalendar and NSDateComponents to remove the time component.

Something like this should work as a category for NSDate:

- (NSComparisonResult)compareDateOnly:(NSDate *)otherDate {
    NSUInteger dateFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
    NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *selfComponents = [gregorianCalendar components:dateFlags fromDate:self];
    NSDate *selfDateOnly = [gregorianCalendar dateFromComponents:selfComponents];

    NSDateComponents *otherCompents = [gregorianCalendar components:dateFlags fromDate:otherDate];
    NSDate *otherDateOnly = [gregorianCalendar dateFromComponents:otherCompents];
    return [selfDateOnly compare:otherDateOnly];
}

C# Linq Where Date Between 2 Dates

So you are scrolling down because the Answers do not work:

This works like magic (but they say it has efficiency issues for big data, And you do not care just like me)

1- Data Type in Database is "datetime" and "nullable" in my case.

Example data format in DB is like:

2018-11-06 15:33:43.640

An in C# when converted to string is like:

2019-01-03 4:45:16 PM

So the format is :

yyyy/MM/dd hh:mm:ss tt

2- So you need to prepare your datetime variables in the proper format first:

Example 1

yourDate.ToString("yyyy/MM/dd hh:mm:ss tt")

Example 2 - Datetime range for the last 30 days

    DateTime dateStart = DateTime.Now.AddDays(-30);
    DateTime dateEnd = DateTime.Now.AddDays(1).AddTicks(-1);

3- Finally the linq query you lost your day trying to find (Requires EF 6)

using System.Data.Entity;

_dbContext.Shipments.Where(s => (DbFunctions.TruncateTime(s.Created_at.Value) >= dateStart && DbFunctions.TruncateTime(s.Created_at.Value) <= dateEnd)).Count();

To take time comparison into account as well :

(DbFunctions.CreateDateTime(s.Created_at.Value.Year, s.Created_at.Value.Month, s.Created_at.Value.Day, s.Created_at.Value.Hour, s.Created_at.Value.Minute, s.Created_at.Value.Second) >= dateStart && DbFunctions.CreateDateTime(s.Created_at.Value.Year, s.Created_at.Value.Month, s.Created_at.Value.Day, s.Created_at.Value.Hour, s.Created_at.Value.Minute, s.Created_at.Value.Second) <= dateEnd)

Note the following method mentioned on other stackoverflow questions and answers will not work correctly:

....
&&
(
    s.Created_at.Value.Day >= dateStart.Day && s.Created_at.Value.Day <= dateEnd.Day &&
    s.Created_at.Value.Month >= dateStart.Month && s.Created_at.Value.Month <= dateEnd.Month &&
    s.Created_at.Value.Year >= dateStart.Year && s.Created_at.Value.Year <= dateEnd.Year
)).count();

if the start day was in this month for example and the end day is on the next month, the query will return false and no results, for example:

DatabaseCreatedAtItemThatWeWant = 2018/12/05

startDate = 2018/12/01

EndDate = 2019/01/04

the query will always search for days between 01 and 04 without taking the "month" into account, so "s.Created_at.Value.Day <= dateEnd.Day" will fail

And in case you have really big data you would execute Native SQL Query rather than linq

...
    ... where Shipments.Created_at BETWEEN CAST(@Created_at_from as datetime) AND CAST(@Created_at_to as datetime))
    ....

Thanks

Search all tables, all columns for a specific value SQL Server

The below Query works but very slow... copied from vyaskn.tripod.com

Declare @SearchStr nvarchar(100)

SET  @SearchStr='Search String' BEGIN

CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128),
 @SearchStr2 nvarchar(110)  SET  @TableName = ''    SET @SearchStr2 =
 QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL    
BEGIN       
  SET @ColumnName = ''      
  SET @TableName =  (
    SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' +
    QUOTENAME(TABLE_NAME)) FROM INFORMATION_SCHEMA.TABLES 
    WHERE
    TABLE_TYPE = 'BASE TABLE'
    AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
    AND OBJECTPROPERTY(
      OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)),
        'IsMSShipped') = 0)

  WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)      
  BEGIN
    SET @ColumnName = (
      SELECT MIN(QUOTENAME(COLUMN_NAME))
      FROM INFORMATION_SCHEMA.COLUMNS
      WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
        AND TABLE_NAME = PARSENAME(@TableName, 1)
      AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
      AND QUOTENAME(COLUMN_NAME) > @ColumnName)
      IF @ColumnName IS NOT NULL            
      BEGIN
      INSERT INTO #Results
      EXEC
      (
        'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + 
          ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
        ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
      )             
      END       
    END     
  END

  SELECT ColumnName, ColumnValue FROM #Results END

Serving static web resources in Spring Boot & Spring Security application

  @Override
      public void configure(WebSecurity web) throws Exception {
        web
          .ignoring()
             .antMatchers("/resources/**"); // #3
      }

Ignore any request that starts with "/resources/". This is similar to configuring http@security=none when using the XML namespace configuration.

Is the Javascript date object always one day off?

nevermind, didn't notice the GMT -0400, wich causes the date to be yesterday

You could try to set a default "time" to be 12:00:00

iOS detect if user is on an iPad

Be Careful: If your app is targeting iPhone device only, iPad running with iphone compatible mode will return false for below statement:

#define IPAD     UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad

The right way to detect physical iPad device is:

#define IS_IPAD_DEVICE      ([(NSString *)[UIDevice currentDevice].model hasPrefix:@"iPad"])

This version of the application is not configured for billing through Google Play

The same will happen if your published version is not the same as the version you're testing on your phone.

For example, uploaded version is android:versionCode="1", and the version you're testing on your phone is android:versionCode="2"

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Install pip in docker

You might want to change the DNS settings of the Docker daemon. You can edit (or create) the configuration file at /etc/docker/daemon.json with the dns key, as

{
    "dns": ["your_dns_address", "8.8.8.8"]
}

In the example above, the first element of the list is the address of your DNS server. The second item is the Google’s DNS which can be used when the first one is not available.

Before proceeding, save daemon.json and restart the docker service.

sudo service docker restart

Once fixed, retry to run the build command.

Java 8 - Best way to transform a list: map or foreach?

If using 3rd Pary Libaries is ok cyclops-react defines Lazy extended collections with this functionality built in. For example we could simply write

ListX myListToParse;

ListX myFinalList = myListToParse.filter(elt -> elt != null) .map(elt -> doSomething(elt));

myFinalList is not evaluated until first access (and there after the materialized list is cached and reused).

[Disclosure I am the lead developer of cyclops-react]

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

Object reference not set to an instance of an object.

All versions of .Net:

if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)

.Net 4.0 or later:

if (String.IsNullOrWhitespace(strSearch))

What is the parameter "next" used for in Express?

Next is used to pass control to the next middleware function. If not the request will be left hanging or open.

Configuring diff tool with .gitconfig

Git offers a range of difftools pre-configured "out-of-the-box" (kdiff3, kompare, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff, ecmerge, diffuse, opendiff, p4merge and araxis), and also allows you to specify your own. To use one of the pre-configured difftools (for example, "vimdiff"), you add the following lines to your ~/.gitconfig:

[diff]
    tool = vimdiff

Now, you will be able to run "git difftool" and use your tool of choice.

Specifying your own difftool, on the other hand, takes a little bit more work, see How do I view 'git diff' output with my preferred diff tool/ viewer?

How to find pg_config path

Have same issue on mac, you probably need to

brew install postgresql

then you can run

pip install psycopg2

The brew will fix PATH issue for you

this solution works for me at least.

Groovy write to file (newline)

Might be cleaner to use PrintWriter and its method println.
Just make sure you close the writer when you're done

Converting LastLogon to DateTime format

Get-ADUser -Filter {Enabled -eq $true} -Properties Name,Manager,LastLogon | 
Select-Object Name,Manager,@{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}}

How to check a string for a special character?

You can use string.punctuation and any function like this

import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
    print "Invalid"
else:
    print "Valid"

With this line

invalidChars = set(string.punctuation.replace("_", ""))

we are preparing a list of punctuation characters which are not allowed. As you want _ to be allowed, we are removing _ from the list and preparing new set as invalidChars. Because lookups are faster in sets.

any function will return True if atleast one of the characters is in invalidChars.

Edit: As asked in the comments, this is the regular expression solution. Regular expression taken from https://stackoverflow.com/a/336220/1903116

word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"

Property '...' has no initializer and is not definitely assigned in the constructor

Just go to tsconfig.json and set

"strictPropertyInitialization": false

to get rid of the compilation error.

Otherwise you need to initialize all your variables which is a little bit annoying

GROUP_CONCAT comma separator - MySQL

Or, if you are doing a split - join:

GROUP_CONCAT(split(thing, " "), '----') AS thing_name,

You may want to inclue WITHIN RECORD, like this:

GROUP_CONCAT(split(thing, " "), '----') WITHIN RECORD AS thing_name,

from BigQuery API page

Get index of selected option with jQuery

The first methods seem to work in the browsers that I tested, but the option tags doesn't really correspond to actual elements in all browsers, so the result may vary.

Just use the selectedIndex property of the DOM element:

alert($("#dropDownMenuKategorie")[0].selectedIndex);

Update:

Since version 1.6 jQuery has the prop method that can be used to read properties:

alert($("#dropDownMenuKategorie").prop('selectedIndex'));

Using GPU from a docker container?

Recent enhancements by NVIDIA have produced a much more robust way to do this.

Essentially they have found a way to avoid the need to install the CUDA/GPU driver inside the containers and have it match the host kernel module.

Instead, drivers are on the host and the containers don't need them. It requires a modified docker-cli right now.

This is great, because now containers are much more portable.

enter image description here

A quick test on Ubuntu:

# Install nvidia-docker and nvidia-docker-plugin
wget -P /tmp https://github.com/NVIDIA/nvidia-docker/releases/download/v1.0.1/nvidia-docker_1.0.1-1_amd64.deb
sudo dpkg -i /tmp/nvidia-docker*.deb && rm /tmp/nvidia-docker*.deb

# Test nvidia-smi
nvidia-docker run --rm nvidia/cuda nvidia-smi

For more details see: GPU-Enabled Docker Container and: https://github.com/NVIDIA/nvidia-docker

Insert multiple values using INSERT INTO (SQL Server 2005)

In SQL Server 2008,2012,2014 you can insert multiple rows using a single SQL INSERT statement.

 INSERT INTO TableName ( Column1, Column2 ) VALUES
    ( Value1, Value2 ), ( Value1, Value2 )

Another way

INSERT INTO TableName (Column1, Column2 )
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2

what does the __file__ variable mean/do?

When a module is loaded from a file in Python, __file__ is set to its path. You can then use that with other functions to find the directory that the file is located in.

Taking your examples one at a time:

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

You can see the various values returned from these here:

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

and make sure you run it from different locations (such as ./text.py, ~/python/text.py and so forth) to see what difference that makes.


I just want to address some confusion first. __file__ is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.

http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.

In this case __file__ is an attribute of a module (a module object). In Python a .py file is a module. So import amodule will have an attribute of __file__ which means different things under difference circumstances.

Taken from the docs:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

In your case the module is accessing it's own __file__ attribute in the global namespace.

To see this in action try:

# file: test.py

print globals()
print __file__

And run:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

Understanding Linux /proc/id/maps

memory mapping is not only used to map files into memory but is also a tool to request RAM from kernel. These are those inode 0 entries - your stack, heap, bss segments and more

How can I change the version of npm using nvm?

By looking at www.npmjs.com/install.sh I found there is a way to install a specific version by setting an environment-variable

export npm_install="2.14.14"

Then run the download-script as described at npmjs.com:

curl -L https://www.npmjs.com/install.sh | sh

If you omit setting the npm_install variable, then it will install the the version they have marked as latest

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

That is because you are not fully qualifying your cells object. Try this

With Worksheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

Notice the DOT before Cells?

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

You should install node.js with nvm, because that way you do not have to provide superuser privileges when installing global packages (you can simply execute "npm install -g packagename" without prepending 'sudo').

Brew is fantastic for other things, however. I tend to be biased towards Bower whenever I have the option to install something with Bower.

Which is the default location for keystore/truststore of Java applications?

In Java, according to the JSSE Reference Guide, there is no default for the keystore, the default for the truststore is "jssecacerts, if it exists. Otherwise, cacerts".

A few applications use ~/.keystore as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).

I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.

internet explorer 10 - how to apply grayscale filter?

Use this jQuery plugin https://gianlucaguarini.github.io/jQuery.BlackAndWhite/

That seems to be the only one cross-browser solution. Plus it has a nice fade in and fade out effect.

$('.bwWrapper').BlackAndWhite({
    hoverEffect : true, // default true
    // set the path to BnWWorker.js for a superfast implementation
    webworkerPath : false,
    // to invert the hover effect
    invertHoverEffect: false,
    // this option works only on the modern browsers ( on IE lower than 9 it remains always 1)
    intensity:1,
    speed: { //this property could also be just speed: value for both fadeIn and fadeOut
        fadeIn: 200, // 200ms for fadeIn animations
        fadeOut: 800 // 800ms for fadeOut animations
    },
    onImageReady:function(img) {
        // this callback gets executed anytime an image is converted
    }
});

Does a finally block always get executed in Java?

The finally block will not be called after return in a couple of unique scenarios: if System.exit() is called first, or if the JVM crashes.

Let me try to answer your question in the easiest possible way.

Rule 1 : The finally block always run (Though there are exceptions to it. But let's stick to this for sometime.)

Rule 2 : the statements in the finally block run when control leaves a try or a catch block.The transfer of control can occur as a result of normal execution ,of execution of a break , continue, goto or a return statement, or of a propogation of an exception.

In case of a return statement specifically (since its captioned), the control has to leave the calling method , And hence calls the finally block of the corresponding try-finally structure. The return statement is executed after the finally block.

In case there's a return statement in the finally block also, it will definitely override the one pending at the try block , since its clearing the call stack.

You can refer a better explanation here : http://msdn.microsoft.com/en-us/.... the concept is mostly same in all the high level languages.

Trying to git pull with error: cannot open .git/FETCH_HEAD: Permission denied

I had this message when using git extensions for windows. My fix was to simply close git extensions then open again as administrator

How do I replace text in a selection?

You can use ctrl+F to find the text.
ctrl+h to enter the replacement text. Then ctrl+shift+h to replace the current selected text and move to next matched text.

This is for windows. But you can check in mac also for which you might want to check the key bindings under Preferences.

jQuery bind to Paste Event, how to get the content of the paste

Another approach: That input event will catch also the paste event.

$('textarea').bind('input', function () {
    setTimeout(function () { 
        console.log('input event handled including paste event');
    }, 0);
});

IEnumerable vs List - What to Use? How do they work?

If all you want to do is enumerate them, use the IEnumerable.

Beware, though, that changing the original collection being enumerated is a dangerous operation - in this case, you will want to ToList first. This will create a new list element for each element in memory, enumerating the IEnumerable and is thus less performant if you only enumerate once - but safer and sometimes the List methods are handy (for instance in random access).

Remove leading comma from a string

You can use directly replace function on javascript with regex or define a help function as in php ltrim(left) and rtrim(right):

1) With replace:

var myArray = ",'first string','more','even more'".replace(/^\s+/, '').split(/'?,?'/);

2) Help functions:

if (!String.prototype.ltrim) String.prototype.ltrim = function() {
    return this.replace(/^\s+/, '');
};
if (!String.prototype.rtrim) String.prototype.rtrim = function() {
    return this.replace(/\s+$/, '');
};
var myArray = ",'first string','more','even more'".ltrim().split(/'?,?'/).filter(function(el) {return el.length != 0});;

You can do and other things to add parameter to the help function with what you want to replace the char, etc.

How can I find the dimensions of a matrix in Python?

Suppose you have a which is an array. to get the dimensions of an array you should use shape.

import numpy as np a = np.array([[3,20,99],[-13,4.5,26],[0,-1,20],[5,78,-19]])
a.shape

The output of this will be (4,3)

List comprehension vs. lambda + filter

I thought I'd just add that in python 3, filter() is actually an iterator object, so you'd have to pass your filter method call to list() in order to build the filtered list. So in python 2:

lst_a = range(25) #arbitrary list
lst_b = [num for num in lst_a if num % 2 == 0]
lst_c = filter(lambda num: num % 2 == 0, lst_a)

lists b and c have the same values, and were completed in about the same time as filter() was equivalent [x for x in y if z]. However, in 3, this same code would leave list c containing a filter object, not a filtered list. To produce the same values in 3:

lst_a = range(25) #arbitrary list
lst_b = [num for num in lst_a if num % 2 == 0]
lst_c = list(filter(lambda num: num %2 == 0, lst_a))

The problem is that list() takes an iterable as it's argument, and creates a new list from that argument. The result is that using filter in this way in python 3 takes up to twice as long as the [x for x in y if z] method because you have to iterate over the output from filter() as well as the original list.

Node.js: printing to console without a trailing newline?

None of these solutions work for me, process.stdout.write('ok\033[0G') and just using '\r' just create a new line but don't overwrite on Mac OSX 10.9.2.

EDIT: I had to use this to replace the current line:

process.stdout.write('\033[0G');
process.stdout.write('newstuff');

SQL Last 6 Months

select *
from tbl1
where
datetime_column >= 
DATEADD(m, -6, convert(date, convert(varchar(6), getdate(),112) + '01'))

How to get "GET" request parameters in JavaScript?

You could use jquery.url I did like this:

var xyz = jQuery.url.param("param_in_url");

Check the source code

Updated Source: https://github.com/allmarkedup/jQuery-URL-Parser

How To fix white screen on app Start up?

The white background is coming from the Apptheme.You can show something useful like your application logo instead of white screen.it can be done using custom theme.in your app Theme just add

android:windowBackground=""

attribute. The attribute value may be a image or layered list or any color.

How to sort strings in JavaScript

Answer (in Modern ECMAScript)

list.sort((a, b) => (a.attr > b.attr) - (a.attr < b.attr))

Or

list.sort((a, b) => +(a.attr > b.attr) || -(a.attr < b.attr))

Description

Casting a boolean value to a number yields the following:

  • true -> 1
  • false -> 0

Consider three possible patterns:

  • x is larger than y: (x > y) - (y < x) -> 1 - 0 -> 1
  • x is equal to y: (x > y) - (y < x) -> 0 - 0 -> 0
  • x is smaller than y: (x > y) - (y < x) -> 0 - 1 -> -1

(Alternative)

  • x is larger than y: +(x > y) || -(x < y) -> 1 || 0 -> 1
  • x is equal to y: +(x > y) || -(x < y) -> 0 || 0 -> 0
  • x is smaller than y: +(x > y) || -(x < y) -> 0 || -1 -> -1

So these logics are equivalent to typical sort comparator functions.

if (x == y) {
    return 0;
}
return x > y ? 1 : -1;

How to replace a character by a newline in Vim

You need to use:

:%s/,/^M/g

To get the ^M character, press Ctrl + v followed by Enter.

Force hide address bar in Chrome on Android

Check this has everything you need

http://www.html5rocks.com/en/mobile/fullscreen/

The Chrome team has recently implemented a feature that tells the browser to launch the page fullscreen when the user has added it to the home screen. It is similar to the iOS Safari model.

<meta name="mobile-web-app-capable" content="yes">

How to find the kth largest element in an unsorted array of length n in O(n)?

Haskell Solution:

kthElem index list = sort list !! index

withShape ~[]     []     = []
withShape ~(x:xs) (y:ys) = x : withShape xs ys

sort []     = []
sort (x:xs) = (sort ls `withShape` ls) ++ [x] ++ (sort rs `withShape` rs)
  where
   ls = filter (<  x)
   rs = filter (>= x)

This implements the median of median solutions by using the withShape method to discover the size of a partition without actually computing it.

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was just having this issue with my own program. I turned out that the value I was searching for was not in my reference table. I fixed my reference table, and then the error went away.

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Your HTTP client disconnected.

This could have a couple of reasons:

  • Responding to the request took too long, the client gave up
  • You responded with something the client did not understand
  • The end-user actually cancelled the request
  • A network error occurred
  • ... probably more

You can fairly easily emulate the behavior:

URL url = new URL("http://example.com/path/to/the/file");

int numberOfBytesToRead = 200;

byte[] buffer = new byte[numberOfBytesToRead];
int numberOfBytesRead = url.openStream().read(buffer);

HashMap with multiple values under the same key

I could not post a reply on Paul's comment so I am creating new comment for Vidhya here:

Wrapper will be a SuperClass for the two classes which we want to store as a value.

and inside wrapper class, we can put the associations as the instance variable objects for the two class objects.

e.g.

class MyWrapper {

 Class1 class1obj = new Class1();
 Class2 class2obj = new Class2();
...
}

and in HashMap we can put in this way,

Map<KeyObject, WrapperObject> 

WrapperObj will have class variables: class1Obj, class2Obj

How to determine the version of android SDK installed in computer?

C:\ <path to android sdk> \tools\source.properties (open with notepad)

There you will find it.

How to display request headers with command line curl

If you want more alternatives, You can try installing a Modern command line HTTP client like httpie which is available for most of the Operating Systems with package managers like brew, apt-get, pip, yum etc

eg:- For OSX

brew install httpie

Then you can use it on command line with various options

http GET https://www.google.com

enter image description here

No Title Bar Android Theme

In your manifest use:-

    android:theme="@style/AppTheme" >

in styles.xml:-

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
       <item name="android:windowActionBar">false</item>
   <item name="android:windowNoTitle">true</item>
</style>

Surprisingly this works as yo desire, Using the same parent of AppBaseTheme in AppTheme does not.

Is there a way to ignore a single FindBugs warning?

Update Gradle

dependencies {
    compile group: 'findbugs', name: 'findbugs', version: '1.0.0'
}

Locate the FindBugs Report

file:///Users/your_user/IdeaProjects/projectname/build/reports/findbugs/main.html

Find the specific message

find bugs

Import the correct version of the annotation

import edu.umd.cs.findbugs.annotations.SuppressWarnings;

Add the annotation directly above the offending code

@SuppressWarnings("OUT_OF_RANGE_ARRAY_INDEX")

See here for more info: findbugs Spring Annotation

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

How to convert column with dtype as object to string in Pandas Dataframe

since strings data types have variable length, it is by default stored as object dtype. If you want to store them as string type, you can do something like this.

df['column'] = df['column'].astype('|S80') #where the max length is set at 80 bytes,

or alternatively

df['column'] = df['column'].astype('|S') # which will by default set the length to the max len it encounters

GROUP BY having MAX date

Fast and easy with HAVING:

SELECT * FROM tblpm n 
FROM tblpm GROUP BY control_number 
HAVING date_updated=MAX(date_updated);

In the context of HAVING, MAX finds the max of each group. Only the latest entry in each group will satisfy date_updated=max(date_updated). If there's a tie for latest within a group, both will pass the HAVING filter, but GROUP BY means that only one will appear in the returned table.

Javascript: Call a function after specific time period

ECMAScript 6 introduced arrow functions so now the setTimeout() or setInterval() don't have to look like this:

setTimeout(function() { FetchData(); }, 1000)

Instead, you can use annonymous arrow function which looks cleaner, and less confusing:

setTimeout(() => {FetchData();}, 1000)

How to Apply Gradient to background view of iOS Swift App

SwiftUI: You can use the LinearGradient struct as the first element in a ZStack. As the "bottom" of the ZStack, it will serve as the background color. AngularGradient and RadialGradient are also available.

import SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack {
            LinearGradient(gradient: Gradient(colors: [.red, .blue]), startPoint: .top, endPoint: .bottom)
                .edgesIgnoringSafeArea(.all)
            // Put other content here; it will appear on top of the background gradient
        }
    }
}

__init__() got an unexpected keyword argument 'user'

You can't do

LivingRoom.objects.create(user=instance)

because you have an __init__ method that does NOT take user as argument.

You need something like

#signal function: if a user is created, add control livingroom to the user    
def create_control_livingroom(sender, instance, created, **kwargs):
    if created:
        my_room = LivingRoom()
        my_room.user = instance

Update

But, as bruno has already said it, Django's models.Model subclass's initializer is best left alone, or should accept *args and **kwargs matching the model's meta fields.

So, following better principles, you should probably have something like

class LivingRoom(models.Model):
    '''Living Room object'''
    user = models.OneToOneField(User)

    def __init__(self, *args, temp=65, **kwargs):
        self.temp = temp
        return super().__init__(*args, **kwargs)

Note - If you weren't using temp as a keyword argument, e.g. LivingRoom(65), then you'll have to start doing that. LivingRoom(user=instance, temp=66) or if you want the default (65), simply LivingRoom(user=instance) would do.

PHP new line break in emails

If you output to html or an html e-mail you will need to use <br> or <br /> instead of \n.

If it's just a text e-mail: Are you perhaps using ' instead of "? Although then your values would not be inserted either...

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

May be the browser will do it for you if you do something like:

Copy the div and its attributes and insert it before the old one, then move the content from the old to the new and delete the old?

What is the best way to implement "remember me" for a website?

Store their UserId and a RememberMeToken. When they login with remember me checked generate a new RememberMeToken (which invalidate any other machines which are marked are remember me).

When they return look them up by the remember me token and make sure the UserId matches.

error: pathspec 'test-branch' did not match any file(s) known to git

When I run git branch, it only shows *master, not the remaining two branches.

git branch doesn't list test_branch, because no such local branch exist in your local repo, yet. When cloning a repo, only one local branch (master, here) is created and checked out in the resulting clone, irrespective of the number of branches that exist in the remote repo that you cloned from. At this stage, test_branch only exist in your repo as a remote-tracking branch, not as a local branch.

And when I run

git checkout test-branch

I get the following error [...]

You must be using an "old" version of Git. In more recent versions (from v1.7.0-rc0 onwards),

If <branch> is not found but there does exist a tracking branch in exactly one remote (call it <remote>) with a matching name, treat [git checkout <branch>] as equivalent to

$ git checkout -b <branch> --track <remote>/<branch>

Simply run

git checkout -b test_branch --track origin/test_branch

instead. Or update to a more recent version of Git.

Formatting text in a TextBlock

a good site, with good explanations:

http://www.wpf-tutorial.com/basic-controls/the-textblock-control-inline-formatting/

here the author gives you good examples for what you are looking for! Overal the site is great for research material plus it covers a great deal of options you have in WPF

Edit

There are different methods to format the text. for a basic formatting (the easiest in my opinion):

    <TextBlock Margin="10" TextWrapping="Wrap">
                    TextBlock with <Bold>bold</Bold>, <Italic>italic</Italic> and <Underline>underlined</Underline> text.
    </TextBlock>

Example 1 shows basic formatting with Bold Itallic and underscored text.

Following includes the SPAN method, with this you van highlight text:

   <TextBlock Margin="10" TextWrapping="Wrap">
                    This <Span FontWeight="Bold">is</Span> a
                    <Span Background="Silver" Foreground="Maroon">TextBlock</Span>
                    with <Span TextDecorations="Underline">several</Span>
                    <Span FontStyle="Italic">Span</Span> elements,
                    <Span Foreground="Blue">
                            using a <Bold>variety</Bold> of <Italic>styles</Italic>
                    </Span>.
   </TextBlock>

Example 2 shows the span function and the different possibilities with it.

For a detailed explanation check the site!

Examples

create table with sequence.nextval in oracle

You can use Oracle's SQL Developer tool to do that (My Oracle DB version is 11). While creating a table choose Advanced option and click on the Identity Column tab at the bottom and from there choose Column Sequence. This will generate a AUTO_INCREMENT column (Corresponding Trigger and Squence) for you.

SQL exclude a column using SELECT * [except columnA] FROM tableA?

Depending on the size of your table, you can export it into Excel and transpose it to have a new table in which the columns of original table will be the rows in new table. Then take it back into your SQL database and select the rows according to the condition and insert them into another new table. Finally export this newer table to Excel and do another transpose to have your desired table and take it back to your SQL database.

Not sure if tranpose can be done within SQL database, if yes then it will be even easier.

Jeff

How to run Unix shell script from Java code?

This is a late answer. However, I thought of putting the struggle I had to bear to get a shell script to be executed from a Spring-Boot application for future developers.

  1. I was working in Spring-Boot and I was not able to find the file to be executed from my Java application and it was throwing FileNotFoundFoundException. I had to keep the file in the resources directory and had to set the file to be scanned in pom.xml while the application was being started like the following.

    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
                <include>**/*.sh</include>
            </includes>
        </resource>
    </resources>
    
  2. After that I was having trouble executing the file and it was returning error code = 13, Permission Denied. Then I had to make the file executable by running this command - chmod u+x myShellScript.sh

Finally, I could execute the file using the following code snippet.

public void runScript() {
    ProcessBuilder pb = new ProcessBuilder("src/main/resources/myFile.sh");
    try {
        Process p;
        p = pb.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Hope that solves someone's problem.

Convert string to hex-string in C#

First you'll need to get it into a byte[], so do this:

byte[] ba = Encoding.Default.GetBytes("sample");

and then you can get the string:

var hexString = BitConverter.ToString(ba);

now, that's going to return a string with dashes (-) in it so you can then simply use this:

hexString = hexString.Replace("-", "");

to get rid of those if you want.

NOTE: you could use a different Encoding if you needed to.

"Proxy server connection failed" in google chrome

Try following these steps:

  1. Run Chrome as Administrator.
  2. Go to the settings in Chrome.
  3. Go to Advanced Settings (its all the way down).
  4. Scroll to Network Section and click on ''Change proxy settings''.
  5. A window will pop up with the name ''Internet Properties''
  6. Click on ''LAN settings''
  7. Un-check ''Use a proxy server for your LAN''
  8. Check ''Automatically detect settings''
  9. Click everything ''OK'' and you are done!

How do I delete an exported environment variable?

Walkthrough of creating and deleting an environment variable in bash:

Test if the DUALCASE variable exists:

el@apollo:~$ env | grep DUALCASE
el@apollo:~$ 

It does not, so create the variable and export it:

el@apollo:~$ DUALCASE=1
el@apollo:~$ export DUALCASE

Check if it is there:

el@apollo:~$ env | grep DUALCASE
DUALCASE=1

It is there. So get rid of it:

el@apollo:~$ unset DUALCASE

Check if it's still there:

el@apollo:~$ env | grep DUALCASE
el@apollo:~$ 

The DUALCASE exported environment variable is deleted.

Extra commands to help clear your local and environment variables:

Unset all local variables back to default on login:

el@apollo:~$ CAN="chuck norris"
el@apollo:~$ set | grep CAN
CAN='chuck norris'
el@apollo:~$ env | grep CAN
el@apollo:~$
el@apollo:~$ exec bash
el@apollo:~$ set | grep CAN
el@apollo:~$ env | grep CAN
el@apollo:~$

exec bash command cleared all the local variables but not environment variables.

Unset all environment variables back to default on login:

el@apollo:~$ export DOGE="so wow"
el@apollo:~$ env | grep DOGE
DOGE=so wow
el@apollo:~$ env -i bash
el@apollo:~$ env | grep DOGE
el@apollo:~$

env -i bash command cleared all the environment variables to default on login.

Where is GACUTIL for .net Framework 4.0 in windows 7?

There is no Gacutil included in the .net 4.0 standard installation. They have moved the GAC too, from %Windir%\assembly to %Windir%\Microsoft.NET\Assembly.

They havent' even bothered adding a "special view" for the folder in Windows explorer, as they have for the .net 1.0/2.0 GAC.

Gacutil is part of the Windows SDK, so if you want to use it on your developement machine, just install the Windows SDK for your current platform. Then you will find it somewhere like this (depending on your SDK version):

C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools

There is a discussion on the new GAC here: .NET 4.0 has a new GAC, why?

If you want to install something in GAC on a production machine, you need to do it the "proper" way (gacutil was never meant as a tool for installing stuff on production servers, only as a development tool), with a Windows Installer, or with other tools. You can e.g. do it with PowerShell and the System.EnterpriseServices dll.

On a general note, and coming from several years of experience, I would personally strongly recommend against using GAC at all. Your application will always work if you deploy the DLL with each application in its bin folder as well. Yes, you will get multiple copies of the DLL on your server if you have e.g. multiple web apps on one server, but it's definitely worth the flexibility of being able to upgrade one application without breaking the others (by introducing an incompatible version of the shared DLL in the GAC).

Click through div to underlying elements

Yes, you CAN force overlapping layers to pass through (ignore) click events.
PLUS you CAN have specific children excluded from this behavior...

You can do this, using pointer-events

pointer-events influences the reaction to click-, tap-, scroll- und hover events.


In a layer that should ignore / pass-through mentioned events you set

pointer-events: none; 

Children of that unresponsive layer that need to react mouse / tap events again need:

pointer-events: auto; 

That second part is very helpful if you work with multiple overlapping div layers (probably some parents being transparent), where you need to be able to click on child elements and only that child elements.

Example usage:

    <style>
        .parent {
            pointer-events:none;        
        }
        .child {
            pointer-events:auto;
        }
    </style>
    
    <div class="parent">
      <a href="#">I'm unresponsive</a>
      <a href="#" class="child">I'm clickable again, wohoo !</a>
    </div>

How to enable curl in Wamp server

The steps are as follows :

  1. Close WAMP (if running)
  2. Navigate to WAMP\bin\php\(your version of php)\
  3. Edit php.ini
  4. Search for curl, uncomment extension=php_curl.dll
  5. Navigate to WAMP\bin\Apache\(your version of apache)\bin\
  6. Edit php.ini
  7. Search for curl, uncomment extension=php_curl.dll
  8. Save both
  9. Restart WAMP

How can I add a new column and data to a datatable that already contains data?

Here is an alternate solution to reduce For/ForEach looping, this would reduce looping time and updates quickly :)

 dt.Columns.Add("MyRow", typeof(System.Int32));
 dt.Columns["MyRow"].Expression = "'0'";

IIS Manager in Windows 10

Launch Windows Features On/Off and select your IIS options for installation.

For custom site configuration, ensure IIS Management Console is marked for installation under Web Management Tools.

String formatting in Python 3

I like this approach

my_hash = {}
my_hash["goals"] = 3 #to show number
my_hash["penalties"] = "5" #to show string
print("I scored %(goals)d goals and took %(penalties)s penalties" % my_hash)

Note the appended d and s to the brackets respectively.

output will be:

I scored 3 goals and took 5 penalties

Linux command (like cat) to read a specified quantity of characters

you could also grep the line out and then cut it like for instance:

grep 'text' filename | cut -c 1-5

NPM global install "cannot find module"

add this to beginning of prog(mac):

module.paths.push('/usr/local/lib/node_modules');

Build fails with "Command failed with a nonzero exit code"

I got the same error when linking separate storyboards. The error, "Command CompileSwiftSources failed with a nonzero exit code." is shown because I simply forgot to set the view controller inside the second storyboard that I am linking as 'an initial view controller'.

You cannot call a method on a null-valued expression

The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code

$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider

The error was because you are trying to execute a method that does not exist.

PS C:\Users\Matt> $md5 | gm


   TypeName: System.Security.Cryptography.MD5CryptoServiceProvider

Name                       MemberType Definition                                                                                                                            
----                       ---------- ----------                                                                                                                            
Clear                      Method     void Clear()                                                                                                                          
ComputeHash                Method     byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...

The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.

PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PowerShell by default allows this to happen as defined its StrictMode

When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

SQL Server ORDER BY date and nulls last

Use desc and multiply by -1 if necessary. Example for ascending int ordering with nulls last:

select * 
from
(select null v union all select 1 v union all select 2 v) t
order by -t.v desc

How do I get the full url of the page I am on in C#

I usually use Request.Url.ToString() to get the full url (including querystring), no concatenation required.

Can you Run Xcode in Linux?

If you really want to use Xcode on linux you could get Virtual Box and install Hackintosh on a VM. Edit: Virtual Box Guest Additions is not supported with MacOS Movaje. You will want to use VMware

https://www.vmware.com/

https://hackintosh.com/

How do I search for names with apostrophe in SQL Server?

Double them to escape;

SELECT *
  FROM Header
 WHERE userID LIKE '%''%'

jQuery hover and class selector

test.html

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <title>jQuery Test</title>
        <link rel="stylesheet" type="text/css" href="test.css" />
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="test.js"></script>
    </head>
    <body>
        <div id="menu">
            <div class="menuItem"><a href=#>Bla</a></div>
            <div class="menuItem"><a href=#>Bla</a></div>
            <div class="menuItem"><a href=#>Bla</a></div>
        </div>
    </body>
</html>

test.css

.menuItem
{

    display: inline;
    height: 30px;
    width: 100px;
    background-color: #000;

}

test.js

$( function(){

    $('.menuItem').hover( function(){

        $(this).css('background-color', '#F00');

    },
    function(){

        $(this).css('background-color', '#000');

    });

});

Works :-)

Full path from file input using jQuery

You can't: It's a security feature in all modern browsers.

For IE8, it's off by default, but can be reactivated using a security setting:

When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object.

The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.

In all other current mainstream browsers I know of, it is also turned off. The file name is the best you can get.

More detailed info and good links in this question. It refers to getting the value server-side, but the issue is the same in JavaScript before the form's submission.

How do I wrap text in a span?

I've got a solution that should work in IE6 (and definitely works in 7+ & FireFox/Chrome).
You were on the right track using a span, but the use of a ul was wrong and the css wasn't right.

Try this

<a class="htooltip" href="#">
    Notes

    <span>
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci.
    </span>
</a>
.htooltip, .htooltip:visited, .tooltip:active {
    color: #0077AA;
    text-decoration: none;
}

.htooltip:hover {
    color: #0099CC;
}

.htooltip span {
    display : none;
    position: absolute;
    background-color: black;
    color: #fff;
    padding: 5px 10px 5px 40px;
    text-decoration: none;
    width: 350px;
    z-index: 10;
}

.htooltip:hover span {
    display: block;
}

Everyone was going about this the wrong way. The code isn't valid, ul's cant go in a's, p's can't go in a's, div's cant go in a's, just use a span (remembering to make it display as a block so it will wrap as if it were a div/p etc).

Put byte array to JSON and vice versa

Amazingly now org.json now lets you put a byte[] object directly into a json and it remains readable. you can even send the resulting object over a websocket and it will be readable on the other side. but i am not sure yet if the size of the resulting object is bigger or smaller than if you were converting your byte array to base64, it would certainly be neat if it was smaller.

It seems to be incredibly hard to measure how much space such a json object takes up in java. if your json consists merely of strings it is easily achievable by simply stringifying it but with a bytearray inside it i fear it is not as straightforward.

stringifying our json in java replaces my bytearray for a 10 character string that looks like an id. doing the same in node.js replaces our byte[] for an unquoted value reading <Buffered Array: f0 ff ff ...> the length of the latter indicates a size increase of ~300% as would be expected

"Couldn't read dependencies" error with npm

I figured out I wasn't in the correct folder. I needed goto the folder I just cloned before I ran this command.

Joining two table entities in Spring Data JPA

@Query("SELECT rd FROM ReleaseDateType rd, CacheMedia cm WHERE ...")

Remove URL parameters without refreshing page

To clear out all the parameters, without doing a page refresh, AND if you are using HTML5, then you can do this:

history.pushState({}, '', 'index.html' ); //replace 'index.html' with whatever your page name is

This will add an entry in the browser history. You could also consider replaceState if you don't wan't to add a new entry and just want to replace the old entry.

stringstream, string, and char* conversion confusion

stringstream.str() returns a temporary string object that's destroyed at the end of the full expression. If you get a pointer to a C string from that (stringstream.str().c_str()), it will point to a string which is deleted where the statement ends. That's why your code prints garbage.

You could copy that temporary string object to some other string object and take the C string from that one:

const std::string tmp = stringstream.str();
const char* cstr = tmp.c_str();

Note that I made the temporary string const, because any changes to it might cause it to re-allocate and thus render cstr invalid. It is therefor safer to not to store the result of the call to str() at all and use cstr only until the end of the full expression:

use_c_str( stringstream.str().c_str() );

Of course, the latter might not be easy and copying might be too expensive. What you can do instead is to bind the temporary to a const reference. This will extend its lifetime to the lifetime of the reference:

{
  const std::string& tmp = stringstream.str();   
  const char* cstr = tmp.c_str();
}

IMO that's the best solution. Unfortunately it's not very well known.

What is the difference between .yaml and .yml extension?

File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml, .yaml or indeed anything else.

The (rather sparse) YAML FAQ recommends that you use .yaml in preference to .yml, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml instead.

So, what really matters is what is inside the file, rather than what its extension is.

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

Create a new "Empty Project" , Add your Cpp file to the new project, delete the line that includes stdafx.

Done.

The project no longer needs the stdafx. It is added automatically when you create projects with installed templates. enter image description here

Creating a SearchView that looks like the material design guidelines

Here's my attempt at doing this:

Step 1: Create a style named SearchViewStyle

<style name="SearchViewStyle" parent="Widget.AppCompat.SearchView">
    <!-- Gets rid of the search icon -->
    <item name="searchIcon">@drawable/search</item>
    <!-- Gets rid of the "underline" in the text -->
    <item name="queryBackground">@null</item>
    <!-- Gets rid of the search icon when the SearchView is expanded -->
    <item name="searchHintIcon">@null</item>
    <!-- The hint text that appears when the user has not typed anything -->
    <item name="queryHint">@string/search_hint</item>
</style>

Step 2: Create a layout named simple_search_view_item.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.SearchView
    android:layout_gravity="end"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    style="@style/SearchViewStyle"
    xmlns:android="http://schemas.android.com/apk/res/android" />  

Step 3: Create a menu item for this search view

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        app:actionLayout="@layout/simple_search_view_item"
        android:title="@string/search"
        android:icon="@drawable/search"
        app:showAsAction="always" />
</menu>  

Step 4: Inflate the menu

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_searchable_activity, menu);
    return true;
}  

Result:

enter image description here

The only thing I wasn't able to do was to make it fill the entire width of the Toolbar. If someone could help me do that then that'd be golden.

Proper usage of .net MVC Html.CheckBoxFor

I had trouble getting this to work and added another solution for anyone wanting/ needing to use FromCollection.

Instead of:

@Html.CheckBoxFor(model => true, item.TemplateId) 

Format html helper like so:

@Html.CheckBoxFor(model => model.SomeProperty, new { @class = "form-control", Name = "SomeProperty"})

Then in the viewmodel/model wherever your logic is:

public void Save(FormCollection frm)
{   
    // to do instantiate object.

    instantiatedItem.SomeProperty = (frm["SomeProperty"] ?? "").Equals("true", StringComparison.CurrentCultureIgnoreCase);

    // to do and save changes in database.
}

Font Awesome not working, icons showing as squares

The /css/all.css file contains the core styling plus all of the icon styles that you’ll need when using Font Awesome. The /webfonts folder contains all of the typeface files that the above CSS references and depends on.

Copy the entire /webfonts folder and the /css/all.css into your project’s static assets directory (or where ever you prefer to keep front end assets or vendor stuff).

Add a reference to the copied /css/all.css file into the of each template or page that you want to use Font Awesome on.

Just Visit - https://fontawesome.com/how-to-use/on-the-web/setup/hosting-font-awesome-yourself You will get the answer.

Convert the first element of an array to a string in PHP

Is there any other way to convert that array into string ?

You don't want to convert the array to a string, you want to get the value of the array's sole element, if I read it correctly.

<?php
  $foo = array( 18 => 'Something' );
  $value = array_shift( $foo );
  echo $value; // 'Something'.

?>

Using array_shift you don't have to worry about the index.

EDIT: Mind you, array_shift is not the only function that will return a single value. array_pop( ), current( ), end( ), reset( ), they will all return that one single element. All of the posted solutions work. Using array shift though, you can be sure that you'll only ever get the first value of the array, even when there are multiple.

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

This is because after the nextInt() finished it's execution, when the nextLine() method is called, it scans the newline character of which was present after the nextInt(). You can do this in either of the following ways:

  1. You can use another nextLine() method just after the nextInt() to move the scanner past the newline character.
  2. You can use different Scanner objects for scanning the integer and string (You can name them scan1 and scan2).
  3. You can use the next method on the scanner object as

    scan.next();

How to create a floating action button (FAB) in android, using AppCompat v21?

@Justin Pollard xml code works really good. As a side note you can add a ripple effect with the following xml lines.

    <item>
    <ripple
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="?android:colorControlHighlight" >
        <item android:id="@android:id/mask">
            <shape android:shape="oval" >
                <solid android:color="#FFBB00" />
            </shape>
        </item>
        <item>
            <shape android:shape="oval" >
                <solid android:color="@color/ColorPrimary" />
            </shape>
        </item>
    </ripple>
</item>

How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

Firebase Cloud Messaging has a server-side APIs that you can call to send messages. See https://firebase.google.com/docs/cloud-messaging/server.

Sending a message can be as simple as using curl to call a HTTP end-point. See https://firebase.google.com/docs/cloud-messaging/server#implementing-http-connection-server-protocol

curl -X POST --header "Authorization: key=<API_ACCESS_KEY>" \
    --Header "Content-Type: application/json" \
    https://fcm.googleapis.com/fcm/send \
    -d "{\"to\":\"<YOUR_DEVICE_ID_TOKEN>\",\"notification\":{\"title\":\"Hello\",\"body\":\"Yellow\"}}"

Displaying tooltip on mouse hover of a text

Use:

ToolTip tip = new ToolTip();
private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
{
    Cursor a = System.Windows.Forms.Cursor.Current;
    if (a == Cursors.Hand)
    {
        Point p = richTextBox1.Location;
        tip.Show(
            GetWord(richTextBox1.Text,
                richTextBox1.GetCharIndexFromPosition(e.Location)),
            this,
            p.X + e.X,
            p.Y + e.Y + 32,
            1000);
    }
}

Use the GetWord function from my other answer to get the hovered word. Use timer logic to disable reshow the tooltip as in prev. example.

In this example right above, the tool tip shows the hovered word by checking the mouse pointer.

If this answer is still not what you are looking fo, please specify the condition that characterizes the word you want to use tooltip on. If you want it for bolded word, please tell me.

How do you add an in-app purchase to an iOS application?

RMStore is a lightweight iOS library for In-App Purchases. It wraps StoreKit API and provides you with handy blocks for asynchronous requests. Purchasing a product is as easy as calling a single method.

For the advanced users, this library also provides receipt verification, content downloads and transaction persistence.

How can I assign the output of a function to a variable using bash?

I think init_js should use declare instead of local!

function scan3() {
    declare -n outvar=$1    # -n makes it a nameref.
    local nl=$'\x0a'
    outvar="output${nl}${nl}"  # two total. quotes preserve newlines
}