Programs & Examples On #Orchestra

sudo: docker-compose: command not found

I will leave this here as a possible fix, worked for me at least and might help others. Pretty sure this would be a linux only fix.

I decided to not go with the pip install and go with the github version (option one on the installation guide).

Instead of placing the copied docker-compose directory into /usr/local/bin/docker-compose from the curl/github command, I went with /usr/bin/docker-compose which is the location of Docker itself and will force the program to run in root. So it works in root and sudo but now won't work without sudo so the opposite effect which is what you want to run it as a user anyways.

How to pass boolean parameter value in pipeline to downstream jobs?

like Jesse Jesse Glick and abguy said you can enumerate string into Boolean type:

Boolean.valueOf(string_variable)

or the opposite Boolean into string:

String.valueOf(boolean_variable)

in my case I had to to downstream Boolean parameter to another job. So for this you will need the use the class BooleanParameterValue :

build job: 'downstream_job_name', parameters:
[
[$class: 'BooleanParameterValue', name: 'parameter_name', value: false],
], wait: true

Gulp command not found after install

I had similar problem I did the following steps and it worked.Go to mac terminal and execute the commands,

1.npm config set prefix /usr/local

2.sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}

This two commands will set the npm path right and you no longer have to use sudo in npm. Next uninstall the gulp

  1. npm uninstall gulp

  2. Installl gulp again without sudo, npm install gulp -g

This should work!!

How do I get a decimal value when using the division operator in Python?

You could also try adding a ".0" at the end of the number.

4.0/100.0

Get index of current item in a PowerShell loop

I am not sure it's possible with an "automatic" variable. You can always declare one for yourself and increment it:

$letters = { 'A', 'B', 'C' }
$letters | % {$counter = 0}{...;$counter++}

Or use a for loop instead...

for ($counter=0; $counter -lt $letters.Length; $counter++){...}

setting content between div tags using javascript

Try the following:

document.getElementById("successAndErrorMessages").innerHTML="someContent"; 

msdn link for detail : innerHTML Property

How do I format a date as ISO 8601 in moment.js?

Answer in 2020 (Includes Timezone Support)

The problem we were having is that, by default, ISOStrings aren't localized to your timezone. So, this is kinda hacky, but here's how we ended up solving this issue:

_x000D_
_x000D_
/** Imports Moment for time utilities. */
const moment = require("moment-timezone")
moment().tz("America/Chicago").format()

//** Returns now in ISO format in Central Time */
export function getNowISO() {
  return `${moment().toISOString(true).substring(0, 23)}Z`
}
_x000D_
_x000D_
_x000D_

This will leave you with an exact ISO-formatted, localized string.

Important note: Moment now suggests using other packages for new projects.

How to check the version of scipy

Using command line:

python -c "import scipy; print(scipy.__version__)"

How to add a touch event to a UIView?

Create a gesture recognizer (subclass), that will implement touch events, like touchesBegan. You can add it to the view after that.

This way you'll use composition instead subclassing (which was the request).

Issue with virtualenv - cannot activate

For me, I simply activate it with this command: pipenv shell

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

For a simple and effective PDF viewer, when you require only limited functionality, you can now (iOS 4.0+) use the QuickLook framework:

First, you need to link against QuickLook.framework and #import <QuickLook/QuickLook.h>;

Afterwards, in either viewDidLoad or any of the lazy initialization methods:

QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.dataSource = self;
previewController.delegate = self;
previewController.currentPreviewItemIndex = indexPath.row;
[self presentModalViewController:previewController animated:YES];
[previewController release];

How to get HttpRequestMessage data

From this answer:

[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
    var content = request.Content;
    string jsonContent = content.ReadAsStringAsync().Result;
}

Note: As seen in the comments, this code could cause a deadlock and should not be used. See this blog post for more detail.

sql delete statement where date is greater than 30 days

You could also use

SELECT * from Results WHERE date < NOW() - INTERVAL 30 DAY;

How to set shape's opacity?

Use this one, I've written this to my app,

<?xml version="1.0" encoding="utf-8"?>
<!--  res/drawable/rounded_edittext.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" android:padding="10dp">
    <solid android:color="#882C383E"/>
    <corners
        android:bottomRightRadius="5dp"
        android:bottomLeftRadius="5dp"
        android:topLeftRadius="5dp"
        android:topRightRadius="5dp"/>
</shape>

How to display a PDF via Android web browser without "downloading" first

Unfortunately the native browser present on Android devices not support this type of file. Let's see if in the 4.0 we will be able to do that.

Convert dd-mm-yyyy string to date

var from = $("#datepicker").val(); 
var f = $.datepicker.parseDate("d-m-Y", from);

Can you nest html forms?

As Craig said, no.

But, regarding your comment as to why:

It might be easier to use 1 <form> with the inputs and the "Update" button, and use copy hidden inputs with the "Submit Order" button in a another <form>.

How to pass parameters to a partial view in ASP.NET MVC?

make sure you add {} around Html.RenderPartial, as:

@{Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});}

not

@Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});

What is the point of "final class" in Java?

Relevant reading: The Open-Closed Principle by Bob Martin.

Key quote:

Software Entities (Classes, Modules, Functions, etc.) should be open for Extension, but closed for Modification.

The final keyword is the means to enforce this in Java, whether it's used on methods or on classes.

How do I keep two side-by-side divs the same height?

you can use jQuery to achieve this easily.

CSS

.left, .right {border:1px solid #cccccc;}

jQuery

$(document).ready(function() {
    var leftHeight = $('.left').height();
    $('.right').css({'height':leftHeight});
});

HTML

   <div class="left">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi malesuada, lacus eu dapibus tempus, ante odio aliquet risus, ac ornare orci velit in sapien. Duis suscipit sapien vel nunc scelerisque in pretium velit mattis. Cras vitae odio sed eros mollis malesuada et eu nunc.</p>
   </div>
   <div class="right">
    <p>Lorem ipsum dolor sit amet.</p>
   </div>

You'll need to include jQuery

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

To get the value of cell, use the following syntax,

datagridviewName(columnFirst, rowSecond).value

But the intellisense and MSDN documentation is wrongly saying rowFirst, colSecond approach...

How to delete rows in tables that contain foreign keys to other tables

Need to set the foreign key option as on delete cascade... in tables which contains foreign key columns.... It need to set at the time of table creation or add later using ALTER table

Update Rows in SSIS OLEDB Destination

Well, found a solution to my problem; Updating all rows using a SQL query and a SQL Task in SSIS Like Below. May help others if they face same challenge in future.

update Original 
set Original.Vaal= t.vaal 
from Original join (select * from staging1  union   select * from staging2) t 
on Original.id=t.id

Chrome not rendering SVG referenced via <img> tag

A simple and easy way; according to https://css-tricks.com/forums/topic/svg-css-background-image-not-showing-in-chrome/ You have to open the .SVG file with a text editor (like notepad) and change

xlink:href="data:img/png;base64,

to:

xlink:href="data:image/png;base64,

it worked for me!

PHP case-insensitive in_array function

$a = [1 => 'funny', 3 => 'meshgaat', 15 => 'obi', 2 => 'OMER'];  

$b = 'omer';

function checkArr($x,$array)
{
    $arr = array_values($array);
    $arrlength = count($arr);
    $z = strtolower($x);

    for ($i = 0; $i < $arrlength; $i++) {
        if ($z == strtolower($arr[$i])) {
            echo "yes";
        }  
    } 
};

checkArr($b, $a);

Select entries between dates in doctrine 2


    EDIT: See the other answers for better solutions

The original newbie approaches that I offered were (opt1):

$qb->where("e.fecha > '" . $monday->format('Y-m-d') . "'");
$qb->andWhere("e.fecha < '" . $sunday->format('Y-m-d') . "'");

And (opt2):

$qb->add('where', "e.fecha between '2012-01-01' and '2012-10-10'");

That was quick and easy and got the original poster going immediately.

Hence the accepted answer.

As per comments, it is the wrong answer, but it's an easy mistake to make, so I'm leaving it here as a "what not to do!"

How to get the current logged in user Id in ASP.NET Core

User.Identity.GetUserId();

does not exist in asp.net identity core 2.0. in this regard, i have managed in different way. i have created a common class for use whole application, because of getting user information.

create a common class PCommon & interface IPCommon adding reference using System.Security.Claims

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Common.Web.Helper
{
    public class PCommon: IPCommon
    {
        private readonly IHttpContextAccessor _context;
        public PayraCommon(IHttpContextAccessor context)
        {
            _context = context;
        }
        public int GetUserId()
        {
            return Convert.ToInt16(_context.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier));
        }
        public string GetUserName()
        {
            return _context.HttpContext.User.Identity.Name;
        }

    }
    public interface IPCommon
    {
        int GetUserId();
        string GetUserName();        
    }    
}

Here the implementation of common class

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Pay.DataManager.Concreate;
using Pay.DataManager.Helper;
using Pay.DataManager.Models;
using Pay.Web.Helper;
using Pay.Web.Models.GeneralViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Pay.Controllers
{

    [Authorize]
    public class BankController : Controller
    {

        private readonly IUnitOfWork _unitOfWork;
        private readonly ILogger _logger;
        private readonly IPCommon _iPCommon;


        public BankController(IUnitOfWork unitOfWork, IPCommon IPCommon, ILogger logger = null)
        {
            _unitOfWork = unitOfWork;
            _iPCommon = IPCommon;
            if (logger != null) { _logger = logger; }
        }


        public ActionResult Create()
        {
            BankViewModel _bank = new BankViewModel();
            CountryLoad(_bank);
            return View();
        }

        [HttpPost, ActionName("Create")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Insert(BankViewModel bankVM)
        {

            if (!ModelState.IsValid)
            {
                CountryLoad(bankVM);
                //TempData["show-message"] = Notification.Show(CommonMessage.RequiredFieldError("bank"), "Warning", type: ToastType.Warning);
                return View(bankVM);
            }


            try
            {
                bankVM.EntryBy = _iPCommon.GetUserId();
                var userName = _iPCommon.GetUserName()();
                //_unitOfWork.BankRepo.Add(ModelAdapter.ModelMap(new Bank(), bankVM));
                //_unitOfWork.Save();
               // TempData["show-message"] = Notification.Show(CommonMessage.SaveMessage(), "Success", type: ToastType.Success);
            }
            catch (Exception ex)
            {
               // TempData["show-message"] = Notification.Show(CommonMessage.SaveErrorMessage("bank"), "Error", type: ToastType.Error);
            }
            return RedirectToAction(nameof(Index));
        }



    }
}

get userId and name in insert action

_iPCommon.GetUserId();

Thanks, Maksud

HTTP vs HTTPS performance

December 2014 Update

You can easily test the difference between HTTP and HTTPS performance in your own browser using the HTTP vs HTTPS Test website by AnthumChris: “This page measures its load time over unsecure HTTP and encrypted HTTPS connections. Both pages load 360 unique, non-cached images (2.04 MB total).”

The results may surprise you.

It's important to have an up to date knowledge about the HTTPS performance because the Let’s Encrypt Certificate Authority will start issuing free, automated, and open SSL certificates in Summer 2015, thanks to Mozilla, Akamai, Cisco, Electronic Frontier Foundation and IdenTrust.

June 2015 Update

Updates on Let’s Encrypt - Arriving September 2015:

More info on Twitter: @letsencrypt

For more info on HTTPS and SSL/TLS performance see:

For more info on the importance of using HTTPS see:

To sum it up, let me quote Ilya Grigorik: "TLS has exactly one performance problem: it is not used widely enough. Everything else can be optimized."

Thanks to Chris - author of the HTTP vs HTTPS Test benchmark - for his comments below.

'Framework not found' in Xcode

I'm pretty new to iOS development. Apparently this problem for me was a result of opening the .xcodeproj Xcode project instead of the .xcworkspace Xcode workspace. I opened the workspace instead and the error has gone away.

How to export a Vagrant virtual machine to transfer it

The easiest way would be to package the Vagrant box and then copy (e.g. scp or rsync) it over to the other PC, add it and vagrant up ;-)

For detailed steps, check this out => Is there any way to clone a vagrant box that is already installed

How to POST JSON Data With PHP cURL?

Please try this code:-

$url = 'url_to_post';

$data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" =>  "Mother","last_name" =>  "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );

$data_string = json_encode(array("customer" =>$data));

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);

curl_close($ch);

echo "$result";

Please initialize the log4j system properly. While running web service

You have to create your own log4j.properties in the classpath folder.

What is the difference between concurrency and parallelism?

Parallelism is simultaneous execution of processes on a multiple cores per CPU or multiple CPUs (on a single motherboard).

Concurrency is when Parallelism is achieved on a single core/CPU by using scheduling algorithms that divides the CPU’s time (time-slice). Processes are interleaved.

Units:

  • 1 or many cores in a single CPU (pretty much all modern day processors)
  • 1 or many CPUs on a motherboard (think old school servers)
  • 1 application is 1 program (think Chrome browser)
  • 1 program can have 1 or many processes (think each Chrome browser tab is a process)
  • 1 process can have 1 or many threads from 1 program (Chrome tab playing Youtube video in 1 thread, another thread spawned for comments section, another for users login info)
  • Thus, 1 program can have 1 or many threads of execution
  • 1 process is thread(s)+allocated memory resources by OS (heap, registers, stack, class memory)

How to convert Excel values into buckets?

The right tool for that is to create a range with your limits and the corresponding names. You can then use the vlookup() function, with the 4th parameter set to Trueto create a range lookup.

enter image description here

Note: my PC uses ; as separator, yours might use ,.
Adjust formula according to your regional settings.

A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error

in my case my arraylist trhows me that error with the JSONObject , but i fin this solution for my array of String objects

List<String> listStrings= new ArrayList<String>();
String json = new Gson().toJson(listStrings);
return json;

Works like charm with angular Gson version 2.8.5

Task continuation on UI thread

If you have a return value you need to send to the UI you can use the generic version like this:

This is being called from an MVVM ViewModel in my case.

var updateManifest = Task<ShippingManifest>.Run(() =>
    {
        Thread.Sleep(5000);  // prove it's really working!

        // GenerateManifest calls service and returns 'ShippingManifest' object 
        return GenerateManifest();  
    })

    .ContinueWith(manifest =>
    {
        // MVVM property
        this.ShippingManifest = manifest.Result;

        // or if you are not using MVVM...
        // txtShippingManifest.Text = manifest.Result.ToString();    

        System.Diagnostics.Debug.WriteLine("UI manifest updated - " + DateTime.Now);

    }, TaskScheduler.FromCurrentSynchronizationContext());

Daemon Threads Explanation

Other posters gave some examples for situations in which you'd use daemon threads. My recommendation, however, is never to use them.

It's not because they're not useful, but because there are some bad side effects you can experience if you use them. Daemon threads can still execute after the Python runtime starts tearing down things in the main thread, causing some pretty bizarre exceptions.

More info here:

https://joeshaw.org/python-daemon-threads-considered-harmful/

https://mail.python.org/pipermail/python-list/2005-February/343697.html

Strictly speaking you never need them, it just makes implementation easier in some cases.

How to force page refreshes or reloads in jQuery?

You can refresh the events after adding new ones by applying the following code: -Release the Events -set Event Source -Re-render Events

  $('#calendar').fullCalendar('removeEvents');
                  $('#calendar').fullCalendar('addEventSource', YoureventSource);         
                  $('#calendar').fullCalendar('rerenderEvents' );

That will solve the problem

Flask raises TemplateNotFound error even though template file exists

My problem was that the file I was referencing from inside my home.html was a .j2 instead of a .html, and when I changed it back jinja could read it.

Stupid error but it might help someone.

Extract file name from path, no matter what the os/path format

In both Python 2 and 3, using the module pathlib2:

import posixpath  # to generate unix paths
from pathlib2 import PurePath, PureWindowsPath, PurePosixPath

def path2unix(path, nojoin=True, fromwinpath=False):
    """From a path given in any format, converts to posix path format
    fromwinpath=True forces the input path to be recognized as a Windows path (useful on Unix machines to unit test Windows paths)"""
    if not path:
        return path
    if fromwinpath:
        pathparts = list(PureWindowsPath(path).parts)
    else:
        pathparts = list(PurePath(path).parts)
    if nojoin:
        return pathparts
    else:
        return posixpath.join(*pathparts)

Usage:

In [9]: path2unix('lala/lolo/haha.dat')
Out[9]: ['lala', 'lolo', 'haha.dat']

In [10]: path2unix(r'C:\lala/lolo/haha.dat')
Out[10]: ['C:\\', 'lala', 'lolo', 'haha.dat']

In [11]: path2unix(r'C:\lala/lolo/haha.dat') # works even with malformatted cases mixing both Windows and Linux path separators
Out[11]: ['C:\\', 'lala', 'lolo', 'haha.dat']

With your testcase:

In [12]: testcase = paths = ['a/b/c/', 'a/b/c', '\\a\\b\\c', '\\a\\b\\c\\', 'a\\b\\c',
    ...: ...     'a/b/../../a/b/c/', 'a/b/../../a/b/c']

In [14]: for t in testcase:
    ...:     print(path2unix(t)[-1])
    ...:
    ...:
c
c
c
c
c
c
c

The idea here is to convert all paths into the unified internal representation of pathlib2, with different decoders depending on the platform. Fortunately, pathlib2 includes a generic decoder called PurePath that should work on any path. In case this does not work, you can force the recognition of windows path using fromwinpath=True. This will split the input string into parts, the last one is the leaf you are looking for, hence the path2unix(t)[-1].

If the argument nojoin=False, the path will be joined back, so that the output is simply the input string converted to a Unix format, which can be useful to compare subpaths across platforms.

How to make a Bootstrap accordion collapse when clicking the header div?

I've noticed a couple of minor flaws in grim's jsfiddle.

To get the pointer to change to a hand for the whole of the panel use:

.panel-heading {
   cursor: pointer;
}

I've removed the <a> tag (a style issue) and kept data-toggle="collapse" data-parent="#accordion" data-target="#collapse..." on panel-heading throughout.

I've added a CSS method for displaying chevron, using font-awesome.css in my jsfiddle:

http://jsfiddle.net/weaversnap/7FqsX/1/

Create or update mapping in elasticsearch

Please note that there is a mistake in the url provided in this answer:

For a PUT mapping request: the url should be as follows:

http://localhost:9200/name_of_index/_mappings/document_type

and NOT

http://localhost:9200/name_of_index/document_type/_mappings

No templates in Visual Studio 2017

In my case, I had all of the required features, but I had installed the Team Explorer version (accidentally used the wrong installer) before installing Professional.

When running the Team Explorer version, only the Blank Solution option was available.

The Team Explorer EXE was located in: "C:\Program Files (x86)\Microsoft Visual Studio\2017\TeamExplorer\Common7\IDE\devenv.exe"

Once I launched the correct EXE, Visual Studio started working as expected.

The Professional EXE was located in: "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\devenv.exe"

Generate random colors (RGB)

color = lambda : [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]

Change mysql user password using command line

As of MySQL 8.0.18 This works fine for me

_x000D_
_x000D_
mysql> SET PASSWORD FOR 'user'@'localhost' = 'userpassword';
_x000D_
_x000D_
_x000D_

Using Intent in an Android application to show another activity

Intent i = new Intent("com.Android.SubActivity");
startActivity(i);

Is there a way to reset IIS 7.5 to factory settings?

You need to uninstall IIS (Internet Information Services) but the key thing here is to make sure you uninstall the Windows Process Activation Service or otherwise your ApplicationHost.config will be still around. When you uninstall WAS then your configuration will be cleaned up and you will truly start with a fresh new IIS (and all data/configuration will be lost).

What is the difference between null=True and blank=True in Django?

null is for database and blank is for fields validation that you want to show on user interface like textfield to get the last name of person. If lastname=models.charfield (blank=true) it didnot ask user to enter last name as this is the optional field now. If lastname=models.charfield (null=true) then it means that if this field doesnot get any value from user then it will store in database as an empty string " ".

javac error: Class names are only accepted if annotation processing is explicitly requested

Using javac ClassName.java to compile the program, then use java ClassName to execute the compiled code. You can't mix javac with the ClassName only (without the java extension).

MySql Inner Join with WHERE clause

Yes you are right. You have placed WHERE clause wrong. You can only use one WHERE clause in single query so try AND for multiple conditions like this:

 SELECT table1.f_id  FROM table1 
   INNER JOIN table2
     ON table2.f_id = table1.f_id
 WHERE table2.f_type = 'InProcess'
   AND f_com_id = '430'
   AND f_status = 'Submitted' 

MessageBox Buttons?

  1. Your call to MessageBox.Show needs to pass MessageBoxButtons.YesNo to get the Yes/No buttons instead of the OK button.

  2. Compare the result of that call (which will block execution until the dialog returns) to DialogResult.Yes....

if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
    // user clicked yes
}
else
{
    // user clicked no
}

How To: Best way to draw table in console app (C#)

I wanted variable-width columns, and I didn't particularly care about the box characters. Also, I needed to print some extra information for each row.

So in case anyone else needs that, I'll save you few minutes:

public class TestTableBuilder
{

    public interface ITextRow
    {
        String Output();
        void Output(StringBuilder sb);
        Object Tag { get; set; }
    }

    public class TableBuilder : IEnumerable<ITextRow>
    {
        protected class TextRow : List<String>, ITextRow
        {
            protected TableBuilder owner = null;
            public TextRow(TableBuilder Owner)
            {
                owner = Owner;
                if (owner == null) throw new ArgumentException("Owner");
            }
            public String Output()
            {
                StringBuilder sb = new StringBuilder();
                Output(sb);
                return sb.ToString();
            }
            public void Output(StringBuilder sb)
            {
                sb.AppendFormat(owner.FormatString, this.ToArray());
            }
            public Object Tag { get; set; }
        }

        public String Separator { get; set; }

        protected List<ITextRow> rows = new List<ITextRow>();
        protected List<int> colLength = new List<int>();

        public TableBuilder()
        {
            Separator = "  ";
        }

        public TableBuilder(String separator)
            : this()
        {
            Separator = separator;
        }

        public ITextRow AddRow(params object[] cols)
        {
            TextRow row = new TextRow(this);
            foreach (object o in cols)
            {
                String str = o.ToString().Trim();
                row.Add(str);
                if (colLength.Count >= row.Count)
                {
                    int curLength = colLength[row.Count - 1];
                    if (str.Length > curLength) colLength[row.Count - 1] = str.Length;
                }
                else
                {
                    colLength.Add(str.Length);
                }
            }
            rows.Add(row);
            return row;
        }

        protected String _fmtString = null;
        public String FormatString
        {
            get
            {
                if (_fmtString == null)
                {
                    String format = "";
                    int i = 0;
                    foreach (int len in colLength)
                    {
                        format += String.Format("{{{0},-{1}}}{2}", i++, len, Separator);
                    }
                    format += "\r\n";
                    _fmtString = format;
                }
                return _fmtString;
            }
        }

        public String Output()
        {
            StringBuilder sb = new StringBuilder();
            foreach (TextRow row in rows)
            {
                row.Output(sb);
            }
            return sb.ToString();
        }

        #region IEnumerable Members

        public IEnumerator<ITextRow> GetEnumerator()
        {
            return rows.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return rows.GetEnumerator();
        }

        #endregion
    }



    static void Main(String[] args)
    {
        TableBuilder tb = new TableBuilder();
        tb.AddRow("When", "ID", "Name");
        tb.AddRow("----", "--", "----");

        tb.AddRow(DateTime.Now, "1", "Name1");
        tb.AddRow(DateTime.Now, "1", "Name2");

        Console.Write(tb.Output());
        Console.WriteLine();

        // or

        StringBuilder sb = new StringBuilder();
        int i = 0;
        foreach (ITextRow tr in tb)
        {
            tr.Output(sb);
            if (i++ > 1) sb.AppendLine("more stuff per line");
        }
        Console.Write(sb.ToString());
    }
}

Output:

When                 ID  Name
----                 --  ----
2/4/2013 8:37:44 PM  1   Name1
2/4/2013 8:37:44 PM  1   Name2

When                 ID  Name
----                 --  ----
2/4/2013 8:37:44 PM  1   Name1
more stuff per line
2/4/2013 8:37:44 PM  1   Name2
more stuff per line

ContractFilter mismatch at the EndpointDispatcher exception

For those who are using NodeJS with axios to make the SOAP requests you must include a SOAPAction header. Check the example below:

axios.post('https://wscredhomosocinalparceria.facilinformatica.com.br/WCF/Soap/Emprestimo.svc?wsdl',
           xmls,
  {headers:
  {
    'Content-Type': 'text/xml',
    SOAPAction: 'http://schemas.facilinformatica.com.br/Facil.Credito.WsCred/IEmprestimo/CalcularPrevisaoDeParcelas'}
  }).then(res => {
    console.log(res)
  }).catch(err => {
    console.log(err.response.data)
  })

How do I make a JSON object with multiple arrays?

On the outermost level, a JSON object starts with a { and end with a }.

Sample data:

{
    "cars": {
        "Nissan": [
            {"model":"Sentra", "doors":4},
            {"model":"Maxima", "doors":4},
            {"model":"Skyline", "doors":2}
        ],
        "Ford": [
            {"model":"Taurus", "doors":4},
            {"model":"Escort", "doors":4}
        ]
    }
}

If the JSON is assigned to a variable called data, then accessing it would be like the following:

data.cars['Nissan'][0].model   // Sentra
data.cars['Nissan'][1].model   // Maxima
data.cars['Nissan'][2].doors   // 2

for (var make in data.cars) {
    for (var i = 0; i < data.cars[make].length; i++) {
        var model = data.cars[make][i].model;
        var doors = data.cars[make][i].doors;
        alert(make + ', ' + model + ', ' + doors);
    }
}

Another approach (using an associative array for car models rather than an indexed array):

{
    "cars": {
        "Nissan": {
            "Sentra": {"doors":4, "transmission":"automatic"},
            "Maxima": {"doors":4, "transmission":"automatic"}
        },
        "Ford": {
            "Taurus": {"doors":4, "transmission":"automatic"},
            "Escort": {"doors":4, "transmission":"automatic"}
        }
    }
}

data.cars['Nissan']['Sentra'].doors   // 4
data.cars['Nissan']['Maxima'].doors   // 4
data.cars['Nissan']['Maxima'].transmission   // automatic

for (var make in data.cars) {
    for (var model in data.cars[make]) {
        var doors = data.cars[make][model].doors;
        alert(make + ', ' + model + ', ' + doors);
    }
}

Edit:

Correction: A JSON object starts with { and ends with }, but it's also valid to have a JSON array (on the outermost level), that starts with [ and ends with ].

Also, significant syntax errors in the original JSON data have been corrected: All key names in a JSON object must be in double quotes, and all string values in a JSON object or a JSON array must be in double quotes as well.

See:

Android WebView Cookie Problem

Couple of comments (at least for APIs >= 21) which I found out from my experience and gave me headaches:

  1. http and https urls are different. Setting a cookie for http://www.example.com is different than setting a cookie for https://www.example.com
  2. A slash in the end of the url can also make a difference. In my case https://www.example.com/ works but https://www.example.com does not work.
  3. CookieManager.getInstance().setCookie is performing an asynchronous operation. So, if you load a url right away after you set it, it is not guaranteed that the cookies will have already been written. To prevent unexpected and unstable behaviours, use the CookieManager#setCookie(String url, String value, ValueCallback callback) (link) and start loading the url after the callback will be called.

I hope my two cents save some time from some people so you won't have to face the same problems like I did.

Use Font Awesome Icons in CSS

You can try this example class. and find icon content here: http://astronautweb.co/snippet/font-awesome/

  #content h2:before {
    display: inline-block;
    font: normal normal normal 14px/1 FontAwesome;
    font-size: inherit;
    text-rendering: auto;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    transform: translate(0, 0);
    content: "\f007";
    }

Is it fine to have foreign key as primary key?

It is generally considered bad practise to have a one to one relationship. This is because you could just have the data represented in one table and achieve the same result.

However, there are instances where you may not be able to make these changes to the table you are referencing. In this instance there is no problem using the Foreign key as the primary key. It might help to have a composite key consisting of an auto incrementing unique primary key and the foreign key.

I am currently working on a system where users can log in and generate a registration code to use with an app. For reasons I won't go into I am unable to simply add the columns required to the users table. So I am going down a one to one route with the codes table.

What's the difference between StaticResource and DynamicResource in WPF?

StaticResource will be resolved on object construction.
DynamicResource will be evaluated and resolved every time control needs the resource.

C: scanf to array

int main()
{
  int array[11];
  printf("Write down your ID number!\n");
  for(int i=0;i<id_length;i++)
  scanf("%d", &array[i]);
  if (array[0]==1)
  {
    printf("\nThis person is a male.");
  }
  else if (array[0]==2)
  {
    printf("\nThis person is a female.");
  }
  return 0;
}

How to install an APK file on an Android phone?

I quote Hello Android because I can't say it better ;-)

You need to enable USB debugging on the phone itself (by starting the Settings application and selecting Applications > Development > USB Debugging), install the Android USB device driver if you haven’t already (Windows only), and then plug the phone into your computer using the USB cable that came with the phone.

Close the emulator window if it’s already open. As long as the phone is plugged in, Eclipse will load and run applications on the phone instead. You need to right-click the project and select Run As > Android Application.

How to leave space in HTML

Either use literal non-breaking space symbol (yes, you can copy/paste it), HTML entity, or, if you're dealing with big pre-formatted block, use white-space CSS property.

How to set timeout for a line of c# code

You can use the Task Parallel Library. To be more exact, you can use Task.Wait(TimeSpan):

using System.Threading.Tasks;

var task = Task.Run(() => SomeMethod(input));
if (task.Wait(TimeSpan.FromSeconds(10)))
    return task.Result;
else
    throw new Exception("Timed out");

Random record from MongoDB

In Python using pymongo:

import random

def get_random_doc():
    count = collection.count()
    return collection.find()[random.randrange(count)]

IndentationError: unindent does not match any outer indentation level

Other posters are probably correct...there might be spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.

Try this:

import sys

def Factorial(n): # return factorial
    result = 1
    for i in range (1,n):
        result = result * i
    print "factorial is ",result
    return result

print Factorial(10)

Android + Pair devices via bluetooth programmatically

The Best way is do not use any pairing code. Instead of onClick go to other function or other class where You create the socket using UUID.
Android automatically pops up for pairing if already not paired.

or see this link for better understanding

Below is code for the same:

private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
    public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
        // Cancel discovery because it's costly and we're about to connect
        mBtAdapter.cancelDiscovery();

        // Get the device MAC address, which is the last 17 chars in the View
        String info = ((TextView) v).getText().toString();
        String address = info.substring(info.length() - 17);

        // Create the result Intent and include the MAC address
        Intent intent = new Intent();
        intent.putExtra(EXTRA_DEVICE_ADDRESS, address);

        // Set result and finish this Activity
        setResult(Activity.RESULT_OK, intent);

      // **add this 2 line code** 
       Intent myIntent = new Intent(view.getContext(), Connect.class);
        startActivityForResult(myIntent, 0);

        finish();
    }
};

Connect.java file is :

public class Connect extends Activity {
private static final String TAG = "zeoconnect";
private ByteBuffer localByteBuffer;
 private InputStream in;
 byte[] arrayOfByte = new byte[4096];
 int bytes;


  public BluetoothDevice mDevice;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.connect);



              try {
                setup();
            } catch (ZeoMessageException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ZeoMessageParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }

 private void setup() throws ZeoMessageException, ZeoMessageParseException  {
    // TODO Auto-generated method stub

        getApplicationContext().registerReceiver(receiver,
                    new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
        getApplicationContext().registerReceiver(receiver,
                    new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));

            BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().
                    getRemoteDevice("**:**:**:**:**:**");// add device mac adress

            try {
                sock = zee.createRfcommSocketToServiceRecord(
                         UUID.fromString("*******************")); // use unique UUID
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            Log.d(TAG, "++++ Connecting");
            try {
                sock.connect();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            Log.d(TAG, "++++ Connected");


            try {
                in = sock.getInputStream();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

              Log.d(TAG, "++++ Listening...");

              while (true) {

                  try {
                      bytes = in.read(arrayOfByte);
                      Log.d(TAG, "++++ Read "+ bytes +" bytes");  
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                }
                        Log.d(TAG, "++++ Done: test()"); 

                        }} 




 private static final LogBroadcastReceiver receiver = new LogBroadcastReceiver();
    public static class LogBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent) {
            Log.d("ZeoReceiver", paramAnonymousIntent.toString());
            Bundle extras = paramAnonymousIntent.getExtras();
            for (String k : extras.keySet()) {
                Log.d("ZeoReceiver", "    Extra: "+ extras.get(k).toString());
            }
        }


    };

    private BluetoothSocket sock;
    @Override
    public void onDestroy() {
        getApplicationContext().unregisterReceiver(receiver);
        if (sock != null) {
            try {
                sock.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }
 }

JavaScript closures vs. anonymous functions

You are both using closures.

I 'm going with the Wikipedia definition here:

In computer science, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables) of that function. A closure—unlike a plain function pointer—allows a function to access those non-local variables even when invoked outside of its immediate lexical scope.

Your friend's attempt clearly uses the variable i, which is non-local, by taking its value and making a copy to store into the local i2.

Your own attempt passes i (which at the call site is in scope) to an anonymous function as an argument. This is not a closure so far, but then that function returns another function that references the same i2. Since inside the inner anonymous function i2 is not a local, this creates a closure.

NSString property: copy or retain?

Through this example copy and retain can be explained like:

NSMutableString *someName = [NSMutableString stringWithString:@"Chris"];

Person *p = [[[Person alloc] init] autorelease];
p.name = someName;

[someName setString:@"Debajit"];

if the property is of type copy then ,

a new copy will be created for the [Person name] string that will hold the contents of someName string. Now any operation on someName string will have no effect on [Person name].

[Person name] and someName strings will have different memory addresses.

But in case of retain,

both the [Person name] will hold the same memory address as of somename string, just the retain count of somename string will be incremented by 1.

So any change in somename string will be reflected in [Person name] string.

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

It's a pity that both of the answers analyze the problem but didn't give a direct answer. Let's see the code.

Z = np.array([1.0, 1.0, 1.0, 1.0])  

def func(TempLake, Z):
    A = TempLake
    B = Z
    return A * B
Nlayers = Z.size
N = 3
TempLake = np.zeros((N+1, Nlayers))
kOUT = np.zeros(N + 1)

for i in xrange(N):
    # store the i-th result of
    # function "func" in i-th item in kOUT
    kOUT[i] = func(TempLake[i], Z)

The error shows that you set the ith item of kOUT(dtype:int) into an array. Here every item in kOUT is an int, can't directly assign to another datatype. Hence you should declare the data type of kOUT when you create it. For example, like:

Change the statement below:

kOUT = np.zeros(N + 1)

into:

kOUT = np.zeros(N + 1, dtype=object)

or:

kOUT = np.zeros((N + 1, N + 1))

All code:

import numpy as np
Z = np.array([1.0, 1.0, 1.0, 1.0])

def func(TempLake, Z):
    A = TempLake
    B = Z
    return A * B

Nlayers = Z.size
N = 3
TempLake = np.zeros((N + 1, Nlayers))

kOUT = np.zeros(N + 1, dtype=object)
for i in xrange(N):
    kOUT[i] = func(TempLake[i], Z)

Hope it can help you.

How to delete a record by id in Flask-SQLAlchemy

You can do this,

User.query.filter_by(id=123).delete()

or

User.query.filter(User.id == 123).delete()

Make sure to commit for delete() to take effect.

window.close() doesn't work - Scripts may close only the windows that were opened by it

I searched for many pages of the web through of the Google and here on the Stack Overflow, but nothing suggested resolved my problem.

After many attempts, I've changed my way of to test that controller. Then I have discovered that the problem occurs always which I reopened the page through of the Ctrl + Shift + T shortcut in Chrome. So the page ran, but without a parent window reference, and because this can't be closed.

How to set the height of table header in UITableView?

I found a nice hack. Add the below line after modifying the frame propery

self.tableView.tableHeaderView = self.tableView.tableHeaderView;

The trick is (I think) that the UITableView is caching the height (the frame actually) when you assign the view to the tableHeaderView property. The above line just assigns the height again.

Convert timedelta to total seconds

More compact way to get the difference between two datetime objects and then convert the difference into seconds is shown below (Python 3x):

from datetime import datetime
        
time1 = datetime.strftime('18 01 2021', '%d %m %Y')
    
time2 = datetime.strftime('19 01 2021', '%d %m %Y')

difference = time2 - time1

difference_in_seconds = difference.total_seconds()

Build the full path filename in Python

This works fine:

os.path.join(dir_name, base_filename + "." + filename_suffix)

Keep in mind that os.path.join() exists only because different operating systems use different path separator characters. It smooths over that difference so cross-platform code doesn't have to be cluttered with special cases for each OS. There is no need to do this for file name "extensions" (see footnote) because they are always connected to the rest of the name with a dot character, on every OS.

If using a function anyway makes you feel better (and you like needlessly complicating your code), you can do this:

os.path.join(dir_name, '.'.join((base_filename, filename_suffix)))

If you prefer to keep your code clean, simply include the dot in the suffix:

suffix = '.pdf'
os.path.join(dir_name, base_filename + suffix)

That approach also happens to be compatible with the suffix conventions in pathlib, which was introduced in python 3.4 after this question was asked. New code that doesn't require backward compatibility can do this:

suffix = '.pdf'
pathlib.PurePath(dir_name, base_filename + suffix)

You might prefer the shorter Path instead of PurePath if you're only handling paths for the local OS.

Warning: Do not use pathlib's with_suffix() for this purpose. That method will corrupt base_filename if it ever contains a dot.


Footnote: Outside of Micorsoft operating systems, there is no such thing as a file name "extension". Its presence on Windows comes from MS-DOS and FAT, which borrowed it from CP/M, which has been dead for decades. That dot-plus-three-letters that many of us are accustomed to seeing is just part of the file name on every other modern OS, where it has no built-in meaning.

Any way to make a WPF textblock selectable?

Apply this style to your TextBox and that's it (inspired from this article):

<Style x:Key="SelectableTextBlockLikeStyle" TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
    <Setter Property="IsReadOnly" Value="True"/>
    <Setter Property="IsTabStop" Value="False"/>
    <Setter Property="BorderThickness" Value="0"/>
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="Padding" Value="-2,0,0,0"/>
    <!-- The Padding -2,0,0,0 is required because the TextBox
        seems to have an inherent "Padding" of about 2 pixels.
        Without the Padding property,
        the text seems to be 2 pixels to the left
        compared to a TextBlock
    -->
    <Style.Triggers>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsMouseOver" Value="False" />
                <Condition Property="IsFocused" Value="False" />
            </MultiTrigger.Conditions>
            <Setter Property="Template">
                <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <TextBlock Text="{TemplateBinding Text}" 
                             FontSize="{TemplateBinding FontSize}"
                             FontStyle="{TemplateBinding FontStyle}"
                             FontFamily="{TemplateBinding FontFamily}"
                             FontWeight="{TemplateBinding FontWeight}"
                             TextWrapping="{TemplateBinding TextWrapping}"
                             Foreground="{DynamicResource NormalText}"
                             Padding="0,0,0,0"
                                       />
                </ControlTemplate>
                </Setter.Value>
            </Setter>
        </MultiTrigger>
    </Style.Triggers>
</Style>

Move SQL Server 2008 database files to a new folder location

You can use Detach/Attach Option in SQL Server Management Studio.

Check this: Move a Database Using Detach and Attach

php - add + 7 days to date format mm dd, YYYY

Another more recent and object style way to do it :

$date = new DateTime('now');
$date->add(new DateInterval('P7D'));

php doc of datetime add

DNS problem, nslookup works, ping doesn't

It's possible that the Windows internal resolver is adding '.local' to the domain name because there's no dots in it. nslookup wouldn't do that.

To verify this possiblity, install 'Wireshark' (previously aka Ethereal) on your client machine and observe any DNS request packets leaving it when you run the ping command.


OK, further investigation on my own XP machine at home reveals that for single label names (i.e. "foo", or "foo.") the system doesn't use DNS at all, and instead uses NBNS (NetBios Name Service).

Using a hint found at http://www.chicagotech.net/netforums/viewtopic.php?t=1476, I found that I was able to force DNS lookups for single label domains by putting a single entry reading "." in the "Append these DNS suffixes (in order)" in the "Advanced TCP/IP settings" dialog

How to install Python MySQLdb module using pip?

My environment are:

  • Windows 10 Pro,
  • Python 3.7 (python-3.7.1-amd64.exe),
  • MySQL 8.0 (mysql-installer-web-community-8.0.13.0.msi)

pip install mysqlclient-1.3.13-cp37-cp37m-win_amd64.whl

works for me.

import MySQLdb, sys


# --------------------------------------------------
# Connect to MySQL
# --------------------------------------------------
try:
    db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="database", charset='cp1251')
except MySQLdb.Error as e:
    print ("Error %d: %s" % (e.args[0], e.args[1]))
    sys.exit()

# Creating cursor 
cursor = db.cursor()

How to list all available Kafka brokers in a cluster?

Using Confluent's REST Proxy API v3:

curl -X GET -H "Accept: application/vnd.api+json" localhost:8082/v3/clusters

where localhost:8082 is Kafka Proxy address.

Gson library in Android Studio

Add following dependency or download Gson jar file

implementation 'com.google.code.gson:gson:2.8.6'

Follow github repo for documentation and more.

jquery find class and get the value

You can also get the value by the following way

$(document).ready(function(){
  $("#start").click(function(){
    alert($(this).find("input[class='myClass']").val());
  });
});

OnClick Send To Ajax

<textarea name='Status'> </textarea>
<input type='button' value='Status Update'>

You have few problems with your code like using . for concatenation

Try this -

$(function () {
    $('input').on('click', function () {
        var Status = $(this).val();
        $.ajax({
            url: 'Ajax/StatusUpdate.php',
            data: {
                text: $("textarea[name=Status]").val(),
                Status: Status
            },
            dataType : 'json'
        });
    });
});

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

Is there any way to show a countdown on the lockscreen of iphone?

Or you could figure out the exacting amount of hours and minutes and have that displayed by puttin it into the timer app that already exist in every iphone :)

Close iOS Keyboard by touching anywhere using Swift

In storyboard:

  1. select the TableView
  2. from the the right-hand-side, select the attribute inspector
  3. in the keyboard section - select the dismiss mode you want

Perform a Shapiro-Wilk Normality Test

You failed to specify the exact columns (data) to test for normality. Use this instead

shapiro.test(heisenberg$HWWIchg)

How can I check the extension of a file?

#!/usr/bin/python

import shutil, os

source = ['test_sound.flac','ts.mp3']

for files in source:
  fileName,fileExtension = os.path.splitext(files)

  if fileExtension==".flac" :
    print 'This file is flac file %s' %files
  elif  fileExtension==".mp3":
    print 'This file is mp3 file %s' %files
  else:
    print 'Format is not valid'

How to pass parameter to function using in addEventListener?

If the this value you want is the just the object that you bound the event handler to, then addEventListener() already does that for you. When you do this:

productLineSelect.addEventListener('change', getSelection, false);

the getSelection function will already be called with this set to the object that the event handler was bound to. It will also be passed an argument that represents the event object which has all sorts of object information about the event.

function getSelection(event) {
    // this will be set to the object that the event handler was bound to
    // event is all the detailed information about the event
}

If the desired this value is some other value than the object you bound the event handler to, you can just do this:

var self = this;
productLineSelect.addEventListener('change',function() {
    getSelection(self)
},false);

By way of explanation:

  1. You save away the value of this into a local variable in your other event handler.
  2. You then create an anonymous function to pass addEventListener.
  3. In that anonymous function, you call your actual function and pass it the saved value of this.

How to create a directory if it doesn't exist using Node.js?

You can just use mkdir and catch the error if the folder exists.
This is async (so best practice) and safe.

fs.mkdir('/path', err => { 
    if (err && err.code != 'EEXIST') throw 'up'
    .. safely do your stuff here  
    })

(Optionally add a second argument with the mode.)


Other thoughts:

  1. You could use then or await by using native promisify.

    const util = require('util'), fs = require('fs');
    const mkdir = util.promisify(fs.mkdir);
    var myFunc = () => { ..do something.. } 
    
    mkdir('/path')
        .then(myFunc)
        .catch(err => { if (err.code != 'EEXIST') throw err; myFunc() })
    
  2. You can make your own promise method, something like (untested):

    let mkdirAsync = (path, mode) => new Promise(
       (resolve, reject) => mkdir (path, mode, 
          err => (err && err.code !== 'EEXIST') ? reject(err) : resolve()
          )
       )
    
  3. For synchronous checking, you can use:

    fs.existsSync(path) || fs.mkdirSync(path)
    
  4. Or you can use a library, the two most popular being

    • mkdirp (just does folders)
    • fsextra (supersets fs, adds lots of useful stuff)

Getting a list item by index

.NET List data structure is an Array in a "mutable shell".

So you can use indexes for accessing to it's elements like:

var firstElement = myList[0];
var secondElement = myList[1];

Starting with C# 8.0 you can use Index and Range classes for accessing elements. They provides accessing from the end of sequence or just access a specific part of sequence:

var lastElement = myList[^1]; // Using Index
var fiveElements = myList[2..7]; // Using Range, note that 7 is exclusive

You can combine indexes and ranges together:

var elementsFromThirdToEnd = myList[2..^0]; // Index and Range together

Also you can use LINQ ElementAt method but for 99% of cases this is really not necessary and just slow performance solution.

How to configure Fiddler to listen to localhost?

By simply adding fiddler to the url

http://localhost.fiddler:8081/

Traffic is routed through fiddler and therefore being displayed on fiddler.

How to validate an email address in PHP

Answered this in 'top question' about emails verification https://stackoverflow.com/a/41129750/1848217

For me the right way for checking emails is:

  1. Check that symbol @ exists, and before and after it there are some non-@ symbols: /^[^@]+@[^@]+$/
  2. Try to send an email to this address with some "activation code".
  3. When the user "activated" his email address, we will see that all is right.

Of course, you can show some warning or tooltip in front-end when user typed "strange" email to help him to avoid common mistakes, like no dot in domain part or spaces in name without quoting and so on. But you must accept the address "hello@world" if user really want it.

Also, you must remember that email address standard was and can evolute, so you can't just type some "standard-valid" regexp once and for all times. And you must remember that some concrete internet servers can fail some details of common standard and in fact work with own "modified standard".

So, just check @, hint user on frontend and send verification emails on given address.

Display string as html in asp.net mvc view

you can use @Html.Raw(str)

See MSDN for more

Returns markup that is not HTML encoded.

This method wraps HTML markup using the IHtmlString class, which renders unencoded HTML.

How to create an Excel File with Nodejs?

Use msexcel-builder. Install it with:

npm install msexcel-builder

Then:

// Create a new workbook file in current working-path 
var workbook = excelbuilder.createWorkbook('./', 'sample.xlsx')

// Create a new worksheet with 10 columns and 12 rows 
var sheet1 = workbook.createSheet('sheet1', 10, 12);

// Fill some data 
sheet1.set(1, 1, 'I am title');
for (var i = 2; i < 5; i++)
  sheet1.set(i, 1, 'test'+i);

// Save it 
workbook.save(function(ok){
  if (!ok) 
    workbook.cancel();
  else
    console.log('congratulations, your workbook created');
});

Return first N key:value pairs from dict

I have tried a few of the answers above and note that some of them are version dependent and do not work in version 3.7.

I also note that since 3.6 all dictionaries are ordered by the sequence in which items are inserted.

Despite dictionaries being ordered since 3.6 some of the statements you expect to work with ordered structures don't seem to work.

The answer to the OP question that worked best for me.

itr = iter(dic.items())
lst = [next(itr) for i in range(3)]

Intersect Two Lists in C#

public static List<T> ListCompare<T>(List<T> List1 , List<T> List2 , string key )
{
    return List1.Select(t => t.GetType().GetProperty(key).GetValue(t))
                .Intersect(List2.Select(t => t.GetType().GetProperty(key).GetValue(t))).ToList();
}

Global Events in Angular

I have created a pub-sub sample here:

http://www.syntaxsuccess.com/viewarticle/pub-sub-in-angular-2.0

The idea is to use RxJs Subjects to wire up an Observer and and Observables as a generic solution for emitting and subscribing to custom events. In my sample I use a customer object for demo purposes

this.pubSubService.Stream.emit(customer);

this.pubSubService.Stream.subscribe(customer => this.processCustomer(customer));

Here is a live demo as well: http://www.syntaxsuccess.com/angular-2-samples/#/demo/pub-sub

when exactly are we supposed to use "public static final String"?

public makes it accessible across other classes. static makes it uniform value across all the class instances. final makes it non-modifiable value. So basically it's a "constant" value which is same across all the class instances and which cannot be modified. With respect to your concern "What I don't understand is why people use that even if the constant will be used only in one place and only in the same class. Why declaring it? Why don't we just use the variable?" I would say since it is a public field the constant value can also be used elsewhere in some other class using ClassName.value. eg: a class named Math may have PI as final static long value which can be accessed as Math.PI.

Laravel 4: how to run a raw SQL?

Laravel raw sql – Insert query:

lets create a get link to insert data which is accessible through url . so our link name is ‘insertintodb’ and inside that function we use db class . db class helps us to interact with database . we us db class static function insert . Inside insert function we will write our PDO query to insert data in database . in below query we will insert ‘ my title ‘ and ‘my content’ as data in posts table .

put below code in your web.php file inside routes directory :

Route::get('/insertintodb',function(){
DB::insert('insert into posts(title,content) values (?,?)',['my title','my content']);
});

Now fire above insert query from browser link below :

localhost/yourprojectname/insertintodb

You can see output of above insert query by going into your database table .you will find a record with id 1 .

Laravel raw sql – Read query :

Now , lets create a get link to read data , which is accessible through url . so our link name is ‘readfromdb’. we us db class static function read . Inside read function we will write our PDO query to read data from database . in below query we will read data of id ‘1’ from posts table .

put below code in your web.php file inside routes directory :

Route::get('/readfromdb',function() {
    $result =  DB::select('select * from posts where id = ?', [1]);
    var_dump($result);
});

now fire above read query from browser link below :

localhost/yourprojectname/readfromdb

How do I tell a Python script to use a particular version

You can add a shebang line the to the top of the script:

#!/usr/bin/env python2.7

But that will only work when executing as ./my_program.py.

If you execute as python my_program.py, then the whatever Python version that which python returns will be used.

In re: to virtualenv use: virtualenv -p /usr/bin/python3.2 or whatever to set it up to use that Python executable.

How can I pad an integer with zeros on the left?

Check my code that will work for integer and String.

Assume our first number is 2. And we want to add zeros to that so the the length of final string will be 4. For that you can use following code

    int number=2;
    int requiredLengthAfterPadding=4;
    String resultString=Integer.toString(number);
    int inputStringLengh=resultString.length();
    int diff=requiredLengthAfterPadding-inputStringLengh;
    if(inputStringLengh<requiredLengthAfterPadding)
    {
        resultString=new String(new char[diff]).replace("\0", "0")+number;
    }        
    System.out.println(resultString);

How to override a JavaScript function

You can override any built-in function by just re-declaring it.

parseFloat = function(a){
  alert(a)
};

Now parseFloat(3) will alert 3.

Use YAML with variables

This is how I was able to configure yaml files to refer to variable.

I have values.yaml where we have root level fields which are used as template variables inside values.yaml

values.yaml

.....  
databaseUserPropName: spring.datasource.username  
databaseUserName: sa  
.....  
secrets:
    type: Opaque  
    name: dbservice-secrets  
    data:  
      - name: "{{ .Values.databaseUserPropName }}"  
        value: "{{ .Values.databaseUserName }}"  
.....

When referencing these values in secret.yaml, we would use tpl function using syntax {{ tpl TEMPLATE_STRING VALUES }}

secret.yaml

when using inside range i:e iteration

  {{ range .Values.deployments.secrets.data }}
    {{ tpl .name $ }}: "{{ tpl .value $ }}"
  {{ end }}

when directly referring as variable

  {{ tpl .Values.deployments.secrets.data.name . }}
  {{ tpl .Values.deployments.secrets.data.value . }}

$ - this is global variable and will always point to the root context . - this variable will point to the root context based on where it used.

Modify XML existing content in C#

Well, If you want to update a node in XML, the XmlDocument is fine - you needn't use XmlTextWriter.

XmlDocument doc = new XmlDocument();
doc.Load("D:\\build.xml");
XmlNode root = doc.DocumentElement;
XmlNode myNode = root.SelectSingleNode("descendant::books");
myNode.Value = "blabla";
doc.Save("D:\\build.xml");

Is having an 'OR' in an INNER JOIN condition a bad idea?

This kind of JOIN is not optimizable to a HASH JOIN or a MERGE JOIN.

It can be expressed as a concatenation of two resultsets:

SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.parentId = m.id
UNION
SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.id = m.parentId

, each of them being an equijoin, however, SQL Server's optimizer is not smart enough to see it in the query you wrote (though they are logically equivalent).

Using SSIS BIDS with Visual Studio 2012 / 2013

Welcome to Microsoft Marketing Speak hell. With the 2012 release of SQL Server, the BIDS, Business Intelligence Designer Studio, plugin for Visual Studio was renamed to SSDT, SQL Server Data Tools. SSDT is available for 2010 and 2012. The problem is, there are two different products called SSDT.

There is SSDT which replaces the database designer thing which was called Data Dude in VS 2008 and in 2010 became database projects. That a free install and if you snag the web installer, that's what you get when you install SSDT. It puts the correct project templates and such into Visual Studio.

There's also the SSDT which is the "BIDS" replacement for developing SSIS, SSRS and SSAS stuff. As of March 2013, it is now available for the 2012 release of Visual Studio. The download is labeled SSDTBI_VS2012_X86.msi Perhaps that's a signal on how the product is going to be referred to in marketing materials. Download links are

None the less, we have Business Intelligence projects available to us in Visual Studio 2012. And the people did rejoice and did feast upon the lambs and toads and tree-sloths and fruit-bats and orangutans and breakfast cereals

enter image description here

Disable XML validation in Eclipse

Window > Preferences > Validation > uncheck XML Validator Manual and Build enter image description here

When to use CouchDB over MongoDB and vice versa

The answers above all over complicate the story.

  1. If you plan to have a mobile component, or need desktop users to work offline and then sync their work to a server you need CouchDB.
  2. If your code will run only on the server then go with MongoDB

That's it. Unless you need CouchDB's (awesome) ability to replicate to mobile and desktop devices, MongoDB has the performance, community and tooling advantage at present.

Angular 2 - innerHTML styling

Use the below method to allow css styles in innerhtml.

import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
.
.
.
.
html: SafeHtml;

constructor(protected _sanitizer: DomSanitizer) {
this.html = this._sanitizer.bypassSecurityTrustHtml(`
<html>
  <head></head>
  <body>
    <div style="display:flex; color: blue;">
      <div>
        <h1>Hello World..!!!!!</h1>
      </div>
    </div>
  </body>
</html>`);
}

Example code stackblitz

Or use the below method to write directly in html. https://gist.github.com/klihelp/4dcac910124409fa7bd20f230818c8d1

How do I grep for all non-ASCII characters?

The following code works:

find /tmp | perl -ne 'print if /[^[:ascii:]]/'

Replace /tmp with the name of the directory you want to search through.

Simulate Keypress With jQuery

You could try this SendKeys jQuery plugin:

http://bililite.com/blog/2011/01/23/improved-sendkeys/

$(element).sendkeys(string) inserts string at the insertion point in an input, textarea or other element with contenteditable=true. If the insertion point is not currently in the element, it remembers where the insertion point was when sendkeys was last called (if the insertion point was never in the element, it appends to the end).

How to set time zone in codeigniter?

Put it in config/config.php, It will work for whole application or index.php of codeigniter.

Conditionally ignoring tests in JUnit 4

The JUnit way is to do this at run-time is org.junit.Assume.

 @Before
 public void beforeMethod() {
     org.junit.Assume.assumeTrue(someCondition());
     // rest of setup.
 }

You can do it in a @Before method or in the test itself, but not in an @After method. If you do it in the test itself, your @Before method will get run. You can also do it within @BeforeClass to prevent class initialization.

An assumption failure causes the test to be ignored.

Edit: To compare with the @RunIf annotation from junit-ext, their sample code would look like this:

@Test
public void calculateTotalSalary() {
    assumeThat(Database.connect(), is(notNull()));
    //test code below.
}

Not to mention that it is much easier to capture and use the connection from the Database.connect() method this way.

List of zeros in python

If you want a function which will return an arbitrary number of zeros in a list, try this:

def make_zeros(number):
    return [0] * number

list = make_zeros(10)

# list now contains: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

How to import an existing directory into Eclipse?

The thing that works best for me when that happens is :

  1. Create a new eclipse project(JAVA)

  2. Take your source file (contents of the src folder!!!) and drag from finder and drop into the src folder in eclipse IDE

  3. Make sure you add your external jars and stuff and tada you're done!!

disabling spring security in spring boot app

The accepted answer didn't work for me.

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

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

How to create a connection string in asp.net c#

add this in web.config file

           <configuration>
              <appSettings>
                 <add key="ConnectionString" value="Your connection string which contains database id and password"/>
            </appSettings>
            </configuration>

.cs file

 public ConnectionObjects()
 {           
    string connectionstring= ConfigurationManager.AppSettings["ConnectionString"].ToString();
 }

Hope this helps.

Refreshing all the pivot tables in my excel workbook with a macro

This VBA code will refresh all pivot tables/charts in the workbook.

Sub RefreshAllPivotTables()

Dim PT As PivotTable
Dim WS As Worksheet

    For Each WS In ThisWorkbook.Worksheets

        For Each PT In WS.PivotTables
          PT.RefreshTable
        Next PT

    Next WS

End Sub

Another non-programatic option is:

  • Right click on each pivot table
  • Select Table options
  • Tick the 'Refresh on open' option.
  • Click on the OK button

This will refresh the pivot table each time the workbook is opened.

How to create a GUID/UUID in Python

If you're using Python 2.5 or later, the uuid module is already included with the Python standard distribution.

Ex:

>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')

How do I pass environment variables to Docker containers?

The problem I had was that I was putting the --env-file at the end of the command

docker run -it --rm -p 8080:80 imagename --env-file ./env.list

Fix

docker run --env-file ./env.list -it --rm -p 8080:80 imagename

Why can't radio buttons be "readonly"?

I've faked readonly on a radio button by disabling only the un-checked radio buttons. It keeps the user from selecting a different value, and the checked value will always post on submit.

Using jQuery to make readonly:

$(':radio:not(:checked)').attr('disabled', true);

This approach also worked for making a select list readonly, except that you'll need to disable each un-selected option.

How to write UPDATE SQL with Table alias in SQL Server 2008?

You can always take the CTE, (Common Tabular Expression), approach.

;WITH updateCTE AS
(
    SELECT ID, TITLE 
    FROM HOLD_TABLE
    WHERE ID = 101
)

UPDATE updateCTE
SET TITLE = 'TEST';

Disable all dialog boxes in Excel while running VB script?

In order to get around the Enable Macro prompt I suggest

Application.AutomationSecurity = msoAutomationSecurityForceDisable

Be sure to return it to default when you are done

Application.AutomationSecurity = msoAutomationSecurityLow

A reminder that the .SaveAs function contains all optional arguments.I recommend removing CreatBackup:= False as it is not necessary.

The most interesting way I think is to create an object of the workbook and access the .SaveAs property that way. I have not tested it but you are never using Workbooks.Open rendering Application.AutomationSecurity inapplicable. Possibly saving resources and time as well.

That said I was able to execute the following without any notifications on Excel 2013 windows 10.

    Option Explicit

    Sub Convert()

    OptimizeVBA (True)  
    'function to set all the things you want to set, but hate keying in

    Application.AutomationSecurity = msoAutomationSecurityForceDisable  
    'this should stop those pesky enable prompts

    ChDir "F:\VBA Macros\Stack Overflow Questions\When changing type xlsm to 
    xlsx stop popup"

    Workbooks.Open ("Book1.xlsm")

    ActiveWorkbook.SaveAs Filename:= _
    "F:\VBA Macros\Stack Overflow Questions\When changing type xlsm to xlsx_ 
    stop popup\Book1.xlsx" _
    , FileFormat:=xlOpenXMLWorkbook

    ActiveWorkbook.Close

    Application.AutomationSecurity = msoAutomationSecurityLow 
    'make sure you set this up when done

    Kill ("F:\VBA Macros\Stack Overflow Questions\When changing type xlsm_ 
    to xlsx stop popup\Book1.xlsx") 'clean up

    OptimizeVBA (False)
    End Sub


    Function OptimizeVBA(ByRef Status As Boolean)

    If Status = True Then
        Application.ScreenUpdating = False
        Application.Calculation = xlCalculationManual
        Application.DisplayAlerts = False
        Application.EnableEvents = False
    Else
        Application.ScreenUpdating = True
        Application.Calculation = xlCalculationAutomatic
        Application.DisplayAlerts = True
        Application.EnableEvents = True
    End If

    End Function

How can I parse a String to BigDecimal?

Try this

 String str="10,692,467,440,017.120".replaceAll(",","");
 BigDecimal bd=new BigDecimal(str);

What is the best way to determine a session variable is null or empty in C#?

Typically I create SessionProxy with strongly typed properties for items in the session. The code that accesses these properties checks for nullity and does the casting to the proper type. The nice thing about this is that all of my session related items are kept in one place. I don't have to worry about using different keys in different parts of the code (and wondering why it doesn't work). And with dependency injection and mocking I can fully test it with unit tests. If follows DRY principles and also lets me define reasonable defaults.

public class SessionProxy
{
    private HttpSessionState session; // use dependency injection for testability
    public SessionProxy( HttpSessionState session )
    {
       this.session = session;  //might need to throw an exception here if session is null
    }

    public DateTime LastUpdate
    {
       get { return this.session["LastUpdate"] != null
                         ? (DateTime)this.session["LastUpdate"] 
                         : DateTime.MinValue; }
       set { this.session["LastUpdate"] = value; }
    }

    public string UserLastName
    {
       get { return (string)this.session["UserLastName"]; }
       set { this.session["UserLastName"] = value; }
    }
}

How to list all files in a directory and its subdirectories in hadoop hdfs

Thanks Radu Adrian Moldovan for the suggestion.

Here is an implementation using queue:

private static List<String> listAllFilePath(Path hdfsFilePath, FileSystem fs)
throws FileNotFoundException, IOException {
  List<String> filePathList = new ArrayList<String>();
  Queue<Path> fileQueue = new LinkedList<Path>();
  fileQueue.add(hdfsFilePath);
  while (!fileQueue.isEmpty()) {
    Path filePath = fileQueue.remove();
    if (fs.isFile(filePath)) {
      filePathList.add(filePath.toString());
    } else {
      FileStatus[] fileStatus = fs.listStatus(filePath);
      for (FileStatus fileStat : fileStatus) {
        fileQueue.add(fileStat.getPath());
      }
    }
  }
  return filePathList;
}

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

Its already answered above. I will summarise the steps to check above.

run git remote -v in project dir. If the output shows remote url starting with https://abc then you may need username password everytime.

So to change the remote url run git remote set-url origin {ssh remote url address starts with mostly [email protected]:}.

Now run git remote -v to verify the changed remote url.

Refer : https://help.github.com/articles/changing-a-remote-s-url/

How to convert a selection to lowercase or uppercase in Sublime Text

For others needing a key binding:

{ "keys": ["ctrl+="], "command": "upper_case" },
{ "keys": ["ctrl+-"], "command": "lower_case" }

Resetting remote to a certain commit

If you want a previous version of file, I would recommend using git checkout.

git checkout <commit-hash>

Doing this will send you back in time, it does not affect the current state of your project, you can come to mainline git checkout mainline

but when you add a file in the argument, that file is brought back to you from a previous time to your current project time, i.e. your current project is changed and needs to be committed.

git checkout <commit-hash> -- file_name
git add .
git commit -m 'file brought from previous time'
git push

The advantage of this is that it does not delete history, and neither does revert a particular code changes (git revert)

Check more here https://www.atlassian.com/git/tutorials/undoing-changes#git-checkout

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

I just encountered this same issue. Turned out the Project URL on the Web property sheet was malformed.

I had just removed a port number, forgot to delete the preceding colon and tried running with: http://localhost:/XYZ

Seems like lots of different issues result in this error message.

Find files with size in Unix

Find can be used to print out the file-size in bytes with %s as a printf. %h/%f prints the directory prefix and filename respectively. \n forces a newline.

Example

find . -size +10000k -printf "%h/%f,%s\n"

Output

./DOTT/extract/DOTT/TENTACLE.001,11358470
./DOTT/Day Of The Tentacle.nrg,297308316
./DOTT/foo.iso,297001116

stdlib and colored output in C

Because you can't print a character with string formating. You can also think of adding a format with something like this

#define PRINTC(c,f,s) printf ("\033[%dm" f "\033[0m", 30 + c, s)

f is format as in printf

PRINTC (4, "%s\n", "bar")

will print blue bar

PRINTC (1, "%d", 'a')

will print red 97

How can I edit javascript in my browser like I can use Firebug to edit CSS/HTML?

Firefox Developer Edition (59.0b6) has Scratchpad (Shift +F4) where you can run javascript

Conditional step/stage in Jenkins pipeline

According to other answers I am adding the parallel stages scenario:

pipeline {
    agent any
    stages {
        stage('some parallel stage') {
            parallel {
                stage('parallel stage 1') {
                    when {
                      expression { ENV == "something" }
                    }
                    steps {
                        echo 'something'
                    }
                }
                stage('parallel stage 2') {
                    steps {
                        echo 'something'
                    }
                }
            }
        }
    }
}

How to calculate age (in years) based on Date of Birth and getDate()

DECLARE @DOB datetime
set @DOB ='11/25/1985'

select floor(
( cast(convert(varchar(8),getdate(),112) as int)-
cast(convert(varchar(8),@DOB,112) as int) ) / 10000
)

source: http://beginsql.wordpress.com/2012/04/26/how-to-calculate-age-in-sql-server/

Plotting time in Python with Matplotlib

You must first convert your timestamps to Python datetime objects (use datetime.strptime). Then use date2num to convert the dates to matplotlib format.

Plot the dates and values using plot_date:

dates = matplotlib.dates.date2num(list_of_datetimes)
matplotlib.pyplot.plot_date(dates, values)

How to change value of process.env.PORT in node.js?

use the below command to set the port number in node process while running node JS programme:

set PORT =3000 && node file_name.js

The set port can be accessed in the code as

process.env.PORT 

Reading a text file using OpenFileDialog in windows forms

Here's one way:

Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
    try
    {
        if ((myStream = theDialog.OpenFile()) != null)
        {
            using (myStream)
            {
                // Insert code to read the stream here.
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
    }
}

Modified from here:MSDN OpenFileDialog.OpenFile

EDIT Here's another way more suited to your needs:

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    OpenFileDialog theDialog = new OpenFileDialog();
    theDialog.Title = "Open Text File";
    theDialog.Filter = "TXT files|*.txt";
    theDialog.InitialDirectory = @"C:\";
    if (theDialog.ShowDialog() == DialogResult.OK)
    {
        string filename = theDialog.FileName;

        string[] filelines = File.ReadAllLines(filename);

        List<Employee> employeeList = new List<Employee>();
        int linesPerEmployee = 4;
        int currEmployeeLine = 0;
        //parse line by line into instance of employee class
        Employee employee = new Employee();
        for (int a = 0; a < filelines.Length; a++)
        {

            //check if to move to next employee
            if (a != 0 && a % linesPerEmployee == 0)
            {
                employeeList.Add(employee);
                employee = new Employee();
                currEmployeeLine = 1;
            }

            else
            {
                currEmployeeLine++;
            }
            switch (currEmployeeLine)
            {
                case 1:
                    employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
                    break;
                case 2:
                    employee.Name = filelines[a].Trim();
                    break;
                case 3:
                    employee.Address = filelines[a].Trim();
                    break;
                case 4:
                    string[] splitLines = filelines[a].Split(' ');

                    employee.Wage = Convert.ToDouble(splitLines[0].Trim());
                    employee.Hours = Convert.ToDouble(splitLines[1].Trim());
                    break;


            }

        }
        //Test to see if it works
        foreach (Employee emp in employeeList)
        {
            MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
                emp.Name + Environment.NewLine +
                emp.Address + Environment.NewLine +
                emp.Wage + Environment.NewLine +
                emp.Hours + Environment.NewLine);
        }
    }
}

Copying sets Java

The copy constructor given by @Stephen C is the way to go when you have a Set you created (or when you know where it comes from). When it comes from a Map.entrySet(), it will depend on the Map implementation you're using:

findbugs says

The entrySet() method is allowed to return a view of the underlying Map in which a single Entry object is reused and returned during the iteration. As of Java 1.6, both IdentityHashMap and EnumMap did so. When iterating through such a Map, the Entry value is only valid until you advance to the next iteration. If, for example, you try to pass such an entrySet to an addAll method, things will go badly wrong.

As addAll() is called by the copy constructor, you might find yourself with a Set of only one Entry: the last one.

Not all Map implementations do that though, so if you know your implementation is safe in that regard, the copy constructor definitely is the way to go. Otherwise, you'd have to create new Entry objects yourself:

Set<K,V> copy = new HashSet<K,V>(map.size());
for (Entry<K,V> e : map.entrySet())
    copy.add(new java.util.AbstractMap.SimpleEntry<K,V>(e));

Edit: Unlike tests I performed on Java 7 and Java 6u45 (thanks to Stephen C), the findbugs comment does not seem appropriate anymore. It might have been the case on earlier versions of Java 6 (before u45) but I don't have any to test.

Is there any way to have a fieldset width only be as wide as the controls in them?

fieldset {display:inline} or fieldset {display:inline-block}

If you want to separate two fieldsets vertically, use a single <br/> between them. This is semantically correct and no harder than it has to be.

Codeigniter's `where` and `or_where`

You can change your code to this:

$where_au = "(library.available_until >= '{date('Y-m-d H:i:s)}' OR library.available_until = '00-00-00 00:00:00')";
$this->db
    ->select('*')
    ->from('library')
    ->where('library.rating >=', $form['slider'])
    ->where('library.votes >=', '1000')
    ->where('library.language !=', 'German')
    ->where($where_au)
    ->where('library.release_year >=', $year_start)
    ->where('library.release_year <=', $year_end)
    ->join('rating_repo', 'library.id = rating_repo.id');

Tip: to watch the generated query you can use

echo $this->db->last_query(); die();

Logging in Scala

With Scala 2.10+ Consider ScalaLogging by Typesafe. Uses macros to deliver a very clean API

https://github.com/typesafehub/scala-logging

Quoting from their wiki:

Fortunately Scala macros can be used to make our lives easier: ScalaLogging offers the class Logger with lightweight logging methods that will be expanded to the above idiom. So all we have to write is:

logger.debug(s"Some ${expensiveExpression} message!")

After the macro has been applied, the code will have been transformed into the above described idiom.

In addition ScalaLogging offers the trait Logging which conveniently provides a Logger instance initialized with the name of the class mixed into:

import com.typesafe.scalalogging.slf4j.LazyLogging

class MyClass extends LazyLogging {
  logger.debug("This is very convenient ;-)")
}

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

select column_name, data_type || '(' || data_length || ')' as datatype
from all_tab_columns 
where TABLE_NAME = upper('myTableName')

How to find the length of an array in shell?

this works well for me

    arglen=$#
    argparam=$*
    if [ $arglen -eq '3' ];
    then
            echo Valid Number of arguments
            echo "Arguments are $*"
    else
            echo only four arguments are allowed
    fi

Unity 2d jumping script

The answer above is now obsolete with Unity 5 or newer. Use this instead!

GetComponent<Rigidbody2D>().AddForce(new Vector2(0,10), ForceMode2D.Impulse);

I also want to add that this leaves the jump height super private and only editable in the script, so this is what I did...

    public float playerSpeed;  //allows us to be able to change speed in Unity
public Vector2 jumpHeight;

// Use this for initialization
void Start () {

}
// Update is called once per frame
void Update ()
{
    transform.Translate(playerSpeed * Time.deltaTime, 0f, 0f);  //makes player run

    if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Space))  //makes player jump
    {
        GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);

This makes it to where you can edit the jump height in Unity itself without having to go back to the script.

Side note - I wanted to comment on the answer above, but I can't because I'm new here. :)

How to determine when a Git branch was created?

Use:

git reflog

to show all the living cycle of your repository in current folder. The branch name that first appear (from down to up) is the source that was created.

855a3ce HEAD@{0}: checkout: moving from development to feature-sut-46
855a3ce HEAD@{1}: checkout: moving from feature-sut-46 to development
855a3ce HEAD@{2}: checkout: moving from feature-jira35 to feature-sut-46
535dd9d HEAD@{3}: checkout: moving from feature-sut-46 to feature-jira35
855a3ce HEAD@{4}: checkout: moving from development to feature-sut-46
855a3ce HEAD@{5}: checkout: moving from feature-jira35 to development
535dd9d HEAD@{6}: commit: insert the format for vendor specific brower - screen.css
855a3ce HEAD@{7}: checkout: moving from development to feature-jira35
855a3ce HEAD@{8}: checkout: moving from master to development

That mean:

  • Branch development is created (checkout -b) from master

  • Branch feature-jira35 is created (checkout -b) from development

  • Branch feature-jira-sut-46 is created (checkout -b) from development

How can I fill out a Python string with spaces?

A nice trick to use in place of the various print formats:

(1) Pad with spaces to the right:

('hi' + '        ')[:8]

(2) Pad with leading zeros on the left:

('0000' + str(2))[-4:]

Is there a “not in” operator in JavaScript for checking object properties?

Personally I find

if (id in tutorTimes === false) { ... }

easier to read than

if (!(id in tutorTimes)) { ... }

but both will work.

Anchor links in Angularjs?

Works for me:

 <a onclick='return false;' href="" class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" ng-href="#profile#collapse{{$index}}"> blalba </a>

git error: failed to push some refs to remote

Rename your branch and then push, e.g.:

git branch -m new-name
git push -u new-name

This worked for me.

Java Loop every minute

If you are using a SpringBoot application it's as simple as

ScheduledProcess

@Log
@Component
public class ScheduledProcess {

    @Scheduled(fixedRate = 5000)
    public void run() {
        log.info("this runs every 5 seconds..");
    }

}

Application.class

@SpringBootApplication
// ADD THIS ANNOTATION TO YOUR APPLICATION CLASS
@EnableScheduling
public class SchedulingTasksApplication {

    public static void main(String[] args) {
        SpringApplication.run(SchedulingTasksApplication.class);
    }
}

how to create a list of lists

First of all do not use list as a variable name- that is a builtin function.

I'm not super clear of what you're asking (a little more context would help), but maybe this is helpful-

my_list = []
my_list.append(np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
my_list.append(np.genfromtxt('temp2.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))

That will create a list (a type of mutable array in python) called my_list with the output of the np.getfromtext() method in the first 2 indexes.

The first can be referenced with my_list[0] and the second with my_list[1]

Better way to check variable for null or empty string?

There is no better way but since it's an operation you usually do quite often, you'd better automatize the process.

Most frameworks offer a way to make arguments parsing an easy task. You can build you own object for that. Quick and dirty example :

class Request
{

    // This is the spirit but you may want to make that cleaner :-)
    function get($key, $default=null, $from=null)
    {
         if ($from) :
             if (isset(${'_'.$from}[$key]));
                return sanitize(${'_'.strtoupper($from)}[$key]); // didn't test that but it should work
         else
             if isset($_REQUEST[$key])
                return sanitize($_REQUEST[$key]);

         return $default;
    }

    // basics. Enforce it with filters according to your needs
    function sanitize($data)
    {
          return addslashes(trim($data));
    }

    // your rules here
    function isEmptyString($data)
    {
        return (trim($data) === "" or $data === null);
    }


    function exists($key) {}

    function setFlash($name, $value) {}

    [...]

}

$request = new Request();
$question= $request->get('question', '', 'post');
print $request->isEmptyString($question);

Symfony use that kind of sugar massively.

But you are talking about more than that, with your "// Handle error here ". You are mixing 2 jobs : getting the data and processing it. This is not the same at all.

There are other mechanisms you can use to validate data. Again, frameworks can show you best pratices.

Create objects that represent the data of your form, then attach processses and fall back to it. It sounds far more work that hacking a quick PHP script (and it is the first time), but it's reusable, flexible, and much less error prone since form validation with usual PHP tends to quickly become spaguetti code.

AngularJS custom filter function

Here's an example of how you'd use filter within your AngularJS JavaScript (rather than in an HTML element).

In this example, we have an array of Country records, each containing a name and a 3-character ISO code.

We want to write a function which will search through this list for a record which matches a specific 3-character code.

Here's how we'd do it without using filter:

$scope.FindCountryByCode = function (CountryCode) {
    //  Search through an array of Country records for one containing a particular 3-character country-code.
    //  Returns either a record, or NULL, if the country couldn't be found.
    for (var i = 0; i < $scope.CountryList.length; i++) {
        if ($scope.CountryList[i].IsoAlpha3 == CountryCode) {
            return $scope.CountryList[i];
        };
    };
    return null;
};

Yup, nothing wrong with that.

But here's how the same function would look, using filter:

$scope.FindCountryByCode = function (CountryCode) {
    //  Search through an array of Country records for one containing a particular 3-character country-code.
    //  Returns either a record, or NULL, if the country couldn't be found.

    var matches = $scope.CountryList.filter(function (el) { return el.IsoAlpha3 == CountryCode; })

    //  If 'filter' didn't find any matching records, its result will be an array of 0 records.
    if (matches.length == 0)
        return null;

    //  Otherwise, it should've found just one matching record
    return matches[0];
};

Much neater.

Remember that filter returns an array as a result (a list of matching records), so in this example, we'll either want to return 1 record, or NULL.

Hope this helps.

Stacked bar chart

You need to transform your data to long format and shouldn't use $ inside aes:

DF <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

library(reshape2)
DF1 <- melt(DF, id.var="Rank")

library(ggplot2)
ggplot(DF1, aes(x = Rank, y = value, fill = variable)) + 
  geom_bar(stat = "identity")

enter image description here

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

InnoDB works slightly different that MyISAM and they both are viable options. You should use what you think it fits the project.

Some keypoints will be:

  1. InnoDB does ACID-compliant transaction. http://en.wikipedia.org/wiki/ACID
  2. InnoDB does Referential Integrity (foreign key relations) http://www.w3resource.com/sql/joins/joining-tables-through-referential-integrity.php
  3. MyIsam does full text search, InnoDB doesn't
  4. I have been told InnoDB is faster on executing writes but slower than MyISAM doing reads (I cannot back this up and could not find any article that analyses this, I do however have the guy that told me this in high regard), feel free to ignore this point or do your own research.
  5. Default configuration does not work very well for InnoDB needs to be tweaked accordingly, run a tool like http://mysqltuner.pl/mysqltuner.pl to help you.

Notes:

  • In my opinion the second point is probably the one were InnoDB has a huge advantage over MyISAM.
  • Full text search not working with InnoDB is a bit of a pain, You can mix different storage engines but be careful when doing so.

Notes2: - I am reading this book "High performance MySQL", the author says "InnoDB loads data and creates indexes slower than MyISAM", this could also be a very important factor when deciding what to use.

Operand type clash: uniqueidentifier is incompatible with int

If you're accessing this via a View then try sp_recompile or refreshing views.

sp_recompile:

Causes stored procedures, triggers, and user-defined functions to be recompiled the next time that they are run. It does this by dropping the existing plan from the procedure cache forcing a new plan to be created the next time that the procedure or trigger is run. In a SQL Server Profiler collection, the event SP:CacheInsert is logged instead of the event SP:Recompile.

Arguments

[ @objname= ] 'object'

The qualified or unqualified name of a stored procedure, trigger, table, view, or user-defined function in the current database. object is nvarchar(776), with no default. If object is the name of a stored procedure, trigger, or user-defined function, the stored procedure, trigger, or function will be recompiled the next time that it is run. If object is the name of a table or view, all the stored procedures, triggers, or user-defined functions that reference the table or view will be recompiled the next time that they are run.

Return Code Values

0 (success) or a nonzero number (failure)

Remarks

sp_recompile looks for an object in the current database only.

The queries used by stored procedures, or triggers, and user-defined functions are optimized only when they are compiled. As indexes or other changes that affect statistics are made to the database, compiled stored procedures, triggers, and user-defined functions may lose efficiency. By recompiling stored procedures and triggers that act on a table, you can reoptimize the queries.

A project with an Output Type of Class Library cannot be started directly

Goto the Solution properties -> on Build right side you see the startup project type. here you need to select the console appication/windows appication.

What is causing this error - "Fatal error: Unable to find local grunt"

None of the above worked for me because i had grunt installed globally (recommended in several of these answers, oddly) and that was messing everything up. Here's what did work:

npm uninstall -g grunt
npm install

Only now was a local grunt installed, and useable, for me.

How to reset db in Django? I get a command 'reset' not found error

python manage.py flush

deleted old db contents,

Don't forget to create new superuser:

python manage.py createsuperuser

Convert NVARCHAR to DATETIME in SQL Server 2008

alter table your_table
alter column LoginDate datetime;

SQLFiddle demo

Copy files on Windows Command Line with Progress

This technet link has some good info for copying large files. I used an exchange server utility mentioned in the article which shows progress and uses non buffered copy functions internally for faster transfer.

In another scenario, I used robocopy. Robocopy GUI makes it easier to get your command line options right.

Difference between java.lang.RuntimeException and java.lang.Exception

  1. User-defined Exception can be Checked Exception or Unchecked Exception, It depends on the class it is extending to.

  2. User-defined Exception can be Custom Checked Exception, if it is extending to Exception class

  3. User-defined Exception can be Custom Unchecked Exception , if it is extending to Run time Exception class.

  4. Define a class and make it a child to Exception or Run time Exception

Fast Bitmap Blur For Android SDK

EDIT (April 2014): This is a question/answer page that still gets a lot of hits it seems. I know I'm always getting upvotes for this post. But if you're reading this, you need to realize the answers posted here (both mine and the accepted answer) are out of date. If you want to implement efficient blur today, you should use RenderScript instead of the NDK or Java. RenderScript runs on Android 2.2+ (using the Android Support Library), so there's no reason not to use it.

The old answer follows, but beware as it's outdated.


For future² Googlers, here is an algorithm that I ported from Yahel's port of Quasimondo's algorithm, but using the NDK. It's based on Yahel's answer, of course. But this is running native C code, so it's faster. Much faster. Like, 40 times faster.

I find that using the NDK is how all image manipulation should be done on Android... it's somewhat annoying to implement at first (read a great tutorial on using JNI and the NDK here), but much better, and near real time for a lot of things.

For reference, using Yahel's Java function, it took 10 seconds to blur my 480x532 pixels image with a blur radius of 10. But it took 250ms using the native C version. And I'm pretty sure it can still be further optimized... I just did a dumb conversion of the java code, there's probably some manipulations that can be shortened, didn't want to spend too much time refactoring the whole thing.

#include <jni.h>
#include <string.h>
#include <math.h>
#include <stdio.h>
#include <android/log.h>
#include <android/bitmap.h>

#define LOG_TAG "libbitmaputils"
#define LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)

typedef struct {
    uint8_t red;
    uint8_t green;
    uint8_t blue;
    uint8_t alpha;
} rgba;

JNIEXPORT void JNICALL Java_com_insert_your_package_ClassName_functionToBlur(JNIEnv* env, jobject obj, jobject bitmapIn, jobject bitmapOut, jint radius) {
    LOGI("Blurring bitmap...");

    // Properties
    AndroidBitmapInfo   infoIn;
    void*               pixelsIn;
    AndroidBitmapInfo   infoOut;
    void*               pixelsOut;

    int ret;

    // Get image info
    if ((ret = AndroidBitmap_getInfo(env, bitmapIn, &infoIn)) < 0 || (ret = AndroidBitmap_getInfo(env, bitmapOut, &infoOut)) < 0) {
        LOGE("AndroidBitmap_getInfo() failed ! error=%d", ret);
        return;
    }

    // Check image
    if (infoIn.format != ANDROID_BITMAP_FORMAT_RGBA_8888 || infoOut.format != ANDROID_BITMAP_FORMAT_RGBA_8888) {
        LOGE("Bitmap format is not RGBA_8888!");
        LOGE("==> %d %d", infoIn.format, infoOut.format);
        return;
    }

    // Lock all images
    if ((ret = AndroidBitmap_lockPixels(env, bitmapIn, &pixelsIn)) < 0 || (ret = AndroidBitmap_lockPixels(env, bitmapOut, &pixelsOut)) < 0) {
        LOGE("AndroidBitmap_lockPixels() failed ! error=%d", ret);
    }

    int h = infoIn.height;
    int w = infoIn.width;

    LOGI("Image size is: %i %i", w, h);

    rgba* input = (rgba*) pixelsIn;
    rgba* output = (rgba*) pixelsOut;

    int wm = w - 1;
    int hm = h - 1;
    int wh = w * h;
    int whMax = max(w, h);
    int div = radius + radius + 1;

    int r[wh];
    int g[wh];
    int b[wh];
    int rsum, gsum, bsum, x, y, i, yp, yi, yw;
    rgba p;
    int vmin[whMax];

    int divsum = (div + 1) >> 1;
    divsum *= divsum;
    int dv[256 * divsum];
    for (i = 0; i < 256 * divsum; i++) {
        dv[i] = (i / divsum);
    }

    yw = yi = 0;

    int stack[div][3];
    int stackpointer;
    int stackstart;
    int rbs;
    int ir;
    int ip;
    int r1 = radius + 1;
    int routsum, goutsum, boutsum;
    int rinsum, ginsum, binsum;

    for (y = 0; y < h; y++) {
        rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
        for (i = -radius; i <= radius; i++) {
            p = input[yi + min(wm, max(i, 0))];

            ir = i + radius; // same as sir

            stack[ir][0] = p.red;
            stack[ir][1] = p.green;
            stack[ir][2] = p.blue;
            rbs = r1 - abs(i);
            rsum += stack[ir][0] * rbs;
            gsum += stack[ir][1] * rbs;
            bsum += stack[ir][2] * rbs;
            if (i > 0) {
                rinsum += stack[ir][0];
                ginsum += stack[ir][1];
                binsum += stack[ir][2];
            } else {
                routsum += stack[ir][0];
                goutsum += stack[ir][1];
                boutsum += stack[ir][2];
            }
        }
        stackpointer = radius;

        for (x = 0; x < w; x++) {

            r[yi] = dv[rsum];
            g[yi] = dv[gsum];
            b[yi] = dv[bsum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;

            stackstart = stackpointer - radius + div;
            ir = stackstart % div; // same as sir

            routsum -= stack[ir][0];
            goutsum -= stack[ir][1];
            boutsum -= stack[ir][2];

            if (y == 0) {
                vmin[x] = min(x + radius + 1, wm);
            }
            p = input[yw + vmin[x]];

            stack[ir][0] = p.red;
            stack[ir][1] = p.green;
            stack[ir][2] = p.blue;

            rinsum += stack[ir][0];
            ginsum += stack[ir][1];
            binsum += stack[ir][2];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;

            stackpointer = (stackpointer + 1) % div;
            ir = (stackpointer) % div; // same as sir

            routsum += stack[ir][0];
            goutsum += stack[ir][1];
            boutsum += stack[ir][2];

            rinsum -= stack[ir][0];
            ginsum -= stack[ir][1];
            binsum -= stack[ir][2];

            yi++;
        }
        yw += w;
    }
    for (x = 0; x < w; x++) {
        rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
        yp = -radius * w;
        for (i = -radius; i <= radius; i++) {
            yi = max(0, yp) + x;

            ir = i + radius; // same as sir

            stack[ir][0] = r[yi];
            stack[ir][1] = g[yi];
            stack[ir][2] = b[yi];

            rbs = r1 - abs(i);

            rsum += r[yi] * rbs;
            gsum += g[yi] * rbs;
            bsum += b[yi] * rbs;

            if (i > 0) {
                rinsum += stack[ir][0];
                ginsum += stack[ir][1];
                binsum += stack[ir][2];
            } else {
                routsum += stack[ir][0];
                goutsum += stack[ir][1];
                boutsum += stack[ir][2];
            }

            if (i < hm) {
                yp += w;
            }
        }
        yi = x;
        stackpointer = radius;
        for (y = 0; y < h; y++) {
            output[yi].red = dv[rsum];
            output[yi].green = dv[gsum];
            output[yi].blue = dv[bsum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;

            stackstart = stackpointer - radius + div;
            ir = stackstart % div; // same as sir

            routsum -= stack[ir][0];
            goutsum -= stack[ir][1];
            boutsum -= stack[ir][2];

            if (x == 0) vmin[y] = min(y + r1, hm) * w;
            ip = x + vmin[y];

            stack[ir][0] = r[ip];
            stack[ir][1] = g[ip];
            stack[ir][2] = b[ip];

            rinsum += stack[ir][0];
            ginsum += stack[ir][1];
            binsum += stack[ir][2];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;

            stackpointer = (stackpointer + 1) % div;
            ir = stackpointer; // same as sir

            routsum += stack[ir][0];
            goutsum += stack[ir][1];
            boutsum += stack[ir][2];

            rinsum -= stack[ir][0];
            ginsum -= stack[ir][1];
            binsum -= stack[ir][2];

            yi += w;
        }
    }

    // Unlocks everything
    AndroidBitmap_unlockPixels(env, bitmapIn);
    AndroidBitmap_unlockPixels(env, bitmapOut);

    LOGI ("Bitmap blurred.");
}

int min(int a, int b) {
    return a > b ? b : a;
}

int max(int a, int b) {
    return a > b ? a : b;
}

Then use it like this (considering a class called com.insert.your.package.ClassName and a native function called functionToBlur, as the code above states):

// Create a copy
Bitmap bitmapOut = bitmapIn.copy(Bitmap.Config.ARGB_8888, true);
// Blur the copy
functionToBlur(bitmapIn, bitmapOut, __radius);

It expects a RGB_8888 bitmap!

To use a RGB_565 bitmap, either create a converted copy before passing the parameter (yuck), or change the function to use a new rgb565 type instead of rgba:

typedef struct {
    uint16_t byte0;
} rgb565;

The problem is that if you do that you can't read .red, .green and .blue of the pixel anymore, you need to read the byte properly, duh. When I needed that before, I did this:

r = (pixels[x].byte0 & 0xF800) >> 8;
g = (pixels[x].byte0 & 0x07E0) >> 3;
b = (pixels[x].byte0 & 0x001F) << 3;

But there's probably some less dumb way of doing it. I'm not much of a low-level C coder, I'm afraid.

Specified argument was out of the range of valid values. Parameter name: site

I had the same issue i resolved it by repairing the iis server in programs and features.

GO TO

Controll panel > uninstall a program and then right click the installed iis express server (installed with Visual Studio) and then click repair.

this is how i solved this issue

Alphabet range in Python

If you are looking to an equivalent of letters[1:10] from R, you can use:

import string
list(string.ascii_lowercase[0:10])

urllib2 and json

Messa's answer only works if the server isn't bothering to check the content-type header. You'll need to specify a content-type header if you want it to really work. Here's Messa's answer modified to include a content-type header:

import json
import urllib2
data = json.dumps([1, 2, 3])
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()

How to import or copy images to the "res" folder in Android Studio?

To import files from OS X Finder into Android Studio, just drag the relevant files to your resource folder.

  • Drag & Drop by default moves files to your project (not what you always want)
  • Pressing ? (Alt) while dragging copies files

Don't find a permanent config option for this, but this is the workaround I'm using

How to switch between frames in Selenium WebDriver using Java

to switchto a frame:

driver.switchTo.frame("Frame_ID");

to switch to the default again.

driver.switchTo().defaultContent();

Learning Ruby on Rails

I've been moving from C# in my professional career to looking at Ruby and RoR in my personal life, and I've found linux to be slightly more appealing personally for development. Particularly now that I've started using git, the implementation is cleaner on linux.

Currently I'm dual booting and getting closer to running Ubuntu full time. I'm using gedit with various plugins for the development environment. And as of late 2010, I'm making the push to use Vim for development, even over Textmate on OS X.

A large amount of the Rails developers are using (gasp) Macs, which has actually got me thinking in that direction.

Although I haven't tried it, Ruby in Steel gives you a Ruby IDE inside the Visual Studio world, and IronRuby is the .NET flavor of Ruby, if you're interested.

As far as books are concerned, the Programming Ruby (also known as the Pickaxe) book from the Pragmatic Programmers is the de-facto for learning Ruby. I bit the bullet and purchased that book and Agile Web Development with Rails; both books have been excellent.

Peepcode screencasts and PDF books have also been great for getting started; at $9 per screencast it's hard to go wrong. I actually bought a 5-pack.

Also check out the following:

I've burned through the backlog of Rails and Rails Envy podcasts in the past month and they have provided wonderful insight into lots of topics, even regarding software development in general.

Android Button Onclick

Use Layout inflater method in your button click. it will change your current .xml to targeted .xml file. Google for layout inflater code.

SQL Server 2005 Using CHARINDEX() To split a string

Here's a little function that will do "NATO encoding" for you:

CREATE FUNCTION dbo.NATOEncode (
   @String varchar(max)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN (
   WITH L1 (N) AS (SELECT 1 UNION ALL SELECT 1),
   L2 (N) AS (SELECT 1 FROM L1, L1 B),
   L3 (N) AS (SELECT 1 FROM L2, L2 B),
   L4 (N) AS (SELECT 1 FROM L3, L3 B),
   L5 (N) AS (SELECT 1 FROM L4, L4 C),
   L6 (N) AS (SELECT 1 FROM L5, L5 C),
   Nums (Num) AS (SELECT Row_Number() OVER (ORDER BY (SELECT 1)) FROM L6)
   SELECT
      NATOString = Substring((
         SELECT
            Convert(varchar(max), ' ' + D.Word)
         FROM
            Nums N
            INNER JOIN (VALUES
               ('A', 'Alpha'),
               ('B', 'Beta'),
               ('C', 'Charlie'),
               ('D', 'Delta'),
               ('E', 'Echo'),
               ('F', 'Foxtrot'),
               ('G', 'Golf'),
               ('H', 'Hotel'),
               ('I', 'India'),
               ('J', 'Juliet'),
               ('K', 'Kilo'),
               ('L', 'Lima'),
               ('M', 'Mike'),
               ('N', 'November'),
               ('O', 'Oscar'),
               ('P', 'Papa'),
               ('Q', 'Quebec'),
               ('R', 'Romeo'),
               ('S', 'Sierra'),
               ('T', 'Tango'),
               ('U', 'Uniform'),
               ('V', 'Victor'),
               ('W', 'Whiskey'),
               ('X', 'X-Ray'),
               ('Y', 'Yankee'),
               ('Z', 'Zulu'),
               ('0', 'Zero'),
               ('1', 'One'),
               ('2', 'Two'),
               ('3', 'Three'),
               ('4', 'Four'),
               ('5', 'Five'),
               ('6', 'Six'),
               ('7', 'Seven'),
               ('8', 'Eight'),
               ('9', 'Niner')
            ) D (Digit, Word)
               ON Substring(@String, N.Num, 1) = D.Digit
         WHERE
            N.Num <= Len(@String)
         FOR XML PATH(''), TYPE
      ).value('.[1]', 'varchar(max)'), 2, 2147483647)
);

This function will work on even very long strings, and performs pretty well (I ran it against a 100,000-character string and it returned in 589 ms). Here's an example of how to use it:

SELECT NATOString FROM dbo.NATOEncode('LD-23DSP-1430');
-- Output: Lima Delta Two Three Delta Sierra Papa One Four Three Zero

I intentionally made it a table-valued function so it could be inlined into a query if you run it against many rows at once, just use CROSS APPLY or wrap the above example in parentheses to use it as a value in the SELECT clause (you can put a column name in the function parameter position).

Return HTML from ASP.NET Web API

Starting with AspNetCore 2.0, it's recommended to use ContentResult instead of the Produce attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885

This doesn't rely on serialization nor on content negotiation.

[HttpGet]
public ContentResult Index() {
    return new ContentResult {
        ContentType = "text/html",
        StatusCode = (int)HttpStatusCode.OK,
        Content = "<html><body>Hello World</body></html>"
    };
}

What characters are valid in a URL?

All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics.

How to update column value in laravel

You may try this:

Page::where('id', $id)->update(array('image' => 'asdasd'));

There are other ways too but no need to use Page::find($id); in this case. But if you use find() then you may try it like this:

$page = Page::find($id);

// Make sure you've got the Page model
if($page) {
    $page->image = 'imagepath';
    $page->save();
}

Also you may use:

$page = Page::findOrFail($id);

So, it'll throw an exception if the model with that id was not found.

Explain ggplot2 warning: "Removed k rows containing missing values"

The behavior you're seeing is due to how ggplot2 deals with data that are outside the axis ranges of the plot. You can change this behavior depending on whether you use scale_y_continuous (or, equivalently, ylim) or coord_cartesian to set axis ranges, as explained below.

library(ggplot2)

# All points are visible in the plot
ggplot(mtcars, aes(mpg, hp)) + 
  geom_point()

In the code below, one point with hp = 335 is outside the y-range of the plot. Also, because we used scale_y_continuous to set the y-axis range, this point is not included in any other statistics or summary measures calculated by ggplot, such as the linear regression line.

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() +
  scale_y_continuous(limits=c(0,300)) +  # Change this to limits=c(0,335) and the warning disappars
  geom_smooth(method="lm")

Warning messages:
1: Removed 1 rows containing missing values (stat_smooth). 
2: Removed 1 rows containing missing values (geom_point).

In the code below, the point with hp = 335 is still outside the y-range of the plot, but this point is nevertheless included in any statistics or summary measures that ggplot calculates, such as the linear regression line. This is because we used coord_cartesian to set the y-axis range, and this function does not exclude points that are outside the plot ranges when it does other calculations on the data.

If you compare this and the previous plot, you can see that the linear regression line in the second plot has a slightly steeper slope, because the point with hp=335 is included when calculating the regression line, even though it's not visible in the plot.

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() +
  coord_cartesian(ylim=c(0,300)) +
  geom_smooth(method="lm")

PHP XML Extension: Not installed

If you are working with php in windows, you can just access to the file "php.ini" located in your php instalation folder and uncomment the ";extension=xmlrpc" line deleting the ";" ("extension=xmlrpc")

Driver executable must be set by the webdriver.ie.driver system property

I just put the driver files directly into my project to not get any dependency to my local machine.

final File file = new File("driver/chromedriver_2_22_mac");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());

driver = new ChromeDriver();

What is the &#xA; character?

&#xA; is the HTML representation in hex of a line feed character. It represents a new line on Unix and Unix-like (for example) operating systems.

You can find a list of such characters at (for example) http://la.remifa.so/unicode/latin1.html

Maven: Non-resolvable parent POM

Inside relative path tag do as follows

<relative>{project_name}/pom.xml</relative>

and then RunAs-> Maven build

It worked for me.

how to write javascript code inside php

At the time the script is executed, the button does not exist because the DOM is not fully loaded. The easiest solution would be to put the script block after the form.

Another solution would be to capture the window.onload event or use the jQuery library (overkill if you only have this one JavaScript).

Convert array of indices to 1-hot encoded numpy array

If using tensorflow, there is one_hot():

import tensorflow as tf
import numpy as np

a = np.array([1, 0, 3])
depth = 4
b = tf.one_hot(a, depth)
# <tf.Tensor: shape=(3, 3), dtype=float32, numpy=
# array([[0., 1., 0.],
#        [1., 0., 0.],
#        [0., 0., 0.]], dtype=float32)>

Matplotlib: "Unknown projection '3d'" error

Just to add to Joe Kington's answer (not enough reputation for a comment) there is a good example of mixing 2d and 3d plots in the documentation at http://matplotlib.org/examples/mplot3d/mixed_subplots_demo.html which shows projection='3d' working in combination with the Axes3D import.

from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.add_subplot(2, 1, 1)
...
ax = fig.add_subplot(2, 1, 2, projection='3d')

In fact as long as the Axes3D import is present the line

from mpl_toolkits.mplot3d import Axes3D
...
ax = fig.gca(projection='3d')

as used by the OP also works. (checked with matplotlib version 1.3.1)

Compute mean and standard deviation by group for multiple variables in a data.frame

Here is probably the simplest way to go about it (with a reproducible example):

library(plyr)
df <- data.frame(ID=rep(1:3, 3), Obs_1=rnorm(9), Obs_2=rnorm(9), Obs_3=rnorm(9))
ddply(df, .(ID), summarize, Obs_1_mean=mean(Obs_1), Obs_1_std_dev=sd(Obs_1),
  Obs_2_mean=mean(Obs_2), Obs_2_std_dev=sd(Obs_2))

   ID  Obs_1_mean Obs_1_std_dev  Obs_2_mean Obs_2_std_dev
1  1 -0.13994642     0.8258445 -0.15186380     0.4251405
2  2  1.49982393     0.2282299  0.50816036     0.5812907
3  3 -0.09269806     0.6115075 -0.01943867     1.3348792

EDIT: The following approach saves you a lot of typing when dealing with many columns.

ddply(df, .(ID), colwise(mean))

  ID      Obs_1      Obs_2      Obs_3
1  1 -0.3748831  0.1787371  1.0749142
2  2 -1.0363973  0.0157575 -0.8826969
3  3  1.0721708 -1.1339571 -0.5983944

ddply(df, .(ID), colwise(sd))

  ID     Obs_1     Obs_2     Obs_3
1  1 0.8732498 0.4853133 0.5945867
2  2 0.2978193 1.0451626 0.5235572
3  3 0.4796820 0.7563216 1.4404602

How to do a for loop in windows command line?

You might also consider adding ".

For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus" is very good idea.

"Failed to install the following Android SDK packages as some licences have not been accepted" error

Tried this on Android Studio and it worked for me:

Tools > SDK Manager (Make sure to check Show Packages below)

SDK Platforms > Show Packages > Android - 28 SDK Platforms > Show Packages > Android - 28

SDK Tools > Show Packages > 28.0.3 SDK Tools > Show Packages > 28.0.3

Android Studio: Module won't show up in "Edit Configuration"

In your module build.gradle file make sure you have the correct plugin set. it should be

apply plugin: 'android'

Twitter Bootstrap dropdown menu

It's also possible to customise your bootstrap build by using:

http://twitter.github.com/bootstrap/customize.html

All the plugins are included by default.

Is there a naming convention for git repositories?

If you plan to create a PHP package you most likely want to put in on Packagist to make it available for other with composer. Composer has the as naming-convention to use vendorname/package-name-is-lowercase-with-hyphens.

If you plan to create a JS package you probably want to use npm. One of their naming conventions is to not permit upper case letters in the middle of your package name.

Therefore, I would recommend for PHP and JS packages to use lowercase-with-hyphens and name your packages in composer or npm identically to your package on GitHub.

How to parse a date?

In response to: "How to convert Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México)) to dd-MM-yy in Java?", it was marked how duplicate

Try this: With java.util.Date, java.text.SimpleDateFormat, it's a simple solution.

public static void main(String[] args) throws ParseException {

    String fecha = "Tue Sep 13 2016 00:00:00 GMT-0500 (Hora de verano central (México))";
    Date f = new Date(fecha);

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    sdf.setTimeZone(TimeZone.getTimeZone("-5GMT"));
    fecha = sdf.format(f);
    System.out.println(fecha);
}

Best practice to return errors in ASP.NET Web API

Building up upon Manish Jain's answer (which is meant for Web API 2 which simplifies things):

1) Use validation structures to response as many validation errors as possible. These structures can also be used to response to requests coming from forms.

public class FieldError
{
    public String FieldName { get; set; }
    public String FieldMessage { get; set; }
}

// a result will be able to inform API client about some general error/information and details information (related to invalid parameter values etc.)
public class ValidationResult<T>
{
    public bool IsError { get; set; }

    /// <summary>
    /// validation message. It is used as a success message if IsError is false, otherwise it is an error message
    /// </summary>
    public string Message { get; set; } = string.Empty;

    public List<FieldError> FieldErrors { get; set; } = new List<FieldError>();

    public T Payload { get; set; }

    public void AddFieldError(string fieldName, string fieldMessage)
    {
        if (string.IsNullOrWhiteSpace(fieldName))
            throw new ArgumentException("Empty field name");

        if (string.IsNullOrWhiteSpace(fieldMessage))
            throw new ArgumentException("Empty field message");

        // appending error to existing one, if field already contains a message
        var existingFieldError = FieldErrors.FirstOrDefault(e => e.FieldName.Equals(fieldName));
        if (existingFieldError == null)
            FieldErrors.Add(new FieldError {FieldName = fieldName, FieldMessage = fieldMessage});
        else
            existingFieldError.FieldMessage = $"{existingFieldError.FieldMessage}. {fieldMessage}";

        IsError = true;
    }

    public void AddEmptyFieldError(string fieldName, string contextInfo = null)
    {
        AddFieldError(fieldName, $"No value provided for field. Context info: {contextInfo}");
    }
}

public class ValidationResult : ValidationResult<object>
{

}

2) Service layer will return ValidationResults, regardless of operation being successful or not. E.g:

    public ValidationResult DoSomeAction(RequestFilters filters)
    {
        var ret = new ValidationResult();

        if (filters.SomeProp1 == null) ret.AddEmptyFieldError(nameof(filters.SomeProp1));
        if (filters.SomeOtherProp2 == null) ret.AddFieldError(nameof(filters.SomeOtherProp2 ), $"Failed to parse {filters.SomeOtherProp2} into integer list");

        if (filters.MinProp == null) ret.AddEmptyFieldError(nameof(filters.MinProp));
        if (filters.MaxProp == null) ret.AddEmptyFieldError(nameof(filters.MaxProp));


        // validation affecting multiple input parameters
        if (filters.MinProp > filters.MaxProp)
        {
            ret.AddFieldError(nameof(filters.MinProp, "Min prop cannot be greater than max prop"));
            ret.AddFieldError(nameof(filters.MaxProp, "Check"));
        }

        // also specify a global error message, if we have at least one error
        if (ret.IsError)
        {
            ret.Message = "Failed to perform DoSomeAction";
            return ret;
        }

        ret.Message = "Successfully performed DoSomeAction";
        return ret;
    }

3) API Controller will construct the response based on service function result

One option is to put virtually all parameters as optional and perform custom validation which return a more meaningful response. Also, I am taking care not to allow any exception to go beyond the service boundary.

    [Route("DoSomeAction")]
    [HttpPost]
    public HttpResponseMessage DoSomeAction(int? someProp1 = null, string someOtherProp2 = null, int? minProp = null, int? maxProp = null)
    {
        try
        {
            var filters = new RequestFilters 
            {
                SomeProp1 = someProp1 ,
                SomeOtherProp2 = someOtherProp2.TrySplitIntegerList() ,
                MinProp = minProp, 
                MaxProp = maxProp
            };

            var result = theService.DoSomeAction(filters);
            return !result.IsError ? Request.CreateResponse(HttpStatusCode.OK, result) : Request.CreateResponse(HttpStatusCode.BadRequest, result);
        }
        catch (Exception exc)
        {
            Logger.Log(LogLevel.Error, exc, "Failed to DoSomeAction");
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, new HttpError("Failed to DoSomeAction - internal error"));
        }
    }

\r\n, \r and \n what is the difference between them?

A carriage return (\r) makes the cursor jump to the first column (begin of the line) while the newline (\n) jumps to the next line and eventually to the beginning of that line. So to be sure to be at the first position within the next line one uses both.

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

Solution 1:

Extract P12 from jks

keytool -importkeystore -srckeystore MyRootCA.jks -destkeystore MyRootCA.p12 -deststoretype PKCS12

Extract PEM from P12 and Edit file and pem from crt file

openssl pkcs12 -in MyRootCA.p12 -clcerts -nokeys -out MyRootCA.crt

Extract key from jks

openssl pkcs12 -in MyRootCA.p12 -nocerts -out encryptedPrivateKey.pem
openssl rsa -in encryptedPrivateKey.pem -out decryptedPrivateKey.key

Solution 2:

Extract PEM and encryptedPrivateKey to txt file```

openssl pkcs12 -in MyRootCA.p12 -out keys_out.txt

Decrypt privateKey

openssl rsa -in encryptedPrivateKey.key [-outform PEM] -out decryptedPrivateKey.key

How to assign pointer address manually in C programming language?

int *p=(int *)0x1234 = 10; //0x1234 is the memory address and value 10 is assigned in that address


unsigned int *ptr=(unsigned int *)0x903jf = 20;//0x903j is memory address and value 20 is assigned 

Basically in Embedded platform we are using directly addresses instead of names

Styling Form with Label above Inputs

I'd prefer not to use an HTML5 only element such as <section>. Also grouping the input fields might painful if you try to generate the form with code. It's always better to produce similar markup for each one and only change the class names. Therefore I would recommend a solution that looks like this :

CSS

label, input {
    display: block;
}
ul.form {
    width  : 500px;
    padding: 0px;
    margin : 0px;
    list-style-type: none;
}
ul.form li  {
    width : 500px;
}
ul.form li input {
    width : 200px;
}
ul.form li textarea {
    width : 450px;
    height: 150px;
}
ul.form li.twoColumnPart {
    float : left;
    width : 250px;
}

HTML

<form name="message" method="post">
    <ul class="form">
        <li class="twoColumnPart">
            <label for="name">Name</label>
            <input id="name" type="text" value="" name="name">
        </li>
        <li class="twoColumnPart">
            <label for="email">Email</label>
            <input id="email" type="text" value="" name="email">
        </li>
        <li>
            <label for="subject">Subject</label>
            <input id="subject" type="text" value="" name="subject">
        </li>
        <li>
            <label for="message">Message</label>
            <textarea id="message" type="text" name="message"></textarea>
        </li>
    </ul>
</form>

Why does ++[[]][+[]]+[+[]] return the string "10"?

Perhaps the shortest possible ways to evaluate an expression into "10" without digits are:

+!+[] + [+[]] // "10"

-~[] + [+[]] // "10"

//========== Explanation ==========\\

+!+[] : +[] Converts to 0. !0 converts to true. +true converts to 1. -~[] = -(-1) which is 1

[+[]] : +[] Converts to 0. [0] is an array with a single element 0.

Then JS evaluates the 1 + [0], thus Number + Array expression. Then the ECMA specification works: + operator converts both operands to a string by calling the toString()/valueOf() functions from the base Object prototype. It operates as an additive function if both operands of an expression are numbers only. The trick is that arrays easily convert their elements into a concatenated string representation.

Some examples:

1 + {} //    "1[object Object]"
1 + [] //    "1"
1 + new Date() //    "1Wed Jun 19 2013 12:13:25 GMT+0400 (Caucasus Standard Time)"

There's a nice exception that two Objects addition results in NaN:

[] + []   //    ""
[1] + [2] //    "12"
{} + {}   //    NaN
{a:1} + {b:2}     //    NaN
[1, {}] + [2, {}] //    "1,[object Object]2,[object Object]"

How does "304 Not Modified" work exactly?

When the browser puts something in its cache, it also stores the Last-Modified or ETag header from the server.

The browser then sends a request with the If-Modified-Since or If-None-Match header, telling the server to send a 304 if the content still has that date or ETag.

The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.

How to get a barplot with several variables side by side grouped by a factor

You can use aggregate to calculate the means:

means<-aggregate(df,by=list(df$gender),mean)
Group.1      tea     coke     beer    water gender
1       1 87.70171 27.24834 24.27099 37.24007      1
2       2 24.73330 25.27344 25.64657 24.34669      2

Get rid of the Group.1 column

means<-means[,2:length(means)]

Then you have reformat the data to be in long format:

library(reshape2)
means.long<-melt(means,id.vars="gender")
  gender variable    value
1      1      tea 87.70171
2      2      tea 24.73330
3      1     coke 27.24834
4      2     coke 25.27344
5      1     beer 24.27099
6      2     beer 25.64657
7      1    water 37.24007
8      2    water 24.34669

Finally, you can use ggplot2 to create your plot:

library(ggplot2)
ggplot(means.long,aes(x=variable,y=value,fill=factor(gender)))+
  geom_bar(stat="identity",position="dodge")+
  scale_fill_discrete(name="Gender",
                      breaks=c(1, 2),
                      labels=c("Male", "Female"))+
  xlab("Beverage")+ylab("Mean Percentage")

enter image description here