Programs & Examples On #Htmltidy

HTML Tidy is an html formatter used to pretty print existing markup.

Sublime Text 2 Code Formatting

I can't speak for the 2nd or 3rd, but if you install Node first, Sublime-HTMLPrettify works pretty well. You have to setup your own key shortcut once it is installed. One thing I noticed on Windows, you may need to edit your path for Node in the %PATH% variable if it is already long (I think the limit is 1024 for the %PATH% variable, and anything after that is ignored.)

There is a Windows bug, but in the issues there is a fix for it. You'll need to edit the HTMLPrettify.py file - https://github.com/victorporof/Sublime-HTMLPrettify/issues/12

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

I'm having a problem with your script in Firefox. When I scroll down, the script continues to add a margin to the page and I never reach the bottom of the page. This occurs because the ActionBox is still part of the page elements. I posted a demo here.

  • One solution would be to add a position: fixed to the CSS definition, but I see this won't work for you
  • Another solution would be to position the ActionBox absolutely (to the document body) and adjust the top.
  • Updated the code to fit with the solution found for others to benefit.

UPDATED:

CSS

#ActionBox {
 position: relative;
 float: right;
}

Script

var alert_top = 0;
var alert_margin_top = 0;

$(function() {
  alert_top = $("#ActionBox").offset().top;
  alert_margin_top = parseInt($("#ActionBox").css("margin-top"),10);

  $(window).scroll(function () {
    var scroll_top = $(window).scrollTop();
    if (scroll_top > alert_top) {
      $("#ActionBox").css("margin-top", ((scroll_top-alert_top)+(alert_margin_top*2)) + "px");
      console.log("Setting margin-top to " + $("#ActionBox").css("margin-top"));
    } else {
      $("#ActionBox").css("margin-top", alert_margin_top+"px");
    };
  });
});

Also it is important to add a base (10 in this case) to your parseInt(), e.g.

parseInt($("#ActionBox").css("top"),10);

What are some uses of template template parameters?

In the solution with variadic templates provided by pfalcon, I found it difficult to actually specialize the ostream operator for std::map due to the greedy nature of the variadic specialization. Here's a slight revision which worked for me:

#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <map>

namespace containerdisplay
{
  template<typename T, template<class,class...> class C, class... Args>
  std::ostream& operator <<(std::ostream& os, const C<T,Args...>& objs)
  {
    std::cout << __PRETTY_FUNCTION__ << '\n';
    for (auto const& obj : objs)
      os << obj << ' ';
    return os;
  }  
}

template< typename K, typename V>
std::ostream& operator << ( std::ostream& os, 
                const std::map< K, V > & objs )
{  

  std::cout << __PRETTY_FUNCTION__ << '\n';
  for( auto& obj : objs )
  {    
    os << obj.first << ": " << obj.second << std::endl;
  }

  return os;
}


int main()
{

  {
    using namespace containerdisplay;
    std::vector<float> vf { 1.1, 2.2, 3.3, 4.4 };
    std::cout << vf << '\n';

    std::list<char> lc { 'a', 'b', 'c', 'd' };
    std::cout << lc << '\n';

    std::deque<int> di { 1, 2, 3, 4 };
    std::cout << di << '\n';
  }

  std::map< std::string, std::string > m1 
  {
      { "foo", "bar" },
      { "baz", "boo" }
  };

  std::cout << m1 << std::endl;

    return 0;
}

Reset local repository branch to be just like remote repository HEAD

This is something I face regularly, & I've generalised the script Wolfgang provided above to work with any branch

I also added an "are you sure" prompt, & some feedback output

#!/bin/bash
# reset the current repository
# WF 2012-10-15
# AT 2012-11-09
# see http://stackoverflow.com/questions/1628088/how-to-reset-my-local-repository-to-be-just-like-the-remote-repository-head
timestamp=`date "+%Y-%m-%d-%H_%M_%S"`
branchname=`git rev-parse --symbolic-full-name --abbrev-ref HEAD`
read -p "Reset branch $branchname to origin (y/n)? "
[ "$REPLY" != "y" ] || 
echo "about to auto-commit any changes"
git commit -a -m "auto commit at $timestamp"
if [ $? -eq 0 ]
then
  echo "Creating backup auto-save branch: auto-save-$branchname-at-$timestamp"
  git branch "auto-save-$branchname-at-$timestamp" 
fi
echo "now resetting to origin/$branchname"
git fetch origin
git reset --hard origin/$branchname

How to prevent column break within an element?

<style>
ul li{display: table;}  
</style>

works perfectly

Java sending and receiving file (byte[]) over sockets

The correct way to copy a stream in Java is as follows:

int count;
byte[] buffer = new byte[8192]; // or 4096, or more
while ((count = in.read(buffer)) > 0)
{
  out.write(buffer, 0, count);
}

Wish I had a dollar for every time I've posted that in a forum.

IIS error, Unable to start debugging on the webserver

in my case, the DefaultAppPool was stopped, I edited the Advanced Settings and set the value of Identity as LocalSystem, after that I start the DefaultAppPool.

View more than one project/solution in Visual Studio

Two ways come to mind...

  1. Open another visual studio window and open the second solution in it.

  2. It would be preferable to add your existing projects to one solution, just right click and add existing project and navigate to the project file(csproj). .... e.g. C:\Users\User\Documents\Visual Studio 2012\Projects\MySqlWindowsFormsApplication1\MySql Windows Forms Project1\MySql Windows Forms Project1.csproj ....In this second way you might want to setup multiple start up projects i.e. for people with client-server apps or apps with dependencies. ....To do this Select the solution then GoTo: Project>>Properties>>Startup Project>> Select Multiple Startup projects and set actions to Start. When you debug, the selected as start will run.

  3. For interest sake you could open another multiple solution windows to view different projects at the same time. http://www.schwammysays.net/visual-studio-2012-tip-multiple-solution-explorers/

How to add a bot to a Telegram Group?

You have to use @BotFather, send it command: /setjoingroups There will be dialog like this:

YOU: /setjoingroups

BotFather: Choose a bot to change group membership settings.

YOU: @YourBot

BotFather: 'Enable' - bot can be added to groups. 'Disable' - block group invitations, the bot can't be added to groups. Current status is: DISABLED

YOU: Enable

BotFather: Success! The new status is: ENABLED.

After this you will see button "Add to Group" in your bot's profile.

PHP: Update multiple MySQL fields in single query

Comma separate the values:

UPDATE settings SET postsPerPage = $postsPerPage, style = $style WHERE id = '1'"

Converting a string to a date in JavaScript

Date.parse almost gets you what you want. It chokes on the am/pm part, but with some hacking you can get it to work:

var str = 'Sun Apr 25, 2010 3:30pm',
    timestamp;

timestamp = Date.parse(str.replace(/[ap]m$/i, ''));

if(str.match(/pm$/i) >= 0) {
    timestamp += 12 * 60 * 60 * 1000;
}

How to deal with persistent storage (e.g. databases) in Docker

It depends on your scenario (this isn't really suitable for a production environment), but here is one way:

Creating a MySQL Docker Container

This gist of it is to use a directory on your host for data persistence.

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

Expanding on Tony's answer, and also answering Dhaval Ptl's question, to get the true accordion effect and only allow one row to be expanded at a time, an event handler for show.bs.collapse can be added like so:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');
});

I modified his example to do this here: http://jsfiddle.net/QLfMU/116/

JavaScript "cannot read property "bar" of undefined

If an object's property may refer to some other object then you can test that for undefined before trying to use its properties:

if (thing && thing.foo)
   alert(thing.foo.bar);

I could update my answer to better reflect your situation if you show some actual code, but possibly something like this:

function someFunc(parameterName) {
   if (parameterName && parameterName.foo)
       alert(parameterName.foo.bar);
}

Lombok added but getters and setters not recognized in Intellij IDEA

If you are on Mac, make sure you enable annotation processing (tick the checkbox) at these 2 places.

1.) Intellij IDEA -> Preferences -> Compiler -> Annotation Processors

2.) File -> Other Settings -> Default Settings -> Compiler -> Annotation Processors

And then

3.) Intellij IDEA -> Preferences -> Plugins ->Browse Repositories-> Search for "Lombok"-> install plugin -> Apply and restart IDEA

4.) And then probably restart Intellij IDEA.

This is my IntelliJ IDEA and Mac Version - IntelliJ IDEA 2017.1.5 Build #IU-171.4694.70 --- Mac OS X 10.12

WPF Binding to parent DataContext

I dont know about XamGrid but that's what i'll do with a standard wpf DataGrid:

<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Since the TextBlock and the TextBox specified in the cell templates will be part of the visual tree, you can walk up and find whatever control you need.

Set scroll position

Also worth noting window.scrollBy(dx,dy) (ref)

How to iterate over a column vector in Matlab?

with many functions in matlab, you don't need to iterate at all.

for example, to multiply by it's position in the list:

m = [1:numel(list)]';
elm = list.*m;

vectorized algorithms in matlab are in general much faster.

PHP Echo text Color

This is an old question, but no one responded to the question regarding centering text in a terminal.

/**
 * Centers a string of text in a terminal window
 *
 * @param string $text The text to center
 * @param string $pad_string If set, the string to pad with (eg. '=' for a nice header)
 *
 * @return string The padded result, ready to echo
 */
function center($text, $pad_string = ' ') {
    $window_size = (int) `tput cols`;
    return str_pad($text, $window_size, $pad_string, STR_PAD_BOTH)."\n";
}

echo center('foo');
echo center('bar baz', '=');

How to place a div below another div?

what about changing the position: relative on your #content #text div to position: absolute

#content #text {
   position:absolute;
   width:950px;
   height:215px;
   color:red;
}

http://jsfiddle.net/CaZY7/12/

then you can use the css properties left and top to position within the #content div

Get Selected value of a Combobox

Maybe you'll be able to set the event handlers programmatically, using something like (pseudocode)

sub myhandler(eventsource)
  process(eventsource.value)
end sub

for each cell
  cell.setEventHandler(myHandler)

But i dont know the syntax for achieving this in VB/VBA, or if is even possible.

How to make CSS width to fill parent?

Use the styles

left: 0px;

or/and

right: 0px;

or/and

top: 0px;

or/and

bottom: 0px;

I think for most cases that will do the job

Nginx: Permission denied for nginx on Ubuntu

This works for me,

sudo chmod -R 777 /var/log/nginx

Converting string to title case

Use ToLower() first, than CultureInfo.CurrentCulture.TextInfo.ToTitleCase on the result to get the correct output.

    //---------------------------------------------------------------
    // Get title case of a string (every word with leading upper case,
    //                             the rest is lower case)
    //    i.e: ABCD EFG -> Abcd Efg,
    //         john doe -> John Doe,
    //         miXEd CaSING - > Mixed Casing
    //---------------------------------------------------------------
    public static string ToTitleCase(string str)
    {
        return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
    }

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

A null value cannot be assigned to a primitive type, like int, long, boolean, etc. If the database column that corresponds to the field in your object can be null, then your field should be a wrapper class, like Integer, Long, Boolean, etc.

The danger is that your code will run fine if there are no nulls in the DB, but will fail once nulls are inserted.

And you can always return the primitive type from the getter. Ex:

  private Integer num;

  public void setNum(Integer i) {
    this.num = i;
  }

  public int getNum() {
    return this.num;
  }

But in most cases you will want to return the wrapper class.

So either set your DB column to not allow nulls, or use a wrapper class.

How to convert int to QString?

I always use QString::setNum().

int i = 10;
double d = 10.75;
QString str;
str.setNum(i);
str.setNum(d);

setNum() is overloaded in many ways. See QString class reference.

CSS/HTML: Create a glowing border around an Input Field

SLaks hit the nail on the head but you might want to look over the changes for inputs in CSS3 in general. Rounded corners and box-shadow are both new features in CSS3 and will let you do exactly what you're looking for. One of my personal favorite links for CSS3/HTML5 is http://diveintohtml5.ep.io/ .

How to find array / dictionary value using key?

It's as simple as this :

$array[$key];

Is there a way to do repetitive tasks at intervals?

I use the following code:

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    fmt.Println("\nToday:", now)

    after := now.Add(1 * time.Minute)
    fmt.Println("\nAdd 1 Minute:", after)

    for {
        fmt.Println("test")
        time.Sleep(10 * time.Second)

        now = time.Now()

        if now.After(after) {
            break
        }
    }

    fmt.Println("done")
}

It is more simple and works fine to me.

SQL Server function to return minimum date (January 1, 1753)

You could write a User Defined Function that returns the min date value like this:

select cast(-53690 as datetime)

Then use that function in your scripts, and if you ever need to change it, there is only one place to do that.

Alternately, you could use this query if you prefer it for better readability:

select cast('1753-1-1' as datetime)

Example Function

create function dbo.DateTimeMinValue()
returns datetime as
begin
    return (select cast(-53690 as datetime))
end

Usage

select dbo.DateTimeMinValue() as DateTimeMinValue

DateTimeMinValue
-----------------------
1753-01-01 00:00:00.000

How do I check for a network connection?

Microsoft windows vista and 7 use NCSI (Network Connectivity Status Indicator) technic:

  1. NCSI performs a DNS lookup on www.msftncsi.com, then requests http://www.msftncsi.com/ncsi.txt. This file is a plain-text file and contains only the text 'Microsoft NCSI'.
  2. NCSI sends a DNS lookup request for dns.msftncsi.com. This DNS address should resolve to 131.107.255.255. If the address does not match, then it is assumed that the internet connection is not functioning correctly.

Difference between Iterator and Listiterator?

Iterator is super class of ListIterator.

Here are the differences between them:

  1. With iterator you can move only forward, but with ListIterator you can move backword also while reading the elements.
  2. With ListIterator you can obtain the index at any point while traversing, which is not possible with iterators.
  3. With iterator you can check only for next element available or not, but in listiterator you can check previous and next elements.
  4. With listiterator you can add new element at any point of time, while traversing. Not possible with iterator.
  5. With listiterator you can modify an element while traversing, which is not possible with iterator.

Iterator look and feel:

 public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove(); //optional-->use only once with next(), 
                         dont use it when u use for:each
    }

ListIterator look and feel:

public interface ListIterator<E> extends Iterator<E> {
    boolean hasNext();
    E next();
    boolean hasPrevious();
    E previous();
    int nextIndex();
    int previousIndex();
    void remove(); //optional
    void set(E e); //optional
    void add(E e); //optional
}

How to get an IFrame to be responsive in iOS Safari?

CSS only solution

HTML

<div class="container">
    <div class="h_iframe">
        <iframe  src="//www.youtube.com/embed/9KunP3sZyI0" frameborder="0" allowfullscreen></iframe>
    </div>
</div>

CSS

html,body {
    height:100%;
}
.h_iframe iframe {
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
}

DEMO

Another demo here with HTML page in iframe

react-router (v4) how to go back?

Simply use

<span onClick={() => this.props.history.goBack()}>Back</span>

How to get the pure text without HTML element using JavaScript?

[2017-07-25] since this continues to be the accepted answer, despite being a very hacky solution, I'm incorporating Gabi's code into it, leaving my own to serve as a bad example.

_x000D_
_x000D_
// my hacky approach:
function get_content() {
  var html = document.getElementById("txt").innerHTML;
  document.getElementById("txt").innerHTML = html.replace(/<[^>]*>/g, "");
}
// Gabi's elegant approach, but eliminating one unnecessary line of code:
function gabi_content() {
  var element = document.getElementById('txt');
  element.innerHTML = element.innerText || element.textContent;
}
// and exploiting the fact that IDs pollute the window namespace:
function txt_content() {
  txt.innerHTML = txt.innerText || txt.textContent;
}
_x000D_
.A {
  background: blue;
}

.B {
  font-style: italic;
}

.C {
  font-weight: bold;
}
_x000D_
<input type="button" onclick="get_content()" value="Get Content (bad)" />
<input type="button" onclick="gabi_content()" value="Get Content (good)" />
<input type="button" onclick="txt_content()" value="Get Content (shortest)" />
<p id='txt'>
  <span class="A">I am</span>
  <span class="B">working in </span>
  <span class="C">ABC company.</span>
</p>
_x000D_
_x000D_
_x000D_

I want to vertical-align text in select box

display: flex;
align-items: center;

MSOnline can't be imported on PowerShell (Connect-MsolService error)

After reviewing Microsoft's TechNet article "Azure Active Directory Cmdlets" -> section "Install the Azure AD Module", it seems that this process has been drastically simplified, thankfully.

As of 2016/06/30, in order to successfully execute the PowerShell commands Import-Module MSOnline and Connect-MsolService, you will need to install the following applications (64-bit only):

  1. Applicable Operating Systems: Windows 7 to 10
    Name: "Microsoft Online Services Sign-in Assistant for IT Professionals RTW"
    Version: 7.250.4556.0 (latest)
    Installer URL: https://www.microsoft.com/en-us/download/details.aspx?id=41950
    Installer file name: msoidcli_64.msi
  2. Applicable Operating Systems: Windows 7 to 10
    Name: "Windows Azure Active Directory Module for Windows PowerShell"
    Version: Unknown but the latest installer file's SHA-256 hash is D077CF49077EE133523C1D3AE9A4BF437D220B16D651005BBC12F7BDAD1BF313
    Installer URL: https://technet.microsoft.com/en-us/library/dn975125.aspx
    Installer file name: AdministrationConfig-en.msi
  3. Applicable Operating Systems: Windows 7 only
    Name: "Windows PowerShell 3.0"
    Version: 3.0 (later versions will probably work too)
    Installer URL: https://www.microsoft.com/en-us/download/details.aspx?id=34595
    Installer file name: Windows6.1-KB2506143-x64.msu

 

enter image description here enter image description here enter image description here

Should IBOutlets be strong or weak under ARC?

I think that most important information is: Elements in xib are automatically in subviews of view. Subviews is NSArray. NSArray owns it's elements. etc have strong pointers on them. So in most cases you don't want to create another strong pointer (IBOutlet)

And with ARC you don't need to do anything in viewDidUnload

MySQL default datetime through phpmyadmin

You're getting that error because the default value current_time is not valid for the type DATETIME. That's what it says, and that's whats going on.

The only field you can use current_time on is a timestamp.

What is the fastest way to send 100,000 HTTP requests in Python?

A solution using tornado asynchronous networking library

from tornado import ioloop, httpclient

i = 0

def handle_request(response):
    print(response.code)
    global i
    i -= 1
    if i == 0:
        ioloop.IOLoop.instance().stop()

http_client = httpclient.AsyncHTTPClient()
for url in open('urls.txt'):
    i += 1
    http_client.fetch(url.strip(), handle_request, method='HEAD')
ioloop.IOLoop.instance().start()

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

Returning the correct format is done by the media-type formatter. As others mentioned, you can do this in the WebApiConfig class:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        ...

        // Configure Web API to return JSON
        config.Formatters.JsonFormatter
        .SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));

        ...
    }
}

For more, check:

In case your actions are returning XML (which is the case by default) and you need just a specific method to return JSON, you can then use an ActionFilterAttribute and apply it to that specific action.

Filter attribute:

public class JsonOutputAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        ObjectContent content = actionExecutedContext.Response.Content as ObjectContent;
        var value = content.Value;
        Type targetType = actionExecutedContext.Response.Content.GetType().GetGenericArguments()[0];

        var httpResponseMsg = new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.OK,
            RequestMessage = actionExecutedContext.Request,
            Content = new ObjectContent(targetType, value, new JsonMediaTypeFormatter(), (string)null)
        };

        actionExecutedContext.Response = httpResponseMsg;
        base.OnActionExecuted(actionExecutedContext);
    }
}

Applying to action:

[JsonOutput]
public IEnumerable<Person> GetPersons()
{
    return _repository.AllPersons(); // the returned output will be in JSON
}

Note that you can omit the word Attribute on the action decoration and use just [JsonOutput] instead of [JsonOutputAttribute].

change <audio> src with javascript

If you are storing metadata in a tag use data attributes eg.

<li id="song1" data-value="song1.ogg"><button onclick="updateSource()">Item1</button></li>

Now use the attribute to get the name of the song

var audio = document.getElementById('audio');
audio.src='audio/ogg/' + document.getElementById('song1').getAttribute('data-value');
audio.load();

angular2: Error: TypeError: Cannot read property '...' of undefined

That's because abc is undefined at the moment of the template rendering. You can use safe navigation operator (?) to "protect" template until HTTP call is completed:

{{abc?.xyz?.name}}

You can read more about safe navigation operator here.

Update:

Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf directive to overcome this problem:

<div *ngIf="arr && arr.length > 0">
    {{arr[0].name}}
</div>

Read more about NgIf directive here.

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

It seems that Microsoft finally is addressing this problem. Current versions in the Insider Editions of Explorer allows creating files with a dot at the front.

Tested with Build 19541

Extract the first word of a string in a SQL Server query

Try This:

Select race_id, race_description
, Case patIndex ('%[ /-]%', LTrim (race_description))
    When 0 Then LTrim (race_description)
    Else substring (LTrim (race_description), 1, patIndex ('%[ /-]%', LTrim (race_description)) - 1)
End race_abbreviation

from tbl_races

The name 'ConfigurationManager' does not exist in the current context

If you're getting a lot of warnings (in my case 64 in a solution!) like

CS0618: 'ConfigurationSettings.AppSettings' is obsolete: 'This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings'

because you're upgrading an older project you can save a lot of time as follows:

  1. Add System.Configuration as a reference to your References section.
  2. Add the following two using statements to the top of each class (.cs) file:

    using System.Configuration; using ConfigurationSettings = System.Configuration.ConfigurationManager;

By this change all occurances of

ConfigurationSettings.AppSettings["mySetting"]

will now reference the right configuration manager, no longer the deprecated one, and all the CS0618 warnings will go away immediately.

Of course, keep in mind that this is a quick hack. On the long term, you should consider refactoring the code.

Convert a string date into datetime in Oracle

Try this: TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')

When to use the JavaScript MIME type application/javascript instead of text/javascript?

application/javascript is the correct type to use but since it's not supported by IE6-8 you're going to be stuck with text/javascript. If you don't care about validity (HTML5 excluded) then just don't specify a type.

How to run java application by .bat file

  • javac (.exe on Windows) binary path must be added into global PATH env. variable.

    javac MyProgram.java

  • or with java (.exe on Windows)

    java MyProgram.jar

print spaces with String.format()

You need to specify the minimum width of the field.

String.format("%" + numberOfSpaces + "s", ""); 

Why do you want to generate a String of spaces of a certain length.

If you want a column of this length with values then you can do:

String.format("%" + numberOfSpaces + "s", "Hello"); 

which gives you numberOfSpaces-5 spaces followed by Hello. If you want Hello to appear on the left then add a minus sign in before numberOfSpaces.

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

If any of the answers doesn't work just remove Android Emulator and reinstall it again. and after that try installing Intel Haxm.

How to add multiple font files for the same font?

To have font variation working correctly, I had to reverse the order of @font-face in CSS.

@font-face {
    font-family: "DejaVuMono";
    src: url("styles/DejaVuSansMono-BoldOblique.ttf");
    font-weight: bold;
    font-style: italic, oblique;
}   
@font-face {
    font-family: "DejaVuMono";
    src: url("styles/DejaVuSansMono-Oblique.ttf");
    font-style: italic, oblique;
}
@font-face {
    font-family: "DejaVuMono";
    src: url("styles/DejaVuSansMono-Bold.ttf");
    font-weight: bold;
}
 @font-face {
    font-family: "DejaVuMono";
    src: url("styles/DejaVuSansMono.ttf");
}

How do I get currency exchange rates via an API such as Google Finance?

If you're looking for a ruby based solution for this problem, I recommend using the Google Calculator method a solution similar to the following: http://j.mp/QIC564

require 'faraday'
require 'faraday_middleware'
require 'json'

# Debug: 
# require "pry"


country_code_src = "USD"
country_code_dst = "INR"
connection = Faraday.get("http://www.google.com/ig/calculator?hl=en&q=1#{country_code_src}=?#{country_code_dst}")

currency_comparison_hash = eval connection.body #Google's output is not JSON, it's a hash

dst_currency_value, *dst_currency_text = *currency_comparison_hash[:rhs].split(' ')
dst_currency_value = dst_currency_value.to_f
dst_currency_text = dst_currency_text.join(' ')

puts "#{country_code_dst} -> #{dst_currency_value} (#{dst_currency_text} to 1 #{country_code_src})"

Equivalent function for DATEADD() in Oracle

Not my answer :

I wasn't too happy with the answers above and some additional searching yielded this :

SELECT SYSDATE AS current_date,

       SYSDATE + 1 AS plus_1_day,

       SYSDATE + 1/24 AS plus_1_hours,

       SYSDATE + 1/24/60 AS plus_1_minutes,

       SYSDATE + 1/24/60/60 AS plus_1_seconds

FROM   dual;

which I found very helpful. From http://sqlbisam.blogspot.com/2014/01/add-date-interval-to-date-or-dateadd.html

What is logits, softmax and softmax_cross_entropy_with_logits?

tf.nn.softmax computes the forward propagation through a softmax layer. You use it during evaluation of the model when you compute the probabilities that the model outputs.

tf.nn.softmax_cross_entropy_with_logits computes the cost for a softmax layer. It is only used during training.

The logits are the unnormalized log probabilities output the model (the values output before the softmax normalization is applied to them).

GenyMotion Unable to start the Genymotion virtual device

If all the other answers here fail (you can check that you have a correctly created host-only network in VirtualBox, which is basically what other answers here come down to):

https://stackoverflow.com/a/33733454/586754 (with screenshot) worked for me.

Basically, go to Windows network adapter settings for the "VirtualBox Host-Only Ethernet Adapter" and check "VirtualBox NDIS6 Bridged Networking Driver".

This made both Genymotion and Xamarin Android Player work again.

How can I check the syntax of Python script without executing it?

for some reason ( I am a py newbie ... ) the -m call did not work ...

so here is a bash wrapper func ...

# ---------------------------------------------------------
# check the python synax for all the *.py files under the
# <<product_version_dir/sfw/python
# ---------------------------------------------------------
doCheckPythonSyntax(){

    doLog "DEBUG START doCheckPythonSyntax"

    test -z "$sleep_interval" || sleep "$sleep_interval"
    cd $product_version_dir/sfw/python
    # python3 -m compileall "$product_version_dir/sfw/python"

    # foreach *.py file ...
    while read -r f ; do \

        py_name_ext=$(basename $f)
        py_name=${py_name_ext%.*}

        doLog "python3 -c \"import $py_name\""
        # doLog "python3 -m py_compile $f"

        python3 -c "import $py_name"
        # python3 -m py_compile "$f"
        test $! -ne 0 && sleep 5

    done < <(find "$product_version_dir/sfw/python" -type f -name "*.py")

    doLog "DEBUG STOP  doCheckPythonSyntax"
}
# eof func doCheckPythonSyntax

How can I determine the current CPU utilization from the shell?

Try this command:

cat /proc/stat

This will be something like this:

cpu  55366 271 17283 75381807 22953 13468 94542 0
cpu0 3374 0 2187 9462432 1393 2 665 0
cpu1 2074 12 1314 9459589 841 2 43 0
cpu2 1664 0 1109 9447191 666 1 571 0
cpu3 864 0 716 9429250 387 2 118 0
cpu4 27667 110 5553 9358851 13900 2598 21784 0
cpu5 16625 146 2861 9388654 4556 4026 24979 0
cpu6 1790 0 1836 9436782 480 3307 19623 0
cpu7 1306 0 1702 9399053 726 3529 26756 0
intr 4421041070 559 10 0 4 5 0 0 0 26 0 0 0 111 0 129692 0 0 0 0 0 95 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 369 91027 1580921706 1277926101 570026630 991666971 0 277768 0 0 0 0 0 0 0 0 0 0 0 0 0
ctxt 8097121
btime 1251365089
processes 63692
procs_running 2
procs_blocked 0

More details:

http://www.mail-archive.com/[email protected]/msg01690.html http://www.linuxhowtos.org/System/procstat.htm

How to get list of dates between two dates in mysql select query

Try:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

Change IPython/Jupyter notebook working directory

I have both 32 and 64 bit python and ipython using WinPython, I wanted both 32 and 64 bit versions to point to the same working directory for ipython notebook.

I followed the above suggestions here I was still unable to get my setup working.

Here's what I did - in case anyone needs it:


It looks like Ipython notebook was using the configuration from C:\pythonPath\winpythonPath\settings\.ipython\profile_default

Even though ipython locate returns C:\users\Username\.ipython

As a result, modifying the ipython_notebook_config.py file did nothing to change my working directory.

Additionally ipython profile_create was not creating the needed python files in C:\pythonPath\winpythonPath\settings\.ipython\profile_default

I'm sure there's a better way, but to resolve this quickly, I copied the edited python files from C:\users\Username\.ipython\profile_default to C:\pythonPath\winpythonPath\settings\.ipython\profile_default

Now (finally) ipython notebook 64 bit runs and provides me the correct working directory

Note on Windows I'm having no issue with the following syntax:

c.NotebookApp.notebook_dir = u'C:/Users/Path_to_working_directory'

Making a flex item float right

You can't use float inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle.

So if you want to position child element to right of parent element you can use margin-left: auto but now child element will also push other div to the right as you can see here Fiddle.

What you can do now is change order of elements and set order: 2 on child element so it doesn't affect second div

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
}_x000D_
.child {_x000D_
  margin-left: auto;_x000D_
  order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child">Ignore parent?</div>_x000D_
  <div>another child</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

Delete element in a slice

Rather than thinking of the indices in the [a:]-, [:b]- and [a:b]-notations as element indices, think of them as the indices of the gaps around and between the elements, starting with gap indexed 0 before the element indexed as 0.

enter image description here

Looking at just the blue numbers, it's much easier to see what is going on: [0:3] encloses everything, [3:3] is empty and [1:2] would yield {"B"}. Then [a:] is just the short version of [a:len(arrayOrSlice)], [:b] the short version of [0:b] and [:] the short version of [0:len(arrayOrSlice)]. The latter is commonly used to turn an array into a slice when needed.

What is http multipart request?

A HTTP multipart request is a HTTP request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.

jQuery - Disable Form Fields

<script type="text/javascript" src="jquery.js"></script>          
<script type="text/javascript">
  $(document).ready(function() {
      $("#suburb").blur(function() {
          if ($(this).val() != '')
              $("#post_code").attr("disabled", "disabled");
          else
              $("#post_code").removeAttr("disabled");
      });

      $("#post_code").blur(function() {
          if ($(this).val() != '')
              $("#suburb").attr("disabled", "disabled");
          else
              $("#suburb").removeAttr("disabled");
      });
  });
</script>

You'll also need to add a value attribute to the first option under your select element:

<option value=""></option>

Submit form using a button outside the <form> tag

Here's a pretty solid solution that incorporates the best ideas so far as well as includes my solution to a problem highlighted with Offerein's. No javascript is used.

If you care about backwards compatibility with IE (and even Edge 13), you can't use the form="your-form" attribute.

Use a standard submit input with display none and add a label for it outside the form:

<form id="your-form">
  <input type="submit" id="your-form-submit" style="display: none;">
</form>

Note the use of display: none;. This is intentional. Using bootstrap's .hidden class conflicts with jQuery's .show() and .hide(), and has since been deprecated in Bootstrap 4.

Now simply add a label for your submit, (styled for bootstrap):

<label for="your-form-submit" role="button" class="btn btn-primary" tabindex="0">
  Submit
</label>

Unlike other solutions, I'm also using tabindex - set to 0 - which means that we are now compatible with keyboard tabbing. Adding the role="button" attribute gives it the CSS style cursor: pointer. Et voila. (See this fiddle).

How to enable and use HTTP PUT and DELETE with Apache2 and PHP?

AllowOverride AuthConfig

try this. Authentication may be the problem. I was working with a CGI script written in C++, and faced some authentication issues when passed DELETE. The above solution helped me. It may help in your case too.


Also even if you don't get the solution for your problem of PUT and DELETE, do not stop working rather use "CORS". It is a google chrome app, which will help you bypass the problem, but remember it is a temporary solution, so that your work or experiments doesn't remain freeze for long. Obviously, you cannot ask your client to have "CORS" enabled to run your solution, as it may compromise systems security.

performSelector may cause a leak because its selector is unknown

To ignore the error only in the file with the perform selector, add a #pragma as follows:

#pragma clang diagnostic ignored "-Warc-performSelector-leaks"

This would ignore the warning on this line, but still allow it throughout the rest of your project.

Counting Number of Letters in a string variable

What is wrong with using string.Length?

// len will be 5
int len = "Hello".Length;

insert data from one table to another in mysql

INSERT INTO mt_magazine_subscription ( 
      magazine_subscription_id, 
      subscription_name, 
      magazine_id, 
      status ) 
VALUES ( 
      (SELECT magazine_subscription_id, 
              subscription_name, 
              magazine_id,'1' as status
       FROM tbl_magazine_subscription 
       ORDER BY magazine_subscription_id ASC));

Regex that matches integers in between whitespace or start/end of string only

This solution matches integers:

  • Negative integers are matched (-1,-2,etc)
  • Single zeroes are matched (0)
  • Negative zeroes are not (-0, -01, -02)
  • Empty spaces are not matched ('')
/^(0|-*[1-9]+[0-9]*)$/

How do I install Python packages on Windows?

Starting with Python 2.7, pip is included by default. Simply download your desired package via

python -m pip install [package-name]

Maven Installation OSX Error Unsupported major.minor version 51.0

Please rather try:

$JAVA_HOME/bin/java -version

Maven uses $JAVA_HOME for classpath resolution of JRE libs. To be sure to use a certain JDK, set it explicitly before compiling, for example:

export JAVA_HOME=/usr/java/jdk1.7.0_51

Isn't there a version < 1.7 and you're using Maven 3.3.1? In this case the reason is a new prerequisite: https://issues.apache.org/jira/browse/MNG-5780

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

How do I use valgrind to find memory leaks?

You can run:

valgrind --leak-check=full --log-file="logfile.out" -v [your_program(and its arguments)]

JSON.parse vs. eval()

Not all browsers have native JSON support so there will be times where you need to use eval() to the JSON string. Use JSON parser from http://json.org as that handles everything a lot easier for you.

Eval() is an evil but against some browsers its a necessary evil but where you can avoid it, do so!!!!!

Convert INT to VARCHAR SQL

Actually you don't need to use STR Or Convert. Just select 'xxx'+LTRIM(ColumnName) does the job. Possibly, LTRIM uses Convert or STR under the hood.

LTRIM also removes need for providing length and usually default 10 is good enough for integer to string conversion.

SELECT LTRIM(ColumnName) FROM TableName

How can strip whitespaces in PHP's variable?

The \s regex argument is not compatible with UTF-8 multybyte strings.

This PHP RegEx is one I wrote to solve this using PCRE (Perl Compatible Regular Expressions) based arguments as a replacement for UTF-8 strings:

function remove_utf8_whitespace($string) { 
   return preg_replace('/\h+/u','',preg_replace('/\R+/u','',$string)); 
}

- Example Usage -

Before:

$string = " this is a test \n and another test\n\r\t ok! \n";

echo $string;

 this is a test
 and another test
         ok!

echo strlen($string); // result: 43

After:

$string = remove_utf8_whitespace($string);

echo $string;

thisisatestandanothertestok!

echo strlen($string); // result: 28

PCRE Argument Listing

Source: https://www.rexegg.com/regex-quickstart.html

Character   Legend  Example Sample Match
\t  Tab T\t\w{2}    T     ab
\r  Carriage return character   see below   
\n  Line feed character see below   
\r\n    Line separator on Windows   AB\r\nCD    AB
    CD
\N  Perl, PCRE (C, PHP, R…): one character that is not a line break \N+ ABC
\h  Perl, PCRE (C, PHP, R…), Java: one horizontal whitespace character: tab or Unicode space separator      
\H  One character that is not a horizontal whitespace       
\v  .NET, JavaScript, Python, Ruby: vertical tab        
\v  Perl, PCRE (C, PHP, R…), Java: one vertical whitespace character: line feed, carriage return, vertical tab, form feed, paragraph or line separator      
\V  Perl, PCRE (C, PHP, R…), Java: any character that is not a vertical whitespace      
\R  Perl, PCRE (C, PHP, R…), Java: one line break (carriage return + line feed pair, and all the characters matched by \v)      

Recursive mkdir() system call on Unix

A very simple solution, just pass in input: mkdir dirname

void execute_command_mkdir(char *input)
{
     char rec_dir[500];
     int s;
     if(strcmp(input,"mkdir") == 0)
        printf("mkdir: operand required");
    else
     {
        char *split = strtok(input," \t");
        while(split)
        {
            if(strcmp(split,"create_dir") != 0)
                strcpy(rec_dir,split);
            split = strtok(NULL, " \t");
        }
        char *split2 = strtok(rec_dir,"/");
        char dir[500];
        strcpy(dir, "");
        while(split2)
        {
            strcat(dir,split2);
            strcat(dir,"/");
            printf("%s %s\n",split2,dir);
            s = mkdir(dir,0700);
            split2 = strtok(NULL,"/");
        }
        strcpy(output,"ok");
    }
        if(s < 0)
            printf(output,"Error!! Cannot Create Directory!!");
}

Escape text for HTML

using System.Web;

var encoded = HttpUtility.HtmlEncode(unencoded);

Laravel: PDOException: could not find driver

Your database driver is missing. To solve the probelm

First install the driver

For ubuntu: For mysql database.

sudo apt-get install php5.6-mysql/php7.2-mysql

You also can search for other database systems.

You also can search for the driver:

sudo apt-cache search drivername

Then Run the cmd php artisan migrate

Centering brand logo in Bootstrap Navbar

Updated 2018

Bootstrap 3

See if this example helps: http://bootply.com/mQh8DyRfWY

The brand is centered using..

.navbar-brand
{
    position: absolute;
    width: 100%;
    left: 0;
    top: 0;
    text-align: center;
    margin: auto;
}

Your markup is for Bootstrap 2, not 3. There is no longer a navbar-inner.

EDIT - Another approach is using transform: translateX(-50%);

.navbar-brand {
  transform: translateX(-50%);
  left: 50%;
  position: absolute;
}

http://www.bootply.com/V7vKDfk46G

Bootstrap 4

In Bootstrap 4, mx-auto or flexbox can be used to center the brand and other elements. See How to position navbar contents in Bootstrap 4 for an explanation.

Also see:

Bootstrap NavBar with left, center or right aligned items

How to define several include path in Makefile

Make's substitutions feature is nice and helped me to write

%.i: src/%.c $(INCLUDE)
        gcc -E $(CPPFLAGS) $(INCLUDE:%=-I %) $< > $@

You might find this useful, because it asks make to check for changes in include folders too

Proper way to renew distribution certificate for iOS

This was a really a helpful thread, I followed the same steps as @junjie mentioned but for me something weird happened, the below are the steps I did.

  1. Went to developer portal and revoked the certificate which was about to expire.
  2. Went to XCode6.4 and in the Account settings, the certificate still showed valid, I went crazy.
  3. Then I opened XCode7, there the certificate was shown with "Reset" button instead of create and I hit the reset button and later in the portal I was able to see an extended certificate present. This is what Apple says about Reset button

If Xcode detects an issue with a signing identity, it displays an appropriate action in Accounts preferences. If Xcode displays a Create button, the signing identity doesn’t exist in Member Center or on your Mac. If Xcode displays a Reset button, the signing identity is not usable on your Mac—for example, it is missing the private key. If you click the Reset button, Xcode revokes and requests the corresponding certificate.

  1. I tried creating an Appstore ipa with that, just to test and it worked fine so I am saved, but still not sure what has happened. May be I had multiple accounts configured in my Mac, dont know.

When to use AtomicReference in Java?

Here is a use case for AtomicReference:

Consider this class that acts as a number range, and uses individual AtmomicInteger variables to maintain lower and upper number bounds.

public class NumberRange {
    // INVARIANT: lower <= upper
    private final AtomicInteger lower = new AtomicInteger(0);
    private final AtomicInteger upper = new AtomicInteger(0);

    public void setLower(int i) {
        // Warning -- unsafe check-then-act
        if (i > upper.get())
            throw new IllegalArgumentException(
                    "can't set lower to " + i + " > upper");
        lower.set(i);
    }

    public void setUpper(int i) {
        // Warning -- unsafe check-then-act
        if (i < lower.get())
            throw new IllegalArgumentException(
                    "can't set upper to " + i + " < lower");
        upper.set(i);
    }

    public boolean isInRange(int i) {
        return (i >= lower.get() && i <= upper.get());
    }
}

Both setLower and setUpper are check-then-act sequences, but they do not use sufficient locking to make them atomic. If the number range holds (0, 10), and one thread calls setLower(5) while another thread calls setUpper(4), with some unlucky timing both will pass the checks in the setters and both modifications will be applied. The result is that the range now holds (5, 4)an invalid state. So while the underlying AtomicIntegers are thread-safe, the composite class is not. This can be fixed by using a AtomicReference instead of using individual AtomicIntegers for upper and lower bounds.

public class CasNumberRange {
    // Immutable
    private static class IntPair {
        final int lower;  // Invariant: lower <= upper
        final int upper;

        private IntPair(int lower, int upper) {
            this.lower = lower;
            this.upper = upper;
        }
    }

    private final AtomicReference<IntPair> values = 
            new AtomicReference<IntPair>(new IntPair(0, 0));

    public int getLower() {
        return values.get().lower;
    }

    public void setLower(int lower) {
        while (true) {
            IntPair oldv = values.get();
            if (lower > oldv.upper)
                throw new IllegalArgumentException(
                    "Can't set lower to " + lower + " > upper");
            IntPair newv = new IntPair(lower, oldv.upper);
            if (values.compareAndSet(oldv, newv))
                return;
        }
    }

    public int getUpper() {
        return values.get().upper;
    }

    public void setUpper(int upper) {
        while (true) {
            IntPair oldv = values.get();
            if (upper < oldv.lower)
                throw new IllegalArgumentException(
                    "Can't set upper to " + upper + " < lower");
            IntPair newv = new IntPair(oldv.lower, upper);
            if (values.compareAndSet(oldv, newv))
                return;
        }
    }
}

How do I print uint32_t and uint16_t variables value?

The macros defined in <inttypes.h> are the most correct way to print values of types uint32_t, uint16_t, and so forth -- but they're not the only way.

Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)

An alternative is to cast the values to a predefined type and use the format for that type.

Types int and unsigned int are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t or uint16_t, respectively. Similarly, long and unsigned long are at least 32 bits wide, and long long and unsigned long long are at least 64 bits wide.

For example, I might write your program like this (with a few additional tweaks):

#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>  

int main(void)
{
    uint32_t a=12, a1;
    uint16_t b=1, b1;
    a1 = htonl(a);
    printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
    b1 = htons(b);
    printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
    return 0;
}

One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>. Such an implementation most likely wouldn't have <stdint.h> either, but the technique is useful for other integer types.

How do I determine the size of my array in C?

A more elegant solution will be

size_t size = sizeof(a) / sizeof(*a);

JavaScript query string

If you have the querystring on hand, use this:

 /**
 * @param qry the querystring
 * @param name name of parameter
 * @returns the parameter specified by name
 * @author [email protected]
 */

function getQueryStringParameter(qry,name){
    if(typeof qry !== undefined && qry !== ""){
        var keyValueArray = qry.split("&");
        for ( var i = 0; i < keyValueArray.length; i++) {
            if(keyValueArray[i].indexOf(name)>-1){
                return keyValueArray[i].split("=")[1];
            }
        }
    }
    return "";
}

Share link on Google+

<meta property="og:title" content="Ali Umair"/>
<meta property="og:description" content="Ali UMair is a web developer"/><meta property="og:image" content="../image" />

<a target="_blank" href="https://plus.google.com/share?url=<? echo urlencode('http://www..'); ?>"><img src="../gplus-black_icon.png" alt="" /></a>

this code will work with image text and description please put meta into head tag

Remove all files in a directory

Bit of a hack but if you would like to keep the directory, the following can be used.

import os
import shutil
shutil.rmtree('/home/me/test') 
os.mkdir('/home/me/test')

sql delete statement where date is greater than 30 days

Instead of converting to varchar to get just the day (convert(varchar(8), [Date], 112)), I prefer keeping it a datetime field and making it only the date (without the time).

SELECT * FROM Results 
WHERE CONVERT(date, [Date]) >= CONVERT(date, GETDATE())

How to create an array from a CSV file using PHP and the fgetcsv function

I came up with this pretty basic code. I think it could be useful to anyone.

$link = "link to the CSV here"
$fp = fopen($link, 'r');

while(($line = fgetcsv($fp)) !== FALSE) {
    foreach($line as $key => $value) {
        echo $key . " - " . $value . "<br>";
    }
}


fclose($fp);

How to make a flat list out of list of lists?

The accepted answer did not work for me when dealing with text-based lists of variable lengths. Here is an alternate approach that did work for me.

l = ['aaa', 'bb', 'cccccc', ['xx', 'yyyyyyy']]

Accepted answer that did not work:

flat_list = [item for sublist in l for item in sublist]
print(flat_list)
['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'xx', 'yyyyyyy']

New proposed solution that did work for me:

flat_list = []
_ = [flat_list.extend(item) if isinstance(item, list) else flat_list.append(item) for item in l if item]
print(flat_list)
['aaa', 'bb', 'cccccc', 'xx', 'yyyyyyy']

What does void mean in C, C++, and C#?

It indicates the absence of a return value in a function.

Some languages have two sorts of subroutines: procedures and functions. Procedures are just a sequence of operations, whereas a function is a sequence of operations that return a result.

In C and its derivatives, the difference between the two is not explicit. Everything is basically a function. the void keyword indicates that it's not an "actual" function, since it doesn't return a value.

How to use Object.values with typescript?

Instead of

Object.values(myObject);

use

Object["values"](myObject);

In your example case:

const values = Object["values"](data).map(x => x.substr(0, x.length - 4));

This will hide the ts compiler error.

How to change a text with jQuery

Could do it with :contains() selector as well:

$('#toptitle:contains("Profil")').text("New word");

example: http://jsfiddle.net/niklasvh/xPRzr/

Using NOT operator in IF conditions

It is generally not a bad idea to avoid the !-operator if you have the choice. One simple reason is that it can be a source of errors, because it is possible to overlook it. More readable can be: if(conditionA==false) in some cases. This mainly plays a role if you skip the else part. If you have an else-block anyway you should not use the negation in the if-condition.

Except for composed-conditions like this:

if(!isA() && isB() && !isNotC())

Here you have to use some sort of negation to get the desired logic. In this case, what really is worth thinking about is the naming of the functions or variables. Try to name them so you can often use them in simple conditions without negation.

In this case you should think about the logic of isNotC() and if it could be replaced by a method isC() if it makes sense.

Finally your example has another problem when it comes to readability which is even more serious than the question whether to use negation or not: Does the reader of the code really knows when doSomething() returns true and when false? If it was false was it done anyway? This is a very common problem, which ends in the reader trying to find out what the return values of functions really mean.

What does <a href="#" class="view"> mean?

Don't forget to look at the Javascript as well. My guess is that there is custom Javascript code getting executed when you click on the link and it's that Javascript that is generating the URL and navigating to it.

np.mean() vs np.average() in Python NumPy?

np.mean always computes an arithmetic mean, and has some additional options for input and output (e.g. what datatypes to use, where to place the result).

np.average can compute a weighted average if the weights parameter is supplied.

Getting a list of associative array keys

Try this:

var keys = [];
for (var key in dictionary) {
  if (dictionary.hasOwnProperty(key)) {
    keys.push(key);
  }
}

hasOwnProperty is needed because it's possible to insert keys into the prototype object of dictionary. But you typically don't want those keys included in your list.

For example, if you do this:

Object.prototype.c = 3;
var dictionary = {a: 1, b: 2};

and then do a for...in loop over dictionary, you'll get a and b, but you'll also get c.

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

In order to update your project to the latest version of java available in your environment, follow these steps:

  1. Open your pom.xml file
  2. Switch your view to Effective POM tab
  3. Open Find Dialog (ctrl + F) to search for maven-compiler-plugin
  4. Copy the the following lines

_x000D_
_x000D_
<plugin>_x000D_
 <artifactId>maven-compiler-plugin</artifactId>_x000D_
 <version>3.1</version>
_x000D_
_x000D_
_x000D_

  1. Click on pom.xml tab to open your project pom configuration
  2. Inside your <build> ... </build> configuration section, paste the configuration copied and modify it as...

_x000D_
_x000D_
        <plugins>_x000D_
     <plugin>_x000D_
      <artifactId>maven-compiler-plugin</artifactId>_x000D_
      <version>3.1</version>_x000D_
    _x000D_
      <configuration>_x000D_
       <source>1.8</source>_x000D_
       <target>1.8</target>_x000D_
      </configuration>_x000D_
     </plugin>_x000D_
    </plugins>
_x000D_
_x000D_
_x000D_

  1. save your configuration
  2. Right Click in your project Click on [Maven -> Update Project] and Click on OK in the displayed update dialog box.

Done!

Pass element ID to Javascript function

Check this: http://jsfiddle.net/h7kRt/1/,

you should change in jsfiddle on top-left to No-wrap in <head>

Your code looks good and it will work inside a normal page. In jsfiddle your function was being defined inside a load handler and thus is in a different scope. By changing to No-wrap you have it in the global scope and can use it as you wanted.

ImageMagick security policy 'PDF' blocking conversion

Works in Ubuntu 20.04

Add this line inside <policymap>

<policy domain="module" rights="read|write" pattern="{PS,PDF,XPS}" />

Comment these lines:

  <!--
  <policy domain="coder" rights="none" pattern="PS" />
  <policy domain="coder" rights="none" pattern="PS2" />
  <policy domain="coder" rights="none" pattern="PS3" />
  <policy domain="coder" rights="none" pattern="EPS" />
  <policy domain="coder" rights="none" pattern="PDF" />
  <policy domain="coder" rights="none" pattern="XPS" />
   -->

How to re import an updated package while in Python Interpreter?

Update for Python3: (quoted from the already-answered answer, since the last edit/comment here suggested a deprecated method)

In Python 3, reload was moved to the imp module. In 3.4, imp was deprecated in favor of importlib, and reload was added to the latter. When targeting 3 or later, either reference the appropriate module when calling reload or import it.

Takeaway:

  • Python3 >= 3.4: importlib.reload(packagename)
  • Python3 < 3.4: imp.reload(packagename)
  • Python2: continue below

Use the reload builtin function:

https://docs.python.org/2/library/functions.html#reload

When reload(module) is executed:

  • Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called a second time.
  • As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero.
  • The names in the module namespace are updated to point to any new or changed objects.
  • Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.

Example:

# Make a simple function that prints "version 1"
shell1$ echo 'def x(): print "version 1"' > mymodule.py

# Run the module
shell2$ python
>>> import mymodule
>>> mymodule.x()
version 1

# Change mymodule to print "version 2" (without exiting the python REPL)
shell2$ echo 'def x(): print "version 2"' > mymodule.py

# Back in that same python session
>>> reload(mymodule)
<module 'mymodule' from 'mymodule.pyc'>
>>> mymodule.x()
version 2

Get value from JToken that may not exist (best practices)

TYPE variable = jsonbody["key"]?.Value<TYPE>() ?? DEFAULT_VALUE;

e.g.

bool attachMap = jsonbody["map"]?.Value<bool>() ?? false;

How to SSH into Docker?

It is a short way but not permanent

first create a container

docker run  ..... -p 22022:2222 .....

port 22022 on your host machine will map on 2222, we change the ssh port on container later , then on your container executing the following commands

apt update && apt install  openssh-server # install ssh server
passwd #change root password

in file /etc/ssh/sshd_config change these : uncomment Port and change it to 2222

Port 2222

uncomment PermitRootLogin to

PermitRootLogin yes

and finally restart ssh server

/etc/init.d/ssh start

you can login to your container now

ssh -p 2022 root@HostIP

Remember : if you restart the container you need to restart ssh server again

How to remove last n characters from every element in the R vector

Here is an example of what I would do. I hope it's what you're looking for.

char_array = c("foo_bar","bar_foo","apple","beer")
a = data.frame("data"=char_array,"data2"=1:4)
a$data = substr(a$data,1,nchar(a$data)-3)

a should now contain:

  data data2
1 foo_ 1
2 bar_ 2
3   ap 3
4    b 4

How to determine whether a year is a leap year?

If you don't want to import calendar and apply .isleap method you can try this:

def isleapyear(year):
    if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
        return True
    return False

Cannot set some HTTP headers when using System.Net.WebRequest

I ran into same issue below piece of code worked for me

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

request.Headers["UserAgent"] = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; 
Trident/5.0)"

How do I empty an input value with jQuery?

$('.reset').on('click',function(){
           $('#upload input, #upload select').each(
                function(index){  
                    var input = $(this);
                    if(input.attr('type')=='text'){
                        document.getElementById(input.attr('id')).value = null;
                    }else if(input.attr('type')=='checkbox'){
                        document.getElementById(input.attr('id')).checked = false;
                    }else if(input.attr('type')=='radio'){
                        document.getElementById(input.attr('id')).checked = false;
                    }else{
                        document.getElementById(input.attr('id')).value = '';
                        //alert('Type: ' + input.attr('type') + ' -Name: ' + input.attr('name') + ' -Value: ' + input.val());
                    }
                }
            );
        });

Font Awesome 5 font-family issue

I had to set searchPseudoElements to to true to get it working in Angular5.

import fontawesome from '@fortawesome/fontawesome';
...
fontawesome.config.searchPseudoElements = true;
...
content: "\f12a";
font-family: 'Font Awesome 5 Solid';

How can I use "." as the delimiter with String.split() in java

If performance is an issue, you should consider using StringTokenizer instead of split. StringTokenizer is much much faster than split, even though it is a "legacy" class (but not deprecated).

How can I get useful error messages in PHP?

You can also run the file in the Terminal (command line) like so: php -f filename.php.

This runs your code and gives you the same output in case of any errors that you'd see in the error.log. It mentions the error and the line number.

Android : Fill Spinner From Java Code Programmatically

Here is an example to fully programmatically:

  • init a Spinner.
  • fill it with data via a String List.
  • resize the Spinner and add it to my View.
  • format the Spinner font (font size, colour, padding).
  • clear the Spinner.
  • add new values to the Spinner.
  • redraw the Spinner.

I am using the following class vars:

Spinner varSpinner;
List<String> varSpinnerData;

float varScaleX;
float varScaleY;    

A - Init and render the Spinner (varRoot is a pointer to my main Activity):

public void renderSpinner() {


    List<String> myArraySpinner = new ArrayList<String>();

    myArraySpinner.add("red");
    myArraySpinner.add("green");
    myArraySpinner.add("blue");     

    varSpinnerData = myArraySpinner;

    Spinner mySpinner = new Spinner(varRoot);               

    varSpinner = mySpinner;

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myArraySpinner);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
    mySpinner.setAdapter(spinnerArrayAdapter);

B - Resize and Add the Spinner to my View:

    FrameLayout.LayoutParams myParamsLayout = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT, 
            FrameLayout.LayoutParams.WRAP_CONTENT);
    myParamsLayout.gravity = Gravity.NO_GRAVITY;             

    myParamsLayout.leftMargin = (int) (100 * varScaleX);
    myParamsLayout.topMargin = (int) (350 * varScaleY);             
    myParamsLayout.width = (int) (300 * varScaleX);;
    myParamsLayout.height = (int) (60 * varScaleY);;


    varLayoutECommerce_Dialogue.addView(mySpinner, myParamsLayout);

C - Make the Click handler and use this to set the font.

    mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {

            Log.i("renderSpinner -> ", "onItemSelected: " + myPosition + "/" + myID);

            ((TextView) parentView.getChildAt(0)).setTextColor(Color.GREEN);
            ((TextView) parentView.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) (varScaleY * 22.0f) );
            ((TextView) parentView.getChildAt(0)).setPadding(1,1,1,1);


        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }

    });

}   

D - Update the Spinner with new data:

private void updateInitSpinners(){

     String mySelected = varSpinner.getSelectedItem().toString();
     Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);


     varSpinnerData.clear();

     varSpinnerData.add("Hello World");
     varSpinnerData.add("Hello World 2");

     ((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
     varSpinner.invalidate();
     varSpinner.setSelection(1);

}

}

What I have not been able to solve in the updateInitSpinners, is to do varSpinner.setSelection(0); and have the custom font settings activated automatically.

UPDATE:

This "ugly" solution solves the varSpinner.setSelection(0); issue, but I am not very happy with it:

private void updateInitSpinners(){

    String mySelected = varSpinner.getSelectedItem().toString();
    Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);


    varSpinnerData.clear();

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, varSpinnerData);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    varSpinner.setAdapter(spinnerArrayAdapter);  


    varSpinnerData.add("Hello World");
    varSpinnerData.add("Hello World 2");

    ((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
    varSpinner.invalidate();
    varSpinner.setSelection(0);

}

}

Hope this helps......

Align two divs horizontally side by side center to the page using bootstrap css

Make sure you wrap your "row" inside the class "container" . Also add reference to bootstrap in your html.
Something like this should work:
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
 <body>
     <p>lets learn!</p>
  <div class="container">
          <div class="row">
              <div class="col-lg-6" style="background-color: red;">
                  ONE
              </div>
              <div class="col-lg-2" style="background-color: blue;">
                  TWO
              </div>
              <div class="col-lg-4" style="background-color: green;">
              THREE
           </div>
          </div>
      </div>
 </body>
 </html>

Adding System.Web.Script reference in class library

You need to add a reference to System.Web.Extensions.dll in project for System.Web.Script.Serialization error.

Combine Regexp?

1 + 2 + 4 conditions: starts|ends, but not in the middle

/^@[^@]*@?$|^@?[^@]*@$/

is almost the same that:

/^@?[^@]*@?$/

but this one matches any string without @, sample 'my name is hal9000'

How to delete/remove nodes on Firebase

The problem is that you call remove on the root of your Firebase:

ref = new Firebase("myfirebase.com")
ref.remove();

This will remove the entire Firebase through the API.

You'll typically want to remove specific child nodes under it though, which you do with:

ref.child(key).remove();

Use PHP to create, edit and delete crontab jobs?

You could try overriding the EDITOR environment variable with something like ed which can take a sequence of edit commands over standard input.

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

I guess an img tag is needed as a child of an a tag, the following way:

<a download="YourFileName.jpeg" href="data:image/jpeg;base64,iVBO...CYII=">
    <img src="data:image/jpeg;base64,iVBO...CYII="></img>
</a>

or

<a download="YourFileName.jpeg" href="/path/to/OtherFile.jpg">
    <img src="/path/to/OtherFile.jpg"></img>
</a>

Only using the a tag as explained in #15 didn't worked for me with the latest version of Firefox and Chrome, but putting the same image data in both a.href and img.src tags worked for me.

From JavaScript it could be generated like this:

var data = canvas.toDataURL("image/jpeg");

var img = document.createElement('img');
img.src = data;

var a = document.createElement('a');
a.setAttribute("download", "YourFileName.jpeg");
a.setAttribute("href", data);
a.appendChild(img);

var w = open();
w.document.title = 'Export Image';
w.document.body.innerHTML = 'Left-click on the image to save it.';
w.document.body.appendChild(a);

Error converting data types when importing from Excel to SQL Server 2008

There is a workaround.

  1. Import excel sheet with numbers as float (default).
  2. After importing, Goto Table-Design
  3. Change DataType of the column from Float to Int or Bigint
  4. Save Changes
  5. Change DataType of the column from Bigint to any Text Type (Varchar, nvarchar, text, ntext etc)
  6. Save Changes.

That's it.

Passing arguments to C# generic new() of templated type

If all is you need is convertion from ListItem to your type T you can implement this convertion in T class as conversion operator.

public class T
{
    public static implicit operator T(ListItem listItem) => /* ... */;
}

public static string GetAllItems(...)
{
    ...
    List<T> tabListItems = new List<T>();
    foreach (ListItem listItem in listCollection) 
    {
        tabListItems.Add(listItem);
    } 
    ...
}

How to rename a class and its corresponding file in Eclipse?

Shift + Alt + r (Right click file -> Refactor -> Rename) when cursor is on class name. The file and constructors will be also changed.

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

Passing an array of data as an input parameter to an Oracle procedure

This is one way to do it:

SQL> set serveroutput on
SQL> CREATE OR REPLACE TYPE MyType AS VARRAY(200) OF VARCHAR2(50);
  2  /

Type created

SQL> CREATE OR REPLACE PROCEDURE testing (t_in MyType) IS
  2  BEGIN
  3    FOR i IN 1..t_in.count LOOP
  4      dbms_output.put_line(t_in(i));
  5    END LOOP;
  6  END;
  7  /

Procedure created

SQL> DECLARE
  2    v_t MyType;
  3  BEGIN
  4    v_t := MyType();
  5    v_t.EXTEND(10);
  6    v_t(1) := 'this is a test';
  7    v_t(2) := 'A second test line';
  8    testing(v_t);
  9  END;
 10  /

this is a test
A second test line

To expand on my comment to @dcp's answer, here's how you could implement the solution proposed there if you wanted to use an associative array:

SQL> CREATE OR REPLACE PACKAGE p IS
  2    TYPE p_type IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;
  3  
  4    PROCEDURE pp (inp p_type);
  5  END p;
  6  /

Package created
SQL> CREATE OR REPLACE PACKAGE BODY p IS
  2    PROCEDURE pp (inp p_type) IS
  3    BEGIN
  4      FOR i IN 1..inp.count LOOP
  5        dbms_output.put_line(inp(i));
  6      END LOOP;
  7    END pp;
  8  END p;
  9  /

Package body created
SQL> DECLARE
  2    v_t p.p_type;
  3  BEGIN
  4    v_t(1) := 'this is a test of p';
  5    v_t(2) := 'A second test line for p';
  6    p.pp(v_t);
  7  END;
  8  /

this is a test of p
A second test line for p

PL/SQL procedure successfully completed

SQL> 

This trades creating a standalone Oracle TYPE (which cannot be an associative array) with requiring the definition of a package that can be seen by all in order that the TYPE it defines there can be used by all.

Octave/Matlab: Adding new elements to a vector

x(end+1) = newElem is a bit more robust.

x = [x newElem] will only work if x is a row-vector, if it is a column vector x = [x; newElem] should be used. x(end+1) = newElem, however, works for both row- and column-vectors.

In general though, growing vectors should be avoided. If you do this a lot, it might bring your code down to a crawl. Think about it: growing an array involves allocating new space, copying everything over, adding the new element, and cleaning up the old mess...Quite a waste of time if you knew the correct size beforehand :)

How do you implement a class in C?

My strategy is:

  • Define all code for the class in a separate file
  • Define all interfaces for the class in a separate header file
  • All member functions take a "ClassHandle" which stands in for the instance name (instead of o.foo(), call foo(oHandle)
  • The constructor is replaced with a function void ClassInit(ClassHandle h, int x, int y,...) OR ClassHandle ClassInit(int x, int y,...) depending on the memory allocation strategy
  • All member variables are store as a member of a static struct in the class file, encapsulating it in the file, preventing outside files from accessing it
  • The objects are stored in an array of the static struct above, with predefined handles (visible in the interface) or a fixed limit of objects that can be instantiated
  • If useful, the class can contain public functions that will loop through the array and call the functions of all the instantiated objects (RunAll() calls each Run(oHandle)
  • A Deinit(ClassHandle h) function frees the allocated memory (array index) in the dynamic allocation strategy

Does anyone see any problems, holes, potential pitfalls or hidden benefits/drawbacks to either variation of this approach? If I am reinventing a design method (and I assume I must be), can you point me to the name of it?

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

This error could be thrown if you add your signing config(create signing key and add to the "Project Structure" > "Modules" > "Signing Configs") but forget to point out in "Project Structure" > "Build Variants" > "Build Types" > "Signing Config".

The signing config field shouldn't be empty! (Like in the picture below) Otherwise, you will see

"INSTALL_PARSE_FAILED_NO_CERTIFICATES...APK signature verification failed." 

error if you try to install a release variant. (or another variant with the same misconfiguration)

Signing Config Example

How to specify an alternate location for the .m2 folder or settings.xml permanently?

It's funny how other answers ignore the fact that you can't write to that file...

There are a few workarounds that come to my mind which could help use an arbitrary C:\redirected\settings.xml and use the mvn command as usual happily ever after.

mvn alias

In a Unix shell (or on Cygwin) you can create

alias mvn='mvn --global-settings "C:\redirected\settings.xml"'

so when you're calling mvn blah blah from anywhere the config is "automatically" picked up.
See How to create alias in cmd? if you want this, but don't have a Unix shell.

mvn wrapper

Configure your environment so that mvn is resolved to a wrapper script when typed in the command line:

  • Remove your MVN_HOME/bin or M2_HOME/bin from your PATH so mvn is not resolved any more.
  • Add a folder to PATH (or use an existing one)
  • In that folder create an mvn.bat file with contents:

    call C:\your\path\to\maven\bin\mvn.bat --global-settings "C:\redirected\settings.xml" %*
    

Note: if you want some projects to behave differently you can just create mvn.bat in the same folder as pom.xml so when you run plain mvn it resolves to the local one.

Use where mvn at any time to check how it is resolved, the first one will be run when you type mvn.

mvn.bat hack

If you have write access to C:\your\path\to\maven\bin\mvn.bat, edit the file and add set MAVEN_CMD_LINE_ARG to the :runm2 part:

@REM Start MAVEN2
:runm2
set MAVEN_CMD_LINE_ARGS=--global-settings "C:\redirected\settings.xml" %MAVEN_CMD_LINE_ARGS%
set CLASSWORLDS_LAUNCHER=...

mvn.sh hack

For completeness, you can change the C:\your\path\to\maven\bin\mvn shell script too by changing the exec "$JAVACMD" command's

${CLASSWORLDS_LAUNCHER} "$@"

part to

${CLASSWORLDS_LAUNCHER} --global-settings "C:\redirected\settings.xml" "$@"

Suggestion/Rant

As a person in IT it's funny that you don't have access to your own home folder, for me this constitutes as incompetence from the company you're working for: this is equivalent of hiring someone to do software development, but not providing even the possibility to use anything other than notepad.exe or Microsoft Word to edit the source files. I'd suggest to contact your help desk or administrator and request write access at least to that particular file so that you can change the path of the local repository.

Disclaimer: None of these are tested for this particular use case, but I successfully used all of them previously for various other software.

How to interpret "loss" and "accuracy" for a machine learning model

They are two different metrics to evaluate your model's performance usually being used in different phases.

Loss is often used in the training process to find the "best" parameter values for your model (e.g. weights in neural network). It is what you try to optimize in the training by updating weights.

Accuracy is more from an applied perspective. Once you find the optimized parameters above, you use this metrics to evaluate how accurate your model's prediction is compared to the true data.

Let us use a toy classification example. You want to predict gender from one's weight and height. You have 3 data, they are as follows:(0 stands for male, 1 stands for female)

y1 = 0, x1_w = 50kg, x2_h = 160cm;

y2 = 0, x2_w = 60kg, x2_h = 170cm;

y3 = 1, x3_w = 55kg, x3_h = 175cm;

You use a simple logistic regression model that is y = 1/(1+exp-(b1*x_w+b2*x_h))

How do you find b1 and b2? you define a loss first and use optimization method to minimize the loss in an iterative way by updating b1 and b2.

In our example, a typical loss for this binary classification problem can be: (a minus sign should be added in front of the summation sign)

We don't know what b1 and b2 should be. Let us make a random guess say b1 = 0.1 and b2 = -0.03. Then what is our loss now?

so the loss is

Then you learning algorithm (e.g. gradient descent) will find a way to update b1 and b2 to decrease the loss.

What if b1=0.1 and b2=-0.03 is the final b1 and b2 (output from gradient descent), what is the accuracy now?

Let's assume if y_hat >= 0.5, we decide our prediction is female(1). otherwise it would be 0. Therefore, our algorithm predict y1 = 1, y2 = 1 and y3 = 1. What is our accuracy? We make wrong prediction on y1 and y2 and make correct one on y3. So now our accuracy is 1/3 = 33.33%

PS: In Amir's answer, back-propagation is said to be an optimization method in NN. I think it would be treated as a way to find gradient for weights in NN. Common optimization method in NN are GradientDescent and Adam.

Run a task every x-minutes with Windows Task Scheduler

Hourly task example

While taking the advice above with schtasks, you can see in the UI what must be done to perform an hourly task. When you edit trigger begin the task on a schedule, One Time (this is the key). Then you can select "Repeat task every:" 1 hour or whatever you wish. See screenshot:

Which terminal command to get just IP address and nothing else?

hostname -I  

This command will give you the exact ip address as you want in Ubuntu.

Updating PartialView mvc 4

Controller :

public ActionResult Refresh(string ID)
    {
        DetailsViewModel vm = new DetailsViewModel();  // Model
        vm.productDetails = _product.GetproductDetails(ID); 
        /* "productDetails " is a property in "DetailsViewModel"
        "GetProductDetails" is a method in "Product" class
        "_product" is an interface of "Product" class */

        return PartialView("_Details", vm); // Details is a partial view
    }

In yore index page you should to have refresh link :

     <a href="#" id="refreshItem">Refresh</a>

This Script should be also in your index page:

<script type="text/javascript">

    $(function () {
    $('a[id=refreshItem]:last').click(function (e) {
        e.preventDefault();

        var url = MVC.Url.action('Refresh', 'MyController', { itemId: '@(Model.itemProp.itemId )' }); // Refresh is an Action in controller, MyController is a controller name

        $.ajax({
            type: 'GET',
            url: url,
            cache: false,
            success: function (grid) {
                $('#tabItemDetails').html(grid);
                clientBehaviors.applyPlugins($("#tabProductDetails")); // "tabProductDetails" is an id of div in your "Details partial view"
            }
        });
    });
});

Return Bit Value as 1/0 and NOT True/False in SQL Server

 Try this:- SELECT Case WHEN COLUMNNAME=0 THEN 'sex'
              ELSE WHEN COLUMNNAME=1 THEN 'Female' END AS YOURGRIDCOLUMNNAME FROM YOURTABLENAME

in your query for only true or false column

OpenJDK availability for Windows OS

OpenSCG maintains OpenJDK 6 installers for 32-bit Windows and other operating systems.

To configure it, create a JAVA_HOME environment variable and set it to C:\OpenSCG\openjdk-6.0.24 or whatever is the current version. Then add %JAVA_HOME%\bin; to the beginning of your PATH environment variable.

You can edit your environment variables by contextual clicking (My) Computer, selecting Properties, clicking Advanced system settings if you’re in Windows 7, clicking the Advanced tab and then clicking Environment Variables.

How to print the ld(linker) search path

The question is tagged Linux, but maybe this works as well under Linux?

gcc -Xlinker -v

Under Mac OS X, this prints:

@(#)PROGRAM:ld  PROJECT:ld64-224.1
configured to support archs: armv6 armv7 armv7s arm64 i386 x86_64 armv6m armv7m armv7em
Library search paths:
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib
Framework search paths:
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/System/Library/Frameworks/
[...]

The -Xlinker option of gcc above just passes -v to ld. However:

ld -v

doesn't print the search path.

Undefined symbols for architecture x86_64 on Xcode 6.1

I just had this error when I opened a (quite) old project, created in Xcode 4~ish, in Xcode 6.4. While the linked Frameworks were visible in the Project sidebar, I overlooked that there were no linked libraries in the Target Build Phases tab. Once I fixed that, it compiled fine.

In Android EditText, how to force writing uppercase?

Use input filter

editText = (EditText) findViewById(R.id.enteredText);
editText.setFilters(new InputFilter[]{new InputFilter.AllCaps()});

Calling other function in the same controller?

Try:

return $this->sendRequest($uri);

Since PHP is not a pure Object-Orieneted language, it interprets sendRequest() as an attempt to invoke a globally defined function (just like nl2br() for example), but since your function is part of a class ('InstagramController'), you need to use $this to point the interpreter in the right direction.

How to normalize a histogram in MATLAB?

My answer to this is the same as in an answer to your earlier question. For a probability density function, the integral over the entire space is 1. Dividing by the sum will not give you the correct density. To get the right density, you must divide by the area. To illustrate my point, try the following example.

[f, x] = hist(randn(10000, 1), 50); % Create histogram from a normal distribution.
g = 1 / sqrt(2 * pi) * exp(-0.5 * x .^ 2); % pdf of the normal distribution

% METHOD 1: DIVIDE BY SUM
figure(1)
bar(x, f / sum(f)); hold on
plot(x, g, 'r'); hold off

% METHOD 2: DIVIDE BY AREA
figure(2)
bar(x, f / trapz(x, f)); hold on
plot(x, g, 'r'); hold off

You can see for yourself which method agrees with the correct answer (red curve).

enter image description here

Another method (more straightforward than method 2) to normalize the histogram is to divide by sum(f * dx) which expresses the integral of the probability density function, i.e.

% METHOD 3: DIVIDE BY AREA USING sum()
figure(3)
dx = diff(x(1:2))
bar(x, f / sum(f * dx)); hold on
plot(x, g, 'r'); hold off

Hide Button After Click (With Existing Form on Page)

Here is another solution using Jquery I find it a little easier and neater than inline JS sometimes.

    <html>
    <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script>

        /* if you prefer to functionize and use onclick= rather then the .on bind
        function hide_show(){
            $(this).hide();
            $("#hidden-div").show();
        }
        */

        $(function(){
            $("#chkbtn").on('click',function() {
                $(this).hide();
                $("#hidden-div").show();
            }); 
        });
    </script>
    <style>
    .hidden-div {
        display:none
    }
    </style>
    </head>
    <body>
    <div class="reform">
        <form id="reform" action="action.php" method="post" enctype="multipart/form-data">
        <input type="hidden" name="type" value="" />
            <fieldset>
                content here...
            </fieldset>

                <div class="hidden-div" id="hidden-div">

            <fieldset>
                more content here that is hidden until the button below is clicked...
            </fieldset>
        </form>
                </div>
                <span style="display:block; padding-left:640px; margin-top:10px;"><button id="chkbtn">Check Availability</button></span>
    </div>
    </body>
    </html>

Get properties and values from unknown object

This example trims all the string properties of an object.

public static void TrimModelProperties(Type type, object obj)
{
    var propertyInfoArray = type.GetProperties(
                                    BindingFlags.Public | 
                                    BindingFlags.Instance);
    foreach (var propertyInfo in propertyInfoArray)
    {
        var propValue = propertyInfo.GetValue(obj, null);
        if (propValue == null) 
            continue;
        if (propValue.GetType().Name == "String")
            propertyInfo.SetValue(
                             obj, 
                             ((string)propValue).Trim(), 
                             null);
    }
}

Get Selected Item Using Checkbox in Listview

I had similar problem. Provided xml sample is put as single ListViewItem, and i couldn't click on Item itself, but checkbox was workng.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/source_container"
    >
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/menu_source_icon"
        android:background="@drawable/bla"
        android:layout_margin="5dp"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/menu_source_name"
        android:text="Test"
        android:textScaleX="1.5"
        android:textSize="20dp"
        android:padding="8dp"
        android:layout_weight="1"
        android:layout_gravity="center_vertical"
        android:textColor="@color/source_text_color"/>
    <CheckBox
        android:layout_width="40dp"
        android:layout_height="match_parent"
        android:id="@+id/menu_source_check_box"/>

</LinearLayout>

Solution: add attribute

android:focusable="false"

to CheckBox control.

How do you read a file into a list in Python?

If you have multiple numbers per line and you have multiple lines, you can read them in like this:

    #!/usr/bin/env python

    from os.path import dirname

    with open(dirname(__file__) + '/data/path/filename.txt') as input_data:
        input_list= [map(int,num.split()) for num in input_data.readlines()]

regex error - nothing to repeat

regular expression normally uses * and + in theory of language. I encounter the same bug while executing the line code

re.split("*",text)

to solve it, it needs to include \ before * and +

re.split("\*",text)

Installing specific laravel version with composer create-project

To install specific version of laravel try this & simply command on terminal

composer create-project --prefer-dist laravel/laravel:5.5.0 {dir-name}

Print a div using javascript in angularJS single page application

I don't think there's any need of writing this much big codes.

I've just installed angular-print bower package and all is set to go.

Just inject it in module and you're all set to go Use pre-built print directives & fun is that you can also hide some div if you don't want to print

http://angular-js.in/angularprint/

Mine is working awesome .

How to enable Google Play App Signing

There is a much simpler solution that will take a minute.

  1. In google play console, select Release management -> App signing
  2. Choose the first option, the one with Generate encrypted private key with Android Studio (or something like that; I cannot turn back to see that page anymore)
  3. In Android Studio generate your Android App Bundle (.aap file) from Build -> Generate Signed Bundle / APK..., choose Android App Bundle option and don't forget to check Export Encrypted key (needed to enroll your app Google Play App signing) option. If you do not have a keystore generated, generate one ad-hoc.
  4. Now the "tricky" part. After the .aap is generated, Android Studio will pop up a notification in the bottom right corner containing a path to the location where the .aap file is saved. In the same notification, if you will expand it you will find another link to the path where the private key was saved (called private_key.pepk). If you miss this notification, don't worry, just open Event Log window by clicking the Event Log button on the bottom right side and you will find the same info. Open that location.For me was C:\Users\yourUser\.android

enter image description here

  1. Go back in browser and press APP SIGNING PRIVATE KEY button and browse to the private key location on your computer.

Done!

Now you are able to upload your release that you generated earlier :) Good luck!

Python, how to check if a result set is empty?

You can do like this :

count = 0
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=serverName;"
                      "Trusted_Connection=yes;")
cursor = cnxn.cursor()
cursor.execute(SQL query)
for row in cursor:
    count = 1
    if true condition:
        print("True")
    else:
        print("False")
if count == 0:
    print("No Result")

Thanks :)

Android: I lost my android key store, what should I do?

If you lost a keystore file, don't create/update the new one with another set of value. First do the thorough search. Because it will overwrite the old one, so it will not match to your previous apk.

If you use eclipse most probably it will store in default path. For MAC (eclipse) it will be in your elispse installation path something like:

/Applications/eclipse/Eclipse.app/Contents/MacOS/

then your keystore file without any extension. You need root privilege to access this path (file).

how to specify local modules as npm package dependencies

After struggling much with the npm link command (suggested solution for developing local modules without publishing them to a registry or maintaining a separate copy in the node_modules folder), I built a small npm module to help with this issue.

The fix requires two easy steps.

First:

npm install lib-manager --save-dev

Second, add this to your package.json:

{  
  "name": "yourModuleName",  
  // ...
  "scripts": {
    "postinstall": "./node_modules/.bin/local-link"
  }
}

More details at https://www.npmjs.com/package/lib-manager. Hope it helps someone.

Object Library Not Registered When Adding Windows Common Controls 6.0

I can confirm that this is not fixable by unregistering and registering the MSCOMCTRL.OCX like before. I have been trying to pin down which update is the source of the problem and it looks like it's either IE10 or IE10 in combination with some other update that's causing the problem. If I can get more time to invest in this I'll update my post but in the meantime uninstalling IE10 resolves the issue.

__FILE__ macro shows full path

If you are using CMAKE with GNU compiler this global define works fine:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__MY_FILE__='\"$(notdir $(abspath $<))\"'")

How do I import the javax.servlet API in my Eclipse project?

I was getting a null pointer exception during project creation related to "Dynamic Web Module".

To get the project to compile (that is, to javax.servlet to import successfully) I had to go to project's Properties, pick Project Facets in the sidebar, tick Dynamic Web Module and click Apply.

Surprisingly, this time "Dynamic Web Module" facet installed correctly, and import started to work.

Create a Dropdown List for MVC3 using Entity Framework (.edmx Model) & Razor Views && Insert A Database Record to Multiple Tables

Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:

  1. You should never send your model to the view => This is correct
  2. If you create a ViewModel, and include the Model as member in the ViewModel, then you effectively sent your model to the View => this is BAD
  3. Using dictionaries to send the options to the view => this not good style

So how can you create a better coupling?

I would use a tool like AutoMapper or ValueInjecter to map between ViewModel and Model. AutoMapper does seem to have the better syntax and feel to it, but the current version lacks a very severe topic: It is not able to perform the mapping from ViewModel to Model (under certain circumstances like flattening, etc., but this is off topic) So at present I prefer to use ValueInjecter.

So you create a ViewModel with the fields you need in the view. You add the SelectList items you need as lookups. And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist: You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList from the view to the controller.

  // StaffTypes is an IEnumerable<StaffType> from dbContext
  // viewModel is the viewModel initialized to copy content of Model Employee  
  // viewModel.StaffTypes is of type SelectList

  viewModel.StaffTypes =
    new SelectList(
        StaffTypes.OrderBy( item => item.Name )
        "StaffTypeID",
        "Type",
        viewModel.StaffTypeID
    );

In the view you just have to call

@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )

Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel. You then check for validation. If the validation fails, you have to remember to re-populate the viewModel.StaffTypes SelectList, because this item will be null on entering the post function. So I tend to have those population things separated into a function. You just call back return new View(viewModel) if anything is wrong. Validation errors found by MVC3 will automatically be shown in the view.

If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState to get info on that.

If the viewModel is valid you have to perform the next step:

If it is a create of a new item, you have to populate a model from the viewModel (best suited is ValueInjecter). Then you can add it to the EF collection of that type and commit changes.

If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel back to the model (again using ValueInjecter gets you do that very quick). After that you can SaveChanges and are done.

Feel free to ask if anything is unclear.

How do I activate a Spring Boot profile when running from IntelliJ?

If you actually make use of spring boot run configurations (currently only supported in the Ultimate Edition) it's easy to pre-configure the profiles in "Active Profiles" setting.

enter image description here

Python error when trying to access list by index - "List indices must be integers, not str"

players is a list which needs to be indexed by integers. You seem to be using it like a dictionary. Maybe you could use unpacking -- Something like:

name, score = player

(if the player list is always a constant length).

There's not much more advice we can give you without knowing what query is and how it works.

It's worth pointing out that the entire code you posted doesn't make a whole lot of sense. There's an IndentationError on the second line. Also, your function is looping over some iterable, but unconditionally returning during the first iteration which isn't usually what you actually want to do.

How can I convert NSDictionary to NSData and vice versa?

Use NSJSONSerialization:

NSDictionary *dict;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];

NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:dataFromDict
                                                             options:NSJSONReadingAllowFragments
                                                               error:&error];

The latest returns id, so its a good idea to check the returned object type after you cast (here i casted to NSDictionary).

Could not find any resources appropriate for the specified culture or the neutral culture

I had the same issue when trying to run an update-database command on EF. Turns out the migration that was throwing the exception had the .resx file excluded from the project. I just right-clicked the .resx file and clicked "Include In Project". Problem solved.

Get image dimensions

You can use the getimagesize function like this:

list($width, $height) = getimagesize('path to image');
echo "width: " . $width . "<br />";
echo "height: " .  $height;

Display image at 50% of its "native" size

The zoom property sounds as though it's perfect for Adam Ernst as it suits his target device. However, for those who need a solution to this and have to support as many devices as possible you can do the following:

<img src="..." onload="this.width/=2;this.onload=null;" />

The reason for the this.onload=null addition is to avoid older browsers that sometimes trigger the load event twice (which means you can end up with quater-sized images). If you aren't worried about that though you could write:

<img src="..." onload="this.width/=2;" />

Which is quite succinct.

jQuery UI - Draggable is not a function?

I had the same problem for another reason and my eye needed one hour to find out. I had copy-pasted the script tags that load jquery :

<script src="**https**://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="**http**://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>

My website was using https when accessed from a mobile browser and refused to load jquery-ui without https.

1067 error on attempt to start MySQL

I ran into the same errors. Similar approach for me. From what I can tell, there is something weird going on with the reference to the datadir in the my.ini file. Even when I manually edited it I could not seem to have any effect on it, until I blew EVERYTHING AWAY. Wish I had better news...do a DB backup first.

For me the key to getting this to work was:

1) Remove the previous installation from settings->control panel. Restart your machine.

2) Once machine comes back up, forcefully delete the previous installation directory. [mine is C:\apps\MySQL\MySQLServer-5.5\, as I REFUSE to use c:\program files\..]

3) Forcefully delete the previous datadir directory [mine was c:\data\mysql].

4) Forcefully delete the previous default data directory [C:\Documents and Settings\All Users\Application Data\MySQL].

5) Re-run the install, selected the same installation directory. Skip the instance configurator/wizard at the end of the install.

6) Make sure the ../bin directory gets added to the path. Verify it.

7) Manually run the instance configurator/wizard.
Set the root password, port [3306]. It will try to start it. Again, mine FAILED to start [duh! nothing new there!!!]

8) Now, manually edit the my.ini file in the install directory, and correct the datadir setting to be [datadir="C:/Data/MySQL/"] MATCH CAPITALIZATION !!!!

9) Verify the service is setup correctly via the command-prompt [sc qc mysql <enter>].
Should look like:

C:\dev\cmdz>sc qc mysql

[SC] GetServiceConfig SUCCESS

SERVICE_NAME: mysql
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : "C:\apps\MySQL\MySQLServer-5.5\bin\mysqld" --defaults-file="C:\apps\MySQL\MySQLServer-5.5\my.ini" MySQL
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : MySQL
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem

10) Copy the contents of the default data-directory created under C:\Documents and Settings\All Users\Application Data\MySQL [basically everything in this directory to your desired data directory c:\data\mysql]. Make sure you get the C:\Documents and Settings\All Users\Application Data\MySQL\mysql directory. This has host.frm file, and others.
You should end up with a directory now of c:\data\MySQL\mysql...

11) Rename the default directory C:\Documents and Settings\All Users\Application Data\MySQL To C:\Documents and Settings\All Users\Application Data\MySQLxxx So it cannot find it...

12) Say a quick prayer...

13) Give it a kick start from command line with [net start mysql]

That got it working for me...

Best of Luck!

Find first element in a sequence that matches a predicate

J.F. Sebastian's answer is most elegant but requires python 2.6 as fortran pointed out.

For Python version < 2.6, here's the best I can come up with:

from itertools import repeat,ifilter,chain
chain(ifilter(predicate,seq),repeat(None)).next()

Alternatively if you needed a list later (list handles the StopIteration), or you needed more than just the first but still not all, you can do it with islice:

from itertools import islice,ifilter
list(islice(ifilter(predicate,seq),1))

UPDATE: Although I am personally using a predefined function called first() that catches a StopIteration and returns None, Here's a possible improvement over the above example: avoid using filter / ifilter:

from itertools import islice,chain
chain((x for x in seq if predicate(x)),repeat(None)).next()

How to define an empty object in PHP

stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.

When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.

<?php
// ways of creating stdClass instances
$x = new stdClass;
$y = (object) null;        // same as above
$z = (object) 'a';         // creates property 'scalar' = 'a'
$a = (object) array('property1' => 1, 'property2' => 'b');
?>

stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.

<?php
// CTest does not derive from stdClass
class CTest {
    public $property1;
}
$t = new CTest;
var_dump($t instanceof stdClass);            // false
var_dump(is_subclass_of($t, 'stdClass'));    // false
echo get_class($t) . "\n";                   // 'CTest'
echo get_parent_class($t) . "\n";            // false (no parent)
?>

You cannot define a class named 'stdClass' in your code. That name is already used by the system. You can define a class named 'Object'.

You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.

(tested on PHP 5.2.8)

Get first element of Series without knowing the index

Use iloc to access by position (rather than label):

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]: 
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]: 
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1

Best TCP port number range for internal applications

Short answer: use an unassigned user port

Over achiever's answer - Select and deploy a resource discovery solution. Have the server select a private port dynamically. Have the clients use resource discovery.

The risk that that a server will fail because the port it wants to listen on is not available is real; at least it's happened to me. Another service or a client might get there first.

You can almost totally reduce the risk from a client by avoiding the private ports, which are dynamically handed out to clients.

The risk that from another service is minimal if you use a user port. An unassigned port's risk is only that another service happens to be configured (or dyamically) uses that port. But at least that's probably under your control.

The huge doc with all the port assignments, including User Ports, is here: http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt look for the token Unassigned.

git - pulling from specific branch

git-pull - Fetch from and integrate with another repository or a local branch

git pull [options] [<repository> [<refspec>...]]

You can refer official git doc https://git-scm.com/docs/git-pull

Ex :

git pull origin dev

how to take user input in Array using java?

import java.util.Scanner;

class Example{

//Checks to see if a string is consider an integer.

public static boolean isInteger(String s){

    if(s.isEmpty())return false;

    for (int i = 0; i <s.length();++i){

        char c = s.charAt(i);

        if(!Character.isDigit(c) && c !='-')

            return false;
    }

    return true;
}

//Get integer. Prints out a prompt and checks if the input is an integer, if not it will keep asking.

public static int getInteger(String prompt){
    Scanner input = new Scanner(System.in);
    String in = "";
    System.out.println(prompt);
    in = input.nextLine();
    while(!isInteger(in)){
        System.out.println(prompt);
        in = input.nextLine();
    }
    input.close();
    return Integer.parseInt(in);
}

public static void main(String[] args){
    int [] a = new int[6];
    for (int i = 0; i < a.length;++i){
        int tmp = getInteger("Enter integer for array_"+i+": ");//Force to read an int using the methods above.
        a[i] = tmp;
    }

}

}

check if a std::vector contains a certain object?

See question: How to find an item in a std::vector?

You'll also need to ensure you've implemented a suitable operator==() for your object, if the default one isn't sufficient for a "deep" equality test.

static files with express.js

use below inside your app.js

app.use(express.static('folderName'));

(folderName is folder which has files) - remember these assets are accessed direct through server path (i.e. http://localhost:3000/abc.png (where as abc.png is inside folderName folder)

How do you share constants in NodeJS modules?

import and export (prob need something like babel as of 2018 to use import)

types.js

export const BLUE = 'BLUE'
export const RED = 'RED'

myApp.js

import * as types from './types.js'

const MyApp = () => {
  let colour = types.RED
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

How to run a Runnable thread in Android at defined intervals?

For repeating task you can use

new Timer().scheduleAtFixedRate(task, runAfterADelayForFirstTime, repeaingTimeInterval);

call it like

new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {

            }
        },500,1000);

The above code will run first time after half second(500) and repeat itself after each second(1000)

Where

task being the method to be executed

after the time to initial execution

(interval the time for repeating the execution)

Secondly

And you can also use CountDownTimer if you want to execute a Task number of times.

    new CountDownTimer(40000, 1000) { //40000 milli seconds is total time, 1000 milli seconds is time interval

     public void onTick(long millisUntilFinished) {
      }
      public void onFinish() {
     }
    }.start();

//Above codes run 40 times after each second

And you can also do it with runnable. create a runnable method like

Runnable runnable = new Runnable()
    {
        @Override
        public void run()
        {

        }
    };

And call it in both these ways

new Handler().postDelayed(runnable, 500 );//where 500 is delayMillis  // to work on mainThread

OR

new Thread(runnable).start();//to work in Background 

Python reading from a file and saving to utf-8

Process text to and from Unicode at the I/O boundaries of your program using open with the encoding parameter. Make sure to use the (hopefully documented) encoding of the file being read. The default encoding varies by OS (specifically, locale.getpreferredencoding(False) is the encoding used), so I recommend always explicitly using the encoding parameter for portability and clarity (Python 3 syntax below):

with open(filename, 'r', encoding='utf8') as f:
    text = f.read()

# process Unicode text

with open(filename, 'w', encoding='utf8') as f:
    f.write(text)

If still using Python 2 or for Python 2/3 compatibility, the io module implements open with the same semantics as Python 3's open and exists in both versions:

import io
with io.open(filename, 'r', encoding='utf8') as f:
    text = f.read()

# process Unicode text

with io.open(filename, 'w', encoding='utf8') as f:
    f.write(text)

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

For me the problem was that I made a new target in my app by duplicating an existing one, but forgot to add the target to the Podfile. For some reason, the cloned target did work for days without problems, but after a while it failed to build by this error. I had to create a new target entry for my cloned project target in the Podfile then run pod install.

Plotting images side by side using matplotlib

If the images are in an array and you want to iterate through each element and print it, you can write the code as follows:

plt.figure(figsize=(10,10)) # specifying the overall grid size

for i in range(25):
    plt.subplot(5,5,i+1)    # the number of images in the grid is 5*5 (25)
    plt.imshow(the_array[i])

plt.show()

Also note that I used subplot and not subplots. They're both different

Aligning label and textbox on same line (left and right)

You should use CSS to align the textbox. The reason your code above does not work is because by default a div's width is the same as the container it's in, therefore in your example it is pushed below.

The following would work.

<td  colspan="2" class="cell">
                <asp:Label ID="Label6" runat="server" Text="Label"></asp:Label>        
                <asp:TextBox ID="TextBox3" runat="server" CssClass="righttextbox"></asp:TextBox>       
</td>

In your CSS file:

.cell
{
text-align:left;
}

.righttextbox
{
float:right;
}

How to break out of while loop in Python?

Walrus operator (assignment expressions added to python 3.8) and while-loop-else-clause can do it more pythonic:

myScore = 0
while ans := input("Roll...").lower() == "r":
    # ... do something
else:
    print("Now I'll see if I can break your score...")

Auto refresh page every 30 seconds

Use setInterval instead of setTimeout. Though in this case either will be fine but setTimeout inherently triggers only once setInterval continues indefinitely.

<script language="javascript">
setInterval(function(){
   window.location.reload(1);
}, 30000);
</script>

JQuery, setTimeout not working

You've got a couple of issues here.

Firstly, you're defining your code within an anonymous function. This construct:

(function() {
  ...
)();

does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.

You're passing in a code block to setTimeout(). The problem is that update() is not within scope when executed like that. It however if you pass in a function pointer instead so this works:

(function() {
  $(document).ready(function() {update();});

  function update() { 
    $("#board").append(".");
    setTimeout(update, 1000);     }
  }
)();

because the function pointer update is within scope of that block.

But like I said, there is no need for the anonymous function so you can rewrite it like this:

$(document).ready(function() {update();});

function update() { 
  $("#board").append(".");
  setTimeout(update, 1000);     }
}

or

$(document).ready(function() {update();});

function update() { 
  $("#board").append(".");
  setTimeout('update()', 1000);     }
}

and both of these work. The second works because the update() within the code block is within scope now.

I also prefer the $(function() { ... } shortened block form and rather than calling setTimeout() within update() you can just use setInterval() instead:

$(function() {
  setInterval(update, 1000);
});

function update() {
  $("#board").append(".");
}

Hope that clears that up.

Where can I download mysql jdbc jar from?

Here's a one-liner using Maven:

mvn dependency:get -Dartifact=mysql:mysql-connector-java:5.1.38

Then, with default settings, it's available in:

$HOME/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar

Just replace the version number if you need a different one.

Setting Java heap space under Maven 2 on Windows

You are looking for 2 options to java:

  • -Xmx maximum heap size
  • -Xms starting heap size

Put them in your command line invocation of the java executable, like this:

java -Xms512M -Xmx1024M my.package.MainClass

Keep in mind that you may want the starting and max heap sizes to be the same, depending on the application, as it avoids resizing the heap during runtime (which can take up time in applications that need to be responsive). Resizing the heap can entail moving a lot of objects around and redoing bookkeeping.

For every-day projects, make them whatever you think is good enough. Profile for help.

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

The .Trim() function will do all the work for you!

I was trying the code above, but after the "trim" function, and I noticed it's all "clean" even before it reaches the replace code!

String input:       "This is an example string.\r\n\r\n"
Trim method result: "This is an example string."

Source: http://www.dotnetperls.com/trim

Most concise way to convert a Set<T> to a List<T>

Try this for Set:

Set<String> listOfTopicAuthors = .....
List<String> setList = new ArrayList<String>(listOfTopicAuthors); 

Try this for Map:

Map<String, String> listOfTopicAuthors = .....
// List of values:
List<String> mapValueList = new ArrayList<String>(listOfTopicAuthors.values());
// List of keys:
List<String> mapKeyList = new ArrayList<String>(listOfTopicAuthors.KeySet());

How to align input forms in HTML

Well for the very basics you can try aligning them in the table. However the use of table is bad for layout since table is meant for contents.

What you can use is CSS floating techniques.

CSS Code

.styleform label{float:left;}
.styleform input{margin-left:200px;} /* this gives space for the label on the left */
.styleform .clear{clear:both;} /* prevent elements from stacking weirdly */

HTML

<div class="styleform">
<form>
<label>First Name:</label><input type="text" name="first" /><div class="clear"></div>
<label>Last Name:</label><input type="text" name="first" /><div class="clear"></div>
<label>Email:</label><input type="text" name="first" /><div class="clear"></div>
</form>
</div>

An elaborated article I wrote can be found answering the question of IE7 float problem: IE7 float right problems

Understanding Matlab FFT example

It sounds like you need to some background reading on what an FFT is (e.g. http://en.wikipedia.org/wiki/FFT). But to answer your questions:

Why does the x-axis (frequency) end at 500?

Because the input vector is length 1000. In general, the FFT of a length-N input waveform will result in a length-N output vector. If the input waveform is real, then the output will be symmetrical, so the first 501 points are sufficient.

Edit: (I didn't notice that the example padded the time-domain vector.)

The frequency goes to 500 Hz because the time-domain waveform is declared to have a sample-rate of 1 kHz. The Nyquist sampling theorem dictates that a signal with sample-rate fs can support a (real) signal with a maximum bandwidth of fs/2.

How do I know the frequencies are between 0 and 500?

See above.

Shouldn't the FFT tell me, in which limits the frequencies are?

No.

Does the FFT only return the amplitude value without the frequency?

The FFT simply assigns an amplitude (and phase) to every frequency bin.

Count rows with not empty value

Solved using a solution i found googling by Yogi Anand: https://productforums.google.com/d/msg/docs/3qsR2m-1Xx8/sSU6Z6NYLOcJ

The example below counts the number of non-empty rows in the range A3:C, remember to update both ranges in the formula with your range of interest.

=ArrayFormula(SUM(SIGN(MMULT(LEN(A3:C), TRANSPOSE(SIGN(COLUMN(A3:C)))))))

Also make sure to avoid circular dependencies, it will happen if you for example count the number of non-empty rows in A:C and place this formula in the A or C column.

Removing spaces from a variable input using PowerShell 4.0

You're close. You can strip the whitespace by using the replace method like this:

$answer.replace(' ','')

There needs to be no space or characters between the second set of quotes in the replace method (replacing the whitespace with nothing).

sql query to return differences between two tables

This will do the trick, similar with Tiago's solution, return "source" table as well.

select [First name], [Last name], max(_tabloc) as _tabloc
from (
  select [First Name], [Last name], 't1' as _tabloc from table1
  union all
  select [First name], [Last name], 't2' as _tabloc from table2
) v
group by [Fist Name], [Last name]
having count(1)=1

result will contain differences between tables, in column _tabloc you will have table reference.

BeautifulSoup: extract text from anchor tag

print(link_addres.contents[0])

It will print the context of the anchor tags

example:

 statement_title = statement.find('h2',class_='briefing-statement__title')
 statement_title_text = statement_title.a.contents[0]

Reading rows from a CSV file in Python

The Easiest way is this way :

from csv import reader

# open file in read mode
with open('file.csv', 'r') as read_obj:
    # pass the file object to reader() to get the reader object
    csv_reader = reader(read_obj)
    # Iterate over each row in the csv using reader object
    for row in csv_reader:
        # row variable is a list that represents a row in csv
        print(row)

output:
['Year:', 'Dec:', 'Jan:']
['1', '50', '60']
['2', '25', '50']
['3', '30', '30']
['4', '40', '20']
['5', '10', '10']

A full list of all the new/popular databases and their uses?

The SQLite database engine

With library for most popular languages

  • .Net
  • perl
  • Feel free to edit this and add more links

How to get image size (height & width) using JavaScript?

You can only really do this using a callback of the load event as the size of the image is not known until it has actually finished loading. Something like the code below...

var imgTesting = new Image();

function CreateDelegate(contextObject, delegateMethod)
{
    return function()
    {
        return delegateMethod.apply(contextObject, arguments);
    }
}

function imgTesting_onload()
{
    alert(this.width + " by " + this.height);
}


imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
imgTesting.src = 'yourimage.jpg';

How can I capture the result of var_dump to a string?

Long string: Just use echo($var); instead of dump($var);.

Object or Array: var_dump('<pre>'.json_encode($var).'</pre>);'

React Checkbox not sending onChange

It's better not to use refs in such cases. Use:

<input
    type="checkbox"
    checked={this.state.active}
    onClick={this.handleClick}
/>

There are some options:

checked vs defaultChecked

The former would respond to both state changes and clicks. The latter would ignore state changes.

onClick vs onChange

The former would always trigger on clicks. The latter would not trigger on clicks if checked attribute is present on input element.

How to get rid of the "No bootable medium found!" error in Virtual Box?

It's Never late. This error shows that you have After Installation of OS in Virtual Box you Remove the ISO file from Virtual Box Setting or you change your OS ISO file location. Thus you can Solve your Problem bY following given steps or you can watch video at Link

  1. Open Virtual Box and Select you OS from List in Left side.
  2. Then Select Setting. (setting Windows will open)
  3. The Select on "Storage" From Left side Panel.
  4. Then select on "empty" disk Icon on Right side panel.
  5. Under "Attribute" Section you can See another Disk icon. select o it.
  6. Then Select on "Choose Virtual Optical Disk file" and Select your OS ISO file.
  7. Restart VirtualBox and Start you OS.

To watch Video click on Below link: Link

Pandas (python): How to add column to dataframe for index?

How about this:

from pandas import *

idx = Int64Index([171, 174, 173])
df = DataFrame(index = idx, data =([1,2,3]))
print df

It gives me:

     0
171  1
174  2
173  3

Is this what you are looking for?