Programs & Examples On #Idle processing

Using a PagedList with a ViewModel ASP.Net MVC

The fact that you're using a view model has no bearing. The standard way of using PagedList is to store "one page of items" as a ViewBag variable. All you have to determine is what collection constitutes what you'll be paging over. You can't logically page multiple collections at the same time, so assuming you chose Instructors:

ViewBag.OnePageOfItems = myViewModelInstance.Instructors.ToPagedList(pageNumber, 10);

Then, the rest of the standard code works as it always has.

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.

How do I convert a string to a double in Python?

>>> x = "2342.34"
>>> float(x)
2342.3400000000001

There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).

How do you do relative time in Rails?

Something like this would work.

def relative_time(start_time)
  diff_seconds = Time.now - start_time
  case diff_seconds
    when 0 .. 59
      puts "#{diff_seconds} seconds ago"
    when 60 .. (3600-1)
      puts "#{diff_seconds/60} minutes ago"
    when 3600 .. (3600*24-1)
      puts "#{diff_seconds/3600} hours ago"
    when (3600*24) .. (3600*24*30) 
      puts "#{diff_seconds/(3600*24)} days ago"
    else
      puts start_time.strftime("%m/%d/%Y")
  end
end

Android selector & text color

In res/color place a file "text_selector.xml":

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/blue" android:state_focused="true" />
    <item android:color="@color/blue" android:state_selected="true" />
    <item android:color="@color/green" />
</selector>

Then in TextView use it:

<TextView
    android:id="@+id/value_1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Text"
    android:textColor="@color/text_selector"
    android:textSize="15sp"
    />

And in code you'll need to set a click listener.

private var isPressed = false

private fun TextView.setListener() {
    this.setOnClickListener { v ->
        run {
            if (isPressed) {
                v.isSelected = false
                v.clearFocus()
            } else {
                v.isSelected = true
                v.requestFocus()
            }
            isPressed = !isPressed
        }
    }
}

override fun onResume() {
    super.onResume()
    textView.setListener()
}

override fun onPause() {
    textView.setOnClickListener(null)
    super.onPause()
}

Sorry if there are errors, I changed a code before publishing and didn't check.

how to get last insert id after insert query in codeigniter active record

because you have initiated the Transaction over the data insertion so, The first check the transaction completed or not. once you start the transaction, it should be committed or rollback according to the status of the transaction;

function add_post($post_data){
  $this->db->trans_begin() 
  $this->db->insert('posts',$post_data);
  $this->db->trans_complete();
  if ($this->db->trans_status() === FALSE){
    $this->db->trans_rollback();
    return 0;
  }else{
    $this->db->trans_commit();
    return $this->db->insert_id();
  }
}``

in the above, we have committed the data on the successful transaction even you get the timestamp

React setState not updating state

In case of hooks, you should use useEffect hook.

const [fruit, setFruit] = useState('');

setFruit('Apple');

useEffect(() => {
  console.log('Fruit', fruit);
}, [fruit])

Best way to generate xml?

Use lxml.builder class, from: http://lxml.de/tutorial.html#the-e-factory

import lxml.builder as lb
from lxml import etree

nstext = "new story"
story = lb.E.Asset(
  lb.E.Attribute(nstext, name="Name", act="set"),
  lb.E.Relation(lb.E.Asset(idref="Scope:767"),
            name="Scope", act="set")
  )

print 'story:\n', etree.tostring(story, pretty_print=True)

Output:

story:
<Asset>
  <Attribute name="Name" act="set">new story</Attribute>
  <Relation name="Scope" act="set">
    <Asset idref="Scope:767"/>
  </Relation>
</Asset>

Add a property to a JavaScript object using a variable as the name?

With ECMAScript 2015 you can do it directly in object declaration using bracket notation:

var obj = {
  [key]: value
}

Where key can be any sort of expression (e.g. a variable) returning a value:

var obj = {
  ['hello']: 'World',
  [x + 2]: 42,
  [someObject.getId()]: someVar
}

BackgroundWorker vs background Thread

You know, sometimes it's just easier to work with a BackgroundWorker regardless of if you're using Windows Forms, WPF or whatever technology. The neat part about these guys is you get threading without having to worry too much about where you're thread is executing, which is great for simple tasks.

Before using a BackgroundWorker consider first if you wish to cancel a thread (closing app, user cancellation) then you need to decide if your thread should check for cancellations or if it should be thrust upon the execution itself.

BackgroundWorker.CancelAsync() will set CancellationPending to true but won't do anything more, it's then the threads responsibility to continually check this, keep in mind also that you could end up with a race condition in this approach where your user cancelled, but the thread completed prior to testing for CancellationPending.

Thread.Abort() on the other hand will throw an exception within the thread execution which enforces cancellation of that thread, you must be careful about what might be dangerous if this exception was suddenly raised within the execution though.

Threading needs very careful consideration no matter what the task, for some further reading:

Parallel Programming in the .NET Framework Managed Threading Best Practices

adding comment in .properties files

The property file task is for editing properties files. It contains all sorts of nice features that allow you to modify entries. For example:

<propertyfile file="build.properties">
    <entry key="build_number"
        type="int"
        operation="+"
        value="1"/>
</propertyfile>

I've incremented my build_number by one. I have no idea what the value was, but it's now one greater than what it was before.

  • Use the <echo> task to build a property file instead of <propertyfile>. You can easily layout the content and then use <propertyfile> to edit that content later on.

Example:

<echo file="build.properties">
# Default Configuration
source.dir=1
dir.publish=1
# Source Configuration
dir.publish.html=1
</echo>
  • Create separate properties files for each section. You're allowed a comment header for each type. Then, use to batch them together into one single file:

Example:

<propertyfile file="default.properties"
    comment="Default Configuration">
    <entry key="source.dir" value="1"/>
    <entry key="dir.publish" value="1"/>
<propertyfile>

<propertyfile file="source.properties"
    comment="Source Configuration">
    <entry key="dir.publish.html" value="1"/>
<propertyfile>
<concat destfile="build.properties">
    <fileset dir="${basedir}">
        <include name="default.properties"/>
        <include name="source.properties"/>
    </fileset>
</concat>

<delete>
    <fileset dir="${basedir}">
         <include name="default.properties"/>
        <include name="source.properties"/>
    </fileset>
</delete>      

Ternary operator in PowerShell

Since a ternary operator is usually used when assigning value, it should return a value. This is the way that can work:

$var=@("value if false","value if true")[[byte](condition)]

Stupid, but working. Also this construction can be used to quickly turn an int into another value, just add array elements and specify an expression that returns 0-based non-negative values.

How do I specify the exit code of a console application in .NET?

Just an another way:

public static class ApplicationExitCodes
{
    public static readonly int Failure = 1;
    public static readonly int Success = 0;
}

How do I decompile a .NET EXE into readable C# source code?

Reflector is no longer free in general, but they do offer it for free to open source developers: http://reflectorblog.red-gate.com/2013/07/open-source/

But a few companies like DevExtras and JetBrains have created free alternatives:

DevExtras CodeReflect

JetBrains DotPeek

Comparing two arrays & get the values which are not common

PS > $c = Compare-Object -ReferenceObject (1..5) -DifferenceObject (1..6) -PassThru
PS > $c
6

How to return history of validation loss in Keras

Another option is CSVLogger: https://keras.io/callbacks/#csvlogger. It creates a csv file appending the result of each epoch. Even if you interrupt training, you get to see how it evolved.

background-image: url("images/plaid.jpg") no-repeat; wont show up

You either use :

background-image: url("images/plaid.jpg");
background-repeat: no-repeat;

... or

background: transparent url("images/plaid.jpg") top left no-repeat;

... but definitively not

background-image: url("images/plaid.jpg") no-repeat;

EDIT : Demo at JSFIDDLE using absolute paths (in case you have troubles referring to your images with relative paths).

How to convert any date format to yyyy-MM-dd

string DateString = "11/12/2009";
IFormatProvider culture = new CultureInfo("en-US", true); 
DateTime dateVal = DateTime.ParseExact(DateString, "yyyy-MM-dd", culture);

These Links might also Help you

DateTime.ToString() Patterns

String Format for DateTime [C#]

NLS_NUMERIC_CHARACTERS setting for decimal

Jaanna, the session parameters in Oracle SQL Developer are dependent on your client computer, while the NLS parameters on PL/SQL is from server.

For example the NLS_NUMERIC_CHARACTERS on client computer can be ',.' while it's '.,' on server.

So when you run script from PL/SQL and Oracle SQL Developer the decimal separator can be completely different for the same script, unless you alter session with your expected NLS_NUMERIC_CHARACTERS in the script.

One way to easily test your session parameter is to do:

select to_number(5/2) from dual;

Remove last character from C++ string

str.erase(str.begin() + str.size() - 1)

str.erase(str.rbegin()) does not compile unfortunately, since reverse_iterator cannot be converted to a normal_iterator.

C++11 is your friend in this case.

Example of multipart/form-data

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l or an ECHO server and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

Print multiple arguments in Python

print("Total score for %s is %s  " % (name, score))

%s can be replace by %d or %f

How to configure socket connect timeout

I just wrote an extension class in order to allow timeouts in connections. Use it exactly as you would use the standard Connect() methods, with an extra parameter named timeout.

using System;
using System.Net;
using System.Net.Sockets;

/// <summary>
/// Extensions to Socket class
/// </summary>
public static class SocketExtensions
{
    /// <summary>
    /// Connects the specified socket.
    /// </summary>
    /// <param name="socket">The socket.</param>
    /// <param name="host">The host.</param>
    /// <param name="port">The port.</param>
    /// <param name="timeout">The timeout.</param>
    public static void Connect(this Socket socket, string host, int port, TimeSpan timeout)
    {
        AsyncConnect(socket, (s, a, o) => s.BeginConnect(host, port, a, o), timeout);
    }

    /// <summary>
    /// Connects the specified socket.
    /// </summary>
    /// <param name="socket">The socket.</param>
    /// <param name="addresses">The addresses.</param>
    /// <param name="port">The port.</param>
    /// <param name="timeout">The timeout.</param>
    public static void Connect(this Socket socket, IPAddress[] addresses, int port, TimeSpan timeout)
    {
        AsyncConnect(socket, (s, a, o) => s.BeginConnect(addresses, port, a, o), timeout);
    }

    /// <summary>
    /// Asyncs the connect.
    /// </summary>
    /// <param name="socket">The socket.</param>
    /// <param name="connect">The connect.</param>
    /// <param name="timeout">The timeout.</param>
    private static void AsyncConnect(Socket socket, Func<Socket, AsyncCallback, object, IAsyncResult> connect, TimeSpan timeout)
    {
        var asyncResult = connect(socket, null, null);
        if (!asyncResult.AsyncWaitHandle.WaitOne(timeout))
        {
            try
            {
                socket.EndConnect(asyncResult);
            }
            catch (SocketException)
            { }
            catch (ObjectDisposedException)
            { }
        }
    }

PHP import Excel into database (xls & xlsx)

This is best plugin with proper documentation and examples

https://github.com/PHPOffice/PHPExcel

Plus point: you can ask for help in its discussion forum and you will get response within a day from the author itself, really impressive.

Extract a part of the filepath (a directory) in Python

You have to put the entire path as a parameter to os.path.split. See The docs. It doesn't work like string split.

setTimeout in for-loop does not print consecutive values

You can use the extra arguments to setTimeout to pass parameters to the callback function.

for (var i = 1; i <= 2; i++) {
    setTimeout(function(j) { alert(j) }, 100, i);
}

Note: This doesn't work on IE9 and below browsers.

Unmount the directory which is mounted by sshfs in Mac

Just for reference I found this worked for me.

diskutil unmount /path/to/directory/

When I used the umount command I got an error that recommended this diskutil command.

Node.js: Gzip compression?

For compressing the file you can use below code

var fs = require("fs");
var zlib = require('zlib');
fs.createReadStream('input.txt').pipe(zlib.createGzip())
.pipe(fs.createWriteStream('input.txt.gz'));
console.log("File Compressed.");

For decompressing the same file you can use below code

var fs = require("fs");
var zlib = require('zlib');
fs.createReadStream('input.txt.gz')
.pipe(zlib.createGunzip())
.pipe(fs.createWriteStream('input.txt'));
console.log("File Decompressed.");

What Java ORM do you prefer, and why?

Eclipse Link, for many reasons, but notably I feel like it has less bloat than other main stream solutions (at least less in-your-face bloat).

Oh and Eclipse Link has been chosen to be the reference implementation for JPA 2.0

Select where count of one field is greater than one

Use the HAVING, not WHERE clause, for aggregate result comparison.

Taking the query at face value:

SELECT * 
  FROM db.table 
HAVING COUNT(someField) > 1

Ideally, there should be a GROUP BY defined for proper valuation in the HAVING clause, but MySQL does allow hidden columns from the GROUP BY...

Is this in preparation for a unique constraint on someField? Looks like it should be...

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

To track down the correct parameters you need to go first to ?plot.default, which refers you to ?par and ?axis:

plot(1, 1 ,xlab="x axis", ylab="y axis",  pch=19,
           col.lab="red", cex.lab=1.5,    #  for the xlab and ylab
           col="green")                   #  for the points

Show / hide div on click with CSS

CSS does not have an onlclick event handler. You have to use Javascript.

See more info here on CSS Pseudo-classes: http://www.w3schools.com/css/css_pseudo_classes.asp

a:link {color:#FF0000;}    /* unvisited link - link is untouched */
a:visited {color:#00FF00;} /* visited link - user has already been to this page */
a:hover {color:#FF00FF;}   /* mouse over link - user is hovering over the link with the mouse or has selected it with the keyboard */
a:active {color:#0000FF;}  /* selected link - the user has clicked the link and the browser is loading the new page */

How to access single elements in a table in R

That is so basic that I am wondering what book you are using to study? Try

data[1, "V1"]  # row first, quoted column name second, and case does matter

Further note: Terminology in discussing R can be crucial and sometimes tricky. Using the term "table" to refer to that structure leaves open the possibility that it was either a 'table'-classed, or a 'matrix'-classed, or a 'data.frame'-classed object. The answer above would succeed with any of them, while @BenBolker's suggestion below would only succeed with a 'data.frame'-classed object.

I am unrepentant in my phrasing despite the recent downvote. There is a ton of free introductory material for beginners in R: https://cran.r-project.org/other-docs.html

How to remove CocoaPods from a project?

If you just want to remove one pod and keep others you may have installed, open the podfile in your app directory and delete the one you want to remove. Then navigate to your app directory using terminal and type:

pod update

This will remove the pod you removed from the podfile. You will see it has been removed in the terminal:

Analyzing dependencies
Removing FirebaseUI
Removing UICircularProgressRing

Note that this method will also pull any updates to the other pods in your podfile. You may or may not want that.

Object of class DateTime could not be converted to string

$Date = $row['Received_date']->format('d/m/Y');

then it cast date object from given in database

How can I combine multiple rows into a comma-delimited list in Oracle?

I have always had to write some PL/SQL for this or I just concatenate a ',' to the field and copy into an editor and remove the CR from the list giving me the single line.

That is,

select country_name||', ' country from countries

A little bit long winded both ways.

If you look at Ask Tom you will see loads of possible solutions but they all revert to type declarations and/or PL/SQL

Ask Tom

Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED

You have to install redis server first;

You can install redis server on mac by following step -

  $ curl -O http://download.redis.io/redis-stable.tar.gz
  $ tar xzvf redis-stable.tar.gz
  $ cd redis-stable
  $ make
  $ make test
  $ sudo make install
  $ redis-server

Good luck.

d3 add text to circle

Here is an example showing some text in circles with data from a json file: http://bl.ocks.org/4474971. Which gives the following:

enter image description here

The main idea behind this is to encapsulate the text and the circle in the same "div" as you would do in html to have the logo and the name of the company in the same div in a page header.

The main code is:

var width = 960,
    height = 500;

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)

d3.json("data.json", function(json) {
    /* Define the data for the circles */
    var elem = svg.selectAll("g")
        .data(json.nodes)

    /*Create and place the "blocks" containing the circle and the text */  
    var elemEnter = elem.enter()
        .append("g")
        .attr("transform", function(d){return "translate("+d.x+",80)"})

    /*Create the circle for each block */
    var circle = elemEnter.append("circle")
        .attr("r", function(d){return d.r} )
        .attr("stroke","black")
        .attr("fill", "white")

    /* Create the text for each block */
    elemEnter.append("text")
        .attr("dx", function(d){return -20})
        .text(function(d){return d.label})
})

and the json file is:

{"nodes":[
  {"x":80, "r":40, "label":"Node 1"}, 
  {"x":200, "r":60, "label":"Node 2"}, 
  {"x":380, "r":80, "label":"Node 3"}
]}

The resulting html code shows the encapsulation you want:

<svg width="960" height="500">
    <g transform="translate(80,80)">
        <circle r="40" stroke="black" fill="white"></circle>
        <text dx="-20">Node 1</text>
    </g>
    <g transform="translate(200,80)">
        <circle r="60" stroke="black" fill="white"></circle>
        <text dx="-20">Node 2</text>
    </g>
    <g transform="translate(380,80)">
        <circle r="80" stroke="black" fill="white"></circle>
        <text dx="-20">Node 3</text>
    </g>
</svg>

How to assign a heredoc value to a variable in Bash?

$TEST="ok"
read MYTEXT <<EOT
this bash trick
should preserve
newlines $TEST
long live perl
EOT
echo -e $MYTEXT

Can I grep only the first n lines of a file?

grep -A 10 <Pattern>

This is to grab the pattern and the next 10 lines after the pattern. This would work well only for a known pattern, if you don't have a known pattern use the "head" suggestions.

Generating a SHA-256 hash from the Linux command line

For the sha256 hash in base64, use:

echo -n foo | openssl dgst -binary -sha1 | openssl base64

Example

echo -n foo | openssl dgst -binary -sha1 | openssl base64
C+7Hteo/D9vJXQ3UfzxbwnXaijM=

Detecting Back Button/Hash Change in URL

Use the jQuery hashchange event plugin instead. Regarding your full ajax navigation, try to have SEO friendly ajax. Otherwise your pages shown nothing in browsers with JavaScript limitations.

how to download file in react js

We can user react-download-link component to download content as File.

<DownloadLink
label="Download"
filename="fileName.txt"
exportFile={() => "Client side cache data here…"}/>

https://frugalisminds.com/how-to-download-file-in-react-js-react-download-link/

CSS / HTML Navigation and Logo on same line

You need to apply the logo class to the image...then float the ul

Codepen Demo

HTML

<img class="logo" src="http://i.imgur.com/hCrQkJi.png">

CSS

.navigation-bar ul {
  padding: 0px;
  margin: 0px;
  text-align: center;
  float: left;
  background: white;
}

Using (Ana)conda within PyCharm

this might be repetitive. I was trying to use pycharm to run flask - had anaconda 3, pycharm 2019.1.1 and windows 10. Created a new conda environment - it threw errors. Followed these steps -

  1. Used the cmd to install python and flask after creating environment as suggested above.

  2. Followed this answer.

  3. As suggested above, went to Run -> Edit Configurations and changed the environment there as well as in (2).

Obviously kept the correct python interpreter (the one in the environment) everywhere.

Calculate RSA key fingerprint

Reproducing content from AWS forums here, because I found it useful to my use case - I wanted to check which of my keys matched ones I had imported into AWS

openssl pkey -in ~/.ssh/ec2/primary.pem -pubout -outform DER | openssl md5 -c

Where:

  • primary.pem is the private key to check

Note that this gives a different fingerprint from the one computed by ssh-keygen.

Remove privileges from MySQL database

The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*.

So if you want to remove all the privileges and start totally from scratch do the following:

  • Revoke all privileges on database level:

    REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';

  • Drop the user 'phpmyadmin'@'localhost'

    DROP USER 'phpmyadmin'@'localhost';

Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.

To give you a bit background on what described above: as soon as you create a user the mysql.user table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'. If you do a show grants for 'phpmyadmin'@'localhost'; you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL to this user on database level, this will be stored in the table mysql.db. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb'; you will see a 'Y' on every priv.

Above described shows the scenario you have on your db at the present. So having a user that only has USAGE privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS; he has no other privileges.

javascript setTimeout() not working

If your in a situation where you need to pass parameters to the function you want to execute after timeout, you can wrap the "named" function in an anonymous function.

i.e. works

setTimeout(function(){ startTimer(p1, p2); }, 1000);

i.e. won't work because it will call the function right away

setTimeout( startTimer(p1, p2), 1000);

Html.Textbox VS Html.TextboxFor

Ultimately they both produce the same HTML but Html.TextBoxFor() is strongly typed where as Html.TextBox isn't.

1:  @Html.TextBox("Name")
2:  Html.TextBoxFor(m => m.Name)

will both produce

<input id="Name" name="Name" type="text" />

So what does that mean in terms of use?

Generally two things:

  1. The typed TextBoxFor will generate your input names for you. This is usually just the property name but for properties of complex types can include an underscore such as 'customer_name'
  2. Using the typed TextBoxFor version will allow you to use compile time checking. So if you change your model then you can check whether there are any errors in your views.

It is generally regarded as better practice to use the strongly typed versions of the HtmlHelpers that were added in MVC2.

Execution failed for task ':app:processDebugResources' even with latest build tools

as a quick fix to this question, make sure your compile Sdk verion, your buildtoolsversion, your appcompat, and finally your support library are all running on the same sdk version, for further clarity take a look at the image i just uploaded. Cheers. Follow the red annotations and get rid of that trouble.

enter image description here

Can I check if Bootstrap Modal Shown / Hidden?

With Bootstrap 4:

if ($('#myModal').hasClass('show')) {
    alert("Modal is visible")
}

Using an index to get an item, Python

values = ['A', 'B', 'C', 'D', 'E']
values[0] # returns 'A'
values[2] # returns 'C'
# etc.

HttpClient won't import in Android Studio

ApacheHttp Client is removed in v23 sdk. You can use HttpURLConnection or third party Http Client like OkHttp.

ref : https://developer.android.com/preview/behavior-changes.html#behavior-apache-http-client

Shell Script: Execute a python program from within a shell script

Imho, writing

python /path/to/script.py

Is quite wrong, especially in these days. Which python? python2.6? 2.7? 3.0? 3.1? Most of times you need to specify the python version in shebang tag of python file. I encourage to use

#!/usr/bin/env python2 #or python2.6 or python3 or even python3.1
for compatibility.

In such case, is much better to have the script executable and invoke it directly:

#!/bin/bash

/path/to/script.py

This way the version of python you need is only written in one file. Most of system these days are having python2 and python3 in the meantime, and it happens that the symlink python points to python3, while most people expect it pointing to python2.

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

Maximum size of an Array in Javascript

You could try something like this to test and trim the length:

http://jsfiddle.net/orolo/wJDXL/

_x000D_
_x000D_
var longArray = [1, 2, 3, 4, 5, 6, 7, 8];_x000D_
_x000D_
if (longArray.length >= 6) {_x000D_
  longArray.length = 3;_x000D_
}_x000D_
_x000D_
alert(longArray); //1, 2, 3
_x000D_
_x000D_
_x000D_

Insert a row to pandas dataframe

The simplest way add a row in a pandas data frame is:

DataFrame.loc[ location of insertion ]= list( )

Example :

DF.loc[ 9 ] = [ ´Pepe’ , 33, ´Japan’ ]

NB: the length of your list should match that of the data frame.

Can I create a One-Time-Use Function in a Script or Stored Procedure?

I know I might get criticized for suggesting dynamic SQL, but sometimes it's a good solution. Just make sure you understand the security implications before you consider this.

DECLARE @add_a_b_func nvarchar(4000) = N'SELECT @c = @a + @b;';
DECLARE @add_a_b_parm nvarchar(500) = N'@a int, @b int, @c int OUTPUT';

DECLARE @result int;
EXEC sp_executesql @add_a_b_func, @add_a_b_parm, 2, 3, @c = @result OUTPUT;
PRINT CONVERT(varchar, @result); -- prints '5'

Date only from TextBoxFor()

This worked for me.

@Html.TextBoxFor(m => m.DateOfBirth, "{0:MM/dd/yyyy}", new { size = "12", @class = "DOB", tabindex = 121 })

Declaring an unsigned int in Java

For unsigned numbers you can use these classes from Guava library:

They support various operations:

  • plus
  • minus
  • times
  • mod
  • dividedBy

The thing that seems missing at the moment are byte shift operators. If you need those you can use BigInteger from Java.

What does the percentage sign mean in Python

The % does two things, depending on its arguments. In this case, it acts as the modulo operator, meaning when its arguments are numbers, it divides the first by the second and returns the remainder. 34 % 10 == 4 since 34 divided by 10 is three, with a remainder of four.

If the first argument is a string, it formats it using the second argument. This is a bit involved, so I will refer to the documentation, but just as an example:

>>> "foo %d bar" % 5
'foo 5 bar'

However, the string formatting behavior is supplemented as of Python 3.1 in favor of the string.format() mechanism:

The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer str.format() interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text.

And thankfully, almost all of the new features are also available from python 2.6 onwards.

how to check if a datareader is null or empty

This

Example:

objCar.StrDescription = (objSqlDataReader["fieldDescription"].GetType() != typeof(DBNull)) ? (String)objSqlDataReader["fieldDescription"] : "";

How to convert float to int with Java

As to me, easier: (int) (a +.5) // a is a Float. Return rounded value.

Not dependent on Java Math.round() types

What is the most effective way to get the index of an iterator of an std::vector?

I would prefer it - vec.begin() precisely for the opposite reason given by Naveen: so it wouldn't compile if you change the vector into a list. If you do this during every iteration, you could easily end up turning an O(n) algorithm into an O(n^2) algorithm.

Another option, if you don't jump around in the container during iteration, would be to keep the index as a second loop counter.

Note: it is a common name for a container iterator,std::container_type::iterator it;.

How to remove the last character from a bash grep output

cat file.txt | grep "company_name" | cut -d '=' -f 2 | cut -d ';' -f 1

How to remove an element from a list by index

Like others mentioned pop and del are the efficient ways to remove an item of given index. Yet just for the sake of completion (since the same thing can be done via many ways in Python):

Using slices (this does not do in place removal of item from original list):

(Also this will be the least efficient method when working with Python list, but this could be useful (but not efficient, I reiterate) when working with user defined objects that do not support pop, yet do define a __getitem__ ):

>>> a = [1, 2, 3, 4, 5, 6]
>>> index = 3 # Only positive index

>>> a = a[:index] + a[index+1 :]
# a is now [1, 2, 3, 5, 6]

Note: Please note that this method does not modify the list in place like pop and del. It instead makes two copies of lists (one from the start until the index but without it (a[:index]) and one after the index till the last element (a[index+1:])) and creates a new list object by adding both. This is then reassigned to the list variable (a). The old list object is hence dereferenced and hence garbage collected (provided the original list object is not referenced by any variable other than a).

This makes this method very inefficient and it can also produce undesirable side effects (especially when other variables point to the original list object which remains un-modified).

Thanks to @MarkDickinson for pointing this out ...

This Stack Overflow answer explains the concept of slicing.

Also note that this works only with positive indices.

While using with objects, the __getitem__ method must have been defined and more importantly the __add__ method must have been defined to return an object containing items from both the operands.

In essence, this works with any object whose class definition is like:

class foo(object):
    def __init__(self, items):
        self.items = items

    def __getitem__(self, index):
        return foo(self.items[index])

    def __add__(self, right):
        return foo( self.items + right.items )

This works with list which defines __getitem__ and __add__ methods.

Comparison of the three ways in terms of efficiency:

Assume the following is predefined:

a = range(10)
index = 3

The del object[index] method:

By far the most efficient method. It works will all objects that define a __del__ method.

The disassembly is as follows:

Code:

def del_method():
    global a
    global index
    del a[index]

Disassembly:

 10    0 LOAD_GLOBAL     0 (a)
       3 LOAD_GLOBAL     1 (index)
       6 DELETE_SUBSCR   # This is the line that deletes the item
       7 LOAD_CONST      0 (None)
      10 RETURN_VALUE
None

pop method:

It is less efficient than the del method and is used when you need to get the deleted item.

Code:

def pop_method():
    global a
    global index
    a.pop(index)

Disassembly:

 17     0 LOAD_GLOBAL     0 (a)
        3 LOAD_ATTR       1 (pop)
        6 LOAD_GLOBAL     2 (index)
        9 CALL_FUNCTION   1
       12 POP_TOP
       13 LOAD_CONST      0 (None)
       16 RETURN_VALUE

The slice and add method.

The least efficient.

Code:

def slice_method():
    global a
    global index
    a = a[:index] + a[index+1:]

Disassembly:

 24     0 LOAD_GLOBAL    0 (a)
        3 LOAD_GLOBAL    1 (index)
        6 SLICE+2
        7 LOAD_GLOBAL    0 (a)
       10 LOAD_GLOBAL    1 (index)
       13 LOAD_CONST     1 (1)
       16 BINARY_ADD
       17 SLICE+1
       18 BINARY_ADD
       19 STORE_GLOBAL   0 (a)
       22 LOAD_CONST     0 (None)
       25 RETURN_VALUE
None

Note: In all three disassembles ignore the last two lines which basically are return None. Also the first two lines are loading the global values a and index.

What evaluates to True/False in R?

T and TRUE are True, F and FALSE are False. T and F can be redefined, however, so you should only rely upon TRUE and FALSE. If you compare 0 to FALSE and 1 to TRUE, you will find that they are equal as well, so you might consider them to be True and False as well.

Redirect all output to file in Bash

Command:

foo >> output.txt 2>&1

appends to the output.txt file, without replacing the content.

How do I fix the npm UNMET PEER DEPENDENCY warning?

npm no longer installs peer dependencies so you need to install them manually, just do an npm install on the needed deps, and then try to install the main one again.


Reply to comment:

it's right in that message, it says which deps you're missing

UNMET PEER DEPENDENCY angular-animate@^1.5.0 +-- 
UNMET PEER DEPENDENCY angular-aria@^1.5.0 +-- [email protected] +
UNMET PEER DEPENDENCY angular-messages@^1.5.0 `-- [email protected]` 

So you need to npm install angular angular-animate angular-aria angular-material angular-messages mdi

Vertically center text in a 100% height div?

Even though this question is pretty old, here's a solution that works with both single and multiple lines that need to be centered vertically (could easily be centered both vertically & horizontally as seen in the css in the Demo.

HTML

<div class="parent">
    <div class="child">Text that needs to be vertically centered</div>
</div>


CSS

.parent {
    position: relative;
    height: 400px;
}

.child {
    position: absolute;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

Java Serializable Object to Byte Array

I would like to transmit it as byte[] over sockets to another machine

// When you connect
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
// When you want to send it
oos.writeObject(appMessage);

where it is rebuilt from the bytes received.

// When you connect
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
// When you want to receive it
AppMessage appMessage = (AppMessage)ois.readObject();

How to run multiple .BAT files within a .BAT file

All the other answers are correct: use call. For example:

 call "msbuild.bat"

History

In ancient DOS versions it was not possible to recursively execute batch files. Then the call command was introduced that called another cmd shell to execute the batch file and returned execution back to the calling cmd shell when finished.

Obviously in later versions no other cmd shell was necessary anymore.

In the early days many batch files depended on the fact that calling a batch file would not return to the calling batch file. Changing that behaviour without additional syntax would have broken many systems like batch menu systems (using batch files for menu structures).

As in many cases with Microsoft, backward compatibility therefore is the reason for this behaviour.

Tips

If your batch files have spaces in their names, use quotes around the name:

call "unit tests.bat"

By the way: if you do not have all the names of the batch files, you could also use for to do this (it does not guarantee the correct order of batch file calls; it follows the order of the file system):

FOR %x IN (*.bat) DO call "%x"

You can also react on errorlevels after a call. Use:

exit /B 1   # Or any other integer value in 0..255

to give back an errorlevel. 0 denotes correct execution. In the calling batch file you can react using

if errorlevel neq 0 <batch command>

Use if errorlevel 1 if you have an older Windows than NT4/2000/XP to catch all errorlevels 1 and greater.

To control the flow of a batch file, there is goto :-(

if errorlevel 2 goto label2
if errorlevel 1 goto label1
...
:label1
...
:label2
...

As others pointed out: have a look at build systems to replace batch files.

Convert varchar to float IF ISNUMERIC

-- TRY THIS --

select name= case when isnumeric(empname)= 1 then 'numeric' else 'notmumeric' end from [Employees]

But conversion is quit impossible

select empname=
case
when isnumeric(empname)= 1 then empname
else 'notmumeric'
end
from [Employees]

read complete file without using loop in java

You can try using Scanner if you are using JDK5 or higher.

Scanner scan = new Scanner(file);  
scan.useDelimiter("\\Z");  
String content = scan.next(); 

Or you can also use Guava

String data = Files.toString(new File("path.txt"), Charsets.UTF8);

How do I lowercase a string in C?

If we're going to be as sloppy as to use tolower(), do this:

char blah[] = "blah blah Blah BLAH blAH\0"; int i=0; while(blah[i]|=' ', blah[++i]) {}

But, well, it kinda explodes if you feed it some symbols/numerals, and in general it's evil. Good interview question, though.

What's the best way to do a backwards loop in C/C#/C++?

// this is how I always do it
for (i = n; --i >= 0;){
   ...
}

Get string after character

For the text after the first = and before the next =

cut -d "=" -f2 <<< "$your_str"

or

sed -e 's#.*=\(\)#\1#' <<< "$your_str"

For all text after the first = regardless of if there are multiple =

cut -d "=" -f2- <<< "$your_str"

How to sleep for five seconds in a batch file/cmd

ping waits for about 5 seconds before timing out, not 1 second as was stated above. That is, unless you tell it to only wait for 1 second before timing out.

ping 1.0.0.1 -n 1 -w 1000

will ping once, wait only 1 second (1000 ms) for a response, then time out.

So an approximately 20-second delay would be:

ping 1.0.0.1 -n 20 -w 1000

How to convert a data frame column to numeric type?

Though others have covered the topic pretty well, I'd like to add this additional quick thought/hint. You could use regexp to check in advance whether characters potentially consist only of numerics.

for(i in seq_along(names(df)){
     potential_numcol[i] <- all(!grepl("[a-zA-Z]",d[,i]))
}
# and now just convert only the numeric ones
d <- sapply(d[,potential_numcol],as.numeric)

For more sophisticated regular expressions and a neat why to learn/experience their power see this really nice website: http://regexr.com/

Replace input type=file by an image

its really simple you can try this:

$("#image id").click(function(){
    $("#input id").click();
});

How to set the current working directory?

It work for Mac also

import os
path="/Users/HOME/Desktop/Addl Work/TimeSeries-Done"
os.chdir(path)

To check working directory

os.getcwd()

How do I detect whether a Python variable is a function?

If this is for Python 2.x or for Python 3.2+, you can also use callable(). It used to be deprecated, but is now undeprecated, so you can use it again. You can read the discussion here: http://bugs.python.org/issue10518. You can do this with:

callable(obj)

If this is for Python 3.x but before 3.2, check if the object has a __call__ attribute. You can do this with:

hasattr(obj, '__call__')

The oft-suggested types.FunctionTypes approach is not correct because it fails to cover many cases that you would presumably want it to pass, like with builtins:

>>> isinstance(open, types.FunctionType)
False

>>> callable(open)
True

The proper way to check properties of duck-typed objects is to ask them if they quack, not to see if they fit in a duck-sized container. Don't use types.FunctionType unless you have a very specific idea of what a function is.

Multi-gradient shapes

Have you tried to overlay one gradient with a nearly-transparent opacity for the highlight on top of another image with an opaque opacity for the green gradient?

How to emulate a do-while loop in Python?

For me a typical while loop will be something like this:

xBool = True
# A counter to force a condition (eg. yCount = some integer value)

while xBool:
    # set up the condition (eg. if yCount > 0):
        (Do something)
        yCount = yCount - 1
    else:
        # (condition is not met, set xBool False)
        xBool = False

I could include a for..loop within the while loop as well, if situation so warrants, for looping through another set of condition.

Remove NaN from pandas series

If you have a pandas serie with NaN, and want to remove it (without loosing index):

serie = serie.dropna()

# create data for example
data = np.array(['g', 'e', 'e', 'k', 's']) 
ser = pd.Series(data)
ser.replace('e', np.NAN)
print(ser)

0      g
1    NaN
2    NaN
3      k
4      s
dtype: object

# the code
ser = ser.dropna()
print(ser)

0    g
3    k
4    s
dtype: object

How to redirect to a different domain using NGINX?

If you would like to redirect requests for "domain1.com" to "domain2.com", you could create a server block that looks like this:

server {
    listen 80;
    server_name domain1.com;
    return 301 $scheme://domain2.com$request_uri;
}

"Operation must use an updateable query" error in MS Access

UPDATE [GS] INNER JOIN [Views] ON 
([Views].Hostname = [GS].Hostname) 
AND ([GS].APPID = [Views].APPID) <------------ This is the difference 
SET 
    [GS].APPID = [Views].APPID, 
    [GS].[Name] = [Views].[Name], 
    [GS].Hostname = [Views].Hostname, 
    [GS].[Date] = [Views].[Date], 
    [GS].[Unit] = [Views].[Unit], 
    [GS].[Owner] = [Views].[Owner];

How to "wait" a Thread in Android

Write Thread.sleep(1000); it will make the thread sleep for 1000ms

printf a variable in C

As Shafik already wrote you need to use the right format because scanf gets you a char. Don't hesitate to look here if u aren't sure about the usage: http://www.cplusplus.com/reference/cstdio/printf/

Hint: It's faster/nicer to write x=x+1; the shorter way: x++;

Sorry for answering what's answered just wanted to give him the link - the site was really useful to me all the time dealing with C.

How can I generate a tsconfig.json file?

install TypeScript :

npm install typescript

add tsc script to package.json:

"scripts": {
  "tsc": "tsc"
 },

run this:

npx tsc --init

Java Array, Finding Duplicates

Print all the duplicate elements. Output -1 when no repeating elements are found.

import java.util.*;

public class PrintDuplicate {

    public static void main(String args[]){
        HashMap<Integer,Integer> h = new HashMap<Integer,Integer>();


        Scanner s=new Scanner(System.in);
        int ii=s.nextInt();
        int k=s.nextInt();
        int[] arr=new  int[k];
        int[] arr1=new  int[k];
        int l=0;
        for(int i=0; i<arr.length; i++)
            arr[i]=s.nextInt();
        for(int i=0; i<arr.length; i++){
            if(h.containsKey(arr[i])){
                h.put(arr[i], h.get(arr[i]) + 1);
                arr1[l++]=arr[i];
            } else {
                h.put(arr[i], 1);
            }
        }
        if(l>0)
        { 
            for(int i=0;i<l;i++)
                System.out.println(arr1[i]);
        }
        else
            System.out.println(-1);
    }
}

How to allow user to pick the image with Swift?

Incase if you don't want to have a separate button, here is a another way. Attached a gesture on imageView itself, where on tap of image a alert will popup with two option. You will have the option to choose either from gallery/photo library or to cancel the alert.

import UIKit
import CoreData

class AddDetailsViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var imageView: UIImageView!

var picker:UIImagePickerController? = UIImagePickerController()

@IBAction func saveButton(sender: AnyObject) {
    let managedContext = (UIApplication.sharedApplication().delegate as? AppDelegate)!.managedObjectContext

    let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext)

    let person = Person(entity: entity!, insertIntoManagedObjectContext: managedContext)

    person.image = UIImageJPEGRepresentation(imageView.image!, 1.0) //imageView.image

    do {
         try person.managedObjectContext?.save()
         //people.append(person)
       } catch let error as NSError {
         print("Could not save \(error)")
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(AddDetailsViewController.tapGesture(_:)))
    imageView.addGestureRecognizer(tapGesture)
    imageView.userInteractionEnabled = true

    picker?.delegate = self
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func tapGesture(gesture: UIGestureRecognizer) {
    let alert:UIAlertController = UIAlertController(title: "Profile Picture Options", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)

    let gallaryAction = UIAlertAction(title: "Open Gallary", style: UIAlertActionStyle.Default) {
        UIAlertAction in self.openGallary()
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
        UIAlertAction in self.cancel()
    }

    alert.addAction(gallaryAction)
    alert.addAction(cancelAction)

    self.presentViewController(alert, animated: true, completion: nil)

}


func openGallary() {
    picker!.allowsEditing = false
    picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    presentViewController(picker!, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        imageView.contentMode = .ScaleAspectFit
        imageView.image = pickedImage
    }

    dismissViewControllerAnimated(true, completion: nil)
}

func cancel(){
    print("Cancel Clicked")
}

}

Adding more to the question, implemented the logic to store images in CoreData.

How to create a new img tag with JQuery, with the src and id from a JavaScript object?

For those who need the same feature in IE 8, this is how I solved the problem:

  var myImage = $('<img/>');

               myImage.attr('width', 300);
               myImage.attr('height', 300);
               myImage.attr('class', "groupMediaPhoto");
               myImage.attr('src', photoUrl);

I could not force IE8 to use object in constructor.

Sorting using Comparator- Descending order (User defined classes)

String[] s = {"a", "x", "y"};
Arrays.sort(s, new Comparator<String>() {

    @Override
    public int compare(String o1, String o2) {
        return o2.compareTo(o1);
    }
});
System.out.println(Arrays.toString(s));

-> [y, x, a]

Now you have to implement the Comparator for your Person class. Something like (for ascending order): compare(Person a, Person b) = a.id < b.id ? -1 : (a.id == b.id) ? 0 : 1 or Integer.valueOf(a.id).compareTo(Integer.valueOf(b.id)).

To minimize confusion you should implement an ascending Comparator and convert it to a descending one with a wrapper (like this) new ReverseComparator<Person>(new PersonComparator()).

Byte and char conversion in Java

new String(byteArray, Charset.defaultCharset())

This will convert a byte array to the default charset in java. It may throw exceptions depending on what you supply with the byteArray.

How to copy a row from one SQL Server table to another

Jarrett's answer creates a new table.

Scott's answer inserts into an existing table with the same structure.

You can also insert into a table with different structure:

INSERT Table2
(columnX, columnY)
SELECT column1, column2 FROM Table1
WHERE [Conditions]

How to style readonly attribute with CSS?

Note that textarea[readonly="readonly"] works if you set readonly="readonly" in HTML but it does NOT work if you set the readOnly-attribute to true or "readonly" via JavaScript.

For the CSS selector to work if you set readOnly with JavaScript you have to use the selector textarea[readonly].

Same behavior in Firefox 14 and Chrome 20.

To be on the safe side, i use both selectors.

textarea[readonly="readonly"], textarea[readonly] {
...
}

How to append data to div using JavaScript?

Using appendChild:

var theDiv = document.getElementById("<ID_OF_THE_DIV>");
var content = document.createTextNode("<YOUR_CONTENT>");
theDiv.appendChild(content);

Using innerHTML:
This approach will remove all the listeners to the existing elements as mentioned by @BiAiB. So use caution if you are planning to use this version.

var theDiv = document.getElementById("<ID_OF_THE_DIV>");
theDiv.innerHTML += "<YOUR_CONTENT>"; 

How to populate a dropdownlist with json data in jquery?

To populate ComboBox with JSON, you can consider using the: jqwidgets combobox, too.

removing html element styles via javascript

Use

particular_node.classList.remove("<name-of-class>")

For native javascript

Check if registry key exists using VBScript

I found the solution.

dim bExists
ssig="Unable to open registry key"

set wshShell= Wscript.CreateObject("WScript.Shell")
strKey = "HKEY_USERS\.Default\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Digest\"
on error resume next
present = WshShell.RegRead(strKey)
if err.number<>0 then
    if right(strKey,1)="\" then    'strKey is a registry key
        if instr(1,err.description,ssig,1)<>0 then
            bExists=true
        else
            bExists=false
        end if
    else    'strKey is a registry valuename
        bExists=false
    end if
    err.clear
else
    bExists=true
end if
on error goto 0
if bExists=vbFalse then
    wscript.echo strKey & " does not exist."
else
    wscript.echo strKey & " exists."
end if

How to ignore a property in class if null, using json.net

Here's an option that's similar, but provides another choice:

public class DefaultJsonSerializer : JsonSerializerSettings
{
    public DefaultJsonSerializer()
    {
        NullValueHandling = NullValueHandling.Ignore;
    }
}

Then, I use it like this:

JsonConvert.SerializeObject(postObj, new DefaultJsonSerializer());

The difference here is that:

  • Reduces repeated code by instantiating and configuring JsonSerializerSettings each place it's used.
  • Saves time in configuring every property of every object to be serialized.
  • Still gives other developers flexibility in serialization options, rather than having the property explicitly specified on a reusable object.
  • My use-case is that the code is a 3rd party library and I don't want to force serialization options on developers who would want to reuse my classes.
  • Potential drawbacks are that it's another object that other developers would need to know about, or if your application is small and this approach wouldn't matter for a single serialization.

How to use QTimer

mytimer.h:

    #ifndef MYTIMER_H
    #define MYTIMER_H

    #include <QTimer>

    class MyTimer : public QObject
    {
        Q_OBJECT
    public:
        MyTimer();
        QTimer *timer;

    public slots:
        void MyTimerSlot();
    };

    #endif // MYTIME

mytimer.cpp:

#include "mytimer.h"
#include <QDebug>

MyTimer::MyTimer()
{
    // create a timer
    timer = new QTimer(this);

    // setup signal and slot
    connect(timer, SIGNAL(timeout()),
          this, SLOT(MyTimerSlot()));

    // msec
    timer->start(1000);
}

void MyTimer::MyTimerSlot()
{
    qDebug() << "Timer...";
}

main.cpp:

#include <QCoreApplication>
#include "mytimer.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Create MyTimer instance
    // QTimer object will be created in the MyTimer constructor
    MyTimer timer;

    return a.exec();
}

If we run the code:

Timer...
Timer...
Timer...
Timer...
Timer...
...

resources

Failed to load AppCompat ActionBar with unknown error in android studio

June 2018 Issue fixed by using a different appcompact version. Use these codes onto your project dependencies...

In build.gradle(Module: app) add this dependency

implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'

Happy Coding... :)

What is the difference between Amazon SNS and Amazon SQS?

You can see SNS as a traditional topic which you can have multiple Subscribers. You can have heterogeneous subscribers for one given SNS topic, including Lambda and SQS, for example. You can also send SMS messages or even e-mails out of the box using SNS. One thing to consider in SNS is only one message (notification) is received at once, so you cannot take advantage from batching.

SQS, on the other hand, is nothing but a queue, where you store messages and subscribe one consumer (yes, you can have N consumers to one SQS queue, but it would get messy very quickly and way harder to manage considering all consumers would need to read the message at least once, so one is better off with SNS combined with SQS for this use case, where SNS would push notifications to N SQS queues and every queue would have one subscriber, only) to process these messages. As of Jun 28, 2018, AWS Supports Lambda Triggers for SQS, meaning you don't have to poll for messages any more.

Furthermore, you can configure a DLQ on your source SQS queue to send messages to in case of failure. In case of success, messages are automatically deleted (this is another great improvement), so you don't have to worry about the already processed messages being read again in case you forgot to delete them manually. I suggest taking a look at Lambda Retry Behaviour to better understand how it works.

One great benefit of using SQS is that it enables batch processing. Each batch can contain up to 10 messages, so if 100 messages arrive at once in your SQS queue, then 10 Lambda functions will spin up (considering the default auto-scaling behaviour for Lambda) and they'll process these 100 messages (keep in mind this is the happy path as in practice, a few more Lambda functions could spin up reading less than the 10 messages in the batch, but you get the idea). If you posted these same 100 messages to SNS, however, 100 Lambda functions would spin up, unnecessarily increasing costs and using up your Lambda concurrency.

However, if you are still running traditional servers (like EC2 instances), you will still need to poll for messages and manage them manually.

You also have FIFO SQS queues, which guarantee the delivery order of the messages. SQS FIFO is also supported as an event source for Lambda as of November 2019

Even though there's some overlap in their use cases, both SQS and SNS have their own spotlight.

Use SNS if:

  • multiple subscribers is a requirement
  • sending SMS/E-mail out of the box is handy

Use SQS if:

  • only one subscriber is needed
  • batching is important

How can I get the concatenation of two lists in Python without modifying either one?

You can also use sum, if you give it a start argument:

>>> list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
>>> all_lists = sum([list1, list2, list3], [])
>>> all_lists
[1, 2, 3, 'a', 'b', 'c', 7, 8, 9]

This works in general for anything that has the + operator:

>>> sum([(1,2), (1,), ()], ())
(1, 2, 1)

>>> sum([Counter('123'), Counter('234'), Counter('345')], Counter())
Counter({'1':1, '2':2, '3':3, '4':2, '5':1})

>>> sum([True, True, False], False)
2

With the notable exception of strings:

>>> sum(['123', '345', '567'], '')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]

Error in contrasts when defining a linear model in R

Metrics and Svens answer deals with the usual situation but for us who work in non-english enviroments if you have exotic characters (å,ä,ö) in your character variable you will get the same result, even if you have multiple factor levels.

Levels <- c("Pri", "För") gives the contrast error, while Levels <- c("Pri", "For") doesn't

This is probably a bug.

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

You are using str methods on an open file object.

You can read the file as a list of lines by simply calling list() on the file object:

with open('goodlines.txt') as f:
    mylist = list(f)

This does include the newline characters. You can strip those in a list comprehension:

with open('goodlines.txt') as f:
    mylist = [line.rstrip('\n') for line in f]

What is Inversion of Control?

To understand IoC, we should talk about Dependency Inversion.

Dependency inversion: Depend on abstractions, not on concretions.

Inversion of control: Main vs Abstraction, and how the Main is the glue of the systems.

DIP and IoC

I wrote about this with some good examples, you can check them here:

https://coderstower.com/2019/03/26/dependency-inversion-why-you-shouldnt-avoid-it/

https://coderstower.com/2019/04/02/main-and-abstraction-the-decoupled-peers/

https://coderstower.com/2019/04/09/inversion-of-control-putting-all-together/

Can I use CASE statement in a JOIN condition?

I think you need two case statements:

SELECT  *
FROM    sys.indexes i
    JOIN sys.partitions p
        ON i.index_id = p.index_id 
    JOIN sys.allocation_units a
        ON 
        -- left side of join on statement
            CASE
               WHEN a.type IN (1, 3)
                   THEN a.container_id
               WHEN a.type IN (2)
                   THEN a.container_id
            END 
        = 
        -- right side of join on statement
            CASE
               WHEN a.type IN (1, 3)
                   THEN p.hobt_id
               WHEN a.type IN (2)
                   THEN p.partition_id
            END             

This is because:

  • the CASE statement returns a single value at the END
  • the ON statement compares two values
  • your CASE statement was doing the comparison inside of the CASE statement. I would guess that if you put your CASE statement in your SELECT you would get a boolean '1' or '0' indicating whether the CASE statement evaluated to True or False

Convert string to date then format the date

tl;dr

LocalDate.parse( "2011-01-01" )
         .format( DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) ) 

java.time

The other Answers are now outdated. The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes.

ISO 8601

The input string 2011-01-01 happens to comply with the ISO 8601 standard formats for date-time text. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate ld = LocalDate.parse( "2011-01-01" ) ;

Generate a String in the same format by calling toString.

String output = ld.toString() ;

2011-01-01

DateTimeFormatter

To parse/generate other formats, use a DateTimeFormatter.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) ;
String output = ld.format( f ) ;

01-01-2011


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

connecting to phpMyAdmin database with PHP/MySQL

The database is a MySQL database, not a phpMyAdmin database. phpMyAdmin is only PHP code that connects to the DB.

mysql_connect('localhost', 'username', 'password') or die (mysql_error());
mysql_select_database('db_name') or die (mysql_error());

// now you are connected

How to create EditText with rounded corners?

Try this one,

  1. Create rounded_edittext.xml file in your Drawable

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle" android:padding="15dp">
    
        <solid android:color="#FFFFFF" />
        <corners
            android:bottomRightRadius="0dp"
            android:bottomLeftRadius="0dp"
            android:topLeftRadius="0dp"
            android:topRightRadius="0dp" />
        <stroke android:width="1dip" android:color="#f06060" />
    </shape>
    
  2. Apply background for your EditText in xml file

    <EditText
        android:id="@+id/edit_expiry_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:background="@drawable/rounded_edittext"
        android:hint="@string/shop_name"
        android:inputType="text" />  
    
  3. You will get output like this

enter image description here

Converting a float to a string without rounding it

I know this is too late but for those who are coming here for the first time, I'd like to post a solution. I have a float value index and a string imgfile and I had the same problem as you. This is how I fixed the issue

index = 1.0
imgfile = 'data/2.jpg'
out = '%.1f,%s' % (index,imgfile)
print out

The output is

1.0,data/2.jpg

You may modify this formatting example as per your convenience.

How to solve "Fatal error: Class 'MySQLi' not found"?

In addition to uncommenting the php_mysqli.dll extension in php.ini, also uncomment the extension_dir directive in php.ini and specify your location:

extension_dir = "C:\software\php\dist\ext"

This made it work for me.

Difference between virtual and abstract methods

First of all you should know the difference between a virtual and abstract method.

Abstract Method

  • Abstract Method resides in abstract class and it has no body.
  • Abstract Method must be overridden in non-abstract child class.

Virtual Method

  • Virtual Method can reside in abstract and non-abstract class.
  • It is not necessary to override virtual method in derived but it can be.
  • Virtual method must have body ....can be overridden by "override keyword".....

What is the meaning of "POSIX"?

Let me give the churlish "unofficial" explanation.

POSIX is a set of standards which attempts to distinguish "UNIX" and UNIX-like systems from those which are incompatible with them. It was created by the U.S. government for procurement purposes. The idea was that the U.S. federal procurements needed a way to legally specify the requirements for various sorts of bids and contracts in a way that could be used to exclude systems to which a given existing code base or programming staff would NOT be portable.

Since POSIX was written post facto ... to describe a loosely similar set of competing systems ... it was NOT written in a way that could be implemented.

So, for example, Microsoft's NT was written with enough POSIX conformance to qualify for some bids ... even though the POSIX subsystem was essentially useless in terms of practical portability and compatibility with UNIX systems.

Various other standards for UNIX have been written over the decades. Things like the SPEC1170 (specified eleven hundred and seventy function calls which had to be implemented compatibly) and various incarnations of the SUS (Single UNIX Specification).

For the most part these "standards" have been inadequate to any practical technical application. They most exist for argumentation, legal wrangling and other dysfunctional reasons.

Save the console.log in Chrome to a file

A lot of good answers but why not just use JSON.stringify(your_variable) ? Then take the contents via copy and paste (remove outer quotes). I posted this same answer also at: How to save the output of a console.log(object) to a file?

Label python data points on plot

How about print (x, y) at once.

from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)
for xy in zip(A, B):                                       # <--
    ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--

plt.grid()
plt.show()

enter image description here

How to redirect to previous page in Ruby On Rails?

request.referer is set by Rack and is set as follows:

def referer
  @env['HTTP_REFERER'] || '/'
end

Just do a redirect_to request.referer and it will always redirect to the true referring page, or the root_path ('/'). This is essential when passing tests that fail in cases of direct-nav to a particular page in which the controller throws a redirect_to :back

Error using eclipse for Android - No resource found that matches the given name

One general solution to such tiny errors is that you close eclipse and start is again.. 3 irritating problems were solved.. its the problem with eclipse.. some times it didn resolve "R.id", the it didn find @string/somebutton, and then again some random thing... if nothing logical comes in your mind, try this, n conjure d result.. :)

Fastest way to check if a string is JSON in PHP?

This will return true if your string represents a json array or object:

function isJson($str) {
    $json = json_decode($str);
    return $json && $str != $json;
}

It rejects json strings that only contains a number, string or boolean, although those strings are technically valid json.

var_dump(isJson('{"a":5}')); // bool(true)
var_dump(isJson('[1,2,3]')); // bool(true)
var_dump(isJson('1')); // bool(false)
var_dump(isJson('1.5')); // bool(false)
var_dump(isJson('true')); // bool(false)
var_dump(isJson('false')); // bool(false)
var_dump(isJson('null')); // bool(false)
var_dump(isJson('hello')); // bool(false)
var_dump(isJson('')); // bool(false)

It is the shortest way I can come up with.

ADB Driver and Windows 8.1

In Windows 7, 8 or 8.1, in Devices Manager:

  1. Select tree 'Android Device': remove 'Android Composite ADB Interface' [?]
  2. Press on main root of devices tree and call context menu (by right mouse click) and click on 'Update configuration'
  3. After updating your device should appear in 'Other devices'
  4. Select your device, call context menu from it and choose 'Update driver' and perform this updating

DataRow: Select cell value by a given column name

Be careful on datatype. If not match it will throw an error.

var fieldName = dataRow.Field<DataType>("fieldName");

PHP - check if variable is undefined

The isset() function does not check if a variable is defined.

It seems you've specifically stated that you're not looking for isset() in the question. I don't know why there are so many answers stating that isset() is the way to go, or why the accepted answer states that as well.

It's important to realize in programming that null is something. I don't know why it was decided that isset() would return false if the value is null.

To check if a variable is undefined you will have to check if the variable is in the list of defined variables, using get_defined_vars(). There is no equivalent to JavaScript's undefined (which is what was shown in the question, no jQuery being used there).

In the following example it will work the same way as JavaScript's undefined check.

$isset = isset($variable);
var_dump($isset); // false

But in this example, it won't work like JavaScript's undefined check.

$variable = null;
$isset = isset($variable);
var_dump($isset); // false

$variable is being defined as null, but the isset() call still fails.

So how do you actually check if a variable is defined? You check the defined variables.

Using get_defined_vars() will return an associative array with keys as variable names and values as the variable values. We still can't use isset(get_defined_vars()['variable']) here because the key could exist and the value still be null, so we have to use array_key_exists('variable', get_defined_vars()).

$variable = null;
$isset = array_key_exists('variable', get_defined_vars());
var_dump($isset); // true


$isset = array_key_exists('otherVariable', get_defined_vars());
var_dump($isset); // false

However, if you're finding that in your code you have to check for whether a variable has been defined or not, then you're likely doing something wrong. This is my personal belief as to why the core PHP developers left isset() to return false when something is null.

Refresh image with a new one at the same url

One answer is to hackishly add some get query parameter like has been suggested.

A better answer is to emit a couple of extra options in your HTTP header.

Pragma: no-cache
Expires: Fri, 30 Oct 1998 14:19:41 GMT
Cache-Control: no-cache, must-revalidate

By providing a date in the past, it won't be cached by the browser. Cache-Control was added in HTTP/1.1 and the must-revalidate tag indicates that proxies should never serve up an old image even under extenuating circumstances, and the Pragma: no-cache isn't really necessary for current modern browsers/caches but may help with some crufty broken old implementations.

How to clear input buffer in C?

I encounter a problem trying to implement the solution

while ((c = getchar()) != '\n' && c != EOF) { }

I post a little adjustment 'Code B' for anyone who maybe have the same problem.

The problem was that the program kept me catching the '\n' character, independently from the enter character, here is the code that gave me the problem.

Code A

int y;

printf("\nGive any alphabetic character in lowercase: ");
while( (y = getchar()) != '\n' && y != EOF){
   continue;
}
printf("\n%c\n", toupper(y));

and the adjustment was to 'catch' the (n-1) character just before the conditional in the while loop be evaluated, here is the code:

Code B

int y, x;

printf("\nGive any alphabetic character in lowercase: ");
while( (y = getchar()) != '\n' && y != EOF){
   x = y;
}
printf("\n%c\n", toupper(x));

The possible explanation is that for the while loop to break, it has to assign the value '\n' to the variable y, so it will be the last assigned value.

If I missed something with the explanation, code A or code B please tell me, I’m barely new in c.

hope it helps someone

Using putty to scp from windows to Linux

Use scp priv_key.pem source user@host:target if you need to connect using a private key.

or if using pscp then use pscp -i priv_key.ppk source user@host:target

Ambiguous overload call to abs(double)

The header <math.h> is a C std lib header. It defines a lot of stuff in the global namespace. The header <cmath> is the C++ version of that header. It defines essentially the same stuff in namespace std. (There are some differences, like that the C++ version comes with overloads of some functions, but that doesn't matter.) The header <cmath.h> doesn't exist.

Since vendors don't want to maintain two versions of what is essentially the same header, they came up with different possibilities to have only one of them behind the scenes. Often, that's the C header (since a C++ compiler is able to parse that, while the opposite won't work), and the C++ header just includes that and pulls everything into namespace std. Or there's some macro magic for parsing the same header with or without namespace std wrapped around it or not. To this add that in some environments it's awkward if headers don't have a file extension (like editors failing to highlight the code etc.). So some vendors would have <cmath> be a one-liner including some other header with a .h extension. Or some would map all includes matching <cblah> to <blah.h> (which, through macro magic, becomes the C++ header when __cplusplus is defined, and otherwise becomes the C header) or <cblah.h> or whatever.

That's the reason why on some platforms including things like <cmath.h>, which ought not to exist, will initially succeed, although it might make the compiler fail spectacularly later on.

I have no idea which std lib implementation you use. I suppose it's the one that comes with GCC, but this I don't know, so I cannot explain exactly what happened in your case. But it's certainly a mix of one of the above vendor-specific hacks and you including a header you ought not to have included yourself. Maybe it's the one where <cmath> maps to <cmath.h> with a specific (set of) macro(s) which you hadn't defined, so that you ended up with both definitions.

Note, however, that this code still ought not to compile:

#include <cmath>

double f(double d)
{
  return abs(d);
}

There shouldn't be an abs() in the global namespace (it's std::abs()). However, as per the above described implementation tricks, there might well be. Porting such code later (or just trying to compile it with your vendor's next version which doesn't allow this) can be very tedious, so you should keep an eye on this.

How to bind DataTable to Datagrid

In cs file

DataTable employeeData = CreateDataTable();
gridEmployees.DataContext = employeeData.DefaultView;

In xaml file

<DataGrid Name="gridEmployees" ItemsSource="{Binding}">

Select element based on multiple classes

Chain selectors are not limited just to classes, you can do it for both classes and ids.

Classes

.classA.classB {
/*style here*/
}

Class & Id

.classA#idB {
/*style here*/
}

Id & Id

#idA#idB {
/*style here*/
}

All good current browsers support this except IE 6, it selects based on the last selector in the list. So ".classA.classB" will select based on just ".classB".

For your case

li.left.ui-class-selector {
/*style here*/
}

or

.left.ui-class-selector {
/*style here*/
}

How to set the maximum memory usage for JVM?

You shouldn't have to worry about the stack leaking memory (it is highly uncommon). The only time you can have the stack get out of control is with infinite (or really deep) recursion.

This is just the heap. Sorry, didn't read your question fully at first.

You need to run the JVM with the following command line argument.

-Xmx<ammount of memory>

Example:

-Xmx1024m

That will allow a max of 1GB of memory for the JVM.

How do I convert date/time from 24-hour format to 12-hour AM/PM?

Use smaller h

// 24 hrs 
H:i 
// output 14:20

// 12 hrs 
h:i 
// output 2:20

Gradle project refresh failed after Android Studio update

Make sure that nothing is interfering with your app files (specially in Windows), in my case this problem arise due to a text editor that was holding some XML file and Android Studio wasn't able to modify it.

Source file not compiled Dev C++

I was facing the same issue as described above.

It can be resolved by creating a new project and creating a new file in that project. Save the file and then try to build and run.

Hope that helps. :)

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

Intellij idea cannot resolve anything in maven

I have just had this issue when adding <dependency>...</dependency> elements to a <profile>. I just found that if I add (insert) the unresolved dependency elements to the <dependencies> element, the dependencies are downloaded from the maven repository; I can then remove the dependency element from the dependencies element.

How to find the kafka version in linux

There are several methods to find kafka version

Method 1 simple:-

ps -ef|grep kafka

it will displays all running kafka clients in the console... Ex:- /usr/hdp/current/kafka-broker/bin/../libs/kafka-clients-0.10.0.2.5.3.0-37.jar we are using 0.10.0.2.5.3.0-37 version of kafka

Method 2:- go to

cd /usr/hdp/current/kafka-broker/libs
ll |grep kafka

Ex:- kafka_2.10-0.10.0.2.5.3.0-37.jar kafka-clients-0.10.0.2.5.3.0-37.jar

same result as method 1 we can find the version of kafka using in kafka libs.

Relative div height

When you set a percentage height on an element who's parent elements don't have heights set, the parent elements have a default

height: auto;

You are asking the browser to calculate a height from an undefined value. Since that would equal a null-value, the result is that the browser does nothing with the height of child elements.

Besides using a JavaScript solution you could use this deadly easy table method:

#parent3 {
    display: table;
    width: 100%;
}

#parent3 .between {
    display: table-row;
}

#parent3 .child {
    display: table-cell;
}

Preview on http://jsbin.com/IkEqAfi/1

  • Example 1: Not working
  • Example 2: Fix height
  • Example 3: Table method

But: Bare in mind, that the table method only works properly in all modern Browsers and the Internet Explorer 8 and higher. As Fallback you could use JavaScript.

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;

This is all you need to:

  1. Add the id column
  2. Populate it with a sequence from 1 to count(*).
  3. Set it as primary key / not null.

Credit is given to @resnyanskiy who gave this answer in a comment.

JavaScript Object Id

If you want to lookup/associate an object with a unique identifier without modifying the underlying object, you can use a WeakMap:

// Note that object must be an object or array,
// NOT a primitive value like string, number, etc.
var objIdMap=new WeakMap, objectCount = 0;
function objectId(object){
  if (!objIdMap.has(object)) objIdMap.set(object,++objectCount);
  return objIdMap.get(object);
}

var o1={}, o2={}, o3={a:1}, o4={a:1};
console.log( objectId(o1) ) // 1
console.log( objectId(o2) ) // 2
console.log( objectId(o1) ) // 1
console.log( objectId(o3) ) // 3
console.log( objectId(o4) ) // 4
console.log( objectId(o3) ) // 3

Using a WeakMap instead of Map ensures that the objects can still be garbage-collected.

Count unique values with pandas per groups

IIUC you want the number of different ID for every domain, then you can try this:

output = df.drop_duplicates()
output.groupby('domain').size()

output:

    domain
facebook.com    1
google.com      1
twitter.com     2
vk.com          3
dtype: int64

You could also use value_counts, which is slightly less efficient.But the best is Jezrael's answer using nunique:

%timeit df.drop_duplicates().groupby('domain').size()
1000 loops, best of 3: 939 µs per loop
%timeit df.drop_duplicates().domain.value_counts()
1000 loops, best of 3: 1.1 ms per loop
%timeit df.groupby('domain')['ID'].nunique()
1000 loops, best of 3: 440 µs per loop

Delete commit on gitlab

Supose you have the following scenario:

* 1bd2200 (HEAD, master) another commit
* d258546 bad commit
* 0f1efa9 3rd commit
* bd8aa13 2nd commit
* 34c4f95 1st commit

Where you want to remove d258546 i.e. "bad commit".

You shall try an interactive rebase to remove it: git rebase -i 34c4f95

then your default editor will pop with something like this:

 pick bd8aa13 2nd commit
 pick 0f1efa9 3rd commit
 pick d258546 bad commit
 pick 1bd2200 another commit

 # Rebase 34c4f95..1bd2200 onto 34c4f95
 #
 # Commands:
 #  p, pick = use commit
 #  r, reword = use commit, but edit the commit message
 #  e, edit = use commit, but stop for amending
 #  s, squash = use commit, but meld into previous commit
 #  f, fixup = like "squash", but discard this commit's log message
 #  x, exec = run command (the rest of the line) using shell
 #
 # These lines can be re-ordered; they are executed from top to bottom.
 #
 # If you remove a line here THAT COMMIT WILL BE LOST.
 #
 # However, if you remove everything, the rebase will be aborted.
 #
 # Note that empty commits are commented out

just remove the line with the commit you want to strip and save+exit the editor:

 pick bd8aa13 2nd commit
 pick 0f1efa9 3rd commit
 pick 1bd2200 another commit
 ...

git will proceed to remove this commit from your history leaving something like this (mind the hash change in the commits descendant from the removed commit):

 * 34fa994 (HEAD, master) another commit
 * 0f1efa9 3rd commit
 * bd8aa13 2nd commit
 * 34c4f95 1st commit

Now, since I suppose that you already pushed the bad commit to gitlab, you'll need to repush your graph to the repository (but with the -f option to prevent it from being rejected due to a non fastforwardeable history i.e. git push -f <your remote> <your branch>)

Please be extra careful and make sure that none coworker is already using the history containing the "bad commit" in their branches.

Alternative option:

Instead of rewrite the history, you may simply create a new commit which negates the changes introduced by your bad commit, to do this just type git revert <your bad commit hash>. This option is maybe not as clean, but is far more safe (in case you are not fully aware of what are you doing with an interactive rebase).

How to add a class with React.js?

this is pretty useful:

https://github.com/JedWatson/classnames

You can do stuff like

classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'

// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'

// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'

or use it like this

var btnClass = classNames('btn', this.props.className, {
  'btn-pressed': this.state.isPressed,
  'btn-over': !this.state.isPressed && this.state.isHovered
});

Route [login] not defined

In app\Exceptions\Handler.php

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest(route('auth.login'));
}

Utils to read resource text file to String (Java)

The following cods work for me:

compile group: 'commons-io', name: 'commons-io', version: '2.6'

@Value("classpath:mockResponse.json")
private Resource mockResponse;

String mockContent = FileUtils.readFileToString(mockResponse.getFile(), "UTF-8");

What is the difference between Cygwin and MinGW?

Don't overlook AT&T's U/Win software, which is designed to help you compile Unix applications on windows (last version - 2012-08-06; uses Eclipse Public License, Version 1.0).

Like Cygwin they have to run against a library; in their case POSIX.DLL. The AT&T guys are terrific engineers (same group that brought you ksh and dot) and their stuff is worth checking out.

Table cell widths - fixing width, wrapping/truncating long words

As long as you fix the width of the table itself and set the table-layout property, this is pretty simple :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <style type="text/css">
        td { width: 30px; overflow: hidden; }
        table { width : 90px; table-layout: fixed; }
    </style>
</head>
<body>

    <table border="2">
        <tr>
            <td>word</td>
            <td>two words</td>
            <td>onereallylongword</td>

        </tr>
    </table>
</body>
</html>

I've tested this in IE6 and 7 and it seems to work fine.

TypeScript Objects as Dictionary types as in C#

You can also use the Record type in typescript :

export interface nameInterface { 
    propName : Record<string, otherComplexInterface> 
}

What is the difference between Spring, Struts, Hibernate, JavaServer Faces, Tapestry?

Difference between Spring, Struts and Hibernate are following:

  1. Spring is an Application Framework but Struts and hibernate is not.
  2. Spring and Hibernate are Light weighted but Struts 2 is not.
  3. Spring and Hibernate has layered architecture but Struts 2 doesn't.
  4. Spring and Hibernate support loose coupling but Struts 2 doesn't.
  5. Struts 2 and Hibernate have tag library but Spring doesn't.
  6. Spring and Hibernate have easy integration with ORM technologies but Struts doesn't.
  7. Struts 2 has easy integration with client-side technologies but Spring and Hibernate don't have.

Excel function to make SQL-like queries on worksheet data?

Sometimes SUM_IF can get the job done.

Suppose you have a sheet of product information, including unique productID in column A and unit price in column P. And a sheet of purchase order entries with product IDs in column A, and you want column T to calculate the unit price for the entry.

The following formula will do the trick in cell Entries!T2 and can be copied to the other cells in the same column.

=SUMIF(Products!$A$2:$A$9999,Entries!$A2, Products!$P$2:$9999)

Then you could have another column with number of items per entry and multiply it with the unit price to get total cost for the entry.

SCCM 2012 application install "Failed" in client Software Center

I'm assuming you figured this out already but:

Technical Reference for Log Files in Configuration Manager

That's a list of client-side logs and what they do. They are located in Windows\CCM\Logs

AppEnforce.log will show you the actual command-line executed and the resulting exit code for each Deployment Type (only for the new style ConfigMgr Applications)

This is my go-to for troubleshooting apps. Haven't really found any other logs that are exceedingly useful.

Eclipse error: R cannot be resolved to a variable

In addition to install the build tools and restart the update manager I also had to restart Eclipse to make this work.

How to call a REST web service API from JavaScript?

I think add if (this.readyState == 4 && this.status == 200) to wait is better:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
        var response = xhttp.responseText;
        console.log("ok"+response);
    }
};
xhttp.open("GET", "your url", true);

xhttp.send();

Display calendar to pick a date in java

I wrote a DateTextField component.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class DateTextField extends JTextField {

    private static String DEFAULT_DATE_FORMAT = "MM/dd/yyyy";
    private static final int DIALOG_WIDTH = 200;
    private static final int DIALOG_HEIGHT = 200;

    private SimpleDateFormat dateFormat;
    private DatePanel datePanel = null;
    private JDialog dateDialog = null;

    public DateTextField() {
        this(new Date());
    }

    public DateTextField(String dateFormatPattern, Date date) {
        this(date);
        DEFAULT_DATE_FORMAT = dateFormatPattern;
    }

    public DateTextField(Date date) {
        setDate(date);
        setEditable(false);
        setCursor(new Cursor(Cursor.HAND_CURSOR));
        addListeners();
    }

    private void addListeners() {
        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent paramMouseEvent) {
                if (datePanel == null) {
                    datePanel = new DatePanel();
                }
                Point point = getLocationOnScreen();
                point.y = point.y + 30;
                showDateDialog(datePanel, point);
            }
        });
    }

    private void showDateDialog(DatePanel dateChooser, Point position) {
        Frame owner = (Frame) SwingUtilities
                .getWindowAncestor(DateTextField.this);
        if (dateDialog == null || dateDialog.getOwner() != owner) {
            dateDialog = createDateDialog(owner, dateChooser);
        }
        dateDialog.setLocation(getAppropriateLocation(owner, position));
        dateDialog.setVisible(true);
    }

    private JDialog createDateDialog(Frame owner, JPanel contentPanel) {
        JDialog dialog = new JDialog(owner, "Date Selected", true);
        dialog.setUndecorated(true);
        dialog.getContentPane().add(contentPanel, BorderLayout.CENTER);
        dialog.pack();
        dialog.setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
        return dialog;
    }

    private Point getAppropriateLocation(Frame owner, Point position) {
        Point result = new Point(position);
        Point p = owner.getLocation();
        int offsetX = (position.x + DIALOG_WIDTH) - (p.x + owner.getWidth());
        int offsetY = (position.y + DIALOG_HEIGHT) - (p.y + owner.getHeight());

        if (offsetX > 0) {
            result.x -= offsetX;
        }

        if (offsetY > 0) {
            result.y -= offsetY;
        }

        return result;
    }

    private SimpleDateFormat getDefaultDateFormat() {
        if (dateFormat == null) {
            dateFormat = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
        }
        return dateFormat;
    }

    public void setText(Date date) {
        setDate(date);
    }

    public void setDate(Date date) {
        super.setText(getDefaultDateFormat().format(date));
    }

    public Date getDate() {
        try {
            return getDefaultDateFormat().parse(getText());
        } catch (ParseException e) {
            return new Date();
        }
    }

    private class DatePanel extends JPanel implements ChangeListener {
        int startYear = 1980;
        int lastYear = 2050;

        Color backGroundColor = Color.gray;
        Color palletTableColor = Color.white;
        Color todayBackColor = Color.orange;
        Color weekFontColor = Color.blue;
        Color dateFontColor = Color.black;
        Color weekendFontColor = Color.red;

        Color controlLineColor = Color.pink;
        Color controlTextColor = Color.white;

        JSpinner yearSpin;
        JSpinner monthSpin;
        JButton[][] daysButton = new JButton[6][7];

        DatePanel() {
            setLayout(new BorderLayout());
            setBorder(new LineBorder(backGroundColor, 2));
            setBackground(backGroundColor);

            JPanel topYearAndMonth = createYearAndMonthPanal();
            add(topYearAndMonth, BorderLayout.NORTH);
            JPanel centerWeekAndDay = createWeekAndDayPanal();
            add(centerWeekAndDay, BorderLayout.CENTER);

            reflushWeekAndDay();
        }

        private JPanel createYearAndMonthPanal() {
            Calendar cal = getCalendar();
            int currentYear = cal.get(Calendar.YEAR);
            int currentMonth = cal.get(Calendar.MONTH) + 1;

            JPanel panel = new JPanel();
            panel.setLayout(new FlowLayout());
            panel.setBackground(controlLineColor);

            yearSpin = new JSpinner(new SpinnerNumberModel(currentYear,
                    startYear, lastYear, 1));
            yearSpin.setPreferredSize(new Dimension(56, 20));
            yearSpin.setName("Year");
            yearSpin.setEditor(new JSpinner.NumberEditor(yearSpin, "####"));
            yearSpin.addChangeListener(this);
            panel.add(yearSpin);

            JLabel yearLabel = new JLabel("Year");
            yearLabel.setForeground(controlTextColor);
            panel.add(yearLabel);

            monthSpin = new JSpinner(new SpinnerNumberModel(currentMonth, 1,
                    12, 1));
            monthSpin.setPreferredSize(new Dimension(35, 20));
            monthSpin.setName("Month");
            monthSpin.addChangeListener(this);
            panel.add(monthSpin);

            JLabel monthLabel = new JLabel("Month");
            monthLabel.setForeground(controlTextColor);
            panel.add(monthLabel);

            return panel;
        }

        private JPanel createWeekAndDayPanal() {
            String colname[] = { "S", "M", "T", "W", "T", "F", "S" };
            JPanel panel = new JPanel();
            panel.setFont(new Font("Arial", Font.PLAIN, 10));
            panel.setLayout(new GridLayout(7, 7));
            panel.setBackground(Color.white);

            for (int i = 0; i < 7; i++) {
                JLabel cell = new JLabel(colname[i]);
                cell.setHorizontalAlignment(JLabel.RIGHT);
                if (i == 0 || i == 6) {
                    cell.setForeground(weekendFontColor);
                } else {
                    cell.setForeground(weekFontColor);
                }
                panel.add(cell);
            }

            int actionCommandId = 0;
            for (int i = 0; i < 6; i++)
                for (int j = 0; j < 7; j++) {
                    JButton numBtn = new JButton();
                    numBtn.setBorder(null);
                    numBtn.setHorizontalAlignment(SwingConstants.RIGHT);
                    numBtn.setActionCommand(String
                            .valueOf(actionCommandId));
                    numBtn.setBackground(palletTableColor);
                    numBtn.setForeground(dateFontColor);
                    numBtn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
                            JButton source = (JButton) event.getSource();
                            if (source.getText().length() == 0) {
                                return;
                            }
                            dayColorUpdate(true);
                            source.setForeground(todayBackColor);
                            int newDay = Integer.parseInt(source.getText());
                            Calendar cal = getCalendar();
                            cal.set(Calendar.DAY_OF_MONTH, newDay);
                            setDate(cal.getTime());

                            dateDialog.setVisible(false);
                        }
                    });

                    if (j == 0 || j == 6)
                        numBtn.setForeground(weekendFontColor);
                    else
                        numBtn.setForeground(dateFontColor);
                    daysButton[i][j] = numBtn;
                    panel.add(numBtn);
                    actionCommandId++;
                }

            return panel;
        }

        private Calendar getCalendar() {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(getDate());
            return calendar;
        }

        private int getSelectedYear() {
            return ((Integer) yearSpin.getValue()).intValue();
        }

        private int getSelectedMonth() {
            return ((Integer) monthSpin.getValue()).intValue();
        }

        private void dayColorUpdate(boolean isOldDay) {
            Calendar cal = getCalendar();
            int day = cal.get(Calendar.DAY_OF_MONTH);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            int actionCommandId = day - 2 + cal.get(Calendar.DAY_OF_WEEK);
            int i = actionCommandId / 7;
            int j = actionCommandId % 7;
            if (isOldDay) {
                daysButton[i][j].setForeground(dateFontColor);
            } else {
                daysButton[i][j].setForeground(todayBackColor);
            }
        }

        private void reflushWeekAndDay() {
            Calendar cal = getCalendar();
            cal.set(Calendar.DAY_OF_MONTH, 1);
            int maxDayNo = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
            int dayNo = 2 - cal.get(Calendar.DAY_OF_WEEK);
            for (int i = 0; i < 6; i++) {
                for (int j = 0; j < 7; j++) {
                    String s = "";
                    if (dayNo >= 1 && dayNo <= maxDayNo) {
                        s = String.valueOf(dayNo);
                    }
                    daysButton[i][j].setText(s);
                    dayNo++;
                }
            }
            dayColorUpdate(false);
        }

        public void stateChanged(ChangeEvent e) {
            dayColorUpdate(true);

            JSpinner source = (JSpinner) e.getSource();
            Calendar cal = getCalendar();
            if (source.getName().equals("Year")) {
                cal.set(Calendar.YEAR, getSelectedYear());
            } else {
                cal.set(Calendar.MONTH, getSelectedMonth() - 1);
            }
            setDate(cal.getTime());
            reflushWeekAndDay();
        }
    }
}

Relative Paths in Javascript in an external file

I found this to work for me.

    <script> document.write(unescape('%3Cscript src="' + window.location.protocol + "//" +     
    window.location.host + "/" + 'js/general.js?ver=2"%3E%3C/script%3E'))</script>

between script tags of course... (I'm not sure why the script tags didn't show up in this post)...

Android - setOnClickListener vs OnClickListener vs View.OnClickListener

  1. First of all, there is no difference between View.OnClickListener and OnClickListener. If you just use View.OnClickListener directly, then you don't need to write-

    import android.view.View.OnClickListener

  2. You set an OnClickListener instance (e.g. myListener named object)as the listener to a view via setOnclickListener(). When a click event is fired, that myListener gets notified and it's onClick(View view) method is called. Thats where we do our own task. Hope this helps you.

How to create a HTML Table from a PHP array?

Build two foreach loops and iterate through your array. Print out the value and add HTML table tags around that.

How to create custom exceptions in Java?

public class MyException extends Exception {
        // special exception code goes here
}

Throw it as:

 throw new MyException ("Something happened")

Catch as:

catch (MyException e)
{
   // something
}

Align Div at bottom on main Div

Give your parent div position: relative, then give your child div position: absolute, this will absolute position the div inside of its parent, then you can give the child bottom: 0px;

See example here:

http://jsfiddle.net/PGMqs/1/

OAuth 2.0 Authorization Header

For those looking for an example of how to pass the OAuth2 authorization (access token) in the header (as opposed to using a request or body parameter), here is how it's done:

Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42

How to serialize object to CSV file?

I wrote a simple class that uses OpenCSV and has two static public methods.

static public File toCSVFile(Object object, String path, String name) {
    File pathFile = new File(path);
    pathFile.mkdirs();
    File returnFile = new File(path + name);
    try {

        CSVWriter writer = new CSVWriter(new FileWriter(returnFile));
        writer.writeNext(new String[]{"Member Name in Code", "Stored Value", "Type of Value"});
        for (Field field : object.getClass().getDeclaredFields()) {
            writer.writeNext(new String[]{field.getName(), field.get(object).toString(), field.getType().getName()});
        }
        writer.flush();
        writer.close();
        return returnFile;
    } catch (IOException e) {
        Log.e("EasyStorage", "Easy Storage toCSVFile failed.", e);
        return null;
    } catch (IllegalAccessException e) {
        Log.e("EasyStorage", "Easy Storage toCSVFile failed.", e);
        return null;
    }
}

static public void fromCSVFile(Object object, File file) {
    try {
        CSVReader reader = new CSVReader(new FileReader(file));
        String[] nextLine = reader.readNext(); // Ignore the first line.
        while ((nextLine = reader.readNext()) != null) {
            if (nextLine.length >= 2) {
                try {
                    Field field = object.getClass().getDeclaredField(nextLine[0]);
                    Class<?> rClass = field.getType();
                    if (rClass == String.class) {
                        field.set(object, nextLine[1]);
                    } else if (rClass == int.class) {
                        field.set(object, Integer.parseInt(nextLine[1]));
                    } else if (rClass == boolean.class) {
                        field.set(object, Boolean.parseBoolean(nextLine[1]));
                    } else if (rClass == float.class) {
                        field.set(object, Float.parseFloat(nextLine[1]));
                    } else if (rClass == long.class) {
                        field.set(object, Long.parseLong(nextLine[1]));
                    } else if (rClass == short.class) {
                        field.set(object, Short.parseShort(nextLine[1]));
                    } else if (rClass == double.class) {
                        field.set(object, Double.parseDouble(nextLine[1]));
                    } else if (rClass == byte.class) {
                        field.set(object, Byte.parseByte(nextLine[1]));
                    } else if (rClass == char.class) {
                        field.set(object, nextLine[1].charAt(0));
                    } else {
                        Log.e("EasyStorage", "Easy Storage doesn't yet support extracting " + rClass.getSimpleName() + " from CSV files.");
                    }
                } catch (NoSuchFieldException e) {
                    Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
                } catch (IllegalAccessException e) {
                    Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);

                }
            } // Close if (nextLine.length >= 2)
        } // Close while ((nextLine = reader.readNext()) != null)
    } catch (FileNotFoundException e) {
        Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
    } catch (IOException e) {
        Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
    } catch (IllegalArgumentException e) {
        Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
    }
}

I think with some simple recursion these methods could be modified to handle any Java object, but for me this was adequate.

How to get disk capacity and free space of remote computer

There are two issues I encountered with the other suggestions

    1) Drive mappings are not supported if you run the powershell under task scheduler
    2) You may get Access is denied errors errors trying to used "get-WmiObject" on remote computers (depending on your infrastructure setup, of course)

The alternative that doesn't suffer from these issues is to use GetDiskFreeSpaceEx with a UNC path:

function getDiskSpaceInfoUNC($p_UNCpath, $p_unit = 1tb, $p_format = '{0:N1}')
{
    # unit, one of --> 1kb, 1mb, 1gb, 1tb, 1pb
    $l_typeDefinition = @' 
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
        [return: MarshalAs(UnmanagedType.Bool)] 
        public static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, 
            out ulong lpFreeBytesAvailable, 
            out ulong lpTotalNumberOfBytes, 
            out ulong lpTotalNumberOfFreeBytes); 
'@
    $l_type = Add-Type -MemberDefinition $l_typeDefinition -Name Win32Utils -Namespace GetDiskFreeSpaceEx -PassThru

    $freeBytesAvailable     = New-Object System.UInt64 # differs from totalNumberOfFreeBytes when per-user disk quotas are in place
    $totalNumberOfBytes     = New-Object System.UInt64
    $totalNumberOfFreeBytes = New-Object System.UInt64

    $l_result = $l_type::GetDiskFreeSpaceEx($p_UNCpath,([ref]$freeBytesAvailable),([ref]$totalNumberOfBytes),([ref]$totalNumberOfFreeBytes)) 

    $totalBytes     = if($l_result) { $totalNumberOfBytes    /$p_unit } else { '' }
    $totalFreeBytes = if($l_result) { $totalNumberOfFreeBytes/$p_unit } else { '' }

    New-Object PSObject -Property @{
        Success   = $l_result
        Path      = $p_UNCpath
        Total     = $p_format -f $totalBytes
        Free      = $p_format -f $totalFreeBytes
    } 
}

Enable PHP Apache2

You can use a2enmod or a2dismod to enable/disable modules by name.

From terminal, run: sudo a2enmod php5 to enable PHP5 (or some other module), then sudo service apache2 reload to reload the Apache2 configuration.

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

To get the address of p do:

int **pp = &p;

and you can go on:

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

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

auto pp = std::addressof(p);

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

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

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

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

In C++ you can do:

cout << "addr: " << pp;

How to update a value in a json file and save it through node.js

// read file and make object
let content = JSON.parse(fs.readFileSync('file.json', 'utf8'));
// edit or add property
content.expiry_date = 999999999999;
//write file
fs.writeFileSync('file.json', JSON.stringify(content));

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

If you want to pass a JavaScript object/hash (ie. an associative array in PHP) then you would do:

$.post('/url/to/page', {'key1': 'value', 'key2': 'value'});

If you wanna pass an actual array (ie. an indexed array in PHP) then you can do:

$.post('/url/to/page', {'someKeyName': ['value','value']});

If you want to pass a JavaScript array then you can do:

$.post('/url/to/page', {'someKeyName': variableName});

Display names of all constraints for a table in Oracle SQL

maybe this can help:

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

cheers

"This project is incompatible with the current version of Visual Studio"

What most people forget it is that the files of visual studio are just text files, that have some peculiars configurations that will show to the program how to open it. that is, we can change this because it's just a text in some file in there in your project folders.

Well, knowing this, what we have to do is very simple!

The first step is knowing what kind of project it is this project that stay unload. (for example: Class Library)

The Second step is create a new one (Class Library) because you know that your visual studio will create a version supported by himself. Unload this one and click in "Edit csproj".

It's in this file that we can found the configuration that tell to VS how this proj will be loaded and his name is ProjectGuid, this serial number has a variation according the type and version of project.

Now, look at your "ok project", copy the "ProjectGuid" TAG, paste on csproj that unloaded, and pay attention to the little differences and make this files almost equals, except for the tags ItemGroup that represent the references of the project.

Doing that, save all files and close your VS and open again, now your project should load normally.

I hope that this informations help somebody to understand a bit more how the VS works and help solve the problems when necessary.

What range of values can integer types store in C++

You should look at the specialisations of the numeric_limits<> template for a given type. Its in the header.

Generics in C#, using type of a variable as parameter

The point about generics is to give compile-time type safety - which means that types need to be known at compile-time.

You can call generic methods with types only known at execution time, but you have to use reflection:

// For non-public methods, you'll need to specify binding flags too
MethodInfo method = GetType().GetMethod("DoesEntityExist")
                             .MakeGenericMethod(new Type[] { t });
method.Invoke(this, new object[] { entityGuid, transaction });

Ick.

Can you make your calling method generic instead, and pass in your type parameter as the type argument, pushing the decision one level higher up the stack?

If you could give us more information about what you're doing, that would help. Sometimes you may need to use reflection as above, but if you pick the right point to do it, you can make sure you only need to do it once, and let everything below that point use the type parameter in a normal way.

How do I make an image smaller with CSS?

You can resize images using CSS just fine if you're modifying an image tag:

<img src="example.png" style="width:2em; height:3em;" />

You cannot scale a background-image property using CSS2, although you can try the CSS3 property background-size.

What you can do, on the other hand, is to nest an image inside a span. See the answer to this question: Stretch and scale CSS background

App.Config file in console application C#

You can add a reference to System.Configuration in your project and then:

using System.Configuration;

then

string sValue = ConfigurationManager.AppSettings["BatchFile"];

with an app.config file like this:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
       <add key="BatchFile" value="blah.bat" />
   </appSettings>
</configuration>

Formula to check if string is empty in Crystal Reports

if {le_gur_bond.gur1}="" or IsNull({le_gur_bond.gur1})   Then
    ""
else 
 "and " + {le_gur_bond.gur2} + " of "+ {le_gur_bond.grr_2_address2}

ASP.Net MVC Redirect To A Different View

 if (true)
 {
   return View();
 }
 else
 {
   return View("another view name");
 }

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

I had this issue as well on Windows 10. Closing all my Jupyter Notebook sessions and re-running the pip install --upgrade commands as an administrator made the issue go away.

macOS on VMware doesn't recognize iOS device

Do what is suggested in the answer, but make sure you also click inside the VM so that OSX has the focus before you plug in the phone. In my case, I had to do that to make it work.

How to search for a string in an arraylist

List <String> list = new ArrayList();  
           list.add("behold"); 
           list.add("bend"); 
           list.add("bet"); 
           list.add("bear"); 
           list.add("beat"); 
           list.add("become"); 
           list.add("begin");

           List <String> listClone = new ArrayList<String>(); 
           Pattern pattern = Pattern.compile("bea",Pattern.CASE_INSENSITIVE); //incase u r not concerned about upper/lower case
           for (String string : list) {
               if(pattern.matcher(string).find()) {
                   listClone.add(string);
                   continue;
               }
           }
        System.out.println(listClone);

Creating an R dataframe row-by-row

One can add rows to NULL:

df<-NULL;
while(...){
  #Some code that generates new row
  rbind(df,row)->df
}

for instance

df<-NULL
for(e in 1:10) rbind(df,data.frame(x=e,square=e^2,even=factor(e%%2==0)))->df
print(df)

Passive Link in Angular 2 - <a href=""> equivalent

You have prevent the default browser behaviour. But you don’t need to create a directive to accomplish that.

It’s easy as the following example:

my.component.html

<a href="" (click)="goToPage(pageIndex, $event)">Link</a>

my.component.ts

goToPage(pageIndex, event) {
  event.preventDefault();
  console.log(pageIndex);
}

Display a view from another controller in ASP.NET MVC

You can use:

return View("../Category/NotFound", model);

It was tested in ASP.NET MVC 3, but should also work in ASP.NET MVC 2.

How to set Spinner default value to null?

Base on @Jonik answer I have created fully functional extension to ArrayAdapter

class SpinnerArrayAdapter<T> : ArrayAdapter<T> {

    private val selectText : String
    private val resource: Int
    private val fieldId : Int
    private val inflater : LayoutInflater

    constructor(context: Context?, resource: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, objects) {
        this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
        this.resource = resource
        this.fieldId = 0
        this.inflater = LayoutInflater.from(context)
    }
    constructor(context: Context?, resource : Int, objects: List<T>, selectText : String? = null) : super(context, resource, objects) {
        this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
        this.resource = resource
        this.fieldId = 0
        this.inflater = LayoutInflater.from(context)
    }
    constructor(context: Context?, resource: Int, textViewResourceId: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
        this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
        this.resource = resource
        this.fieldId = textViewResourceId
        this.inflater = LayoutInflater.from(context)
    }
    constructor(context: Context?, resource : Int, textViewResourceId: Int, objects: List<T>, selectText : String? = null) : super(context, resource, textViewResourceId,  objects) {
        this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
        this.resource = resource
        this.fieldId = textViewResourceId
        this.inflater = LayoutInflater.from(context)
    }

    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View {
        if(position == 0) {
            return initialSelection(true)
        }

        return createViewFromResource(inflater, position -1, convertView, parent, resource)
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        if(position == 0) {
            return initialSelection(false)
        }
        return createViewFromResource(inflater, position -1, convertView, parent, resource)
    }

    override fun getCount(): Int {
        return super.getCount() + 1 // adjust for initial selection
    }

    private fun initialSelection(inDropDown: Boolean) : View {
        // Just simple TextView as initial selection.
        val view = TextView(context)
        view.setText(selectText)
        view.setPadding(8, 0, 8, 0)

        if(inDropDown) {
            // Hide when dropdown is open
            view.height = 0
        }
        return view
    }

    private fun createViewFromResource(inflater: LayoutInflater, position: Int,
                                       @Nullable convertView: View?, parent: ViewGroup?, resource: Int): View {
        val view: View
        val text: TextView?

        if (convertView == null || (convertView is TextView)) {
            view = inflater.inflate(resource, parent, false)
        } else {
            view = convertView
        }

        try {
            if (fieldId === 0) {
                //  If no custom field is assigned, assume the whole resource is a TextView
                text = view as TextView
            } else {
                //  Otherwise, find the TextView field within the layout
                text = view.findViewById(fieldId)

                if (text == null) {
                    throw RuntimeException("Failed to find view with ID "
                            + context.getResources().getResourceName(fieldId)
                            + " in item layout")
                }
            }
        } catch (e: ClassCastException) {
            Log.e("ArrayAdapter", "You must supply a resource ID for a TextView")
            throw IllegalStateException(
                    "ArrayAdapter requires the resource ID to be a TextView", e)
        }

        val item = getItem(position)
        if (item is CharSequence) {
            text.text = item
        } else {
            text.text = item!!.toString()
        }

        return view
    }

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I have resolved this issue after selecting the "Target Compatibility" to 1.8 Java version. File -> Project Structure -> Modules.

TypeScript and field initializers

In some scenarios it may be acceptable to use Object.create. The Mozilla reference includes a polyfill if you need back-compatibility or want to roll your own initializer function.

Applied to your example:

Object.create(Person.prototype, {
    'Field1': { value: 'ASD' },
    'Field2': { value: 'QWE' }
});

Useful Scenarios

  • Unit Tests
  • Inline declaration

In my case I found this useful in unit tests for two reasons:

  1. When testing expectations I often want to create a slim object as an expectation
  2. Unit test frameworks (like Jasmine) may compare the object prototype (__proto__) and fail the test. For example:
var actual = new MyClass();
actual.field1 = "ASD";
expect({ field1: "ASD" }).toEqual(actual); // fails

The output of the unit test failure will not yield a clue about what is mismatched.

  1. In unit tests I can be selective about what browsers I support

Finally, the solution proposed at http://typescript.codeplex.com/workitem/334 does not support inline json-style declaration. For example, the following does not compile:

var o = { 
  m: MyClass: { Field1:"ASD" }
};

Postgresql - select something where date = "01/01/11"

With PostgreSQL there are a number of date/time functions available, see here.

In your example, you could use:

SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';

If you are running this query regularly, it is possible to create an index using the date_trunc function as well:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );

One advantage of this is there is some more flexibility with timezones if required, for example:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';

What is the fastest way to create a checksum for large files in C#

You're doing something wrong (probably too small read buffer). On a machine of undecent age (Athlon 2x1800MP from 2002) that has DMA on disk probably out of whack (6.6M/s is damn slow when doing sequential reads):

Create a 1G file with "random" data:

# dd if=/dev/sdb of=temp.dat bs=1M count=1024    
1073741824 bytes (1.1 GB) copied, 161.698 s, 6.6 MB/s

# time sha1sum -b temp.dat
abb88a0081f5db999d0701de2117d2cb21d192a2 *temp.dat

1m5.299s

# time md5sum -b temp.dat
9995e1c1a704f9c1eb6ca11e7ecb7276 *temp.dat

1m58.832s

This is also weird, md5 is consistently slower than sha1 for me (reran several times).

Delete directory with files in it?

As seen in most voted comment on PHP manual page about rmdir() (see http://php.net/manual/es/function.rmdir.php), glob() function does not return hidden files. scandir() is provided as an alternative that solves that issue.

Algorithm described there (which worked like a charm in my case) is:

<?php 
    function delTree($dir)
    { 
        $files = array_diff(scandir($dir), array('.', '..')); 

        foreach ($files as $file) { 
            (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file"); 
        }

        return rmdir($dir); 
    } 
?>

Vagrant stuck connection timeout retrying

In my case, giving it a static IP address, simply solved the problem:

config.vm.network "private_network", ip: "192.168.50.50"

Prevent multiple instances of a given app in .NET?

Hanselman has a post on using the WinFormsApplicationBase class from the Microsoft.VisualBasic assembly to do this.

Pause in Python

In Windows, you can use the msvcrt module.

msvcrt.kbhit() Return true if a keypress is waiting to be read.

msvcrt.getch() Read a keypress and return the resulting character. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed.

If you want it to also work on Unix-like systems you can try this solution using the termios and fcntl modules.

Can't push to the heroku

You could also select webpack build manually from the UI enter image description here

Force browser to refresh css, javascript, etc

If you want to be sure that these files are properly refreshed by Chrome for all users, then you need to have must-revalidate in the Cache-Control header. This will make Chrome re-check files to see if they need to be re-fetched.

Recommend the following response header:

Cache-Control: must-validate

This tells Chrome to check with the server, and see if there is a newer file. If there is a newer file, it will receive it in the response. If not, it will receive a 304 response, and the assurance that the one in the cache is up to date.

If you do NOT set this header, then in the absence of any other setting that invalidates the file, Chrome will never check with the server to see if there is a newer version.

Here is a blog post that discusses the issue further.

How do I read configuration settings from Symfony2 config.yml?

I learnt a easy way from code example of http://tutorial.symblog.co.uk/

1) notice the ZendeskBlueFormBundle and file location

# myproject/app/config/config.yml

imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: @ZendeskBlueFormBundle/Resources/config/config.yml }

framework:

2) notice Zendesk_BlueForm.emails.contact_email and file location

# myproject/src/Zendesk/BlueFormBundle/Resources/config/config.yml

parameters:
    # Zendesk contact email address
    Zendesk_BlueForm.emails.contact_email: [email protected]

3) notice how i get it in $client and file location of controller

# myproject/src/Zendesk/BlueFormBundle/Controller/PageController.php

    public function blueFormAction($name, $arg1, $arg2, $arg3, Request $request)
    {
    $client = new ZendeskAPI($this->container->getParameter("Zendesk_BlueForm.emails.contact_email"));
    ...
    }

Recursively look for files with a specific extension

To find all the pom.xml files in your current directory and print them, you can use:

find . -name 'pom.xml' -print

Eclipse add Tomcat 7 blank server name

I had same issue before: the server name was not appearing in server while configuring with eclipse

I tried all the solutions which are provided over here, but they didn't work for me.

I resolved it, by simply following these simple tips

Step1: Windows --> Preferences --> Server --> Run time Environments --> Add --> select the tomcat version which was unavailable before --> next --> browse the location of your server with same version

Step2: go to servers and select your server version --> next --> Finish

Issue resolved!!! :)

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

I've found a working code:

JSONParser parser = new JSONParser();
Object obj  = parser.parse(content);
JSONArray array = new JSONArray();
array.add(obj);

Where is the application.properties file in a Spring Boot project?

In the your first journey in spring boot project I recommend you to start with Spring Starter Try this link here.

enter image description here

It will auto generate the project structure for you like this.application.perperties it will be under /resources.

application.properties important change,

server.port = Your PORT(XXXX) by default=8080
server.servlet.context-path=/api (SpringBoot version 2.x.)
server.contextPath-path=/api (SpringBoot version < 2.x.)

Any way you can use application.yml in case you don't want to make redundancy properties setting.

Example
application.yml

server:
   port: 8080 
   contextPath: /api

application.properties

server.port = 8080
server.contextPath = /api

".addEventListener is not a function" why does this error occur?

Try this one:

var comment = document.querySelector("button");
function showComment() {
  var place = document.querySelector('#textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
}
comment.addEventListener('click', showComment, false);

Use querySelector instead of className

Get a substring of a char*

Assuming you know the position and the length of the substring:

char *buff = "this is a test string";
printf("%.*s", 4, buff + 10);

You could achieve the same thing by copying the substring to another memory destination, but it's not reasonable since you already have it in memory.

This is a good example of avoiding unnecessary copying by using pointers.

C linked list inserting node at the end

After you malloc a node make sure to set node->next = NULL.

int addNodeBottom(int val, node *head)
{    
    node *current = head;
    node *newNode = (node *) malloc(sizeof(node));
    if (newNode == NULL) {
        printf("malloc failed\n");
        exit(-1);
    }    

    newNode->value = val;
    newNode->next = NULL;

    while (current->next) {
        current = current->next;
    }    
    current->next = newNode;
    return 0;
}    

I should point out that with this version the head is still used as a dummy, not used for storing a value. This lets you represent an empty list by having just a head node.