Q:

ASP.NET Identity or ASP.NET Membership?

I have a brand new MVC5 project and I need user management. When I create a new project, Visual Studio goes through and adds a significant amount of code for me so that I can utilize the concept of authentication and authorization.
Question: Is ASP.NET Identity a "good" solution for user management outside of a web application? I would like to one day add a mobile application to the mix and I would like the same BLL codebase to be used for the web application and the mobile app.
Also, my very limited understanding of ASP.NET Identity is that it uses HttpContext behind the scenes to  "wire up" the authentication and authorization. As such, I can use attributes on my controller actions such as [Authorize] to inherit the authorization behavior. I really like this feature but I'm concerned that this approach won't work with mobile apps necessarily because HttpContext is not being used.
One thing to note here is that I also do not like that I have the IdentityConfig.cs class inside of my MVC project using DBContext directly. I have been fiddling  with using an n-tier approach but I cannot seem to successfully break away the auth/auth portion into a proper BLL/DAL architecture model.
So, I guess I have two questions in all:

Is ASP.NET Identity a "good" auth/auth choice for both web & mobile apps
If "yes", how can I tear out the RoleManager/UserManager classes to a BLL and have them pull utilize a Data Access Layer?

A:

1) Yes, by all means go for ASP.Net Identity 2 authentication if you are planning to build mobile apps later. Check out this post to learn more about ASP.Net Identity 2.
I ended up using ASP.Net identity 2 OAuth authentication for my webapi project that's also designed to cater to mobile apps. There is no need to worry about Httpcontext. All that you need to keep track of in the client side (be it a web app or mobile app) is the access_token issued by OAuth.
2) Yes. ASP.Net Identity 2 is extremely flexible in that it even allows you to use another DB engine such as MySQL to store user/roles information. Check this out. I put all the customized OWIN specific tables in a different BLL and plugged that into the WebAPI project. Both are linked via interfaces because the DAL resides in a different project. Combine it with a great DI framework such as StructureMap/Ninject/SimpleInjector and you won't have to worry about DbContext messing up with your architecture model.


Q:

Purely functional data structures with copy-on-write?

I want to have the advantage of functional data structures (multiple versions of data that can share structure) but be able to modify it in an imperative style.
What I'm thinking about (and a possible use): a RPG game in which whole game history is stored (for example, to allow for travelling back in time). Using copy-on-write, I could simply clone the structure holding game state and modify it by introducing a new turn - but have access to the earlier turns (not necessarily all of them, maybe just selected snapshots of game state), without the penalty of having to copy everything every time.

Let's say foo is a map.
bar = foo.clone()

Nothing of foo's structure (for example, tree) gets copied yet. However,
from now on bar is treated as a copy and no changes are allowed to propagate
back to `foo'.
baz = bar[someKey]
baz.modifyInSomeWay()

Now

a new object gets created, that is a modified copy of baz.
bar is replaced with a new map, holding new baz (possibly retaining
some of foo's structure).
foo is unaffected.

But if we then do...
baz.modifyAgain()

...baz can be just modified, because we have a recent version of it. bar
doesn't need to be changed.
All this requires holding some version information about foo and bar,
increasing it on foo.clone(), and passing it to baz somehow (by making it
a proxy object?).
Also, any part of structure that has been cloned becomes a 'part of history'
and can't be changed anymore, which could be enforced at run-time.

This resembles JavaScript's prototypes a bit, but I it's more as it allows for changes
to propagate upwards. I think it would be something like a version control system.

Has this been done, and to what extent?
Is this a good idea? If not, is there a way to save it?
How could it be implemented? I was thinking about building it on top of some high-level GC-ed language, like Python.

A:

Functional ("persistent") data structures are typically recursively built up out of immutable nodes (e.g. singly linked list where common suffixes are shared, search tree or heap where only the parts of the tree structure that are on the path from the root to the updated item need copying).
Anything where the entire set has to be copied for every modification is bad.  In those cases, you'd tend to overlay small "diffs" that are checked (taking extra time) with recursion to previous versions.  Every so often, when the diffs become too large, you could do a deep copy/rebuild (so the amortized cost is not as bad).
Persistent data structures can have significant overhead, but if you have very efficient allocation of small objects (JVM GC qualifies), they can be very practical - in the best case, equally as fast as the mutable equivalent, giving persistence only at the cost of the memory used - which can be much less than a full copy on every update.
Depending on your language, you'll probably find the syntax you want difficult to achieve without operator overloading for assignment.  Lvalues (mutable references) in C++ definitely require non-persistent semantics.


Q:

Forecasting with ARIMA and xreg in R

I'm having trouble with my first forecasting implementation in R. What I'd like to achieve is to predict the variable Y with 2 exogenous variables X1 and X2. The 3 datasets are each represented as a single column with 12 rows.
From another Stackpost I followed a similar approach:
DataSample <- data.frame(Y=Y[,1],Month=rep(1:12,1),
                     X1=X1[,1],X2=X2[,1])

predictor_matrix <- cbind(Month=model.matrix(~as.factor(DataSample$Month)),
                          X1=DataSample$X1,
                          X2=DataSample$X2)
# Remove intercept
predictor_matrix <- predictor_matrix[,-1]

# Rename columns
colnames(predictor_matrix) <- c("January","February","March","April","May","June","July","August","September","October","November","X1","X2")

# Variable to be modeled
var <- ts(DataSample$Y, frequency=12)

#Find ARIMA
modArima <- auto.arima(var, xreg = predictor_matrix)

At this line I get the following error:

Error in optim(init[mask], armaCSS, method = optim.method, hessian =
  FALSE,  :    non-finite value supplied by optim

I presume that my predictor_matrix is not in the correct format but I can't find the error.
Any help would be appreciated,

A:

You have indicated "datasets are ... 12 rows". Your predictor matrix has 13 columns (11 months [of dummy variables?] and 2 other variables). Therefore, you necessarily have a linear dependence among the columns and the optimization procedure fails.
You need (ideally much) more data to support the number of predictor variables and/or a sparser set of predictors.


Q:

amazon S3 database options and using EC2 as a REST api from S3

I am hosting my website on S3.
On my local host I am using backboneJS above a PHP Rest API that uses mySQL as a database.
So i opened an EC2 to host my Rest API but then realized this means cross domain AJAX.
How can i use EC2 as a Rest API if my index.html sits on S3?
What are my other DB options for S3?
many thanks,

A:

Your JavaScript is being executed on web pages served from S3, and it has to access a REST API from a server you run on EC2. Unless the web pages and server are in the same domain (say, example.com), this will be a cross-origin request, prohibited by browsers by default.
Solution 1: have your S3 pages and your EC2 server in the same domain. S3 allows static website hosting that makes your S3 objects (web pages) available at the address of your choice. Put them and your EC2 server at addresses on the same domain, and it can work.
Solution 2: have your REST API server allow cross-origin requests. Since you control this EC2 server you can modify it to tell web browsers to allow pages from other domains to make such requests to your server. This involves setting several headers on your responses, and usually requires your server to respond to HTTP OPTIONS requests properly, too. See the CORS specification to get started on that.
You also ask about other DB options. If you keep your own EC2 server to provide the REST API it can use pretty much any kind of database you like, either running on the same or other EC2 instances, or database-as-a-service offerings like AWS RDB or AWS DynamoDB. But if you want to connect to the database directly from your web pages' JavaScript you would have to use a service that provides an HTTP API directly and that supports CORS. RDB does not provide an HTTP API at all, and DynamoDB does not seem to support CORS at this time, so neither of them would work.


Q:

Why am I getting RangeError: Maximum call stack size exceeded when watching for change to parent scope variable (filtered ng-repeat array)?

My problem is I want to watch for changes to a filtered array created with ng-repeat, for that I'm referencing to the parent scope since I've learned ng-repeat creates its own scope, and while watching the array with $scope.$watch actually works (it accurately detects changes to the array), I get multiple console log errors saying: angular.js:12520 RangeError: Maximum call stack size exceeded.
Anyone have any inputs to what I can do to solve the problem?
HTML:
<div class="module-card" ng-repeat="module in ($parent.filteredModules = (modules | released : true | moduleFilter : allFilters | unique: 'name' | orderBy : sortFunc : orderedAsc | limitTo : limitResults)) track by $index">
JS:
$scope.$watch('filteredModules', function(newVal, oldVal){
   console.log(newVal, oldVal);
}, true)

A:

Solved the problem by using $scope.$watchCollection instead.. If anyone bumps into the same problem.


Q:

How to say "don't take it to heart" in Italian?

How do you say "don't take it to heart" in Italian? I think it could be translated as "fregatene". Any ideas?

A:

Well, we say non prendertela a cuore

prendere a cuore
Interessarsi attivamente di qualcosa, curarsene in modo fattivo.

Fregatene is in my opinion a bit too colloquial and slightly rude compared to the English expression.

A:

fregatene would fit more either don't care or even don't give a .... because it's a little harsh.

How do you say "don't take it to heart" in Italian?

You could say:

Non prendertela (closest non-literal translation);
Lascia perdere (let go), and
Non importa (it doesn't matter)


Q:

Simplest .jpg Display in Python 3

I want to display a .jpg (or other picture file) in Python 3. PIL seems to have ended at 2.7. The ways I've looked use python 2. I don't want to change any pixel values, just display the file on the window. What's the simplest way?

A:

Try Pillow, it should work on python 2 and 3:
http://python-pillow.github.io


Q:

Can I obtain raw depth data/map from PHAB2 Pro?

I want to buy a Lenovo PHAB2 Pro mobile phone to learn Tango's depth perception.  So can I obtain raw depth maps or data from PHAB2 Pro? And if possible could you tell me how to do it? Is Tango C API useful? Or does PHAB2 Pro have other open-source package or Development kit that I can use?
Thanks！:)

A:

1 & 2 - Raw Depth Maps are not available natively, but for an idea of how to get them see Here.  I've not done it.
However you do have the Point Cloud representation of the data to work with.
3 & 4 - It seems the majority of developers do not directly use the C API, but instead work with the UNITY SDK. There is a very good reference on which APIs to choose here.  The PHAB2 does not have any different Development kit from the Dev Kit tablet.


Q:

How do I change the value of a specific DataGridView Cell?

I've been trying to add a feature to my program that allows you to choose a file using OpenFileDialog (when you double click on a DataGridView cell) and change the value of that cell to the path of the file you chose. I have no idea what the command is to do that. I've tried to guess and I looked up on the internet and couldn't find anything.
Private Sub dgSound_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgSound.CellDoubleClick

    If e.ColumnIndex = 3 Then 'Index of "file" column
        Dim file As String = ""
        OpenFileDialog1.ShowDialog()
        file = OpenFileDialog1.FileName

        'Contents of cell that was clicked = file

    End If

End Sub

A:

I'd use CellClick rather than CellContentClick as follows...
  Private Sub dgSound_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgSound.CellClick
    If e.ColumnIndex = 3 Then 'Index of "file" column
      Dim file As String = ""
      OpenFileDialog1.ShowDialog()
      file = OpenFileDialog1.FileName

      'Contents of cell that was clicked = file
      dgSound.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = file

    End If

  End Sub


Q:

Cucumber scenario with quotes in the text

I'd like to have quotes in my scenario data.  It's not working when that data has quotes in it.  An example modified from The Cucumber Book would be:
Then I should see the "<message>" message

 Examples:
 | type | message |
 | Swiss | I love Swiss cheese |
 | Blue | I love "Blue" cheese |
 | Cheddar | I love Cheddar cheese |

In my particular case I get an undefined step definition message because of "Blue" in the second scenario above.  Is there a way I should be escaping the quotes?  (I've tried backslashes but that didn't make any difference.)

A:

My guess is that your current step definition looks like:
Then /I should see the "([^"]+)" message/ do |message|
    p message
end

The [^"] tells the regex to match anything except double-quotes. This would be why your "Blue" example does not match.
Given that you are only looking for one argument, it would be safe to do:
Then /I should see the "(.*)" message/ do |message|
    p message
end

Using (.*) would match everything between the quotes, including the quotes around Blue.


Q:

PYTHON: What is necessary to be able to call a method from within the same class?

I feel like I am missing a major piece of how this code is working, or something really strange is going on.  I have included a method called "handle" which is being passed to thread.start_new_thread as a parameter, however it seems that this method is not being recognized/executed.  Even within the PythonWin editor, when you type "self." it will usually prepopulate a list of recognized options, and handle is not showing up in this version, but in a working version of this file it does show up within the editor.
Here is the code:
(lots of imports go here)
class AppServerSvc (win32serviceutil.ServiceFramework):
    _svc_name_ = "flaspsrv"
    _svc_display_name_ = "Flash Policy Server"
    _svc_description_ = "Initialize Flash Policy Server"

    def __init__(self,args):
        logging.basicConfig(filename='C:\\Uploads\\testing.log', level=logging.DEBUG, filemode='a', format='%(asctime)s %(levelname)s %(message)s')
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.hWaitStop = win32event.CreateEvent(None,0,0,None)
        socket.setdefaulttimeout(60)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_,''))
        self.main()

    def main(self):
        try:
            self.sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        except AttributeError:
            # AttributeError catches Python built without IPv6
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error:
            # socket.error catches OS with IPv6 disabled
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            logging.info('Listening on port 843')
            self.sock.bind(('localhost', 843))
            self.sock.listen(5)

        try:
            while True:
                thread.start_new_thread(self.handle, self.sock.accept())
        except socket.error, e:
            logging.info('Error accepting connection: %s' % (e[1],))

    def handle(self, conn, addr):
        logging.info('Temp2')
        addrstr = '%s:%s' % (addr[0],addr[1])
        try:
            logging.info('Connection from %s' % (addrstr,))
            with contextlib.closing(conn):
                # It's possible that we won't get the entire request in
                # a single recv, but very unlikely.
                request = conn.recv(1024).strip()
                if request != '<policy-file-request/>\0':
                    logging.info('Unrecognized request from %s: %s' % (addrstr, request))
                    return
                logging.info('Valid request received from %s' % (addrstr,))
                fo = file('flashpolicy.xml', 'rb')
                conn.sendall(fo.read(10001))
                logging.info('Sent policy file to %s' % (addrstr,))
        except socket.error, e:
            logging.info('Error handling connection from %s: %s' % (addrstr, e[1]))
        except Exception, e:
            logging.info('Error handling connection from %s: %s' % (addrstr, e[1]))

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(AppServerSvc)

A:

Change the line
thread.start_new_thread(self.handle, self.sock.accept())

to
thread.start_new_thread(self.handle, *self.sock.accept())

From the documentation of socket.accept(), this socket method returns a tuple (conn, address), where as your handler accepts three parameters (including a reference to self).
The second and third parameter of thread.start_new_thread is the args (positional arguments) and kwargs (key word arguments) that are supposed to be passed to the callback registered with the threading module. So unless you unpack the arguments from socket.accept(), you would likely be receiving a Type Error.
So you need to unpack the return tuple from self.socket before passing as an argument to handle.


Q:

Different database for each django site

Suppose we have multiple sites (using sites-framework of Django) running on the same django instance.
MyModel.objects.filter(site_id=request.site, slug=slug)[0] might be an overhead in the future. So I was wondering if I could split the databases for this model(s) for querying faster.
So if request.site is 1, running
MyModel.objects.get(slug=slug)

will query only db1.
If request.site is 2, running
MyModel.objects.get(slug=slug)

will query only db2.
I will be getting request.site from the request parameter of the view as value of site will be dynamically determined according to the subdomain used: de, fr, etc.

A:

You may create a custom router to do this:
Example:
def get_current_site():
   SITE_ID = getattr(settings, 'SITE_ID', 1)
   site_name = Site.objects.get(id=SITE_ID)
   return site_name

DATABASE_ROUTERS = ['CustomDatabaseRouter',] #a setting that Django understands.

class CustomDatabaseRouter(object):

  def db_for_read(self, model, **hints):
     site_name = get_current_site()
     if site_name  in ['site1']:
         return 'db1'
     if site_name in ['site2']:
        return 'db2'
     return 'default'

  def db_for_write(self, model, **hints):
     site_name = get_current_site()
     if site_name  in ['site1']:
         return 'db1'
     if site_name in ['site2']:
        return 'db2'
     return 'default'

  def allow_syncdb(self, model, **hints):
     site_name = get_current_site()
     if site_name in ['site1'] and db == 'db1':
         return True
     if site_name in ['site2'] and db == 'db2':
        return True
     return False

You can readup more here
https://docs.djangoproject.com/en/dev/topics/db/multi-db/


Q:

What is the syntax for using pandoc with RStudio Markdown for conversion to MS Word? How can it be used to include bibliography and inline citations?

RStudio now supports directly knitting .Rmd files into docx format --pure gold for someone who is the technical side of most collaborations where the final revisions of the article are going to be done in Word.
However, I had just barely figured out how to get R, knitr, and pandoc to play with each other and so I am looking for some help in making the transition while the documentation is still in its infancy.
My file converts with no problem using the yaml code block as follows:
---
title: "Testing"
output:
  word_document:
    fig_width: 5
    fig_height: 5
    fig_caption: true
---

and the documentation says that, assuming I have a file 'myLibrary.bib' in the same directory as my .Rmd file, I should be able to add something like this:
    pandoc_args: [
      bibliography: "myLibrary.bib"
    ]

or
pandoc_args: [
      --bibliography "myLibrary.bib"
    ]

but I can't seem to find any examples of how to format this in the obvious places: here
or here
Bonus points for code that also links the bibliography to the myJournalFormat.csl file also in the same folder.

A:

You need to enclose  your arguments in  quotation marks, ("") and be separated by commas
If I have a bibliography file called biblio.bib and the csl file is chicago-author-date.csl,
the following will front matter will work
---
title: "Example Doc"
output:
  word_document:
    pandoc_args: [
      "--csl", "chicago-author-date.csl",
      "--bibliography", "biblio.bib"
    ]
---


Q:

Performance measures : Java vs JavaCard

I implemented two algorithms in Java.
To compare their effectiveness, I call each function 1000 times and compare the execution time (using System.currentTimeMillis()).
It needs 2500 ms to execute the first one and 1300 ms for the second one.
With these results, I thought have a significative difference (in term of execution time) in JavaCard.
But if I load 2 applets on a JavaCard, which correspond to the functions described, the first one takes 2000 ms and the second one 1750 ms...
How explain that in Java, it looks almost 2 times faster, but not in JavaCard ?
I paid attention that I don't write in EEPROM but in RAM so it can't be the source of the problem.
Do you have any argument to explain this phenomenon ? Thank you in advance.

A:

You run the algorithm is in two different platform, so the final machine language is not the same.


Q:

A strange behavior about constructors in C++

I show you the code directly.
#include <iostream>
#include <stdio.h>

class A {
   public:
   A(const std::string& name){
    std::string aname = "HAHA_" + name;
    std::cout << aname << std::endl;
    }

    ~A(){
         std::cout << "Done." << std::endl;
    }
};

int main() {

   size_t len = 5;
   char szTmp[30] ={0};
   snprintf(szTmp,sizeof(szTmp),"Getlist_V2_%zd",len);
   A a(std::string(szTmp));
   return 0;
}

The expected results are as follows：
HAHA_Getlist_V2_5
Done.

But It outputs nothing at all.  When I replace A a(std::string(szTmp)); with
A a(szTmp); ,erverything is ok. It confused me for a long time.

A:

A a(std::string(szTmp));

This is a function declaration, believe it or not! So, no A is constructed.
Instead, write this:
A a{std::string(szTmp)};

Or, since an implicit conversion to std::string exists, either of the following will suffice:
A a{szTmp};
A a(szTmp);


Q:

How to compile an app on Xcode without developer account

as you know from Xcode 7 and onwards it's possible to compile an app for your device.
Yesterday I tried to compile Kodi on Xcode 7. It says it's possible to compile with Xcode 7 without any developer account in the readme too..
Here is the problem though. I previously had a developer account. Now it's expired.
So when I open up the Xcode I saw that my account is already there with description "Free"..

When I click View Details.. though:

So, there is a iOS developer certificate. But no provision profile. And when I try to compile it says "No matching provisioning profiles found: No provisioning profiles matching an applicable signing identity were found."
It's not possible to fix this error too.. Even when I click Fix Issue in General tab, it says "An App with identifier "org.xbmc.kodi-ios" is not available. Please enter a different string."
How could I create a provisioning profile for this app? Actually for all apps with "*" ?
Is it possible that I could start over this process somehow?!? It may be because I had a developer account before ( and I still have as a member but that's not active )
How could I self sign this app?

A:

Try changing the identifier to something unique to you, like "net.plato.kodi-ios" and then try having Xcode fix the issue.
I eventually got Kodi to compile on my own after tweaking some of the provisioning settings, but I have active developer profiles and haven't ever done anything with the free account.


Q:

"first!" on AR CollectionProxy raises "undefined method [] for nil" after updating from Rails 4.1.4 to 4.2.0

I'm starting to upgrade from Rails 4.1.4 to Rails 4.2.0.  It looks like first! is no longer supported on some active record associations.
What happened to first! (on ActiveRecord::Associations::CollectionProxy) to cause it to fail now?
How can fix the behavior so it works as in 4.1.4?
Rails 4.1:
(byebug) user.organization.registration_codes
#<ActiveRecord::Associations::CollectionProxy [#<RegistrationCode id: 259, code: "AWESOMESAUCE" ... >]>

(byebug) user.organization.registration_codes.first!
#<RegistrationCode id: 259, code: "AWESOMESAUCE" ... >

Rails 4.2:
(byebug) user.organization.registration_codes
#<ActiveRecord::Associations::CollectionProxy [#<RegistrationCode id: 259, code: "AWESOMESAUCE" ... >]>

(byebug)  user.organization.registration_codes.first!
NoMethodError Exception: undefined method `[]' for nil:NilClass
nil

Updated
Digging into ActiveRecord, I find it failing here:
def find_nth(index, offset)
  if loaded?
    @records[index]
  else
    offset += index
    @offsets[offset] ||= find_nth_with_limit(offset, 1).first
  end
end

loaded? returns true, but @records is nil.  Throwing a debugger in and calling find_nth_with_limit(offset, 1).first returns the record that I expect.
first! is defined in finder_methods.rb in active record the issue seems to be that the association thinks its loaded, but @records is nil

A:

This is a regression in Rails.  Calling one of the bang finder methods on a loaded collection in rails 4.2 does not work.
https://github.com/rails/rails/issues/18237


Q:

sending data using ajax, blank response coming from Server Side PHP

I am sending Data to PHP using Ajax.
But blank result receiving.
Client Side Code

    <?php
        foreach($data['Products'] as $val){
            $pro.= $val['product_id'].':'.$val['quantity'].',';
        }
    ?>

{<?php echo rtrim($pro, ',');?>}

Browser Giving:

{18:1,10:1}

Server Side Code
public function update(){
    if ($this->RequestHandler->isAjax()) {
        print_r($this->request->data);
    }
}

Testing:
If i am sending statically data: {18:1,20:1}, in ajax then working fine. returning Array.

A:

Alternate Solution which i have tried and success.
Client Side Code:


Q:

Xcode Auto Layout keeps changing my Layout

I'm trying to let my app look the same on different Screen Sizes, but it seems like Xcode just ignore my Constrains on another screen Size This is what it looks like on an iPhone 7 Sceen
Which is what I want it to look like, but on (for eg) iPhone XR this happens:
the text field get streched
How do I can fix this problem?

A:

You have your elements constrained top-to-bottom. That means something has to stretch when you're on a taller screen.
You probably want the field heights to stay the same, and leave extra space between the last field and the button.
So, constrain your fields top-down, but don't give the last field a bottom constraint.
Then constrain your button to the bottom of the view, so it stays put.
Of course, when your app is run on a smaller device, there won't be enough vertical space for everything... You'll either need to design it to reduce the vertical spacing between fields and labels, or you'll need to put it all in a scroll view.

Edit: As also suggested by Matt
Here is an example using a UIStackView. Each label / field pair is contained in a UIView, so they stay close to each other.
Then, each view is added to a UIStackView, along with the button. The stack view is constrained to all 4 sides of the view (with some padding), and set to:
Axis: Vertical
Alignment: Fill
Distribution: Equal Spacing
Spacing: 0

Result for iPhone 8, SE and XS:

and here is the source for the Storyboard:
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
        <capability name="Safe area layout guides" minToolsVersion="9.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="et4-ph-qFU">
            <objects>
                <viewController id="0KB-bM-lGa" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="5xd-aB-51J">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <stackView opaque="NO" contentMode="scaleToFill" axis="vertical" distribution="equalSpacing" translatesAutoresizingMaskIntoConstraints="NO" id="sJk-vH-8Fe">
                                <rect key="frame" x="20" y="100" width="335" height="527"/>
                                <subviews>
                                    <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="9kL-Fs-g0D">
                                        <rect key="frame" x="0.0" y="0.0" width="335" height="59"/>
                                        <subviews>
                                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Firma:" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="dEJ-Oa-qMo">
                                                <rect key="frame" x="0.0" y="0.0" width="335" height="20.5"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                <nil key="textColor"/>
                                                <nil key="highlightedColor"/>
                                            </label>
                                            <textField opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" placeholder="Firmen Name" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="y80-WD-UsN">
                                                <rect key="frame" x="0.0" y="28.5" width="335" height="30.5"/>
                                                <nil key="textColor"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                                <textInputTraits key="textInputTraits"/>
                                            </textField>
                                        </subviews>
                                        <constraints>
                                            <constraint firstAttribute="trailing" secondItem="y80-WD-UsN" secondAttribute="trailing" id="1Qn-QT-svI"/>
                                            <constraint firstItem="y80-WD-UsN" firstAttribute="leading" secondItem="9kL-Fs-g0D" secondAttribute="leading" id="Zrp-Iv-UpA"/>
                                            <constraint firstItem="y80-WD-UsN" firstAttribute="top" secondItem="dEJ-Oa-qMo" secondAttribute="bottom" constant="8" id="h6I-Cu-Cep"/>
                                            <constraint firstAttribute="trailing" secondItem="dEJ-Oa-qMo" secondAttribute="trailing" id="ojC-Hl-iOQ"/>
                                            <constraint firstItem="dEJ-Oa-qMo" firstAttribute="top" secondItem="9kL-Fs-g0D" secondAttribute="top" id="pAR-uA-9Jm"/>
                                            <constraint firstAttribute="bottom" secondItem="y80-WD-UsN" secondAttribute="bottom" id="sNE-S4-8fz"/>
                                            <constraint firstItem="dEJ-Oa-qMo" firstAttribute="leading" secondItem="9kL-Fs-g0D" secondAttribute="leading" id="ytP-V8-Ljx"/>
                                        </constraints>
                                    </view>
                                    <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="39p-CV-TpJ">
                                        <rect key="frame" x="0.0" y="119.5" width="335" height="59"/>
                                        <subviews>
                                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Kontaktperson:" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="I8h-Ni-H0m">
                                                <rect key="frame" x="0.0" y="0.0" width="335" height="20.5"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                <nil key="textColor"/>
                                                <nil key="highlightedColor"/>
                                            </label>
                                            <textField opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" placeholder="Jon Doe" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="SmT-mA-Gye">
                                                <rect key="frame" x="0.0" y="28.5" width="335" height="30.5"/>
                                                <nil key="textColor"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                                <textInputTraits key="textInputTraits"/>
                                            </textField>
                                        </subviews>
                                        <constraints>
                                            <constraint firstItem="SmT-mA-Gye" firstAttribute="leading" secondItem="39p-CV-TpJ" secondAttribute="leading" id="1jz-77-gyZ"/>
                                            <constraint firstAttribute="bottom" secondItem="SmT-mA-Gye" secondAttribute="bottom" id="A8e-ja-UsG"/>
                                            <constraint firstItem="SmT-mA-Gye" firstAttribute="top" secondItem="I8h-Ni-H0m" secondAttribute="bottom" constant="8" id="SiK-50-qR8"/>
                                            <constraint firstItem="I8h-Ni-H0m" firstAttribute="top" secondItem="39p-CV-TpJ" secondAttribute="top" id="WLB-IN-NPQ"/>
                                            <constraint firstAttribute="trailing" secondItem="SmT-mA-Gye" secondAttribute="trailing" id="X0Z-RS-0DO"/>
                                            <constraint firstItem="I8h-Ni-H0m" firstAttribute="leading" secondItem="39p-CV-TpJ" secondAttribute="leading" id="dGG-p0-EYr"/>
                                            <constraint firstAttribute="trailing" secondItem="I8h-Ni-H0m" secondAttribute="trailing" id="oEK-KL-zgz"/>
                                        </constraints>
                                    </view>
                                    <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Joh-pH-Jnd">
                                        <rect key="frame" x="0.0" y="238.5" width="335" height="59"/>
                                        <subviews>
                                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="E-Mail Addresse:" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="swE-G9-gnC">
                                                <rect key="frame" x="0.0" y="0.0" width="335" height="20.5"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                <nil key="textColor"/>
                                                <nil key="highlightedColor"/>
                                            </label>
                                            <textField opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" placeholder="abc@123.com" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="kn2-FC-VFP">
                                                <rect key="frame" x="0.0" y="28.5" width="335" height="30.5"/>
                                                <nil key="textColor"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                                <textInputTraits key="textInputTraits"/>
                                            </textField>
                                        </subviews>
                                        <constraints>
                                            <constraint firstItem="kn2-FC-VFP" firstAttribute="leading" secondItem="Joh-pH-Jnd" secondAttribute="leading" id="3VZ-an-qei"/>
                                            <constraint firstAttribute="trailing" secondItem="swE-G9-gnC" secondAttribute="trailing" id="WLe-fg-xNA"/>
                                            <constraint firstAttribute="trailing" secondItem="kn2-FC-VFP" secondAttribute="trailing" id="nkU-6E-Lze"/>
                                            <constraint firstAttribute="bottom" secondItem="kn2-FC-VFP" secondAttribute="bottom" id="pV0-RW-IwL"/>
                                            <constraint firstItem="swE-G9-gnC" firstAttribute="leading" secondItem="Joh-pH-Jnd" secondAttribute="leading" id="rgy-dy-9Cu"/>
                                            <constraint firstItem="kn2-FC-VFP" firstAttribute="top" secondItem="swE-G9-gnC" secondAttribute="bottom" constant="8" id="wcW-le-EHd"/>
                                            <constraint firstItem="swE-G9-gnC" firstAttribute="top" secondItem="Joh-pH-Jnd" secondAttribute="top" id="xBd-ta-26w"/>
                                        </constraints>
                                    </view>
                                    <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="veV-Mu-et4">
                                        <rect key="frame" x="0.0" y="358" width="335" height="59"/>
                                        <subviews>
                                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Anliegen:" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="I4g-ZA-iAN">
                                                <rect key="frame" x="0.0" y="0.0" width="335" height="20.5"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="17"/>
                                                <nil key="textColor"/>
                                                <nil key="highlightedColor"/>
                                            </label>
                                            <textField opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" placeholder="Wofür brauchen Sie uns?" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="UhO-oc-ZcI">
                                                <rect key="frame" x="0.0" y="28.5" width="335" height="30.5"/>
                                                <nil key="textColor"/>
                                                <fontDescription key="fontDescription" type="system" pointSize="14"/>
                                                <textInputTraits key="textInputTraits"/>
                                            </textField>
                                        </subviews>
                                        <constraints>
                                            <constraint firstAttribute="trailing" secondItem="I4g-ZA-iAN" secondAttribute="trailing" id="CSx-cq-YKB"/>
                                            <constraint firstAttribute="bottom" secondItem="UhO-oc-ZcI" secondAttribute="bottom" id="H5B-U5-afD"/>
                                            <constraint firstAttribute="trailing" secondItem="UhO-oc-ZcI" secondAttribute="trailing" id="J4D-oz-gSp"/>
                                            <constraint firstItem="UhO-oc-ZcI" firstAttribute="top" secondItem="I4g-ZA-iAN" secondAttribute="bottom" constant="8" id="QJV-SW-hxN"/>
                                            <constraint firstItem="UhO-oc-ZcI" firstAttribute="leading" secondItem="veV-Mu-et4" secondAttribute="leading" id="TW5-Lk-gT2"/>
                                            <constraint firstItem="I4g-ZA-iAN" firstAttribute="leading" secondItem="veV-Mu-et4" secondAttribute="leading" id="fKN-rs-kcE"/>
                                            <constraint firstItem="I4g-ZA-iAN" firstAttribute="top" secondItem="veV-Mu-et4" secondAttribute="top" id="sp7-X4-5aY"/>
                                        </constraints>
                                    </view>
                                    <button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="ctf-8E-t6W">
                                        <rect key="frame" x="0.0" y="477" width="335" height="50"/>
                                        <color key="backgroundColor" red="0.46202266219999999" green="0.83828371759999998" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                        <constraints>
                                            <constraint firstAttribute="height" constant="50" id="5t4-xU-Fc6"/>
                                        </constraints>
                                        <state key="normal" title="Senden">
                                            <color key="titleColor" red="1" green="0.14913141730000001" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                        </state>
                                        <userDefinedRuntimeAttributes>
                                            <userDefinedRuntimeAttribute type="number" keyPath="layer.cornerRadius">
                                                <integer key="value" value="12"/>
                                            </userDefinedRuntimeAttribute>
                                        </userDefinedRuntimeAttributes>
                                    </button>
                                </subviews>
                            </stackView>
                        </subviews>
                        <color key="backgroundColor" red="0.62352941176470589" green="0.61960784313725492" blue="0.62352941176470589" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                        <constraints>
                            <constraint firstItem="sJk-vH-8Fe" firstAttribute="leading" secondItem="dku-bN-ckm" secondAttribute="leading" constant="20" id="CMC-tA-en4"/>
                            <constraint firstItem="dku-bN-ckm" firstAttribute="trailing" secondItem="sJk-vH-8Fe" secondAttribute="trailing" constant="20" id="NyP-xd-gmz"/>
                            <constraint firstItem="sJk-vH-8Fe" firstAttribute="top" secondItem="dku-bN-ckm" secondAttribute="top" constant="80" id="StM-g1-3te"/>
                            <constraint firstItem="dku-bN-ckm" firstAttribute="bottom" secondItem="sJk-vH-8Fe" secondAttribute="bottom" constant="40" id="YlG-nO-gt4"/>
                        </constraints>
                        <viewLayoutGuide key="safeArea" id="dku-bN-ckm"/>
                    </view>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="qpy-jO-wVd" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="153" y="52"/>
        </scene>
    </scenes>
</document>


Q:

java: perform set, setbit, get and getbit in hashmap

Edited
I am trying to implement the following functions in my program using hashmap.

get
getBit
set
setBit

Here is the code.
static HashMap<String, Object> hashmap = new HashMap<String, Object>();

public static String dictGet(String key){
    String val = (String) hashmap.get(key);
    return val;
}

public static int dictGet(String key, int pos){
    String val = (String) hashmap.get(key);
    byte[] bytes = val.getBytes();
    byte byt = bytes[pos /8];
    System.out.println("Byte : "+byt);
    return (byt >> (pos % 8) ) & 1;

}
public static void dictSet(String key, String val){
    hashmap.put(key, val);
}
public static void dictSet(String key, int pos, byte bitval){
    String val = (String) hashmap.get(key);
    byte[] bytes = val.getBytes();
    byte byt = bytes[pos /8];

    if(bitval == 1){
        bytes[pos /8] = (byte) (bytes[pos /8]| (1 << (pos % 8)));
    }
    else if(bitval == 0){
        bytes[pos /8] = (byte) (bytes[pos /8] & ~(1 << (pos % 8)));
    }

    hashmap.put(key, new String(bytes));
}

I want to achieve O(1) complexity for each of these functions. But currently getBit() and setBit() functions are taking O(n) time complexity.
Any help is appreciated.

A:

This is very inefficient. val.getBytes() will allocate new array (actually more than one) and encode whole string into it every time you call it. This is likely going to be the most expensive operation in this snippet.
Moreover, this code mixes two completely different representations. To make your intentions clear and avoid mistakes, you should stick to one. If you want to operate on bytes, store byte[] in your hash map. If you want to operate on characters or code points use charAt or codePointAt. If you need to convert between those representation, do it once during initialization.
Notice also, that getBytes encodes the string using platform's default charset. This, most likely, is not what you want and your code will break, if UTF-16 is used.
Here is an example using StringBuilder, Note that in Java char has 16 bits and this code uses that full range:
package test;

import java.util.HashMap;
import java.util.Map;

public class Test {

      Map<String, StringBuilder> map = new HashMap<>();

      void setBit(final String key, final int n) {
          final StringBuilder s = this.map.get(key);
          final char c = s.charAt(n / 16);
          s.setCharAt(n / 16, (char) (c | 1 << n % 16));
      }

      int getBit(final String key, final int n) {
          final StringBuilder s = this.map.get(key);
          final int c = s.charAt(n / 16);
          return (c << n % 16 & 0x8000) != 0 ? 1 : 0;
      }

      CharSequence getValue(final String key) {
          return this.map.get(key);
      }

      public static void main(final String[] args) {
          final Test t = new Test();
          t.map.put("x", new StringBuilder("abc"));
          t.map.put("y", new StringBuilder("abc"));
          t.setBit("x", 3);
          t.setBit("y", 4);

          // many methods accept any CharSequence not just String
          final CharSequence xValue = t.getValue("x");
          final CharSequence yValue = t.getValue("y");
          System.out.println(String.join(",", xValue, yValue));
      }
}


Q:

How do I assemble a  using jQuery append()?

I'm trying to use the append function and encountered this:
$("#details").append('
');
for (var i = 0; i < 10; i++) {
    $("#details").append('
something
');
}
$("#details").append('
');

It appears that the
 elements renders OUTSIDE the
 tag.
Is this a jQuery bug?

A:

Nope, you can't use it like that. append is an atomic operation, which creates the element directly.
// The
 element is added to #details, then it is selected and the jQuery
// selection is put in the "list" variable.
var list = $('
').appendTo('#details');
for (var i = 0; i < 10; i++) {
    // New
 elements are created here and added to the
 element.
    list.append('
something
');
}

Alternatively, generate the HTML and add it all at once (this will be more similar to your original code):
var html = '
';
for (var i = 0; i < 10; i++) {
    html += '
something
';
}
html += '
';
$('#details').append(html);

This code is noticeably faster when dealing with many elements.
If you need a reference to the list, just do the following instead of $('#details').append(html);:
var list = $(html).appendTo('#details');

A:

No, it's a programmer bug.
s are attached to their
 or
, not to its container.  And appending a close tag is nonsensical.
You're basically working as if what you were appending were raw HTML, and it's not; you're actually working with the DOM.
Try this:
var list = $("#details").append('

').find('ul');
for (var i = 0; i < 10; i++)
    list.append('
something
');

Note: please see (and upvote) Blixt's answer, which expands on a couple different options that are superior for various purposes.  It deserves attention and hasn't been getting it.

A:

I think there's a problem in your loop
for (var i = - i < 10; i++)
    $("#details").append('
something
');

should be I think
for (var i = 0; i < 10; i++)
    $("#details ul").append('
something
');

and lose the following from the end
$("#details").append('
');

Working Demo
EDIT:
Based on George IV's comment, in order to avoid appending
 elements to any
 that may be a child of the element with id "details", simply give the
 element an id when you append it-
$("#details").append('
');

for (var i = 0; i < 10; i++)
    $("#appended").append('
something
');

you may also find this article interesting - 43,439 reasons to use append() correctly


Q:

C printf: variable string column width, left align

I'm trying to format printf string output:
printf("%*s %*s %*s %*s %*s %*s %*s %*s %*s\n",
maxlen[0], "intf", maxlen[1], "ssid", maxlen[2],
"bssid", maxlen[3], "vlan", maxlen[4], "STA",
maxlen[5], "tx-pkts", maxlen[6], "rx-pkts", maxlen[7],
 "security", maxlen[8], "Capabilities");

where maxlen is an array with values 5, 13,17, 4, 3, 7, 7, 15, and 12 in this case.
However, in the output, the strings are right aligned, meaning they are floated to the right of their width-sized blocks. Output:
intf          ssid             bssid vlan STA tx-pkts rx-pkts        security Capabilities
Is there a way to float these strings to the left?
So instead of [][][][][][][]security, I want security[][][][][][][]for the width==15second-to-last block, for example.
I tried creating a spacesarray of strings, like below:
char **spaces = (char**)malloc(9*sizeof(char*));
then, for each i,  calloc spaces[i], and then, instead of doing "%*s", I do %s%s, where the second string printed is spaces[i].
But even this doesn't seem to work because I would need to do
snprintf(spaces[i], maxlen[i]-size_of_string, "  (however many spaces)    ");

And I don't know how many spaces to hardcode for the third argument. There is no " " * length operation like in python, to create a length sized string of " " characters.

A:

To left-align the output in the width given, add a - sign to the format specifier
printf("%-*s %-*s %-*s %-*s %-*s %-*s %-*s %-*s %-*s\n", ... );

The arguments supplied for width can be a computed int value. You can hard-code the width like this
printf("%-10s\n", "string");

If you don't know how much space will be taken, you can use a temporary string
char tempstr[100];
int len = sprintf(tempstr, "%d", value);
printf("%s%-*s\n", tempstr, 30 - len, "string");


Q:

play 2 animationdrawables after each other

I would like to play 2 animationdrawables after eachother..
When the first one stops, the other one has to start..
The problem is:
AnimationListener is not possible with animationdrawables
Does anybody know a solution?
thank you

A:

try this code
 final Handler handler = new Handler();
                                handler.postDelayed(new Runnable() {
                                  public void run() {
                                      //start 2nd animation
                                  }
                                }, delay);//delay is the time for how long 1st animation takes to complete


Q:

Java Graphics 2d avoid Polyline distorted corners

i'm working on a graphic interface for drawing subway maps. A line is represented with station as circles and a polyline to link them.You can move the stations with a mouseDrag and of course it updates the displaying map in real time. My problem is when stations comes to a certain angle, there is a polyline distortion and the corner created by the 2 lines is out of the station circle display, i'd like to know if there is a way to avoid this.
screenshots of the app with the polyline issue
here's my code for the polyline's draw
//x and y point array creation
    xPoints = new int[this.stationViews.size()];
    yPoints = new int[this.stationViews.size()];
    for (int i=0;i<this.stationViews.size();i++) {
        //fill arrays with the center point of circles representing stations
        xPoints[i] = this.stationViews.get(i).getStation().getPosX()-this.stationViews.size()/2;
        yPoints[i] = this.stationViews.get(i).getStation().getPosY()-this.stationViews.size();
    }

    //setting color
    g2D.setColor(this.line.getColor());

    //set stroke width relative to the zoom level
    int strokeWidth=5;
    if(!this.stationViews.isEmpty()) {
    if (this.stationViews.get(0).getStationSize()>14) {
        strokeWidth = this.stationViews.get(0).getStationSize()-13;
    }else {
        strokeWidth = 3;
    }
    }
    g2D.setStroke(new BasicStroke(strokeWidth));

    //draw the polyline
    if (this.stationViews.size() >1) {
    g2D.drawPolyline(xPoints, yPoints, this.stationViews.size());
    }
    //draw the station (g2D.drawCircle)
    for (StationView stationView : stationViews) {
        stationView.affiche(g2D,this.line.getColor());
    }

thank you for your help

A:

That is called the miter. You seem to be per default using JOIN_MITER, sharp joining of extended lines at the end, which can point far out of the join for small angles.
g2d.setStroke(new BasicStroke(strokeWidth,
    BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 5));

miter a surface forming the beveled end or edge of a piece where a joint is made by cutting two pieces at an angle and fitting them together.

It is also a bishop's cap with a pointy top, hence the name.


Q:

Can't paste array into range with setValue()

I mapped a function to an array which is supposed to give me Yes or No depending on the input when I Logger.log(costsfinalised) the array I get this:
[No, No, No, No, Yes, No, No, Yes, Yes, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No, No]

But when I try to paste it with setValues(costsfinalised), I get an error saying:

'Cannot convert Array into Object'

When I do setValue(costsfinalised) instead, it does work but only with Nos (it is not really what is in the log. Why? How can I paste this array into a range?
var costsfinalised=sourcevalues.map(costs);

  //Logger.log();
  Logger.log(costsfinalised);

destinationsheet.getRange(2,7,costsfinalised.length,1).setValues(costsfinalised);

A:

Problem
You are trying to pass an illegal argument into the method, setValues() accepts only two-dimensional Array instances. You should treat the two-dimensional Array as cell mapping, where elements represent rows and their elements columns:
//pseudo-code;
[
 row 1 : [col1, col2],
 row 2 : [col1, col2]
]

Solution
You can modify your code to generate this Array for you (judging from your code, you want to populate one column, right? Regardless of that, if you add a second loop to generate column values, you will be able to populate Range with custom number of rows and columns):
var col = destinationsheet.getRange(2,7,costsfinalised.length,1);

var temp = [];

for(var i=0; i<costsfinalised.length; i++) {
  var row = [ costsfinalised[i] ];
  temp.push(row);
}

col.setValues(temp);

Alternatives
Alternatively, you can use the map method on your Array (in your case you can simply reference the cost instead of costsfinalised[i] - just don't forget to wrap it as well - return [ cost ]):
var col = destinationsheet.getRange(1,1,costsfinalised.length,1);

var output = costsfinalised.map(function (cost,i) { return [ costsfinalised[i] ]; } );

col.setValues(output);

Useful links

setValues() method reference;
Array built-in reference on MDN;
map() method reference on MDN;


Q:

Co-Domain of composite function

Let's say I have
$f: X \to Y$ where $f(x) = x^2$
$g: Y \to Z$ where $ g(y) = \cos(y)$ and
$h: Z \to X$ where $h(z) = 2x-1$
If I take $ f \circ (g \circ h)$ I get $\cos^2(2x-1)$
What is the co-domain of this function? Is there some sort of rule for finding the co-domain? It's easy enough to find the domain and range but I'm not sure about the co-domain.

A:

The codomain of a composite is always the codomain of the last function in the composite (i.e. the first appearing in the string).
For instance, if you have a sequence of compatible functions
$$f_1 : A_1 \to A_2,\ \ f_2 : A_2 \to A_3,\ \ \cdots,\ \ \ f_n : A_n \to A_{n+1}$$
then the codomain of $f_n \circ f_{n-1} \circ \cdots \circ f_1$ is $A_{n+1}$, which is the codomain of $f_n$.
Likewise, the domain of a composite is always the domain of the first function in the composite (i.e. the last appearing in the string), so the domain of $f_n \circ \cdots \circ f_1$ is $A_1$, which is the domain of $f_1$.
You can apply this general result to your problem.


Q:

A little js exercise

I have some html:

 text

And here is my question:
How can I make the text coloured red using JavaScript and jQuery?

A:

use css() in jquery
$("#foo span").css("color",'red');


Q:

Is this possible to detect a colour is a light or dark colour?

Consider these two pink square:

And this:

As you may know, one is lighter and one is darker or more sharp.
The problem is, I can tell it by human eyes, but is this possible to use a system way or programme way to detect this information? At least, is this possible to have a value that tell me that colour is more like white or that colour is less like white? (Assume I got the RGB code of that colour.) Thanks.

A:

Since you haven't specified any particular language/script to detect the darker/lighter hex, I would like to contribute a PHP solution to this
Demo
$color_one = "FAE7E6"; //State the hex without #
$color_two = "EE7AB7";

function conversion($hex) {
    $r = hexdec(substr($hex,0,2)); //Converting to rgb
    $g = hexdec(substr($hex,2,2));
    $b = hexdec(substr($hex,4,2));

    return $r + $g + $b; //Adding up the rgb values
}

echo (conversion($color_one) > conversion($color_two)) ? 'Color 1 Is Lighter' : 'Color 1 Is Darker';
//Comparing the two converted rgb, the greater one is darker

As pointed out by @Some Guy, I have modified my function for yielding a better/accurate result... (Added Luminance)
function conversion($hex) {
    $r = 0.2126*hexdec(substr($hex,0,2)); //Converting to rgb and multiplying luminance
    $g = 0.7152*hexdec(substr($hex,2,2));
    $b = 0.0722*hexdec(substr($hex,4,2));

    return $r + $g + $b;
}

Demo 2

A:

Below is the Python code to determine light or dark color. The formulation is based on the HSP value. HSP (Highly Sensitive Poo) equation is from http://alienryderflex.com/hsp.html used to determine whether the color is light or dark.
import math
def isLightOrDark(rgbColor=[0,128,255]):
    [r,g,b]=rgbColor
    hsp = math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b))
    if (hsp>127.5):
        return 'light'
    else:
        return 'dark'


Q:

Will increase in flow rate increase the rate of cooling down?

Suppose a hot body is surrounded by a coil of very good thermally conducting pipe with cold water flowing inside which comes at a certain fixed low temperature in the pipe and leaves at some higher temperature after absorbing the heat. Will the rate of the hot body’s cooling down increase or decrease with increase in the water flow rate?
I think the rate of cooling will increase. But this is also in opposition to the intuition that the water will have less time to take away heat from the hot body, hence decreasing the cooling rate. I doubt that this is wrong since though the water is moving faster, water behind with lower temperature is following immediately after.

A:

The cooling rate will increase as the flow rate is increased.
The water in the pipe will heat up as it absorbs heat from the hot body, setting up a temperature distribution in the water within the pipe. Near the inlet it will have the temperature you pump it in with, and the temperature near the outlet will depend on how much heat it has absorbed from the hot body. The greater the flow rate, the less time water will have to absorb heat until it exits the pipe, and the colder it will be near the outlet.
According to Newton's law of cooling, the heat transfer rate to the water along a given piece of the pipe is proportional to the temperature difference between the hot body and the water. Since the water within the pipe is cooler on average when the flow rate is higher, this temperature difference is also higher on average, and so is the cooling rate.
The problem with your intuition is that although a given mass of water does have less time to absorb heat when water is being pumped in faster, now more water is being pumped in, by the same factor. The difference is that this mass of water does not get as hot by the time it leaves the pipe, so it is capable of absorbing more heat from the pipe per unit time as it flows.


Q:

Change input value dynamically with jQuery

I'm trying to change input value and display an alert based on value written by the user. Now it doesn't work unless it goes out of focus. Can I make it work immediately without any waiting period?

jQuery('input').on('change', function () {
    var myInput = jQuery(this);
    if (myInput.val() < 0.2 ) {
        myInput.val('0.2');
        jQuery('.alert').css('display', 'block')
    }
    else {
        jQuery('.alert').css('display', 'none')
    }
});

<input value="">

minimum value is 0.2

A:

1.You can use  input or keyup method.
2.Also .val() will give you a string value, so comparing it with 0.2 convert it to float with the help of parseFloat()
like below:-
Example 1:-

jQuery('input').on('input', function () {
    var myInput = jQuery(this);
    if (parseFloat(myInput.val()) < 0.2 ) {
        jQuery('.alert').css('display', 'block')
    }
    else {
        jQuery('.alert').css('display', 'none')
    }
});

<input value="">

minimum value is 0.2

Example 2:-

jQuery('input').on('keyup', function () {
    var myInput = jQuery(this);
    if (parseFloat(myInput.val()) < 0.2 ) {
        jQuery('.alert').css('display', 'block')
    }
    else {
        jQuery('.alert').css('display', 'none')
    }
});

<input value="">

minimum value is 0.2


Q:

Android studio - Faild to resolve: com.android.support:design:26.0.1 error

I have an error called:
 "Failed to resolve: com.android.support:design:26.0.1".

My android studio version is 3.0 beta 1.
My gradle file is as below:
apply plugin: 'com.android.application'

android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
    applicationId "hojune.example"
    minSdkVersion 17
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile 'com.android.support:design:26.0.1'
}

I want to put "design" to my project, but I can't do it. How can I do it?

A:

Add this to your project level build.gradle file:
repositories {
    maven {
        url "https://maven.google.com"
    }
}

Just to clarify, this should be in the "allprojects" section of the gradle file (Thanks to @tys)

A:

Try to Change
buildToolsVersion "26.0.0"

and
com.android.support:design:26.0.0

Or not change into bulidToolsVersion Change dependencies
compile 'com.android.support:design:26.0.0-alpha1'

A:

I had the same problem i solved it by using
compile 'com.android.support:design:26.0.0-alpha1'


Q:

Wrap a synchronous method into an async one which can be 'waited' upon

I have a synchronous call:
_context.User.Where((u) => (u.UserID == twitterId && u.Type == UserType.Show)).SingleOrDefault();

That I need to wrap into an async one which I can wait on using the await keyword.
How can I achieve this?
Thanks.

A:

You need to wrap your sync call using Task.Run method.
var user = await Task.Run(() =>
   _context.User
           .Where(u => u.UserID == twitterId && u.Type == UserType.Show)
           .SingleOrDefault());

Keep in mind that EntityFramework in version 6.0 will have async interfaces, so you would no longer need to use this code.

A:

QueryableExtensions, added in EF6, make this a breeze:
await _context.User.SingleOrDefaultAsync(u =>
    u.UserID == twitterId
    && u.Type == UserType.Show);

Don't forget to reference System.Data.Entity in the EntityFramework.dll


Q:

Converting a string value to an unkown (at compile time) object type

I have a class type and I have a value in a string:
Class<?> type = Integer.class // <-- in reality, that type is
                              // determined at runtime
String value = "3";           // <-- same here, actually read from a file

My goal is to instantiate an instance of 'type' and fill it with the value of 'value'... So that I have the equivalent of
Integer i = new Integer(value);

Is the only possible way to do that a long chain of if-statements:
if (type == Integer.class) {
  // do this
}

Or is there another clever/right way to do that? The possible class types could be totally different like Integer/Date etc...
Edit1
Here some more context:
I have a file with a number of values which a textual representations of instances of different datatypes:
1|3.4|2011-08-24

In my program, I get a class type and a method in that class which are both unknown to me at compile time.
I want to call that method on an instance of that type, with the values from the file as parameters. But for that I do have to have the corresponding object to that values, in the example that could be an Integer/int, a float/double, a Date.
I can get these datatypes for the formal parameters of the method via reflection, but I'm uncertain about the best way to proceed with the conversion from string to the object...
Maybe this pseudo program will clear things up:
String[] values = getValuesFromFile;
Class<?> type = getType();
Method method = getMethod();
Class<?>[] formalParameterTypes = getMethodParameterTypes();
Object[] objects;
for(int i; i < values.length; i++)
  objects[i] = convert(values[i],formalParameterTypes[i]);
method.invoke(objects);

A:

To my understanding, you want something like this:
Object instance = createMagically(getClass(), getString());

where getClass() might return Integer.class and getString() the value "42". But the value pair Date.class and "15 Apr 2011" is expected too.
At one point you'll have to work with conditions (if/else if) because, in general, every type has it's own conversion rules. There is no universal constructor to create an instance from a String.
So you could implement a "factory" method like this:
public static Object createInstance(Class<?> type, String content) {
  if (type.equals(Integer.class)) return new Integer(content);
  else if // ...
  return content;  // just an idea for a default if the type can't be handled
}

And then again, to use the return value, you may need some more if/else if to determine the actual type (if (value instancof Integer) ...)
So, from my point of view - you have to do a lot of checks, but you can hide the ugly magic in utility classes.


Q:

Go: Call a function passing pointer to array

I have spent a bit of time attempting to do this, and I think I need a global array (not slice), and I want to pass it as a pointer, not by value. The function receiving the pointer needs to test for nil, and if nil, read the array from disk, using eg: "baForm, oOserr = ioutil.ReadFile(sFormName)". The calling function may pass either a global array or an array local to the calling function which I presume will be garbage collected.
The reason for doing this is that I want a standard function to read the forms from disk, and often-used forms are stored globally. Despite whether some may think there is a better way, I still want to know how to achieve this ie: a) have global or local array, b) not pass by value, c) The global arrays will be read only once from disk and the local arrays will be read each time the function is called. TIA.

A:

Here's a sample program that maintains a dynamic forms buffer based on use count. If the ReadForm function finds a form, it returns the address of the form and a nil error.
package main

import (
    "fmt"
    "io/ioutil"
    "math"
    "os"
    "sync"
)

type Form struct {
    Name     string
    useCount int64
    Data     []byte
}

// The capacity of the forms buffer.
const formsCap = 2

// The forms buffer.
var (
    forms     = make(map[string]*Form, formsCap)
    formsLock sync.RWMutex
)

func ReadForm(name string) (form *Form, err os.Error) {
    formsLock.RLock()
    form, ok := forms[name]
    formsLock.RUnlock()
    if !ok {
            form = &Form{name, 0, nil}
    }
    if form.Data == nil {
        data, err := ioutil.ReadFile(name + ".form")
        if err != nil {
            return nil, err
        }
        form = &Form{name, 0, data}
        formsLock.Lock()
        if len(forms) >= formsCap {
            minForm := &Form{useCount: math.MaxInt64}
            for i, f := range forms {
                if f.useCount < minForm.useCount {
                    minForm = f
                }
            }
            minform.Data = nil
        }
        forms[name] = form
        formsLock.Unlock()
    }
    form.useCount++
    return form, nil
}

func main() {
    // form files are named name.form e.g. form1.form
    for _, name := range []string{"form1", "form2", "form3"} {
        f, err := ReadForm(name)
        if err != nil {
            fmt.Println(err)
        } else {
            fmt.Println(string(f.Data))
        }
    }
    fmt.Println(len(forms), forms)
}

EDIT: Map operations are not atomic. Revise the sample program to use a mutex for concurrent access to the forms map.


Q:

Why is the output of this bash script different every time it is run?

I have the following short bash script:
#!/bin/bash
cp /dev/null out.sh
while IFS=' ' read -r b c d e
do
    echo -ne "sendevent " >> out.sh
    echo -ne "/dev/input/event1 " >> out.sh
    echo -ne "$(( 0x$c )) " >> out.sh
    echo -ne "$(( 0x$d )) " >> out.sh
    echo -ne "$(( 0x$e )) " >> out.sh
    echo >> out.sh
done < "in.sh"

It takes in commands read from another script called in.sh in the form of /dev/input/event1: 0003 0039 0000006d, and I need it to output to another script called out.sh in the form of sendevent /dev/input/event1 3 57 109, where it converts the latter three terms from hexadecimal to decimal.
However, when I run the script, I get a quasi-broken output, which changes each time I run it. The correct output should be along the lines of:
sendevent /dev/input/event1 3 57 109
sendevent /dev/input/event1 3 53 40
sendevent /dev/input/event1 3 54 620
#and so on

Here's a picture of my actual output:

Every time I run the script, the output is slightly different, and never uniform as I want it. Why does it output differently every time? How do I fix it so it outputs in the form I want it to?
I've tried adding in sleep .01 after the last echo statement, and it did not fix the problem.
EDIT: As requested, here is a snippet of my in.sh:
/dev/input/event1: 0003 0039 0000006d
/dev/input/event1: 0003 0035 00000028
/dev/input/event1: 0003 0036 0000026c
/dev/input/event1: 0001 014a 00000001
/dev/input/event1: 0000 0000 00000000
/dev/input/event1: 0003 0039 ffffffff
/dev/input/event1: 0001 014a 00000000
/dev/input/event1: 0000 0000 00000000
/dev/input/event1: 0003 0039 0000006e
/dev/input/event1: 0003 0035 0000020f
/dev/input/event1: 0003 0036 000003dd
/dev/input/event1: 0001 014a 00000001
/dev/input/event1: 0000 0000 00000000
/dev/input/event1: 0003 0039 ffffffff
/dev/input/event1: 0001 014a 00000000
/dev/input/event1: 0000 0000 00000000
/dev/input/event1: 0003 0039 0000006f
/dev/input/event1: 0003 0035 000001b6
/dev/input/event1: 0003 0036 00000076
/dev/input/event1: 0001 014a 00000001
/dev/input/event1: 0000 0000 00000000
/dev/input/event1: 0003 0039 ffffffff

And here are two different outputs, run one after another, with the same in.sh:
sendevent /dev/input/event1 3 109
sendevent /dev/input/event1 3 54 620
sendevent /dev/input/event1 1 330 1
sendevent /dev/input/event1 0 0 0
sendevent /dev/input/event1 3 57 4294967295
/dev/input/event1 1 330 0
sendevent /dev/input/event1 0 0
sendevent /dev/input/event1 3 57 110
3 53 527
sendevent /dev/inp3 54 989
/dev/input/event1 1 330 1
sendevent 3 57 4294967295
sendevent /dev/input/event1 /event1 1 330 0
sendevent /dev/input/event1 0 0 0
sendevent /dev/input/event1 57 111
sendevent /dev/input/event1 3 53 438 sendevent /dev/input/event1 3 54
sendevent /dev/input/event1 1 1
sendevent
sendevent /dev/input/event1 57 4294967295
/dev/input/event1 1 330 /dev/input/event1 0 0 0
sendevent /dev/input/event1 3 57 112
sendevent /dev/input/event1 3 53
sendevent /dev/input/event1 3 54 881
sendevent /dev/input/event1
sendevent /dev/input/event1 3 57 t1 0 0 0 4294967295
sendevent 1 330 0
sendevent/dev/input/event1 0 0 0
113
sendevent /dev/input/event1 3 53
sendevent /dev/input/event1 54 901
/dev/input/event1 1 330 1
/dev/input/event1 0 0 0 sendevent /dev/input/event1 3 57 4294967295
330 0

And the second output:
sendevent /dev/input/event1 3 57 109
sendevent /dev/input/event1 3 53 620
sendevent /dev/input/event1  54 1 330 1 /dev/input/event1 0 0 0 sendevent /dev/input/event1 3 57
sendevent /dev/input/event1 1 330
sendevent /dev/input/event1 0 0 0
sendevent /dev/input/event1 3 57 110
/dev/input/event1 3 53
sendevent /dev/input/event1 54 989
/dev/input/event1 1 330
sendevent /dev/input/event1 0 0
sendevent 3 57 4294967295
 sendevent /dev/input/event1 1 0
sendevent 0 0 0
put/event1 sendevent /dev/input/event1 3 111
sendevent 3 53 438
/event1 sendevent /dev/input/event1 3 54
sendevent /dev/input/event1 330 1
0 0 0
nt /dev/input/event1 sendevent /dev/input/event1 3 4294967295
sendevent 0
sendevent /dev/input/event1 0 0 0
sendevent /dev/input/event1 3 57 112
sendevent /dev/input/event1 3 53 247
sendevent /dev/input/event1 3 54 881 sendevent /dev/input/event1 1 330 1
/dev/input/event1 0 0
sendevent /dev/input/event1 57 4294967295
sendevent /dev/input/event1 1 330
sendevent /dev/input/event1 0 0 0
sendevent 3 57 113
sendevent 3 53 246
/event1 sendevent /dev/input/event1 3 54
sendevent /dev/input/event1 330 1
/dev/input/event1 0 0 0
/dev/input/event1 3 57 4294967295 sendevent /dev/input/event1 1 330
sendevent /dev/input/event1 0 0
sendevent 3 57 114
/event1 sendevent /dev/input/event1 3 53
sendevent /dev/input/event1 3 54 882 sendevent /dev/input/event1 1 1
sendevent /dev/input/event1 0 0 0 sendevent /dev/input/event1 3 sendevent /dev/input/event1 1 0
sendevent 0 0 0

A:

The below uses an initial grep pass to sanitize input, avoiding potential shell injection attacks:
#!/bin/sh
grep '^[^ ]\+ [0-9a-f ]\+$' <in.sh | while IFS=' ' read -r _ c d e; do
  printf 'sendevent /dev/input/event1 %d %d %d\n' \
    "$(( 0x$c ))" "$(( 0x$d ))" "$(( 0x$e ))"
done >out.sh

Note:

out.sh is only opened a single time, rather than reopened before every command that wants to write to it, and closed after the end of that individual command (as happens with a >> operator on each write).
Using printf once per line ensures that each write happens as an atomic syscall (when short enough lines are in use, as will reliably be the case here), and also avoids depending on behavior which the POSIX specification for echo explicitly declines to specify; the output of echo -n is explicitly undefined by the standard, whereas treating -e as an option rather than argument is actually contrary to the letter of the standard (and bash's default behavior doing so can be turned off, as with the combination of set -o posix and shopt -s xpg_echo).


Q:

Was there a concept of investing in Harry Potter's wizarding world?

I just saw DampeS8N's comment to this question: What exactly do the Malfoys do for a living?

Lots of investing in businesses and basically living off the interest it generates.

Is there any evidence that there's a concept of investing in a business in Harry Potter's world?

A:

Yes. At the very least, Harry invested in Weasleys Wizard Wheezes


Q:

Proof of fundamental theorem of algebra in Baby Rudin

I am reading Rudin's proof of FTA.

(FTA) Suppose $a_0, \ldots, a_n$ are complex numbers, $n \geq 1$, $a_n \neq 0$, $P(z) = \sum_{k = 0}^n a_k z^k$. Then $P(z) = 0$ for some $z \in \Bbb{C}$.

The first part of the proof goes like this:

WLOG, suppose $a_n = 1$. Let $\mu = \inf_{z \in \Bbb{C}} |P(z)|$. $\lim_{z \to \infty} |P(z)| = \infty$ (details omitted). Hence there is $R_0 >0$ such that $|z| > R_0 \implies |P(z)| > \color{red}{\mu}$. Since $|P|$ is continuous on the closed ball $\overline{B_{R_0}(0)}$, the extreme value theorem shows that $|P(z_0)|=\mu$ for some $z_0$.

However, I don't think the statement in bold is precisely what he meant. Specifically, "there is $R_0>0$ such that $|z|> R_0 \implies |P(z)| > \mu$" does not imply the existence of $z_0 \in \overline{B_{R_0}(0)}$ such that $|P(z_0)|=\mu$:
For example, if we consider the exponential function $f(z) = e^z$, then $\mu = 0$ and $f(z) \neq 0$ for all $z \in \Bbb{C}$. In particular, $|z| > 1 \implies |f(z)|>0$. And $|f|$ is continuous on the closed ball $\overline{B_1(0)}$. But it is not true that there is $z_0 \in \Bbb{C}$ such that $f(z_0)=0$.
In this example, $\lim_{z \to \infty} |f(z)| \neq \infty$ and $\inf_{|z|\leq 1} |f(z)| = e^{-1}\neq \mu$. So I think the condition $\lim_{z \to \infty} |P(z)| = \infty$ can be better utilized to show that  $\inf_{|z|\leq R_0} |P(z)| = \mu$.

Thus, I think he actually meant the following:
Hence there is $R_0>0$ such that $|z|>R_0 \implies |P(z)|>\mu+1$. Let $A = \overline{B_{R_0}(0)}$ and $B = \Bbb{C} \backslash A$. Now from the contrapositive, $|P(z)|\leq \color{red}{\mu+1} \implies z \in A$.
But $\mu+1>\mu:=\inf_{z \in \Bbb{C}}|P(z)|$. So that there is some $z_1 \in \Bbb{C}$ such that $|P(z_1)|<\mu +1$. Above shows that $z_1 \in A$. Now we claim that $\inf_{z \in \Bbb{C}} |P(z)| = \inf_{z \in A} |P(z)|$.
Pick any $z \in \Bbb{C}$. If $z \in A$, then $|P(z)| \geq \inf_{z \in A} |P(z)|$. If $z \in B$, then
$$|P(z)| > \mu+1 > |P(z_1)| \geq \inf_{z \in A} |P(z)|$$
So that $\inf_{z \in A} |P(z)|$ is a lower bound and $\inf_{z \in A} |P(z)|\leq \inf_{z \in \Bbb{C}} |P(z)|$. For $A \subset \Bbb{C}$, $\inf_{z \in \Bbb{C}} |P(z)|\leq \inf_{z \in A} |P(z)|$ and we have  $\inf_{z \in \Bbb{C}} |P(z)|= \inf_{z \in A} |P(z)|= \mu$.
Since $|P|$ is continuous on the compact set $A$, the extreme value theorem shows that $|P(z_0)|= \mu$ for some $z_0 \in A$.

My questions are,

 (1) Have I interpreted that first part of the proof correctly?   (Done)

The complete proof is attached below. I have already gone through the rest of the proof and I understand the logic. Apparently he only uses the fact that $\forall \ z \in \Bbb{C}$, $z = |z|e^{i \theta}$ for some $\theta \in [0,2\pi)$.

(2) But does any part of the proof  involves is indirectly related to any concept/theorem from complex analysis? I know nothing about complex analysis yet so can anyone provide me some keywords?

A:

The usual complex-analytic proof breaks down into two steps.

Step 1. If $p(z)$ has no zeros then $\dfrac{1}{p(z)}$ is bounded.

The proof of this is essentially the same as what has already been done. For $|z| > R_0$ we have $|p(z)| > \mu + 1$ and hence $\frac{1}{|p(z)|} < \frac{1}{\mu + 1}.$ For $|z| \le R_0$ we have a continuous function on a compact set so that's going to be bounded.
Nothing in this step is material that is unique to complex analysis (i.e. that can't be found in real analysis).

Step 2. Every bounded, complex differentiable function is constant.

This is something that doesn't happen on the reals. For instance $\frac{1}{1 + x^2}$ is bounded and differentiable everywhere. In the complex plane, this function blows up near $\pm i$. For $\sin(x)$ one has
$$ \sin(ix) = \frac{e^{i(ix)} - e^{-i(ix)}}{2i} = \frac{e^{-x} - e^{x}}{2i} $$
which blows up as $x \to \infty$.
Step 2 is called Liouville's Theorem. The proof uses Cauchy's Integral Formula which says that if $f$ is complex differentiable everywhere then the $n$-th derivative at $z_0$, $f^{(n)}(z_0)$ can be computed by integrating along a closed path around $z_0$ counterclockwise (e.g. along a circle) by
$$ f^{(n)}(z_0) = \frac{n!}{2\pi i} \oint_\gamma \frac{f(z)}{(z - z_0)^{n + 1}} dz.$$
To prove Liouville's theorem we let $\gamma = \gamma_R$ be the circle centred at $z_0$ of radius $R$. Then on $\gamma_R$, $|z - z_0| = R$. Hence if $|f(z)| \le M$ is bounded
\begin{align}
|f^{(n)}(z_0)| &= \left\lvert \frac{n!}{2\pi i} \oint_{\gamma_R} \frac{f(z)}{(z - z_0)^{n + 1}} dz \right\rvert \\
&\le \frac{n!}{2\pi} \oint_{\gamma_R} \left\lvert \frac{f(z)}{(z - z_0)^{n + 1}} \right\rvert dz \\
&= \frac{n!}{2\pi} \oint_{\gamma_R} \frac{M}{R^{n + 1}} dz \\
&= \frac{n!}{2 \pi} \frac{M}{R^{n + 1}} \operatorname{length}(\gamma_R) \\
&= n!\frac{M}{R^n}
\end{align}
since $\operatorname{length}(\gamma_R) = 2\pi R$ (the circumference of a circle with radius $R$). Now taking $R \to \infty$ it follows that $f^{(n)}(z_0) = 0$ for all $n \ge 1$. Hence $f$ is constant.
For comparison the proof in Rudin's book is more direct. If one were to define a line between complex analysis and real analysis, Cauchy's Integral Formula would be a major part of the distinction. Since Rudin does not use Cauchy's Integral Formula, I think it is safe to say that the proof does not involve complex analysis in any way.


Q:

Setting a property list with Titanium Appcelerator

I'm working with the latest Mobile SDK (1.6) on OS X.
I have this piece of code:
var globalArray = [
        {title:'foo',value:'yes'},
        {title:'bar',value:'no'}
];

Titanium.App.Properties.setList('globalArrayProperty',globalArray);
Titanium.App.Properties.getList('globalArrayProperty')[0].value = 'it works!';
Titanium.API.info('first value : ' + Titanium.App.Properties.getList('globalArrayProperty')[0].value);

I simplified it so that I can explain you where the problem stands.
So, I create an array with a couple of objects.
Then, I'm setting a property depending on this array and then affecting a new value to the first object.
But when I call the display the property, instead of showing the 'it works!' string, it shows the initial one 'yes'.
I tried by adding a couple of lines:
Titanium.App.Properties.setList('globalArrayProperty',globalArray);
var arr = Titanium.App.Properties.getList('globalArrayProperty');
arr[0].value = 'it works!';
// This works
Titanium.API.info('first value with arr: ' + arr[0].value);
// This doesn't work
Titanium.API.info('first value : ' + Titanium.App.Properties.getList('globalArrayProperty')[0].value);

So the intermediate var 'arr' get the property, set it but cannot apply the modification on the property.
Am I missing something?
Thanks,
Regards.

A:

i think you need to set the property list again after updating the array
Titanium.App.Properties.setList('globalArrayProperty',globalArray);
var arr = Titanium.App.Properties.getList('globalArrayProperty');
arr[0].value = 'it works!';
// This works
Titanium.API.info('first value with arr: ' + arr[0].value);

// save changes to property list
Titanium.App.Properties.setList('globalArrayProperty',arr);

// This doesn't work
Titanium.API.info('first value : ' + Titanium.App.Properties.getList('globalArrayProperty')[0].value);


Q:

Plot circles with alpha values in MATLAB

I'm creating a scatter plot of some data, as you do, and I have a number of repeated data points which I'd like to plot as circles with some alpha value so that piling on of extra points at the same location is obvious.
As far as I can tell you cannot set the alpha properties of the little circles that you generate with plot(x, y, 'o'), so I've resorted to drawing thousands of little circles using patch() myself:
x = repmat([1:10], [1 10]);
y = round(10*rand(100, 1))/10;
xlim([0 11])
ylim([0 1])
p = ag_plot_little_circles(x', y, 10, [1 0 .4], 0.2);

function p = ag_plot_little_circles(x, y, circle, col, alpha)
%AG_PLOT_LITTLE_CIRCLES Plot circular circles of relative size circle
% Returns handles to all patches plotted

    % aspect is width / height
    fPos = get(gcf, 'Position');
    % need width, height in data values
    xl = xlim();
    yl = ylim();
    w = circle*(xl(2)-xl(1))/fPos(3);
    h = circle*(yl(2)-yl(1))/fPos(4);

    theta = 0:pi/5:2*pi;
    mx = w*sin(theta);
    my = h*cos(theta);
    num = 0;
    for k = 1:max(size(x))
        for f = 1:size(y,2)
            num = num+1;
            p(num) = patch(x(k)+mx, y(k,f)+my, col, 'FaceColor', col, 'FaceAlpha', alpha, 'EdgeColor', 'none');
        end
    end
end

As you can see, this is not optimal as I need to know and set the size of the plot (xlim and ylim) before I plot it so that the circles end up being circular. If I reshape the plot then they end up as ovals. I also end up with millions of objects, which is a pain when making legends.
Is there an easier way?

A:

I have found no way to have a line marker with alpha in MATLAB.
If you look at line properties (the (mid) low level function behind plot), you will see that you can define markers, and their sole properties are their color (MarkerEdgeColor or MarkerFaceColor), which does not take any alpha (there is no MarkerFaceAlpha property).
So how you do it with patches seems the way to go.
The only thing I can propose to avoid having zillions of objects would be to group them in a hggroup, which will make them appear as a single object in the legend.

A:

I tried to do a general function using patch. It's slow and a bit buggy, but it works OK for simple cases. MATLAB needs a real-line alpha though.
x and y are points to plot, w the width of the line, col the color and a the alpha value.
Example:
x = linspace(-2,2,100);
plotWithAlpha(x,sin(4*x),0.04,'r',0.2)

function [] = plotWithAlpha(x,y,w,col,a)
%function [] = plotWithAlpha(x,y,w,col,a)
    if(size(x,1) ~= 1)
       x = x.';
    end

    if(size(x,1) ~= 1)
       y = y.';
    end

    sz = length(x);

    % Calculate derrivatives of the curve
    X = csaps(1:sz(1),x,1);
    Y = csaps(1:sz(1),y,1);

    mx = fnval(fnder(X,1),1:sz(1)).';
    my = fnval(fnder(Y,1),1:sz(1)).';

    T = [mx my]; %tangent

    % Normalize tangents
    T = bsxfun(@rdivide,T,sqrt(sum(T.^2,2)));

    N = zeros(size(T));

    N(:,2) = 1;
    N(:,1) = -T(:,2)./T(:,1);

    N = bsxfun(@rdivide,N,sqrt(sum(N.^2,2)));

    N = N.';

    hold on

    for i = 2:length(x)
        X = [x(i-1)+w*N(1,i-1) x(i)+w*N(1,i) x(i-1)-w*N(1,i-1) x(i)-w*N(1,i)];
        Y = [y(i-1)+w*N(2,i-1) y(i)+w*N(2,i) y(i-1)-w*N(2,i-1) y(i)-w*N(2,i)];

        % Order the points
        D = pdist([X' Y']);
        D = squareform(D); D(D==0) = Inf;

        inds = 1;
        D(:,1) = Inf;

        [val ind] = min(D(1,:));
        inds(2) = ind;
        D(:,ind) = Inf;

        [val ind] = min(D(ind,:));
        inds(3) = ind;
        D(:,ind) = Inf;

        inds(4) = setxor(inds,1:4);

        X = X(inds);
        Y = Y(inds);

        patch(X,Y,col,'edgeColor','none','FaceAlpha',a)
    end

    hold off

A:

I have the same problem, and my scatter plot has 100,000's of points.
The idea of answer #2 is great, but it was impractical for me to open my plot in Illustrator
because I had too many points.  So I adapted answer #2 into a batch process:
print the figure to a pdf file in matlab:
print -dpdf foo.pdf

convert the pdf file to svg using pdf2svg from debian package pdf2svg:
pdf2svg foo.pdf foo.svg

make all blue objects transparent:
sed '/rgb(0%,0%,100%)/s/fill-opacity:1/fill-opacity:.2' < foo.svg > foo2.svg

convert foo2.svg to pdf using rsvg-convert from debian package
 librsvg2-bin:
rsvg-convert -f pdf -o foo2.pdf foo2.svg


Q:

Is it possible to perform an asynchronous cross-domain file-upload?

It is possible! Read below.

First of all, let me use this diagram to explain how asynchronous file uploads can be achieved:

Sorry. I've shut down one of my domains, and the image is gone now. It was a really nice image though. This was before I found out that Stack Overflow enables uploading images via Imgur.

As you can see, the trick is to let the HTTP-response load into a hidden IFRAME element instead of the page itself. (This is done by setting the target property of the FORM element when submitting the FORM with JavaScript.)
This works. However, the problem I'm facing is that the server-side script is on a different domain. The FORM-submit is a cross-domain HTTP-request. Now, the server-side script has CORS enabled which gives my web-page the rights to read the response-data of HTTP-requests made from my page to that script - but that works only if I receive the HTTP-response via Ajax, ergo, JavaScript.
However, int this case, the response is directed towards the IFRAME element. And once the XML response lands into the IFRAME, its URL will be the remove script - e.g. http://remote-domain.com/script.pl.
Unfortunately, CORS does not cover this case (at least I think) - I am not able to read the contents of the IFRAME since its URL doesn't match the URL of the page (different domain). I get this error:

Unsafe JavaScript attempt to access frame with URL
  hxxp://remote-domain.com/script.pl from frame with URL
  hxxp://my-domain.com/outer.html. Domains, protocols and ports must
  match.

And since the contents of the IFRAME is an XML document, there is no JavaScript code inside the IFRAME which could make use of postMessage or something.
So my question is: How can I get the XML contents from the IFRAME?
As I said above, I am able to retrieve cross-domain HTTP-responses directly (CORS enabled), but it seems that I am not able to read cross-domain HTTP-responses once they load into an IFRAME.
And as if this question is not unsolvable enough, let me exclude these solutions:

easyXDM and similar techniques which require an end-point on the remote domain,
altering the XML response (to include a SCRIPT element),
server-side proxy - I understand that I could have a server-side script on my domain which could serve as a proxy.

So, apart from those two solutions, can this be done?

It can be done!!
It turns out that it is possible to forge a XHR-request (Ajax-request) which imitates a multipart/form-data FORM submit (which is used in the image above to upload the file to the server).
The trick is to use FormData constructor - read this Mozilla Hacks article for more information.
This is how you do it:
// STEP 1
// retrieve a reference to the file
// <input type="file"> elements have a "files" property
var file = input.files[0];

// STEP 2
// create a FormData instance, and append the file to it
var fd = new FormData();
fd.append('file', file);

// STEP 3
// send the FormData instance with the XHR object
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://remote-domain.com/script.pl', true);
xhr.onreadystatechange = responseHandler;
xhr.send(fd);

The above method executes an asynchronous file-uplaod, which is equivalent to the regular file-upload described in the image above and achieved by submitting this form:
<form action="http://remote-domain.com/script.pl"
        enctype="multipart/form-data" method="post">
    <input type="file" name="file">
</form>

Like a Boss :)

A:

Just send a cross-domain XHR request with the data from the form instead of submitting the form. CORS is only for the former.
If you must do it the other way, negotiate with the frame using postMessage.

And since the contents of the IFRAME is an XML document, there is no JavaScript code inside the IFRAME which could make use of postMessage or something.

How does that stop you? Include a script element under the HTML or SVG namespace (<script xmlns="http://www.w3.org/1999/xhtml" type="application/ecmascript" src="..."/>) anywhere in the XML.


Q:

Pooling data from multiple csv files into a cell

I have 33 csv files from different locations and I would like retrieve each file, get the content and dump it in a cell. This cell should contain information (all scalar values) from all the individual files. Each individual file has 3 rows and 16 columns. I would like to create a 99 x 16 cell (called P). 99 rows would be from 3 rows per each of the 33 files. The 16 columns are 16 columns from each file.
So far I have created a loop to retrieve each file:
P=cell(length(Q)*3,16); % Q contain the name of the files
for k=1:length(Q)
dire_FIX = '/Data3/ledata/FHSWD/Scan_data/';
data_path=[dire_FIX Q{k}];
data = spm_select('FPList', fullfile(data_path), sprintf('^%s.*\.csv$', Q{k})); % get each file
Values = load (data)
Here is where I got stuck. Values should be a 3x16 cell. How do I put each Values into P without overwriting the previous Values.
Thank you!

A:

Initialize P to an empty matrix:
P =[];

Put this at the end of your for-loop:
P(:, end+1) = Values{:, 1};
P(:, end+1) = Values{:, 2};
P(:, end+1) = Values{:, 3};

That should do it.


Q:

parent overlaps child's box-shadow

I have 2 divs a parent and a child they both have fixed width and the child has fixed hight too, child div is floated left and it has box-shadow:0 1px 2px 0 rgba(0,0,0,0.4) the problem is that the parent div overlaps child's left shadow I can't add margin-left to the child because its left side is aligned with the left side of a menu div above the parrent div so it has to be exactly where it is.
I tried z-index, minus margin for the parent and so many other things I can't even count but nothing seems to solve the problem.
the code is:

      Some Content...

</body

Its a huge problem for a good UI designer, of curse you know better ;)

A:

Fixed it.
The #wrapper is overflow:hidden so nothing outside its area can be seen including the child's shadow.
All I had to do was to hide only the overflow of its top and bottom so I did this:
#wrapper{
  overflow-y:hidden;
}