Q:

Multiplying and adding images with CImg In C++

I am trying to find C in the following function in CImg
C=B*L+(1-B)S
Where C, L and S are all RGB images of the same size (and B is a single channel grayscale matte)
I cannot figure out how to loop over the pixels.  I've seen code like:
cimg_forXYZ(S,x,y,z) {... }

But I have never see than kind of syntax before, could it be a macro?
Any suggestions are welcome.

A:

If you look into the CImg header, you'll see that that code is, in fact, a macro that thunks down into:
#define cimg_forXY(img,x,y)       cimg_forY(img,y) cimg_forX(img,x)
#define cimg_forX(img,x)          for (int x=0; x<(int)((img).width); ++x)
#define cimg_forY(img,y)          for (int y=0; y<(int)((img).height); ++y)
#define cimg_forZ(img,z)          for (int z=0; z<(int)((img).depth); ++z)
#define cimg_forXYZ(img,x,y,z) cimg_forZ(img,z) cimg_forXY(img,x,y)

Which means that you will have the following loops:
for (int z=0; z<(int)((img).depth); ++z)
    for (int y=0; y<(int)((img).height); ++y)
        for (int x=0; x<(int)((img).width); ++x) {

}

So, now, what you probably want to do is reference either the x, y, and z coordinates, or better, the pointer into the data as you step through, like
cimg_library::CImg<float> image;
//assign, etc
float* ptr = image->ptr();
cimg_forXYZ(S, x, y, z){
    *ptr = *ptr + 10;
    ++ptr;
}

I encourage you to read the CImg header; it's quite elegant.  You'll get a lot of functionality 'for free'.


Q:

Stress Testing Your Mac For Optimal Performance?

Stress testing maybe considered a useful way to determine if your Mac is performing at its optimal level of performance & may also be an indicator of faults of any components within your Mac.
What methods exist (ideally free if possible) to stress test to the max the following components:

CPU
Hard Disk
Ram

Thereby identifying any problem(s) that may exist & if your Mac can handle them ?

A:

There is a built-in hardware test designed by Apple.
With the introduction of Intel-based Macs, Apple has built the AHT utility right into your Mac.
Simply hold down the D key while starting up your Mac to boot into the Apple Hardware Test.
I would not recommend using garden variety www not approved test programs. This would be the same as if you have a car with a speedometer marked 150 MPH would you actually drive it @155 MPH to find out if it holds up using non OEM tires?

A:

CPU: purchase an app which can use up all the cores @ 100% and let it crank until your Mac is a pile of smoking plastic or the power goes out, which ever comes first. Rendering a large & complex animation with the Radiosity setting in Strata Studio Pro can do this for you.
HD: If you don't mind zapping the contents of the HD, run DiskUtility and then Erase the HD using the most stringent Security option available - a 7-pass write with zeros. It'll take days, but the disk heads will be in constant motion the whole time. With a MTBF usually measured in the millions of hours, it'll take more than a century to zap a perfectly constructed disk drive, given perfect electronics and no power dips/sags.
RAM: Take a look at Memtest 4 and run it endlessly.
In essence, I don't think I really, truly understand what you want to stress test here. To me, making sure these three components work optimally would mean:

making sure the Mac has clean, filtered & conditioned power from a
high-end battery-backup device;
guaranteeing near-perfect environmental conditions (constant temperature,
low humidity and low particulate levels)

You could also purchase 'Enterprise' grade hard drives.
All bets are off, though, should a gamma wave come through your neighborhood. In this case, you'd probably be more worried about keeping your skin from bursting into flames.


Q:

Multiple "Symbol X (number Y) is not exported from dependent module" on AIX 7.1

I'm working on AIX 7.1 and having problems linking due to multiple "Symbol X (number Y) is not exported from dependent module".
Error
Could not load program openssl:
Symbol resolution failed for /apps/10.00/openssl/product/openssl-1.0.2f/lib/libssl.so because:
        Symbol EC_curve_nist2nid (number 73) is not exported from dependent
          module /apps/tuxedo/product/12.1/lib/libcrypto.so.
        Symbol EVP_aes_256_cbc_hmac_sha256 (number 274) is not exported from dependent
          module /apps/tuxedo/product/12.1/lib/libcrypto.so.
        Symbol EVP_aes_128_cbc_hmac_sha256 (number 275) is not exported from dependent
          module /apps/tuxedo/product/12.1/lib/libcrypto.so.
        Symbol X509_get_signature_nid (number 282) is not exported from dependent
          module /apps/tuxedo/product/12.1/lib/libcrypto.so.
        Symbol X509_chain_up_ref (number 312) is not exported from dependent
          module /apps/tuxedo/product/12.1/lib/libcrypto.so.
        Symbol X509_chain_check_suiteb (number 313) is not exported from dependent
          module /apps/tuxedo/product/12.1/lib/libcrypto.so.

The below are the dependencies:
$ ldd `which openssl`
/cb/cb10b/rel/server/bin/openssl needs:
         /apps/10.00/openssl/product/openssl-1.0.2f/lib/libssl.so
         /apps/tuxedo/product/12.1/lib/libcrypto.so
         /usr/lib/libpthreads.a(shr_xpg5_64.o)
         /usr/lib/libc.a(shr_64.o)
         /unix

It can be seen that libcrypto.so comes from tuxedo and not openssl.
So I exported LIBPATH to have openssl more before tuxedo libraries. This changes the ldd output as below:-
export LIBPATH=/apps/10.00/openssl/product/openssl-1.0.2f/lib:$LIBPATH
$ ldd `which openssl`
/cb/cb10b/rel/server/bin/openssl needs:
         /apps/10.00/openssl/product/openssl-1.0.2f/lib/libssl.so
         /apps/10.00/openssl/product/openssl-1.0.2f/lib/libcrypto.so
         /usr/lib/libpthreads.a(shr_xpg5_64.o)
         /usr/lib/libc.a(shr_64.o)
         /unix
         /usr/lib/libcrypt.a(shr_64.o)

Although the ldd output shows the dependent libraries being picked from openssl directories. However, when I run the script I still get the same error as above. When I rename libcrypto.so to something else, (say libcrypto.s.bkp), then while running the libcrypto.so from openssl is being picked, so clearly there is something which causes the libcrypto.so to be searched in Tuxedo directory first and later in openssl directory.
I do not know what is causing the tuxedo libraries to have higher priority than the openssl libraries.

A:

I am linking statically(no-shared) and that has solved it:-
    OPENSSL_VERSION=openssl-1.0.2f
On AIX:
./Configure aix64-cc --prefix=$INSTALLDIR/openssl/product/$OPENSSL_VERSION --openssldir=$INSTALLDIR/openssl/product/$OPENSSL_VERSION/openssl threads  no-shared

EDIT:
Also, since I had get it installed on SunOs, here is the instruction
./Configure solaris64-sparcv9-cc --prefix=$INSTALLDIR/openssl/product/$OPENSSL_VERSION --openssldir=$INSTALLDIR/openssl/product/$OPENSSL_VERSION/openssl threads no-shared -KPIC


Q:

Order Notation - Why can't $c$ be in terms of $n$?

For $f(n)$ to be in $O(g(n))$, there must exist a $c > 0$ and $n_0 > 0$ such that
$$0 \leq f(n) \leq cg(n) \text{ for all }n \geq n_0\,.$$
I found a solution to a question where my $c$ is in terms of $n$, but my friend says you can't have that. I'd like to understand why.
My thought process is: if I am given an $n$, I can pick a distinct $c$ that will satisfy the requirements above by using the $c$ in terms of $n$ relationship.
Thank you.

A:

Suppose we define $f(x) = O'(g(x))$ to mean that there is a function $c(x)$ such that $f(x)\leq c(x)g(x)$ for all sufficiently large $x$. Then $f(x) = O'(g(x))$ for almost every pair of functions $f$ and $g$, just by taking $c(x)=f(x)$. So, this definition just isn't a useful way to compare functions.
(I say "almost every pair" because there are issues if we have infinitely many values of $x$ for which $g(x)=0$ and $f(x)\neq 0$ but I don't think it's worth pinning down exactly what functions work and what don't.)


Q:

Shortcut for switching back to last window in Vim?

Ctrlw1w switches to the first window.
If currently I frequently edit in two of several windows, a shortcut for switching back to the last active window would be perfect.
Is there such a shortcut?

A:

did you try
<c-w><c-p>

?
from help:
CTRL-W p                    *CTRL-W_p* *CTRL-W_CTRL-P*
CTRL-W CTRL-P   Go to previous (last accessed) window.

                        *CTRL-W_P* *E441*
CTRL-W P    Go to preview window.  When there is no preview window this is
        an error.
        {not available when compiled without the |+quickfix| feature}

A:

As Kent said
       <c-w><c-p> will go to previous
You can also navigate between windows using the directions h, j, k, and l
<c-w><c-h>
<c-w><c-j>
<c-w><c-k>
<c-w><c-l>

<number><c-w><c-w> will navigate to a specific window

A:

You can build your own short mapping; Vim is infinitely flexible in this regard. For example, many find these useful:
:noremap <C-j> <C-w>j
:noremap <C-k> <C-w>k
:noremap <C-h> <C-w>h
:noremap <C-l> <C-w>l

Also, learn how to look up commands and navigate the built-in :help; it is comprehensive and offers many tips. You won't learn Vim as fast as other editors, but if you commit to continuous learning, it'll prove a very powerful and efficient editor.


Q:

How can I convert toml-rs result to std::collections::HashMap

I'm new to Rust and trying to build something simple to get going. I want to load data from a .toml file and use rustache to render out some text from it.
Rustache appears to take a HashMap as its data source, and I'm sure from looking at the toml-rs docs that I should be able to convert its Table and Array types to HashMaps and Vecs, and I suspect it's got something to do with Decoder, but I can't figure it out.
If somebody could provide a short example of how to do this I would be very grateful.

A:

If your data structure has fixed known depth, then all you need is just to pass a correct type to toml::decode():
let value: toml::Value = toml::Value::Table(Parser::new(input).parse().unwrap());
let data: HashMap<String, Vec<u32>> = toml::decode(value).unwrap();

The code above would parse a document like
x = [1, 2, 3]
y = [4, 5, 6]

However, as far as I can see, rustache provides some kind of builder structure which supports arbitrary nesting. In that case you would need to "apply" toml::Value to rustache::HashBuilder. You don't need to use Decodable for this (though you probably can, with some newtypes) - you just need to write a couple of simple functions:
fn toml_into_hashbuilder<'a>(value: toml::Table, mut hb: rustache::HashBuilder<'a>) -> rustache::HashBuilder<'a> {
    for (k, v) in value {
        match v {
            toml::Value::String(s) => hb.insert_string(k, s),
            toml::Value::Integer(i) => hb.insert_int(k, i),
            toml::Value::Float(f) => hb.insert_float(k, f),
            toml::Value::Boolean(b) => hb.insert_bool(k, b),
            toml::Value::Datetime(s) => hb.insert_string(k, s),
            toml::Value::Array(arr) => hb.insert_vector(k, |vb| toml_into_vecbuilder(arr.clone(), vb)),
            toml::Value::Table(tbl) => hb.insert_hash(k, |hb| toml_into_hashbuilder(tbl.clone(), hb))
        }
    }
    hb
}

fn toml_into_vecbuilder<'a>(value: toml::Array, mut vb: rustache::VecBuilder<'a>) -> rustache::VecBuilder<'a> {
    for v in value {
        match v {
            toml::Value::String(s) => vb.push_string(s),
            toml::Value::Integer(i) => vb.push_int(i),
            toml::Value::Float(f) => vb.push_float(f),
            toml::Value::Boolean(b) => vb.push_bool(b),
            toml::Value::Datetime(s) => vb.push_string(s),
            toml::Value::Array(arr) => vb.push_vector(|vb| toml_into_vecbuilder(arr.clone(), vb)),
            toml::Value::Table(tbl) => vb.push_hash(|hb| toml_into_hashbuilder(tbl.clone(), hb))
        }
    }
    vb
}

let value: toml::Table = Parser::new(input).parse().unwrap();
let hb = toml_into_hashbuilder(value, rustache::HashBuilder::new());
let result = rustache::render_text(your_template, hb);

There are unfortunate clones when handling nested tables and arrays - this is a consequence of an issue in rustache. If it is fixed, clone() could be removed, and the closures should be made move then.


Q:

How do I convert a decimal to hexadecimal using Objective C?

I've been working on a calculator and I wanted to implement conversions from decimal to octal and from decimal to hexadecimal. I'm new to Xcode and Objective C, but I've managed to get a conversion from decimal to octal, it just doesn't seem to work with hexadecimal.
Here's the code I've written to convert a double to octal:
double result = 0;
...
double decToOct = [self popOperand];
NSString *oct = [NSString stringWithFormat:@"%llo", (long long)decToOct];
result = [oct doubleValue];

Using the same scheme (obviously that includes changing @"%llo" with @"%llx") the conversion to hexadecimal works up to a certain point. It does numbers 0 through 9 just fine, but once it hits 10, it comes up as 0. To test, I also input 5395 and it displayed 1513, the desired result.
Because of this, I can only assume that for some reason my code does not want to input the actual letters of the hexadecimal values (e.g. 11 would convert to B but it shows up as 0) .
Any suggestions? Thanks in advance.
UPDATE:
In addition, I have also been using this to display the result:
double result = [self.brain performOperation:operation];
self.display.text = [NSString stringWithFormat:@"%g", result];

result, as listed from the top, is an argument which is eventually returned here, to self.brain performOperation:operation. This is supposed to handle the display of all operations, including: addition, multiplication, etc. but also octal and hexadecimal. Again, it works fine with octal, but not with hexadecimal.

A:

Try this, May be it will help you. Please do let me know if i am wrong here:--->
NSString *decStr = @"11";
NSString *hexStr = [NSString stringWithFormat:@"%lX",
                 (unsigned long)[dec integerValue]];
NSLog(@"%@", hexStr);


Q:

Error with Go modules build using /cmd structure

I'm new to go modules, and am taking them for a spin in a new project which I'm trying to model after the structure described here
Here is an example of my directory structure:
.
├── cmd
│   └── app_name
│       └── main.go
├── go.mod
├── go.sum
├── internal
│   └── bot
│       └── bot.go
└── pkg
    ├── website_name
    │   ├── client.go
    │   ├── client.options.go
    │   ├── server.go
    │   └── server.options.go
    └── lib
        └── lib.go

Is this idiomatically correct? I know there's not a whole lot of consensus out there, but I'd like to follow best practices.
When I run go build I get 'unexpected module path "github.com/ragurney/app_name/cmd/app_name"', but when I run go build ./... it works. Why?

When I move main.go to the top level everything works as expected. Should I just not use the /cmd pattern with modules?

A:

To answer your first question, its completely opinionated and whatever you like best that is also easy to understand for others you should go with (I think it's fine).
To answer your second question the reason go build ./... works as opposed to go build from the root directory is because ./... starts in the current directory (the root) and searches for all program entry-points and builds them. When you move main.go to the root directory, with this new information, go build working then makes sense, as its only looking in the current directory.
You can explicitly say go build ./cmd/app_name which would also work.
Your application structure works perfectly fine with modules, as I use something very similar to it (https://www.ardanlabs.com/blog/2017/02/package-oriented-design.html) and modules work very well for me.


Q:

Libcurl Certificate Pinning working on iPhone but not on Android

This is my C++ code that I am using in Obj-C and JAVA projects.
string readBuffer;
string certificateBeingUsed;
CURL *curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(curl, CURLOPT_URL, "https://apiServer");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 120);
curl_easy_setopt(curl, CURLOPT_ENCODING, GZIP);

curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER , true);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST , 2);
curl_easy_setopt(curl, CURLOPT_CAINFO,certificateBeingUsed);

CURLcode res;
res = curl_easy_perform(curl);

--------------------------------------------------------------------
In Xcode, I have my ceritificate "certificatePinning.der" stored in Resources/Certificates folder.
To use the code above, I set certificateBeingUsed to my certificate path:
certificateBeingUsed = "/Users/graceo/Library/Developer/CoreSimulator/Devices/1BB154CB-276B-4DDC-86C8-4975213D7E3B/data/Containers/Bundle/Application/4819EC2A-CA18-46BF-815F-445B5E3E519F/TestStoryBoardWithLibraryAndSwift.app/certificatePinning.der"

and res returns success with readBuffer containing the response sent from the server.
--------------------------------------------------------------------
In Android Studio, I have my ceritificate "certificatePinning.der" stored in assets folder. (I copy it to the data folder before using it)
To use the code above, I set certificateBeingUsed to my certificate path:
certificateBeingUsed = "/data/data/packageName/certificatePinning.der"

but res returns CURLE_SSL_CACERT_BADFILE (77) and readBuffer is empty
--------------------------------------------------------------------
What is it that I am missing in Android that could not validate the certificate stored with the server's ??
NB:

I have SSL supported in libCurl.
In android if I set it to the certificate cacert.pem it will return success, but I want to use my certificate instead.

A:

This may be a problem with encoding, try to convert your .der file to .pem format using this:
openssl x509 -in cert.crt -inform der -outform pem -out cert.pem


Q:

Videos not loading in flash CS6 published to android and iOS

I'm new to flash so I will try to write it down as clear as i can. I hope you can help me with this and thanks in advance.
I have a project that function like a brochure. Its just a compilation images, text and several videos with a very simple goto pages functions.
the images and text are already included in the fla file while the videos are in my project file directory and streamed from my local hard drive. I'm using the earlier version of flash video component and I'm using flash CS6.
My AS3 Script to load the videos
sp.source = SPContent;
sp.setSize(340, 335);

var VidBtn01 = MovieClip(sp.content).VidBtn01;
var VidBtn02 = MovieClip(sp.content).VidBtn02;

VidBtn01.addEventListener(MouseEvent.CLICK, onClick01);
VidBtn02.addEventListener(MouseEvent.CLICK, onClick02);

UNOVid.addEventListener(Event.REMOVED_FROM_STAGE, stopMovie);
function stopMovie(e:Event=null)
{
UNOVid.stop();
}

function onClick01(evt:MouseEvent):void {
    UNOVid.source = "Video1.flv";
}
VidBtn01.addEventListener(MouseEvent.CLICK, onClick01);

function onClick02(evt:MouseEvent):void {
    UNOVid.source = "Video2.flv";
}
VidBtn02.addEventListener(MouseEvent.CLICK, onClick02);

When test published in flash professional, the projects works really well. When Publishing for android and iOS, flash do not reveal any errors. Upon
testing the published apk and api files, then the problem arise.
Problem 1 Android: All buttons and navigation working, flash video component present but some videos canot be played.
Problem 2 iOS: All buttons and navigation working, videos not playing, cant really tell because flash video component is not being displayed.
All videos are flv 320x240 but of different duration and encoded using flash video encoder same settings. During packaging files included are the
projects swf, the flash video component's swf, the app.xml and all the videos included in the project. The .apk and .api file size is 1.02GB. I also tried
publishing without the videos just to see the file size and both the .apk and .api file is only 3.9mb. Also check the videos folder size in windows
properties, size is 1gb plus.
I checked the installed app on my iOS device using an app called iFile from cydia, all the videos are accounted for with the flash component.
For android upon checking the installed file it revealed and apk file and some .so file. You cant really see if the files are all in there. So I did a little
research and learned that if you change the .apk extension to .rar, you can extract the file in windows to inspect whats inside your published .apk
file. Upon doing sa I was able to see that all the files are accounted for.
I'm using for device testing a generic android tablet running 4.01 IceCreamSandwich and an iPad Air iOS7 jail broken.
My Question for ANDROID

How does android process the apk file, why was the apk files not extracted when installed on my device?
What might be the reason why some of the videos  cannot be played? Hardware Limitation perhaps, any idea?
Will there be a conflict with the New Versions of Android (jellybean/Kitkat) since adobe flash already stopped supporting android?

My Question for iOS

Why was the Flash Video Component missing? Is this a compatibility issue with iOS since the flash video component is an swf file?
I assumed that packaging it would eliminate that issue considering that publishing air for ios includes adobe air in the package. If that's the case isthere another way to deliver the video on stage in iOS?
Is FLV video compatible with iOS if not what video compression should i use?

Lastly how can i publish to Android and iOS without the need to package it with the video. So the final .apk and .api file size is manageable.
Perhaps just adding the videos in a directory within he device's storage using the resolve path method. Can anyone share how i can do this?
Again thanks in advance to all.

A:

I don't have time for a complete answer right now. Here's a partial answer:
You can't use .flv on iOS. You have to encode using the H.264 codec in an .mp4 file. Apple has more-or-less particular specs on the encoding. Look 'em up!
Also, in iOS you'll want to use the StageVideo class combined with the Netstream and NetConnection classes. StageVideo is a requirement for the GPU video processing on iOS devices. BUT when you're running your video code on a desktop machine, or when you're running video in AIR on desktop, you want to use the regular Video Class because you'll be rendering, usually, with the CPU.  So, usually, your code will have to test for the availability of GPU processing and then invoke one function for implementing THAT, or another function if only CPU processing is available.
Video (without components -- which you should forget!) sounds complicated, but it's not THAT complicated. It just takes a little time to learn. Suggestion: study here - http://gotoandlearn.com/play.php?id=46 for the basics of the Video Class. Then read the Adobe AS3 reference on StageVideo.  Then come back here and ask more questions. You'll beat your head against a wall for a day or so, but then you'll really know how to handle video on, at least some mobile devices.
When you're testing on iOS don't forget to publish with GPU rendering.
I'm just learning AIR for Android myself so can't help you there.


Q:

Rails 4, not sending email using sendmail

I am having an issue sending out mail using rails 4 on Debian.
production.rb
config.action_mailer.delivery_method       = :sendmail
config.action_mailer.perform_deliveries    = true
config.action_mailer.raise_delivery_errors = true

controller.rb
ReviewConfirm.confirm(@review).deliver
rails debug output
D, [2014-08-16T09:09:35.851905 #2339] DEBUG -- :
ReviewConfirm#confirm: processed outbound mail in 29.0ms
I, [2014-08-16T09:09:35.951972 #2339]  INFO -- :
Sent mail to mypersonaladdress@gmail.com (99.4ms)
D, [2014-08-16T09:09:35.952421 #2339] DEBUG -- : Date: Sat, 16 Aug 2014 09:09:35 +0000
From: info@mypersonaldomain.com
To: mypersonaladdress@gmail.com

The server is able to send out email, using the command line and PHP. Mail logs are empty for an unknown reason. If anyone could shed any light on this, that would be great.

A:

Ok, turns out
config.action_mailer.delivery_method       = :sendmail should be config.action_mailer.delivery_method       = :smtp


Q:

Multiple pivots within a MYSQL table

I have the following setup for my database:
create table spooner_pec
(
  id int,
  year varchar(20),
  policy_number int,
  primary_name varchar(200),
  experience_rate decimal(10,2),
  mco_name varchar(200)
);

with these values being inserted:
insert into spooner_pec values
(1,'2009',183586,'ZBIN LANDSCAPING INC', 1.22, 'GENEX CARE FOR OHIO'),
(1,'2011',183586,'ZBIN LANDSCAPING INC', 0.93, 'COMPMANAGEMENT HEALTH SYSTEMS, INC.'),
(1,'2012',183586,'ZBIN LANDSCAPING INC', 0.92, 'HEALTH MANAGEMENT SOLUTIONS, INC.'),
(1,'2013',183586,'ZBIN LANDSCAPING INC', 0.50, 'CAREWORKS'),
(1,'2014',183586,'ZBIN LANDSCAPING INC', 0.47, 'UNIVERSITY HOSPITALS COMPCARE'),
(1,'2010',183586,'ZBIN LANDSCAPING INC', 1.27, 'SHEAKLEY UNICOMP')

The query that I have working so far is this:
SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when year = ',
      year,
      ' then experience_rate end) AS `',
      year, '-Pen`'
    ) ORDER BY year
  ) INTO @sql
FROM
  spooner_pec;
SET @sql = CONCAT('SELECT policy_number, primary_name, ', @sql, '
                  FROM spooner_pec
                   GROUP BY policy_number');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

So after a previous question on here and some research I have finally gotten this pivot work correctly.  I am basically just taking all of the individual years and making them columns instead of rows.
So I have one row for each company and then a year-pen column for each year.  Now I need to also have a year-mco column the same way, where in my statement do I add this in?
SQLFiddle

A:

Is this what you're looking for?
SET @sql = NULL;
SET @sql2 = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when year = ',
      year,
      ' then experience_rate end) AS `',
      year, '-Pen`'
    ) ORDER BY year
  ) INTO @sql
FROM
  spooner_pec;

SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when year = ',
      year,
      ' then mco_name end) AS `',
      year, '-Mco`'
    ) ORDER BY year
  ) INTO @sql2
FROM
  spooner_pec;
SET @sql = CONCAT('SELECT policy_number, primary_name, ', @sql, ', ', @sql2, '
              FROM spooner_pec
               GROUP BY policy_number');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


Q:

Is there any possible to create master node in one aws region and worker node in another region?

Is there any possibility to create cluster with eks in one region (eg. ap-south-1) and join worker node from another region (eg. ap-north-east-2). If yes, can anyone tell me how to do this ?

A:

No. It's because you have no power to change anything on master node.
Amazon EKS is fully managed Kubernetes service, you would need to make your own cluster on EC2 instances.


Q:

Will the Sheikh Jaber Al-Ahmed Al-Sabah be the 'longest bridge' in the world?

In any metric, this doesn't seem to qualify as the longest bridge in the world.  I could be miscalculating, but a number of articles are using the title 'longest'.  The articles below are highlights popping up today.
It states it is going to be the longest bridge, but I understand that by viaducts and clearances, it doesn't appear to check any boxes for 'longest bridge.'
Example: "World's Longest Bridge Nears Completion," "The Longest Bridge in the World.." et al.

A:

It depends on exactly what the claim is, but it's certainly not the "longest bridge in the world".
Wikipedia's list of longest bridges, lists Danyang–Kunshan Grand Bridge as the Guinness Records holder with total length of 164km.
Guinness' Longest Road Bridge is Bang Na Expressway with length of 54km.
The Sheikh Jaber Al-Ahmad Al-Sabah Causeway is "only" 48km long, but it's largely over water, so it might qualify as the longest bridge over water depending on how it's measured.
The current longest aggregate bridge over water is Hong Kong-Zhuhai-Macau bridge with total length of 48.3km, which is very close to what the Shaikh Jaber bridge is reported to be.
If the Sheikh is a continuous bridge, it will probably beat the current longest continuous bridge over water, Lake Pontchartrain Causeway (38km).
It's possible that the news reports are incorrectly referring to it as the "longest bridge" when they really mean it will be the longest continuous bridge over water.


Q:

How to finish() the Activity on home button click in android?

I want to finish the Activity on Home Button Click .
I have below code but not get its click event . but still not get clickevent
public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_HOME:
                System.out.println("Home clicked....");
            return true;

            }
        }
        return super.onKeyDown(keyCode, event);
    }

A:

When Home button is pressed, onStop method is called in your activity. So what you may do is to add finish(); in onStop method to destroy your activity. Eventually onDestroy method will be raised to confirm that your activity is finished.

A:

You can't handle "Home" button.
You could try overriding some of these methods though: onStop, onUserLeaveHint

Are you sure you need to do this though?
If you could save your current state through the onPause/onSaveInstanceState and recover it later the OS should be able to handle the Activity's life cycle and finish it if needed.
Can you tell us what is preventing you from doing it that way? :)


Q:

Projection equation

I'm a programmer, not a math expert or statistician by any means, but my organization wants a page in our admin console that displays a projection of how many registrations we can expect to see based on data we have from last year. Here's the math I'm currently working with:
The projection for total registrations in a given year (Ty) is calculated by the equation
￼$$
Ty\; =\; \frac{N}{\frac{\left( \frac{\left( Lp\; +\; Ld \right)}{2} \right)}{Ly}}
$$
where

Ly is the total number of registrations last year
N is the current number of registrations this year (so far)
Lp is the number of registrations at the current percent of completion last year (say we're 15% through this year's registration cycle, so we'll look at where we were at 15% last year)
Ld is the number of registrations at the current time last year (it's July 28, 2014, so look at where we were on July 28, 2013, which, in this case, will be different than Lp because we started registration on a different date last year so the percentages are different)

Thus, if

Ly (total last year) is 616
N (current registered) is 189
Lp (registered at current percent last year) is 219
Ld (registered at current time last year) is 44

then the projection for total registered attendees this year (Ty) is 886.
￼$$
886\; =\; \frac{189}{\frac{\left( \frac{\left( 219\; +\; 44 \right)}{2} \right)}{616}}
$$
This makes sense to me and is in line with the growth we would expect. My question is whether the math is sound, or what suggestions anyone has to improve it.
Thanks!

A:

This is a heuristic, and as such it comes with advantages, disadvantages, and assumptions. Let's go over the idea, see its assumptions, and see the advantages and disadvantages, and one possible (relatively easy) improvement.
Start simple
For the moment, let's forget that there are two ways of talking about how far through a cycle we are. Instead of both time and percentage completion, let's just think about percentage completion.
Then we might look at last year's data and try to make predictions based on that. The absolute simplest thing that we might try is to assume that the number of registrations depends solely and linearly on the number of registrations at a given percentage completion each year. (Ok, the absolute simplest is to assume no change - but this is the second absolute simplest idea).
This leads us to the heuristic
$$\frac{Ty}{Np} = \frac{Ly}{Lp}.$$
(I write $Np$ to emphasize that the number of current registrants is indicating our current percentage). This is saying that at $p$ percent through the project, we expect some absolute percentage of people to have registered - and from last year's data, we take this percentage to be $\frac{Ly}{Lp}$. To to get $Ty$, we multiply through by $Np$ and get
$$Ty = Np \cdot \frac{Ly}{Lp}.$$
Incorporating both date and percentage
But we have a problem: there are actually two ways of talking about how far through the cycle we are. We also have time of year. The absolute simplest way to try to incorporate time is to assume that it is equally important (ok... the absolute simplest is to ignore it). So instead of dealing with $Lp$ alone, we'll deal with the standard average of $Lp$ and $Ld$. This leads to our current formula:
$$Ty = N \cdot \frac{Ly}{\frac{Lp + Ld}{2}}.$$
(Notice this is equivalent to your formula, but written in an unambiguous way which I find easier to interpret; I've also dropped $Np$ in favor of $N$, though we could write $Npd$ to emphasize that the $p$ and the $d$ really come from this $N$). This has the advantage of being intuitively similar to the case above and easy to calculate.
A possible improvement
But the two major assumptions we've made (that the date and percentage completion are equally important; and that the total number of registrants depends linearly on the number of registrants at the current date and percentage completion) are strong assumptions that are almost certainly false.
So you might try to see if they are good enough - perhaps they are, perhaps they aren't. That's the nature of heuristics.
One very natural way to try to improve this method is to toss the assumption that the date and the percentage completion are equally important, and instead weight their importance. So instead of comparing to the average
$$.5Lp + .5Ld,$$
you might compare to
$$w\cdot Lp + (1-w)Ld,$$
where $w$ is some weight between $0$ and $1$. If $w$ is larger, it means that you think the percentage completion is more important. If it's smaller, if means you think the date is more important. How do you find/choose $w$? One way is to sort of guess and check. You look at your previous years' data (hopefully you have more than one year) and you try different $w$. For example, you might try to "predict" last year's data from the data of two years ago with different weights, and see which one works best. A little spreadsheeting with your favorite spreadsheet (or any other number of more programmatic tools) makes this very easy, even though it might sound a bit daunting at first.
In summary
Yes, there is some sense to the math. No, it's not perfect. And there is one potential improvement suggested above.


Q:

Dictionary.ElementAt method is visible in some classes, but not others

I have a Dictionary whose elements I need to iterate through and make changes. I cannot use foreach statement, since it sometimes throws InvalidOperationException, saying that the collection cannot be modified during an enumaration.
I can use a for loop, in conjunction with Dictionary.ElementAt method, and I successfully used it in other classes, but in this particular class, the method ElementAt cannot be found! Any ideas?

A:

ElementAt is an extension method defined in System.Linq.Enumerable.
You need to add a using clause to make it visible:
using System.Linq;

Note that ElementAt on a Dictionary<TKey,TValue> doesn't make a lot of sense, though, as the dictionary implementation does not guarantee elements to be in any specific order, nor that the order does not change if you make changes to the dictionary.


Q:

How do I prevent table view scrolling behind a view?

In a TableViewController, I have an translucent overlay view with a message. The overlay is displayed over the TableViewController correctly but I can still scroll the table view behind this overlay view. How can I prevent the scrolling when the overlay is on top?
I constructed my custom overlay view in my TableViewController:
override func viewDidLoad() {
    super.viewDidLoad()

    loadData(
        id,
        success: {(doc) -> () in
            let frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height)

            let overlayView = EmptyCollectionView(frame : frame)
            overlayView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.8)
            self.view.addSubview(overlayView)

            self.tableView.reloadData()
        },
        error: {..})
}

I tried self.tableView.isUserInteractionEnabled = false

A:

OK - if you are in a UITableViewController, self.view refers to the UITableView itself. You want to add your overlayView as a subview of the table view's superview...
Try this:
tableView.superview?.addSubview(overlayView)

You can simplify a few things as well, and you should implement sizing control to handle changes such as device rotation:
let overlayView = EmptyCollectionView(frame: tableView.frame)

overlayView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

overlayView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.8)

tableView.superview?.addSubview(overlayView)


Q:

New opened window opens but closes immediately

I'm trying to download file from FTP using javascript, for which I created the following topic:

Is it possible to download file from FTP using Javascript?

From there I learned that I can use window.open('ftp://xyz.org/file.zip'); to download the file. It opens a browser new window, but the window closes immediately.
How I can I force it to stay open?
Actually I do all these in Silverlight application:
Here is the code:
HtmlPage.Window.Eval("window.open('" + url+ "', 'Download', 'height=500,width=800,top=10,left=10');");

I also tried this,
string targetFeatures = "height=500,width=800,top=10,left=10";
HtmlPage.Window.Navigate(new Uri(url), "_blank", targetFeatures);

But both results in same : it opens a window, and closes it immediately. I see it just for fraction of second!

A:

I know this doesn't answer your question, and I'm sure you know all of this.  I'm answering more because I don't see this point brought up often. :)
Silverlight has very limited support for client interactions.  Javascript is a shim that in my opinion gets overused to try and bypass things that Silverlight was architectured against.  It would have been very easy for Microsoft to include FTP support in Silverlight but it was excluded for a reason.
However, Silverlight has great support for webservice interactions.  So the recommended way of getting a file would be to call a webservice that would do the FTP transfer for you and then send the contents down to the Silverlight application via the webservice. Possibly even processing it on the webservice side for any business logic etc.
Like I said, I suspect your requirement is to not use a webservice (to pass the bandwith cost onto the user most likely).  But it'd be interesting to know more about your business problem instead of your technical problem for the solution you've chosen.


Q:

What's the deal with Shinobu's hat?

Shinobu originally didn't have a hat, but in Nekomonogatari Black, Shinobu ask Oshino to buy her that hat, he gave it to her as a reward since she was the one who resolved the problem with Black Hanekawa. But since she live in Araragi's shadow, she started to talk more and didn't wear that hat anymore, any specific reason why is that?
Shinobu in Nekomonogatari (Black), Bakemonogatari and in Nisemonogatari:

A:

This is off the top of my head, so I could be barking mad, but this is how I remember it. Spoilers for Kizumonogatari, Nekomonogatari Black, and Nisemonogatari ahead.
Shinobu, in Kizu, tells Koyomi that head-patting is some kind of intimate act of subservience between a vampire servant and master. Koyomi thinks this is a little weird, but goes along with it.
At the end of Kizu, Tsubasa deduces that Shinobu wanted to die the whole time. Koyomi refuses to grant her this, and instead brings about the situation where he's an asymptotically human pseudo vampire and Shinobu is a mostly powerless asymptotically vampiric pseudo human who has to suck Koyomi's blood to survive. Shinobu is furious, and doesn't talk to Koyomi until Karen Bee.
In Neko Black, Shinobu helps defeat Black Hanekawa. Afterwards, Koyomi goes to pat her on the head as a reward, but finds that she's wearing that strange pilot hat. She got the hat to show Koyomi that she was still pissed at him and wasn't going to let him pat her on the head.
Later, in Tsubasa Cat, Shinobu stops being angry at Koyomi and starts living in his shadow. In Karen Bee, she even comes out to talk to him when he's in the bath. Since she's not mad at him anymore, she stops wearing the hat, since she doesn't need to stop him from patting her head.
Edit: Now with actual evidence.
Kizumonogatari, Chapter 4 establishes that head-rubbing is regarded by Shinobu as a sign of obedience. Koyomi has just allowed Shinobu to turn him into a vampire, and Shinobu has asked him if he understands that he must be subservient to her. The first to speak is Koyomi.

“Ha, haa”
“Huh, an ambiguous answer——do you really understand?”
“Um, umm——I understand.”
“Then as a sign of obedience to me, rub my head!”
She said majestically.
....
Rub head.
Uwa, her hair is really soft.
Although there is a lot of hair, it‘s really smooth.
“That‘s enough.”
“....That‘s the sign of obedience?”
“You don't know that?”
She looked at me with contempt.
Vampires use a different set of rules.

Here's Nekomonogatari Black, Chapter 13, where Koyomi goes in to thank Shinobu for her help and finds her wearing the hat. Oshino also tells Koyomi that he gave her the hat. I massaged out some of the grammar mistakes in the translation.

I even wanted to stroke her head.
The sign of obedience—though I wouldn't call it that.
Still, I thought she could let me do at least that—I thought she
  would certainly let me thank her.
“............”
My expectation was largely unfulfilled.
The sense of omnipotence of the look from above in epilogues didn't
  apply here.
As I arrived and met her in the classroom on the first floor, the
  little vampire girl was wearing, of all things, an enigmatic helmet
  with goggles, of the type you wear when riding a moped.
I couldn't stroke her head like this.
“Ah, that? Vampire-chan badgered me about it. After all she is
  the one who solved the whole cat thing, so I gave it to her as a
  prize”
Oshino explained.

The quotes don't explicitly say that Shinobu was wearing the hat to stop Koyomi from rubbing her head, but it seems pretty plain from the context. It was her way of telling Koyomi, without deigning to speak to him, that she hadn't forgiven him.


Q:

Python - Can't change value of item inside a class

I am new to Python, and don't understand why I can't do this.
When I try to change the values in Packet.ItemData from the parent object, it doesn't work. See the "Doesn't work" comments in the code.
import json
from copy import deepcopy

class Event():
    __slots__= 'itemName'

    def __init__(self, itemName):
        self.itemName = itemName

    def encode(self):
        obj = {}
        obj['itemName'] = str(self.itemName)
        return json.dumps(obj)

    def decode(self, json_Str):
        obj = json.loads(json_Str)
        self.itemName = obj['itemName']

class Packet():
    __slots__= 'pID', 'itemData'

    def __init__(self, pID, itemData):
        self.pID = pID
        self.itemData = itemData

    def encode(self):
        obj = {}
        obj['pID'] = int(self.pID)
        obj['itemData'] = str(self.itemData.encode())

        return json.dumps(obj)

    def decode(self, json_Str):
        obj = json.loads(json_Str)
        self.pID = obj['pID']
        self.itemData = Event(0,'')

defaultEvent = Event('Dflt')
defaultPacket = Packet(1, defaultEvent)

event2 = Event('NoName')
print 'event : ', event2.encode()
packet3 = deepcopy(defaultPacket)
packet3.ItemData = event2; #direct assign doesn't work
packet3.ItemData = deepcopy(event2); #deep copy doesn't work
packet3.ItemData.itemName = 'Hello' #event this doesn't work
print 'packet : ', packet3.encode()

I wanted to wrap up the data so I get exactly what I am expecting when encoding and decoding from JSON.

A:

What FJ pointed out is indeed correct...the name of the attribute is itemData not ItemData.
Being new to Python you may have expected that typo to throw an error...something like 'Packet has no attribute ItemData', but this does not happen. Python classes by default store attributes in a dictionary, so assigning to one that did not exist previously is just like adding a new mapping to the dictionary.
Curiously, your code in a roundabout way highlights an exception to this...and that has to do with the descriptor __slots__. __slots__ changes the class to no longer store attributes in a dynamic dictionary, but in a static structure instead. See Usage of __slots__? for more info.
Normally, when __slots__ is defined you can not assign to an attribute that wasn't specified in __slots__. So you may ask....since you defined __slots__ for your classes why didn't you get an AttributeError? The answer is __slots__ will only work for 'new-style classes' See What is the difference between old style and new style classes in Python? to learn about the distinction between old and new-style classes.
Had you defined Packet to inherit from the base class object like class Packet(object): instead of just class Packet() it would have made it a new-style class and you would have indeed gotten an AttributeError when you tried to assign to ItemData


Q:

Is it possible to extract sub-pictures from a master-picture with gimp scripting

I have the following Picture:

And you guessed it: I want to extract all the little pictures into separate files. What I want to now:

Is it possible to do this with one of Gimps scripting interfaces?
Would you use “Batch-Mode”, “Script-Fi”, “Plug-ins” or something else I am not aware of?
If yes: I have no experience with Gimp scripting: How much effort will it be to learn the needed skills?

Of course any additional pointers will be greatly appreciated.

A:

One of the best ways to script GIMP is using the Python language - so that you have full acess to any other resources Python can tap, in addition to GIMP's API
In the case above, I'd proceed to place image guides over the grid lines,  then using the "slice"  plug-in- it will generate a GIMP image for each table cell. Then use Python, could even be the interactive console, to loop through the images and perform extra operations (like saving) on them.
To see what can be done melodramatically in GIMP, check the help->Procedure Database menu entry.
If you don't have a "filters->python-fu" menu entry, you gave to install the GIMP-Python environment. For Linuxes it is available as a separate package, For windows, you will have to google for it, as it requires the install of 3 or 4 different components in the correct order. (Hopefully when GIMP 2.8 - the next version  is out - th Python environment will come built-in on windows installs)


Q:

What is more natural answer?

I just got a question from native speaker.
the question is like this.
When did you first driving?

1.To get a driver licence at driving school, that is my first driving."
  2.The first time I drove was at driving school, to get a driver's license.

What if you have felt #2, I am not familiar at subject sentence as beginner.
so would you please more English? Please don't remove or hide.
if you felt well #1. How can I improve the sentence?
When did you first on trip?

3.When I went to Hong Kong at honeymoon, that's my first trip.  4.My first trip was when I went of Hong Kong on my honeymoon.

Also this, please do same above.
Even you can improve 1~4, please let me know your idea.
updated: is this right?
The first time <(when) I drove> was at [driving school].
(=)
The first time was at driving school.
(+)
I drove for the first time.

A:

Your sentence #2 is fine. Here is an alternative.
The first time I drove was at driving school, when I was getting my driver's license.


Q:

I cannot log in on stackexchange.com

When I try to log in with my email, I get this error:
My email is a Gmail one. When I try to log in using Google, I get this error:
When I try to create an account, I get this error:
I maintain active profiles on several stackexchange sites such as mathematics: https://math.stackexchange.com/users/469826/dapianoman
I suspect that different sites have different password requirements and this may have something to do with my error. When I try to create an account on stackexchange.com with the same login and password credentials I use on math.stackexchange.com, I get a notification that the password is not secure enough.

A:

It looks like you also have two distinct accounts with two distinct sets of credentials. Somehow se.com has got its wires crossed and thought the se.com profiles for both belonged to the same account id. I fixed that up, so you should be able to log in there now.


Q:

How to pick out specific parts of a list?

So I have this list:
Comps = [
    [1000, 500, 200, 100, 700, 350, 120, 900, 800],
    [1001, 501, 201, 101, 701, 351, 121, 901, 801]
    ]

How would I get the results [500, 350, 120] and [501, 351, 121] from this list?
I know how to get the answer [500, 350, 120] if there was only the first list (which would be [1000, 500, 200, 100, 700, 350, 120, 900, 800]) in the variable Comps. However, I am not sure how to work with a list that contains 2 or more lists (also known as "list of list"). I keep getting the error: "IndexError: list index out of range".
What I've done is this:
print(list(Comps[i] for i in [1, 5, 6]))

Here is the full error for those who are interested:
    Traceback (most recent call last):
  File "<pyshell#74>", line 1, in <module>
    print(list(Comps[i] for i in [1, 5, 6]))
  File "<pyshell#74>", line 1, in <genexpr>
    print(list(Comps[i] for i in [1, 5, 6]))
IndexError: list index out of range

A:

The reason you get a IndexError: list index out of range is that Comp is a list with only 2 elements. Element at index 1 is the second list ([1001, 501, 201, 101, 701, 351, 121, 901, 801]) but there's no element at index 5 in Comps.
You could use a nested list comprehension:
>>> Comps = [[1000, 500, 200, 100, 700, 350, 120, 900, 800], [1001, 501, 201, 101, 701, 351, 121, 901, 801]]
>>> [[l[i] for i in [1, 5, 6]] for l in Comps]
[[500, 350, 120], [501, 351, 121]]

If you want them in a flat list:
>>> [l[i] for l in Comps for i in [1, 5, 6]]
[500, 350, 120, 501, 351, 121]

If you work with matrices and arrays, you might want to take a look at numpy:
import numpy as np
comps = np.array([[1000, 500, 200, 100, 700, 350, 120, 900, 800], [1001, 501, 201, 101, 701, 351, 121, 901, 801]])
comps[:,[1, 5, 6]]
# array([[500, 350, 120],
#       [501, 351, 121]])

If you only want one of them:
>>> [Comps[0][i] for i in [1, 5, 6]]
[500, 350, 120]
>>> [Comps[1][i] for i in [1, 5, 6]]
[501, 351, 121]

And with NumPy:
>>> comps[0, [1, 5, 6]]
array([500, 350, 120])
>>> comps[1, [1, 5, 6]]
array([501, 351, 121])


Q:

How to limit a multiple selection of a

I want to limit a multiple selection to 1, because I want this format of list. I want to see all list always and don't want a dropdown list, and If I quit multiple="multiple" apears a dropdown list.
So, this is the code:
gsp:
<div class="field ${hasErrors(bean: cmd, field: 'subtypes', 'error')}">
    <label for="subtypes">
        <g:message code="requestSRO.requestSubtype.label"/>
    </label>
    <g:select name="subtypes" from="${requestSubtypes}" optionKey="code" multiple="multiple" optionValue="description" value="${cmd?.subtypes}" style="width: 100%;height: 100px" disabled="${!requestSubtypes ? true: false}"/>
</div>

I think <g:select> doesn't have a property to set the max limit of selections.

A:

Don't use multiple="multiple" to change the way the select is displayed. Instead, set the size attribute to a number greater than 1.
<g:select size="2" name="subtypes" from="${requestSubtypes}" optionKey="code" optionValue="description" value="${cmd?.subtypes}" style="width: 100%;height: 100px" disabled="${!requestSubtypes ? true: false}"/>

If you want to display the entire list of subtypes, you could set size="${requestSubtypes.size()}".


Q:

Right rotation on array in php

I have an array for example
$a = [1,2,3,4,5];

From this $a, how to take last one and set it first like [5,1,2,3,4]
And how do I take last two arrays to make it like [4,5,1,2,3]

A:

You can combine using array_pop(), which pops the last element of the array out, and array_unshift() to push it to the front of the array. You can create a simple function for this,
function array_pop_unshift($array) {
    array_unshift($array, array_pop($array));
    return $array;
}

Then use it as
$a = [1,2,3,4,5];
$new = array_pop_unshift($a);
print_r($new); // [5,1,2,3,4]

To continue shifting it, just call the function again until you're done, for instance through a for loop,
$a = [1,2,3,4,5];
for ($i = 0; $i < 2; $i++) {
    $new = array_pop_unshift($a);
}
print_r($new); // [4,5,1,2,3]

Live demo at https://3v4l.org/CoJZZ


Q:

Writing code in terminal mode?

I have to write shell code in terminal mode on Ubuntu. I already have the code and it does what it's supposed to, but I don't know how to write it in terminal mode. I am not allowed to use text editors. Below is the code which does what it is suppose to do.
echo "Part 2 of program"

while true
do
read FIRSTNUMBER
read SECONDNUMBER
if [ $FIRSTNUMBER -eq 99 ] || [ $SECONDNUMBER -eq 99 ]; then
    echo "You have exited part 2 of the program"
break;
elif [ $SECONDNUMBER -eq 0 ]; then
    echo "The number must not be 0"

else
    math=$((FIRSTNUMBER / SECONDNUMBER))
    echo "$FIRSTNUMBER DIVIDED BY $SECONDNUMBER = $math"
fi
done

Now I have to create a file and write the code all in terminal mode. Again, I cannot use a text editor. I know how to create a file in terminal mode. However, I do not know how i am supposed to write code on terminal mode without using a text editor. I am supposed to append this code onto a file. Thanks for your help.

A:

This seems like a very artificial restriction, however, for such tasks you can use.
cat > filename.txt

Type or paste (ctrl-shift-v) it in, then press ctrl-D when you're finished. You can use sed -i to correct your typos (unless that's also considered a text editor).
Alternatively, you could host the text somewhere online and use wget or curl to download it.
It's either coming from the keyboard or the net, so those are your options.


Q:

Anyone able to configure a MULTI VM cluster on a single laptop?

Has anyone been able to configure a 2 (or 3) node 3 CDH 4.1 cluster on 1 laptop.
The laptop is connected to the internet via WiFi and the VMs (VirtualBox, CentOS7) are configured to use bridged network. Each VM has a dedicated IP address and they can ping each other, they can ping the host, and they can connect to the internet.
I installed the software using these commands
systemctl disable firewalld.service
reboot
chmod 755 jdk-6u45-linux-x64-rpm.bin
./jdk-6u45-linux-x64-rpm.bin
wget http://archive.cloudera.com/cdh4/redhat/6/x86_64/cdh/cloudera-cdh4.repo
cp cloudera-cdh4.repo /etc/yum.repos.d/
rpm --import http://archive.cloudera.com/cdh4/redhat/6/x86_64/cdh/RPMGPG-KEY-cloudera
yum install hadoop-hdfs-namenode
yum install hadoop-hdfs-journalnode
yum install zookeeper-server
yum install hadoop-hdfs-zkfc
service zookeeper-server init --myid=1
yum install zookeeper-server
service zookeeper-server start

you can see that I have disabled the firewall. However in the zookeeper.log I can see
2014-07-18 17:56:29,910 [myid:1] - WARN [WorkerSender[myid=1]:QuorumCnxManager@368] - Cannot open channel to 2 at election address nn2.abhishek.com/192.168.1.31:3888
java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectOne(QuorumCnxManager.java:354)
at org.apache.zookeeper.server.quorum.QuorumCnxManager.toSend(QuorumCnxManager.java:327)
at org.apache.zookeeper.server.quorum.FastLeaderElection$Messenger$WorkerSender.process(FastLeaderElection.java:393)
at org.apache.zookeeper.server.quorum.FastLeaderElection$Messenger$WorkerSender.run(FastLeaderElection.java:365)
at java.lang.Thread.run(Thread.java:662)
2014-07-18 17:56:29,911 [myid:1] - WARN [WorkerSender[myid=1]:QuorumCnxManager@368] - Cannot open channel to 3 at election address jt1.abhishek.com/192.168.1.32:3888
java.net.NoRouteToHostException: No route to host
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at org.apache.zookeeper.server.quorum.QuorumCnxManager.connectOne(QuorumCnxManager.java:354)
at org.apache.zookeeper.server.quorum.QuorumCnxManager.toSend(QuorumCnxManager.java:327)
at org.apache.zookeeper.server.quorum.FastLeaderElection$Messenger$WorkerSender.process(FastLeaderElection.java:393)
at org.apache.zookeeper.server.quorum.FastLeaderElection$Messenger$WorkerSender.run(FastLeaderElection.java:365)
at java.lang.Thread.run(Thread.java:662)

Somehow I have a feeling that the CDH cannot be installed in this way and specially needs an enterprise setup where there is router and lan etc.
Has anyone been able to install CDH 4.1 on one laptop and 2 VMs? were you able to start zookeeper server?
Please help me out here.

A:

I solved the problem myself.
I had to do the following on all the VMs.
systemctl disable firewalld.service
systemctl stop firewalld.service

I think on one of the machines the firewall was still running.
A good way to troubleshoot this problem is that from every machine you try to do this to all other machines
nc machine.domain.com 3888
if this is working then it means that traffic can flow. In my case, the ping was working but the nc was not.


Q:

Is it safe to change the lens on my new DSLR?

I recently bought myself a shiny new DSLR camera. Before I can use it, I had to do something kind of terrifying: mount the lens.
Now of course, half the advantage of SLR cameras is that the lenses are interchangeable. But sitting there holding an extremely expensive brand new camera and staring into its bare innards, I'm just terrified that if I make one wrong move, a hair or a piece of dust could fall in there, and then the camera will be irreparably damaged and I'll never be able to use it again.
This might sound like a stupid question, but… is it actually “safe” to change the lens on the camera? Is this likely to destroy it?
(Obviously it goes without saying that you should limit the time spent with no lens attached to the minimum number of seconds possible. But even if you have lightning fingers, the camera will still be lenseless for some number of seconds. And it's not like I'm standing in a class 100 cleanroom here! Besides, you don't want to be too rough with the delicate lens mounting either…)

A:

I'm just terrified that if I make one wrong move, a hair or a piece of dust could fall in there, and then the camera will be irreparably damaged and I'll never be able to use it again.

Fear not, young Padawan. Those of us who regularly use dSLRs can attest that simply having dust or hair fall into your dSLR body will NOT irreparably damage anything, and you can even get the dust/hair back out again with simple methods like a bulb blower, or more complex ones involving the arcane methods of sensor cleaning. But dust on the sensor is usually just something you deal with on a regular basis.
A few facts to ease your mind.

The sensor is not exposed when your camera body has no lens on it. A dSLR uses a mirror to take the light coming in from the lens and throw it up into the viewfinder.  When you take a picture, the mirror flips up, to let the light go through to the sensor. But at all other times, that mirror is covering your sensor. You're really only exposing the guts of the camera when changing lenses, if you shoot mirrorless.
Your sensor is also covered by a glass filter. This filter serves several purposes, including filtering out ultraviolet and infrared light to keep them from throwing the colors off on your sensor (which is sensitive past the visible spectrum). But it also protects the sensor. When you "clean the sensor", you're not actually touching it, you're cleaning the glass filter over the sensor.
Your camera, if it's not just brand new to you, but also a relatively new model, probably has sensor shake technology that effectively clears most dust/hairs off the sensor before taking a shot.  You also typically don't see debris on the sensor unless you're shooting stopped down into the f/8 and smaller range, because it's out of focus to the sensor otherwise.
Your brand new shiny shiny camera probably came with a body cap. You can use that to protect the guts of your camera until you're ready to actually mount the lens.  There are also tricks and techniques you can pick up (i.e., turning off the camera, holding it face down so dust falls out, not in, changing the lens in the bag, etc.) to minimize crap getting in while you swap out lenses.

I live in Southern California, where the weather is typically dry, and wet dust doesn't weld itself onto sensors, and I change lenses with wild abandon all the time. I don't do any of the "best practices" methods--I just use a body cap if I think I'm going slow and fumbly while juggling lenses. And I mostly shoot mirrorless these days.
It's basically nothing to worry about, really.  It just takes time and practice and putting behind you the big dent you put in your wallet when you bought the gear, and starting to get to know it as tools. Take a deep breath, screw that lens on, and get started clicking. The more times you do it, the less frightening it becomes.

A:

This might sound like a stupid question, but… is it actually “safe” to change the lens on the camera? Is this likely to destroy it?

Changing lenses is quite safe for your camera, less so for your wallet.
Once you see what your camera can do with different lenses, you'll want to start a small collection. Some lenses, like a typical 50mm f/1.8, are very affordable -- $100-$150 -- and quite good. Do not be taken in. These lenses are the gateway drug of photography! Before you know it, you'll be looking at $600 and $800 and $1200 lenses thinking: Yes, it's a lot of money, but my god look at that bokeh! Companies like lensrentals.com and borrowlenses.com will promise to keep your costs down, but they only feed the addiction.
It's not even just the lenses... if you're carrying a DSLR and a couple of lenses, you're going to need something to carry them in, right? How many of the regulars around Photo.SE do you suppose own fewer than three camera bags? That's right: none of them.
Also, under no circumstances should you consider mounting a Speedlight (or a Speedlite, depending on which team you play for) on your camera. Again, it won't hurt the camera a bit, but it'll lead you down a rabbit hole from which you may never escape. Shortly after you put the flash on your camera, someone is bound to show you how much better your shots will look if you take the flash off your camera. And if you happen to have two or three instead of just one... Don't even think about visiting strobist.com unless you have space in your life for a dozen umbrellas and a million AA batteries.
I'm glad you asked this question at a point where there's still time for early intervention. More often, we get people showing advanced symptoms, like Should I buy the carbon fiber tripod legs, or settle for aluminum and invest that money in an Arca-Swiss geared head? or Now that I've moved up to a 50Mpx sensor, don't I need do buy all new lenses (please say yes)? Thankfully, you have time to kick this habit before it becomes a real problem.
Just turn that mode selector dial to the green setting and pretend that lens is fused to the camera body...

A:

Funny question :) but I can see where you're coming from.
Yes, it's safe to change the lens! It becomes a very quick process once you've done it a few times. At the same time, don't fret about getting it done in the minimum number of seconds.
Some people insist that you should hold the camera with the lens mount facing the ground, but my personal opinion is just change the lens with reasonable care and you'll be fine. This is a procedure that the camera and lens are explicitly designed for - it's not like you're doing something that voids your warranty! Just don't do it at the beach or in a very windy environment, etc - at least not without taking proper precautions first.
If your sensor eventually needs to be cleaned, so be it - that's also a relatively painless process.
Enjoy the world of interchangeable lenses!


Q:

Elastic Beanstalk won't find/use my requirements.txt file and so it cannot find the module "django"

I'm trying to deploy a python web app using django and have successfully setup the EB environment but for some reason, it's not using my requirements.txt file to install the required modules (django and pytz). I see no reference to an invalid requirements.txt so I don't think that's the issue. Here is a file hierarchy and the latest log.
FirstWebApp/
    .elasticbeanstalk/
        config.yml
    mysite/
        #..
    polls/
        #..
    db.sqlite3
    manage.py
    requirements.txt

[Sat Sep 01 21:08:01.508757 2018] [mpm_prefork:notice] [pid 7866] AH00169: caught SIGTERM, shutting down
[Sat Sep 01 21:08:02.599699 2018] [suexec:notice] [pid 11160] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[Sat Sep 01 21:08:02.615594 2018] [so:warn] [pid 11160] AH01574: module wsgi_module is already loaded, skipping
[Sat Sep 01 21:08:02.617699 2018] [http2:warn] [pid 11160] AH10034: The mpm module (prefork.c) is not supported by mod_http2. The mpm determines how things are processed in your server. HTTP/2 has more demands in this regard and the currently selected mpm will just not do. This is an advisory warning. Your server will continue to work, but the HTTP/2 protocol will be inactive.
[Sat Sep 01 21:08:02.617712 2018] [http2:warn] [pid 11160] AH02951: mod_ssl does not seem to be enabled
[Sat Sep 01 21:08:02.618263 2018] [lbmethod_heartbeat:notice] [pid 11160] AH02282: No slotmem from mod_heartmonitor
[Sat Sep 01 21:08:02.618326 2018] [:warn] [pid 11160] mod_wsgi: Compiled for Python/3.6.2.
[Sat Sep 01 21:08:02.618331 2018] [:warn] [pid 11160] mod_wsgi: Runtime using Python/3.6.5.
[Sat Sep 01 21:08:02.620634 2018] [mpm_prefork:notice] [pid 11160] AH00163: Apache/2.4.33 (Amazon) mod_wsgi/3.5 Python/3.6.5 configured -- resuming normal operations
[Sat Sep 01 21:08:02.620651 2018] [core:notice] [pid 11160] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'
[Sat Sep 01 21:08:05.381076 2018] [:error] [pid 11165] [remote 127.0.0.1:0] mod_wsgi (pid=11165): Target WSGI script '/opt/python/current/app/mysite/wsgi.py' cannot be loaded as Python module.
[Sat Sep 01 21:08:05.381116 2018] [:error] [pid 11165] [remote 127.0.0.1:0] mod_wsgi (pid=11165): Exception occurred processing WSGI script '/opt/python/current/app/mysite/wsgi.py'.
[Sat Sep 01 21:08:05.381287 2018] [:error] [pid 11165] [remote 127.0.0.1:0] Traceback (most recent call last):
[Sat Sep 01 21:08:05.381309 2018] [:error] [pid 11165] [remote 127.0.0.1:0]   File "/opt/python/current/app/mysite/wsgi.py", line 12, in <module>
[Sat Sep 01 21:08:05.381313 2018] [:error] [pid 11165] [remote 127.0.0.1:0]     from django.core.wsgi import get_wsgi_application
[Sat Sep 01 21:08:05.381326 2018] [:error] [pid 11165] [remote 127.0.0.1:0] ModuleNotFoundError: No module named 'django'
[Sat Sep 01 21:08:06.384353 2018] [:error] [pid 11165] [remote 127.0.0.1:252] mod_wsgi (pid=11165): Target WSGI script '/opt/python/current/app/mysite/wsgi.py' cannot be loaded as Python module.
[Sat Sep 01 21:08:06.384403 2018] [:error] [pid 11165] [remote 127.0.0.1:252] mod_wsgi (pid=11165): Exception occurred processing WSGI script '/opt/python/current/app/mysite/wsgi.py'.
[Sat Sep 01 21:08:06.384505 2018] [:error] [pid 11165] [remote 127.0.0.1:252] Traceback (most recent call last):
[Sat Sep 01 21:08:06.384528 2018] [:error] [pid 11165] [remote 127.0.0.1:252]   File "/opt/python/current/app/mysite/wsgi.py", line 12, in <module>
[Sat Sep 01 21:08:06.384531 2018] [:error] [pid 11165] [remote 127.0.0.1:252]     from django.core.wsgi import get_wsgi_application
[Sat Sep 01 21:08:06.384560 2018] [:error] [pid 11165] [remote 127.0.0.1:252] ModuleNotFoundError: No module named 'django'
[Sat Sep 01 21:08:07.387609 2018] [:error] [pid 11165] [remote 127.0.0.1:2304] mod_wsgi (pid=11165): Target WSGI script '/opt/python/current/app/mysite/wsgi.py' cannot be loaded as Python module.
[Sat Sep 01 21:08:07.387656 2018] [:error] [pid 11165] [remote 127.0.0.1:2304] mod_wsgi (pid=11165): Exception occurred processing WSGI script '/opt/python/current/app/mysite/wsgi.py'.
[Sat Sep 01 21:08:07.387725 2018] [:error] [pid 11165] [remote 127.0.0.1:2304] Traceback (most recent call last):
[Sat Sep 01 21:08:07.387744 2018] [:error] [pid 11165] [remote 127.0.0.1:2304]   File "/opt/python/current/app/mysite/wsgi.py", line 12, in <module>
[Sat Sep 01 21:08:07.387748 2018] [:error] [pid 11165] [remote 127.0.0.1:2304]     from django.core.wsgi import get_wsgi_application
[Sat Sep 01 21:08:07.387761 2018] [:error] [pid 11165] [remote 127.0.0.1:2304] ModuleNotFoundError: No module named 'django'
[Sat Sep 01 21:08:08.390656 2018] [:error] [pid 11165] [remote 127.0.0.1:2304] mod_wsgi (pid=11165): Target WSGI script '/opt/python/current/app/mysite/wsgi.py' cannot be loaded as Python module.
[Sat Sep 01 21:08:08.390700 2018] [:error] [pid 11165] [remote 127.0.0.1:2304] mod_wsgi (pid=11165): Exception occurred processing WSGI script '/opt/python/current/app/mysite/wsgi.py'.
[Sat Sep 01 21:08:08.390770 2018] [:error] [pid 11165] [remote 127.0.0.1:2304] Traceback (most recent call last):
[Sat Sep 01 21:08:08.390790 2018] [:error] [pid 11165] [remote 127.0.0.1:2304]   File "/opt/python/current/app/mysite/wsgi.py", line 12, in <module>
[Sat Sep 01 21:08:08.390793 2018] [:error] [pid 11165] [remote 127.0.0.1:2304]     from django.core.wsgi import get_wsgi_application
[Sat Sep 01 21:08:08.390807 2018] [:error] [pid 11165] [remote 127.0.0.1:2304] ModuleNotFoundError: No module named 'django'

A:

I just had to commit the requirements.txt file. Django only looks at whatever files have been committed.


Q:

Empty data from a successful authentication using Windows.Security.Authentication

I am upgrading my app from windows 8.1 to windows 10 UWP.  Previously  I was using the Windows.Live API to obtain information about the user including a token that I would pass to the MobileService.LoginAsync Method.  This all had to be scrapped in favor of using windows.security.authentication.  Unfortunately, after the use of the code below, a successfull SSO token request results in an object that is missing most of the data that I need.  For now, just getting a username would be nice, I can expand from there.  Here is the code that I am having issues with...breakpoint set at the end of the if statement reveals the empty account.username field.
string accessToken = "";
        WebAccountProvider wap = await WebAuthenticationCoreManager.FindAccountProviderAsync("https://login.microsoft.com", "consumers");
        WebTokenRequest wt = new WebTokenRequest(wap,"wl.signin", "none");
        WebAccount account;
        WebTokenRequestResult wtrr = await WebAuthenticationCoreManager.RequestTokenAsync(wt);

        if (wtrr.ResponseStatus == WebTokenRequestStatus.Success)

        {

            accessToken = wtrr.ResponseData[0].Token;

            account = wtrr.ResponseData[0].WebAccount;

            var properties = wtrr.ResponseData[0].Properties;

        }

A:

For now, just getting a username would be nice.

If you want to get the user name with WebAuthenticationCoreManager. You can try with following code:
private async void GetMsaTokenAsync(WebAccountProviderCommand command)
{
    WebTokenRequest request = new WebTokenRequest(command.WebAccountProvider, "wl.basic");
    WebTokenRequestResult result = await WebAuthenticationCoreManager.RequestTokenAsync(request);

    if (result.ResponseStatus == WebTokenRequestStatus.Success)
    {
        string token = result.ResponseData[0].Token;

        var restApi = new Uri(@"https://apis.live.net/v5.0/me?access_token=" + token);

        using (var client = new HttpClient())
        {
            var infoResult = await client.GetAsync(restApi);
            string content = await infoResult.Content.ReadAsStringAsync();

            var jsonObject = JsonObject.Parse(content);

            string username = jsonObject["name"].GetString();
        }
    }
}

Using WebAccount.UserName property may not get user's name. But once you have the access token, you can use it to call the Microsoft Live APIs to obtain basic information about the user. For more info, please see Use the token in Connect to identity providers with Web Account Manager.

Additionally...the token received from this response returns "unauthorized" when used with MobileService.LoginWithMicrosoftAccountAsync(accessToken).

This is because the token you've got above is an access token. However, The LoginWithMicrosoftAccountAsync method needs an authentication token.

Parameters
thisClient

Type: Microsoft.WindowsAzure.MobileServices.MobileServiceClient
    The client with which to login.

authenticationToken

Type: System.String
    Live SDK session authentication token.

If you want to authenticates the user with Microsoft Account, you can use service-directed authentication by calling LoginAsync method like following:
var user = await MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);

For more info, please see Add authentication to the app.


Q:

Having trouble understanding sequence diagrams

I've been looking the past few days at several UML tutorials, but I'm having a hard time understanding UML sequence diagrams. From a quick glance and run through the guides it all appears to be fairly straightforward, but when I view the provided examples it kind of gets confusing real quick.
I'm currently trying to prepare the sequence diagram for my PHP website system which has functions such as login, register and private messaging. Each of these are essentially use cases which means each one requires its own sequence diagram, correct? Or are sequence diagrams supposed to show the entire system in one diagram? A lot of the examples I find appear to cover the whole system in one shot, though with so many functions I don't know how that can be done in one diagram.
I've prepared 2 simple ones so far of the login and registration:
Use case 1

Use case 2

A:

Each UML diagram puts an emphasis on a system aspect (in content and form) and abstract other aspects away. You should learn this, in order to decide which diagram to use in which situation, how many of them and how. A great, creative part of system modelling.
In case of sequence diagram, it is a behavior diagram, that shows concrete, straightforward scenarios putting emphasis on the collaborating objects and messages they exchange during the implementation of a scenario.
Although a sequence can show the conditional flow and decision (like in your example, user and pass check) it is not its strength, since is breaking its natural straight time line of events.
So, each use case would theoretically have several sequence diagrams, one for each scenario. However, you should think well if it makes sense do make each sequence, because most of them are trivial. You should concentrate on meaningful scenarios, somehow interesting, that bring value to somebody.
At the end, I would suggest you to also see activity diagram, as it is nicely complementary to sequences. Also behavior, but focused on the sequence of tasks, decisions (a weak point of sequence), paralel tasks, responsabilities and data flows.
One activity can cover several sequences, from another point of view. These are much more clear to non-technical people (customers, users), while sequence is of more use to developers, architects, etc.
Mostly, the combination of several diagrams gives the best results. Sequences naturally need a structural "companion" to define the objects that participate in the scenario: components, domain classes, or similar.


Q:

ngx-charts library: How to change space between y-axis and first group in bar chart

I am working with ngx-charts trying to vizualise some data in a combo-chart of barcharts and line charts. I have most issues worked out, but I cannot figure out what I should change in my code to control the space between the y-axis of my chart, and the initial group in my barchart.
I was wondering has anyone that has worked with ngx-charts before encountered this, and hopefully solved the issue? If anyone knows if this could be a variable set anywhere, the insight would be greatly appreciated.
gap between y-axis and data
Edit: Adding another image to show that this is not an issue with missing data, as on another graph of mine the spacing is equal from both ends.
Equal gap from both y-axes

A:

Answering for myself:
So I've been continuing to have a look myself throughout the day, and I've found a solution. Perhaps not a permanent solution, or even a good solution, but it turns out to have something to do with some transform scss that is being injected into the graph components encountering issues. It seems to be baked into the code from the chart library.
For the moment, which may be a temporary fix for someone else, I have added an extra attribute to my components that are effected such as:
<my-component [attr.transform]="customTransform">

defined 'customTransform' as a string with component scope, and made its value:
this.customTransform = `translate(-35 , 0)`;


Q:

How can i develop Augmented Reality application by using Android SDK?

I want to develop Augment Reality application by using Android SDK. but i have serched a lot i didn't get any good information. what i have learned after searching, by using thirdparty tools we can develop Augmented Reality apps for Android. is this correct? otherwise Plase correct me.
Thanks,
pavan.

A:

See the example here in AndAr project.


Q:

A Hahn-Banach extension problem

Suppose $(X,\Vert\cdot\Vert_X)$ is a Banach space, $Y$ is a subspace of $X$ such that $Y^\perp = \{0\}$, and suppose $Y$ is endowed with its own norm $\Vert\cdot\Vert_Y$ such that $B_Y \subsetneq B_X \cap Y$, so that in particular $X^* \subset Y^*$. Let $M$ be a subspace of $X^*$ and $x \in X$ is such that $B_{Y^*} \cap M \subset x^{-1}(-1,1)$ (where $x$ is understood as a linear functional on $X^*$), can we then assert that there exists $y \in Y$ such that $\Vert y\Vert_Y \leq 1$ and $y|_M = x|_M$?
Thanks for any input.

A:

You can lift $x|_M$ to $Y^{**}$ but not necessarily to $Y.$ For a counterexample consider the embedding of $Y=C[0,1]$ in $X=L^1[0,1]$ with $M=X^*$ and $x=\tfrac 12 1_{[0,1/2]}.$ Functionals in $B_{Y^*}\cap X^*$ correspond to bounded functions with $L^1$ norm at most $1,$ so are in $x^{-1}(-1,1),$ but $x$ is not equal to anything in $Y.$


Q:

js, parse var back to its parent

i have two functions, the parent function is __triggerAction, than child function is __triggerNormal which the parent $current is being updated, how to parse the new
$current = $index

from __triggerNormal back to __triggerAction?
  _triggerAction = function(el, click, fx) {
    var $current, $link;
    $link = el.find('.tab-menu').find('li');
    $current = 0;
    if (click) {
      log('Trigger by click');
      return $link.click(function() {
        return __triggerNormal(this, el, $current, fx);
      });
    } else {
      log('Trigger by hover');
      return $link.hover(function() {
        return __triggerNormal(this, el, $current, fx);
      });
    }
  };

 __triggerNormal = function(thisEl, el, $current, fx) {
    var $index;
    if (!($(thisEl).hasClass("active"))) {
      log('current slide ' + $current);
      log($index = $(thisEl).index());
      __addRemoveClass(thisEl);
      __fxAction(el, fx, $current, $index);
      return $current = $index;
    }
};

A:

Instead of
return __triggerNormal(this, el, $current, fx);

do
$current = __triggerNormal(this, el, $current, fx);
return $current;

$current is not shared between the functions, so inside __triggerNormal,
return $current = $index;

just updates the local variable. You can just write
return $index;

Btw, the return value of event handlers is only used for determining whether to prevent the default action and stop the propagation or not. It does not seems to be necessary in your case to return $current at all.


Q:

Spring deployment-level configuration

When I wrote Java EE apps, I used JBoss Datasources to control which databases the deployment used. E.g. the dev versions would use a throwaway hibernate db, the ref and ops would use stable MySQL deployments. I also used MBeans to configure various other services and rules.
Now that I'm using Spring, I'd like the same functionality - deploy the same code, but with different configuration. Crucially, I'd also like Unit Tests to still run with stub services. My question is this - is there a way, in JBoss, to inject configuration with files which live outside of the WAR/EAR, and also include these files in test resources.

A:

It is possible to add objects into the JNDI context by placing a file named xxx-service.xml into jboss's deploy directory. The app could then lookup the values via JNDI. In the example below the string "development" is added at java:/modes/deployment. To use JNDI in your unit tests use the org.springframework.mock.jndi package.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE server PUBLIC "-//JBoss//DTD MBean Service 4.0//EN"
          "http://www.jboss.org/j2ee/dtd/jboss-service_4_0.dtd">
<server>
   <mbean code="org.jboss.naming.JNDIBindingServiceMgr"
         name="c3po.naming:service=jndi-bindings">
      <attribute name="BindingsConfig" serialDataType="jbxb">
         <jndi:bindings
            xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:jndi="urn:jboss:jndi-binding-service:1.0"
            xs:schemaLocation="urn:jboss:jndi-binding-service:1.0 resource:jndi-binding-service_1_0.xsd"
            >

            <jndi:binding name="java:/modes/deployment">
               <jndi:value type="java.lang.String">development</jndi:value>
            </jndi:binding>

            <jndi:binding name="java:/sites/abc">
               <jndi:value type="java.lang.String">dev.site.example.com</jndi:value>
            </jndi:binding>

<!-- Examples:

            <jndi:binding name="urls/jboss-home">
               <jndi:value type="java.net.URL">http://www.jboss.org</jndi:value>
            </jndi:binding>

            <jndi:binding name="hosts/localhost">
               <jndi:value editor="org.jboss.util.propertyeditor.InetAddressEditor">
                  127.0.0.1
               </jndi:value>
            </jndi:binding>

            <jndi:binding name="maps/testProps">
               <java:properties xmlns:java="urn:jboss:java-properties"
                  xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
                  xs:schemaLocation="urn:jboss:java-properties resource:java-properties_1_0.xsd">
                  <java:property>
                     <java:key>key1</java:key>
                     <java:value>value1</java:value>
                  </java:property>
                  <java:property>
                     <java:key>key2</java:key>
                     <java:value>value2</java:value>
                  </java:property>
               </java:properties>
            </jndi:binding>
-->

         </jndi:bindings>
      </attribute>
      <depends>jboss:service=Naming</depends>
   </mbean>

</server>


Q:

Disable clicking through other controls - WPF

I have Simple application.

<Window x:Class="WpfControlReview.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Height="120" Width="277" ResizeMode="NoResize">
    <Grid>
        <Button HorizontalAlignment="Stretch" Name="button1" VerticalAlignment="Stretch" HorizontalContentAlignment="Center" Click="button1_Click">
        <StackPanel HorizontalAlignment="Stretch" Name="stackPanel1" VerticalAlignment="Stretch" Orientation="Vertical">
            <Label IsHitTestVisible="False" Content="Select your options and press to commit" Name="label1" HorizontalContentAlignment="Center" FontSize="12" />
            <StackPanel Name="stackPanel2" Orientation="Horizontal">
                <Expander Header="Color" x:Name="expander1"/>
                <Expander Header="Make" x:Name="expander2"/>
                <Expander Header="Payment" x:Name="expander3"/>
            </StackPanel>
        </StackPanel>
        </Button>
    </Grid>
</Window>

private void button1_Click(object sender, System.Windows.RoutedEventArgs e)
{
 Application.Current.Shutdown();
}

When I click button application closes. That is what I want.
But when I click on one of the expanders application also closes. How to avoid that? I don't want application to close when user clicks on one of three arrows.

A:

Try checking the source for the click (as Click events bubble up until someone explicitly handles them). And because the Button is a parent of the expander, it will receive its click event too (did you mean to put the expander outside the button?):
private void button1_Click(object sender, System.Windows.RoutedEventArgs e)
{
  if (e.Source == this.button1)
  {
    Application.Current.Shutdown();
  }
}


Q:

What is the connection between the invertibility of a matrix the kernel of the matrix

If the kernel of a matrix A only has the zero vector (ker(A) = {0})
Then why is the matrix A considered invertible because of that?
I know that if ker(A) = 0, then there is only one unique solution of the matrix( assuming that the matrix is made up of a system of linear equations) but what does this tell me about whether or not the matrix is singular?
Can someone explain the logic behind this?

A:

The word "invertible" and its synonym "non-singular" are reserved for linear systems that have unique solutions. Say that the system $Ax = b$ has a solution. Denote such a solution by $x_0.$ Let $x_h$ (the $h$ stands for "homogenous") denote a nonzero solution to the system $Ax =0$ (called the "homogenous system"). It is true that $x_0$ and $x_0 + x_h$ are two separate solutions to the system $Ax=b.$ So, if there is any nonzero vector in $\ker A,$ then $Ax=b$ has two separate solutions, meaning that it cannot be invertible.


Q:

Unable to activate Windows XP

The latest round of Patch Tuesday updates left my Windows XP computer unbootable.  ("Fatal System Error:  The Windows Logon Process system process terminated unexpectedly.")  After much messing around with the recovery console, an XP CD's repair mode, and manually copying registry files around, I have a system that can boot again.  However, I overwrote my OEM XP installation's activation information while trying to run a retail XP CD's setup, so it needs reactivation.
Here's my problem:  I cannot activate it at all.  I log in, Windows tells me I have to activate to continue, I click Yes, and absolutely nothing happens: no windows, no response to keyboard or mouse, no response to Ctrl-Alt-Del, nothing.  Safe mode works, but I can't activate in safe mode (EDIT: not even safe mode with networking).  I read a trick online of pressing [Windows Key]+U to bring up the Microsoft Narrator, and that works, but clicking its Microsoft Web Site link does nothing.
My last attempt to resolve this was to reinstall Windows off of the OEM CD.  Now I have two parallel Windows installations, both on the same hard drive, one with all of my stuff and no way to activate it, one fully activated with no usable programs.
Any ideas?  Any way to activate in safe mode?  Any way to copy activation information from my activated installation to my unactivated installation (since they're both on the same hard drive)?

A:

I would try a system restore back to when it was all okay, run an sfc /scannow and then try to install the updates again via Microsoft Update.
You could also try activating from the command line:
oobe/msoobe /a
EDIT-- It may worth giving a repair installation a go, if you have not already tried to do so.


Q:

How to install app from beta track on Wear OS smartwatch?

I created a standalone smartwatch app for Wear OS. I use a Huawei Watch 2 4G for testing. I now want to have it in the beta track on Google Play Store so that users can test it. I've created some smartphone apps already and put them in the Play Store, so I'm used to the process. What I did so far:

Created entry on Google Play Console
Added a release to the open beta  track
Filled all necessary stuff
Published the app and got the URL to participate in the beta test
Opened the URL while logged in with my test account and agreed to become a tester
Wiped the smartwatch and copied the same account to the watch during setup

Now I don't know how to install the app from the Play Store. On a smartphone I would simply open the URL in a browser and would be able to install it from there. What I tried so far:

Searching for the app name and for the package name on the Play Store on the smartwatch, but it can't find it.
Opening the Play Store entry in a browser and click the install button, but it says that I have no devices.
Opening the URL on the paired smartphone, but it only says that the device is not compatible.

How can I install a standalone Wear OS app that is in the open beta track on Google Play Store?

A:

As suggest in @tofferj 's comment I simply had to wait a few more hours. I'm now able to find it by simply searching for the app name in the Play Store on the smartwatch.
Seems like the status "published" on the Google Play Console doesn't mean that it's already in the search index.


Q:

Spring Integration Web Service with SOAP and JSON

I am new to Spring Integration, and want to know the best way to call a service using both SOAP and JSON payloads.  My configuration appears below.  I have the SOAP flow working, we support multiple namespaces, so I use SI to handle the incoming message, determine the version (from the package name) and route it to the correct endpoint.  As I mentioned, this works.
<int-ws:inbound-gateway id="ContactServiceGateway"
    request-channel="ContactServiceRequestChannel" marshaller="marshaller"
    unmarshaller="marshaller" />

<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="packagesToScan">
        <list>
            <value>com.predictivesolutions.schema.v1</value>
            <value>com.predictivesolutions.schema.v2</value>
                    <value>com.predictivesolutions.schema.v3</value>
        </list>
    </property>
</bean>

<!-- map the ContactService endpoint to the Gateway -->
<bean
    class="org.springframework.ws.server.endpoint.mapping.UriEndpointMapping">
    <property name="mappings">
        <props>
            <prop key="http://localhost:8088/ws-inbound-gateway/ContactService">ContactServiceGateway</prop>

        </props>
    </property>
</bean>

<int:channel id="ContactServiceRequestChannel" />

<int:channel id="ContactServiceRequestChannelWithHeaders">
    <int:interceptors>
        <ref bean="SecurityInterceptor" />
    </int:interceptors>
</int:channel>

<!-- REST Configuration -->

<int-http:inbound-gateway id="ContactRestGateway"
    path="*" request-channel="ContactRestRequestChannel" reply-channel="ContactRestResponseChannel"
    supported-methods="GET, POST, PUT, DELETE" reply-timeout="5000"
    header-mapper="headerMapper" request-payload-type="java.lang.String" />

<bean id="headerMapper" class="com.ps.snt.integration.HeaderMapper">
</bean>

<!-- this routes different versions of the SOAP messages to the appropriate
    channels - we could use annotations of a custom router method instead -->
<int:header-value-router input-channel="ContactServiceRequestChannelWithHeaders"
    header-name="version">
    <int:mapping value="com.predictivesolutions.schema.v1"
        channel="ContactServiceRequestChannel_v1" />
    <int:mapping value="com.predictivesolutions.schema.v2"
        channel="ContactServiceRequestChannel_v2" />
    <int:mapping value="com.predictivesolutions.schema.v3"
        channel="ContactServiceRequestChannel_v3" />
</int:header-value-router>

<!-- create beans all of the different versions -->
<bean id="ContactServiceEndpoint_v1" class="com.ps.snt.integration.ContactServiceEndpoint_v1" />
<bean id="ContactServiceEndpoint_v2" class="com.ps.snt.integration.ContactServiceEndpoint_v2" />
<bean id="ContactServiceEndpoint_v3" class="com.ps.snt.integration.ContactServiceEndpoint_v3" />

<int:service-activator input-channel="ContactServiceRequestChannel_v1"
    ref="ContactServiceEndpoint_v1" />
<int:service-activator input-channel="ContactServiceRequestChannel_v2"
    ref="ContactServiceEndpoint_v2" />
<int:service-activator input-channel="ContactServiceRequestChannel_v3"
    ref="ContactServiceEndpoint_v3" />

I would like to support JSON, and reuse as many components as possible.  The flow would be to handle all incoming requests to /rest/*, determine the version and other header values from the HTTP headers, and then route the message to the same service endpoint as the SOAP calls.  I do this by using a transformer and basically converting the JSON string to the versioned JAXB object.  This works as well.  That configuration appears below:
<int-http:inbound-gateway id="ContactRestGateway"
        path="*" request-channel="ContactRestRequestChannel" reply-channel="ContactRestResponseChannel"
        supported-methods="GET, POST, PUT, DELETE" reply-timeout="5000"
        header-mapper="headerMapper" request-payload-type="java.lang.String" />

    <bean id="headerMapper" class="com.ps.snt.integration.HeaderMapper">
    </bean>

    <int:transformer id="ContactRestResponseChannelTransformer"
        ref="transformerBean" input-channel="ContactRestResponseChannel"
        method="toObject" output-channel="ContactRestRequestChannelTransformed" />
    <bean id="transformerBean" class="com.ps.snt.integration.Transformer" />

    <int:channel id="ContactRestRequestChannel" />
    <int:channel id="ContactRestResponseChannel" />
    <int:channel id="ContactRestRequestChannelTransformed" />

    <int:header-value-router input-channel="ContactRestRequestChannelTransformed"
        header-name="version">
        <int:mapping value="com.predictivesolutions.schema.v1"
            channel="ContactServiceRequestChannel_v1" />
        <int:mapping value="com.predictivesolutions.schema.v2"
            channel="ContactServiceRequestChannel_v2" />
        <int:mapping value="com.predictivesolutions.schema.v3"
            channel="ContactServiceRequestChannel_v3" />
    </int:header-value-router>

So I can get this to work, but I have other services I will eventually need to integrate, so I would like the least amount of configuration as possible.  Some questions:

can I just use one inbound-gateway for both JSON and SOAP?  I need
both /ContactService and /rest/ContactService to be processed by this
gateway.  I could add a router element that uses the content-type to
route to the SOAP flow or the JSON flow.
how do I use SPeL in a transformer element, as in the following
example.  Basically, from the headers I can determine the version of the payload, and was hoping to use the built in jackson transformer:

<int:json-to-object-transformer input-channel="ContactRestRequestChannel" type="headers['packageName'].concat('.').concat(headers['version'])"/>

A:

You can't use SpEL in the type attribute of the transformer. Since version 3.0, you can set the json__TypeId__ header (upstream of the transformer) to either a class or fully qualified class name - which will be used if there is no type attribute on the transformer.
As I said in my comment; the two gateways are using different technology, so it's not clear why you might think you can combine them into one.
Of course, you can consume SOAP over normal HTTP but you will need to parse out the soap headers etc.