text:
Q: Purpose of taking volatile variable in ThreadLocal instance This is one of questions asked to me in one of the technical talks.
public class MyClass {

    volatile int i;
}

I am using the above MyClass as a ThreadLocal, so what is the use of taking any volatile variable inside this?
final ThreadLocal<MyClass> threadLocal = new ThreadLocal<MyClass>();

A: If that instance is used exclusively with ThreadLocal and not passed around, there doesn't appear to be much point in volatile.
Note, however, that MyClass is just a class like any other: there's nothing preventing it from being used in contexts not involving thread-local storage. In those contexts it could well make sense for the variable to be volatile.

A: Volatile keyword in Java guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache.
Volatile variable can be used as an alternative way of achieving synchronization in Java in some cases, like Visibility. with volatile variable its guaranteed that all reader thread will see updated value of volatile variable once write operation  completed, without volatile keyword different reader thread may see different values. Let's understand this with help of an example.
public class C {
   private volatile int COUNTER=0;

    public static void main(String... q)
    {
        new C().call();
    }

    public void call()
    {
        new A().start();
        new B().start();
    }

    class A extends Thread
    {
        public void run()
        {
            int i =0;
            while(i<100)
            {
                COUNTER++;
                System.out.println(" A COUNTER : "+COUNTER+" *** "+"i : "+i);
                try{
                    Thread.sleep(50);
                }
                catch(Exception e)
                {

                }
                i++;
            }
        }
    }

    class B extends Thread
    {
        public void run()
        {
            int i =0;
            while(i<100)
            {
                COUNTER++;
                 System.out.println(" B COUNTER : "+COUNTER+" *** "+"i : "+i);
                   try{
                    Thread.sleep(50);
                }
                catch(Exception e)
                {

                }
                i++;
            }
        }
    }
}

I have shared COUNTER variable between two threads and have used volatile instead of putting synchronization so that value updated will be shared globally in main memory and other thread will get updated value.
Just try above code again by replacing :
private volatile int COUNTER=0;
with
private  int COUNTER=0;
re-run the program and note the difference.

A: According to the documentation

public class ThreadLocal
This class provides thread-local variables. These variables differ
  from their normal counterparts in that each thread that accesses one
  (via its get or set method) has its own, independently initialized
  copy of the variable.

According to the specification

The Java programming language allows threads to access shared
  variables (§17.1). As a rule, to ensure that shared variables are
  consistently and reliably updated, a thread should ensure that it has
  exclusive use of such variables by obtaining a lock that,
  conventionally, enforces mutual exclusion for those shared variables.
The Java programming language provides a second mechanism, volatile
  fields, that is more convenient than locking for some purposes.

So, in your example each thread has its own instance of MyClass. If it is the only using of MyClass, concurrent access to i is to allowed.
volatile is key word for "more convenient than locking" mechanism for "enforces mutual exclusion".
So, you do not need volatile in this code.
In addition, it decreases performance.


text:
Q: Ruby Autotest on Windows and Growl I'm working through Hartl's Ruby on Rails Tutorial for Rails 3, and there's a few things I'm trying to get setup, and I'm a bit stumped.  First, autotest seems to run fine in and of itself.  It does seem to take a bit longer than anything I've seen as to run two tests it's taking over seven seconds, but it works.  However, I'm trying to get it to give Growl notifications.  I found this question and I'm a bit lost by the answer.  The answer advises to modify the .autotest file in the working directory, in this case sample_app.  However, I don't have any .autotest files in that directory.  The only ones I seem to have are in other gems in the main Ruby directory in the gem libraries.  Also, I'm unfamiliar with his Gemlist file as I've got a Gemlist.Lock file that looks similar in that directory, but it has no references to autotest.  The actual Gemfile he posted is the same, but he does have Spork and the Win32 Process which I don't seem to have.
So if I'm supposed to have an .autotest file in my sample_app directory, how do I get one there?  And why doesn't it seem to be in my Gemlist.lock file?
If needed, here's the output from when I run autotest:
C:\Ruby193\work\rails_tutorial\sample_app>autotest
loading autotest/rails_rspec2
C:\Ruby193\bin\ruby -rrubygems -S 'C:/Ruby193/lib/ruby/gems/1.9.1/gems/rspec-core-2.11.1/exe/rspec' --tty 'C:/Ruby193/work/rails_tutorial/sample_app/spec/controllers/pages_controller_spec.rb'

..
Finished in 8.57 seconds
2 examples, 0 failures

Randomized with seed 6674

Any suggestions/assistance would be greatly appreciated.  Thank you.

A: I struggled getting Growl to work in Windows as well. It looks as if you're using MRI via RubyInstaller, where I used JRuby, but maybe my writeup will help.
http://journeymandev.com/2012/7/28/rails-growl-and-windows

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javafx working with the same window problem What I am trying to do:
I have menu and and after click I am trying to remove unnecessary TextFields.
What I did:
I used this example:
"In JavaFX, nodes can simply be removed from a Parent (e.g. an AnchorPane) using .getChildren() following by .remove(Object o)
AnchorPane ap;
ap.getChildren().remove(btn);

I tried to use:
FXMLLoader load=new FXMLLoader(getClass().getResource("LoginRegister.fxml"));
Parent root = load.load();
root.getChildren();

But my root does not have getChildren() function.
Where could be the problem?
Thank you in advance.
EDIT: FOUND THE ANSWER HERE: How to access UI components from SceneBuilder in JavaFX
WHAT I DID WRONG: I USED IN FXML FILE AND IN CONTROLLER DIFFERENT FX:ID's


text:
Q: circuit breaker annotation with Spring mvc(NOT Spring-boot) I am trying to use @CircuitBreaker annotation in spring-mvc project but it does not seem to work.
Does resilience4j-annotations work on a traditional non spring-boot setup?
@Bean
public CircuitBreaker edocCircuitBreaker() {
    LOGGER.info("Creating Circuit");
    CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
            .slowCallDurationThreshold(Duration.ofMillis(1000))
            .minimumNumberOfCalls(2)
            .slidingWindowSize(2)
            .failureRateThreshold(100)
            .build();
    CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.of(circuitBreakerConfig);
    CircuitBreaker serviceClientCircuitBreaker =  circuitBreakerRegistry.circuitBreaker("ClientCircuitBreaker");
    serviceClientCircuitBreaker.getEventPublisher().onStateTransition(this::serviceCircuitOpenHanlder);
    return serviceClientCircuitBreaker;
}

@CircuitBreaker(name="ClientCircuitBreaker")
public String sendAndReceive(String request, RequestParameters parameters) throws RuntimeException {

    StreamSource source = new StreamSource(new StringReader(request));
    StreamResult result = new StreamResult(new StringWriter());

    .....

A: You should use resilience4j-spring. It provides a lot of @Configuration classes for you.
You need to import the Configuration classes:
@Import({ CircuitBreakerConfiguration.class, RetryConfiguration.class, TimeLimiterConfiguration.class, BulkheadConfiguration.class }

The CircuitBreakerConfiguration is important, because it configures the CircuitBreakerAspect bean which is needed so that annotations are working.
You have to create a @Bean which uses your external configuration properties file and fills and returns CircuitBreakerConfigurationProperties.
In resilience4j-spring-boot2 we configure it automatically with @EnableConfigurationProperties(CircuitBreakerProperties.class)


text:
Q: How do I programmatically change an image in an existing UIImageView and make it fit inside the image view's constraints? I have a UIImageView and when I set an image in that view using IB, the image is the correct size when I run the app (40x40). When I programmatically change the image using the code below, the new image is 400x400 or so. This is using the same image that I know works fine if it's set in IB. Do I have to scale the image before I add it to the UIImageView? I assumed auto-layout's constraints would automatically do this for me.
UIImage *messageTypeImage = [UIImage imageNamed:message.imageName];
[messageCell.imageView setImage:messageTypeImage];
[messageCell.contentView layoutIfNeeded];

The UIImageView's content mode is set to "Scale To Fill" and I've tried adding the code below both before and after calling setImage:
[messageCell.imageView setContentMode:UIViewContentModeScaleAspectFill];
[messageCell.imageView setClipsToBounds:YES];

Here's how the constraints are set up for the image view:

A: Are you using iOS 8 SDK? If so, try overriding layoutSubviews in your cell subclass and add this:
   self.contentView.frame = self.bounds;
   self.contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

There are some problems with the contentViews' of collection view/table view cells constraints/masks.

A: Wow. Finally found the answer here. Turns out, there's a default imageView outlet in prototype cells. I was unknowingly using that outlet and not the UIImageView I thought I was using.


text:
Q: Why is a bootstrap method helping in some way? The general methods with bootstrapping is always similar to that:
We have a given sample $x_1,...,x_n$. Then we pick some elements of the sample randomly and put it then back to the sample;
This creates some new samples...
But why is this actually helping? I can't see the sense behind it because we can't create any new information with such methods and our original sample doesn't get more accurate I guess;
So why are we doing it?

A: Bootstrapping is a general technique, where one takes subsamples from a sample and uses it for some statistical task. You're right that no new information is created. It's more of an algorithmic technique for performing some statistical tasks.
A pretty common use in machine learning (e.g. in mini-batch $k$-means, or mini-batch stochastic gradient decent for deep neural networks) is to train the learner iteratively.
This is for computational efficiency, since it is much cheaper to take many small steps in parameter space with subsamples than to use the full population, and it will probabilistically converge to the correct answer anyway.
It's also useful for the "ensemble" learning approach called bagging and as a method for handling class imbalance (e.g. by duplicating the undersampled class's samples).
In statistics, one use is to estimate distributions of sample statistics. Suppose we have a sample $S=\{x_i\}_{i=1}^n$ with bootstrap subsamples $s_i$. One could easily compute the sample mean $\bar{x}$ of $S$. But what is the distribution of $\bar{x}$ as a random variable? One could compute the sample means $\bar{x}_i$ of each $s_i$ to answer this.
There are two good threads related to this on the stats SE: this one and this one.
Also, it is useful in semisupervised learning cases, where we want to do statistical learning on an unlabeled dataset with some tiny labeled seed set.
For instance, in natural language processing, see Waegel's survey here.
This is a little different from the methods mentioned above.


text:
Q: TypeError: ctx.sls.service.package.include.push is not a function I'm trying to include static files with my lambda function.  I am receiving the this error when trying to deploy:

TypeError: ctx.sls.service.package.include.push is not a function

This is the relevant part of my serverless.yml.
package:
  include: ../shared/static/**

A: The issue was package.include expects an array, but I passed it a string.  In yaml, an array (called a sequence) is denoted with a new line, a dash, and a space for each element.
package:
  include:
    - ../shared/templates/**

YAML docs on defining sequences


text:
Q: Drag Drop between GridViews I have two GridViews in my Page which contains multiple items. One is for Existing Items and one for User Cart. The user should drag and drop an item in order to add it to his buying list.
How can I enable drag drop between two or more GridViews?

A: Here is an example of how to drag and drop between different groups within one grouped grid.


text:
Q: Why should I use var instead of a type?
Possible Duplicate:
ReSharper and var

After I have installed ReSharper it demands(by warnings) that I use var whenever possible, for example
UnhandledExceptionEventArgs ue = (UnhandledExceptionEventArgs) t;

ReSharper wants to turn it into
var ue = (UnhandledExceptionEventArgs) t;

I like the first version better, is there any reason to prefer var? better performance? anything? or is it just a code style?

A: When you say "by warnings" what exactly do you mean? I've usually seen it giving a hint that you may want to use var, but nothing as harsh as a warning.
There's no performance difference with var - the code is compiled to the same IL. The potential benefit is in readability - if you've already made the type of the variable crystal clear on the RHS of the assignment (e.g. via a cast or a constructor call), where's the benefit of also having it on the LHS? It's a personal preference though.
If you don't want R# suggesting the use of var, just change the options. One thing about ReSharper: it's very configurable :)

A: As the others have said, there is no difference in the compiled code (IL) when you use either of the following:
var x1 = new object();
object x2 = new object;

I suppose Resharper warns you because it is [in my opinion] easier to read the first example than the second. Besides, what's the need to repeat the name of the type twice?
Consider the following and you'll get what I mean:
KeyValuePair<string, KeyValuePair<string, int>> y1 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));

It's way easier to read this instead:
var y2 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));

A: In this case it is just coding style.
Use of var is only necessary when dealing with anonymous types.
In other situations it's a matter of taste.

A: It's really just a coding style. The compiler generates the exact same for both variants.
See also here for the performance question:

*

*Will using 'var' affect performance?


text:
Q: xml-not-well-formed error in when I try to bind resource in XMPP over Bosh 1 Problem: I am getting xml not well formed error, when I try to bind resource in XMPP over Bosh.
What I tried: I went to xmpp.org to look for proper xml stanza for binding resource(http://xmpp.org/extensions/xep-0206.html#preconditions-sasl), but it seems similar.
Possible answer: I havn't restarted the stream after authentication, can that be the cause of this error?
2 problem: I tried to restart the stream by using the packet(http://xmpp.org/extensions/xep-0206.html#preconditions-sasl) but I got 400 in response code? Any body has any idea why I got that?
Possible answer: I didn't get xmpp:restartLogic attribute in response to initial packet? Can that be the reason for getting 400 error(May be Ejabbered server doesn't support restart)?
Doubt: Anyone got any idea on how to enable restartlogic in Ejabberd or is it enabled by default?
My Log is as follow:

Stanza to read is  = body xmlns='http://jabber.org/protocol/httpbind' sid='8d96d01bb87f526e78b0f0b620dd1c94edd172ee' wait='30' requests='2' inactivity='30' maxpause='120' polling='2' ver='1.8' from='someserver.com' secure='true' authid='2817580747' xmlns:xmpp='urn:xmpp:xbosh' xmlns:stream='http://etherx.jabber.org/streams' xmpp:version='1.0'
Stanza to read is  = stream:features xmlns:stream='http://etherx.jabber.org/streams'
Stanza to read is  = mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-sasl'
Stanza to read is  = mechanism
Stanza to read is  = c xmlns='http://jabber.org/protocol/caps' hash='sha-1' node='http://www.process-one.net/en/ejabberd/' ver='U5DC02T7iwEqfov5b3KpIVgA5+I='/
Stanza to read is  = register xmlns='http://jabber.org/features/iq-register'/
Session creation response received: body secure=true requests=2 inactivity=30 authid=2817580747 sid=8d96d01bb87f526e78b0f0b620dd1c94edd172ee polling=2 xmlns=http://jabber.org/protocol/httpbind wait=30 xmpp=urn:xmpp:xbosh ver=1.8 version=1.0 from=someserver.com stream=http://etherx.jabber.org/streams maxpause=120 ==
        features stream=http://etherx.jabber.org/streams ==
                mechanisms xmlns=urn:ietf:params:xml:ns:xmpp-sasl ==
                        mechanism == PLAIN
                        mechanism == DIGEST-MD5
                        mechanism == SCRAM-SHA-1
                c ver=U5DC02T7iwEqfov5b3KpIVgA5+I= node=http://www.process-one.net/en/ejabberd/ hash=sha-1 xmlns=http://jabber.org/protocol/caps ==
                register xmlns=http://jabber.org/features/iq-register ==
Authenticating: body secure=true requests=2 inactivity=30 authid=2817580747 sid=8d96d01bb87f526e78b0f0b620dd1c94edd172ee polling=2 xmlns=http://jabber.org/protocol/httpbind wait=30 xmpp=urn:xmpp:xbosh ver=1.8 version=1.0 from=someserver.com stream=http://etherx.jabber.org/streams maxpause=120 ==
        features stream=http://etherx.jabber.org/streams ==
                mechanisms xmlns=urn:ietf:params:xml:ns:xmpp-sasl ==
                        mechanism == PLAIN
                        mechanism == DIGEST-MD5
                        mechanism == SCRAM-SHA-1
                c ver=U5DC02T7iwEqfov5b3KpIVgA5+I= node=http://www.process-one.net/en/ejabberd/ hash=sha-1 xmlns=http://jabber.org/protocol/caps ==
                register xmlns=http://jabber.org/features/iq-register ==
Using plain authorization
writtenToAir [0]: AE1haGlAdGVzdC5yYXBpZHNvZnR0ZWNobm9sb2d5LmNvbQBtYWhp
Starting PLAIN authorization
Stanza to read is  = body xmlns='http://jabber.org/protocol/httpbind'
Stanza to read is  = success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/
writtenToAir [0]: Resource
Binding resource
Stanza to read is  = body type='terminate' condition='remote-stream-error' xmlns='http://jabber.org/protocol/httpbind' xmlns:stream='http://etherx.jabber.org/streams'
Stanza to read is  = stream:error
Stanza to read is  = xml-not-well-formed xmlns='urn:ietf:params:xml:ns:xmpp-streams'/


text:
Q: pip installed non specified generator_tools package and fired `AssertionError: Python version 2.5 or 2.6 required` error I'm working on python2.7 under virtual env, I tried to install a project which works perfectly in prod server, with this requirements :
Django==1.3
Jinja2==2.7.1
MarkupSafe==0.18
PyYAML==3.10
Pygments==1.6
South==0.7.3
Sphinx==1.0.7
Twisted==10.0.0
amqplib==1.0.2
anyjson==0.3.3
argparse==1.2.1
billiard==0.3.1
carrot==0.10.4
celery==1.0.6
coverage==3.7.1
decorator==3.4.0
distribute==0.6.24
django-nose==1.2
django-picklefield==0.3.1
django-piston==0.2.2.1
docutils==0.11
iso8601==0.1.4
meld3==0.6.10
nose==1.3.0
oauth==1.0.1
psycopg2==2.5.1
pyOpenSSL==0.12
pycurl==7.19.5
pystache==0.3.1
python-dateutil==2.2
python-foneworx==0.1
-e git://github.com/dmaclay/python-smpp.git@4b37d211ea38f52ae282a469e377baabbcd17199#egg=python_smpp-dev
python-ssmi==0.0.6
simplejson==3.3.2
six==1.5.2
smn-alexandria==0.1.1
supervisor==3.0
-e git://github.com/dustin/twitty-twister@8524750ee73adb57bbe14ef0cfd8aa08e1e59fb3#egg=twittytwister-dev
txAMQP==0.6.2
wokkel==0.7.1
wsgiref==0.1.2
yolk==0.4.3
zope.interface

After running pip install -r requirements.pip, packages got installed one by one, installed generator_tools too (while it is not mentioned in the requirements, probably as dependency?), then I encountered an error saying
ERROR: Command errored out with exit status 1:
     command: /home/.../virtual_env/my_ve/bin/python2 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-pt2wZL/generator-tools/setup.py'"'"'; __file__='"'"'/tmp/pip-install-pt2wZL/generator-tools/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-pt2wZL/generator-tools/pip-egg-info
         cwd: /tmp/pip-install-pt2wZL/generator-tools/
    Complete output (5 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-pt2wZL/generator-tools/setup.py", line 7, in <module>
        assert py_version_s in ("2.5", "2.6"), "Python version 2.5 or 2.6 required"
    AssertionError: Python version 2.5 or 2.6 required
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Retried times & times, with different virtualenv, or by forcing reinstall, ... but the issue is still persisting. Earnestly searched on google but no related issue found.
Does anyone have experience on this or know what would be the solution ? Thnx


text:
Q: Reditied (New Question) :How to create (in QGIS) an "Other" value in the value map? Before you read: my apologies for grammar mistakes, English is not my native writing language and the spellcheck can only help me so far. I am learning QGIS completely on my own and I am trying to follow the training manual but that van only get me so far.
Ok, so far I know how to create a value map with a list of value's to choose from with some attributes in the shapefile I can work in. This makes it easy for the person to add information to  green (were are working on a green database) objects such as author of the object. But I want to think a bit ahead by doing a little bit more than that. I know also to create a unique value list that can retyped. But I want to have a combination of both unique value and value map aka dropdown. Yeah I know you can add other values to a value map in value map edit menu. But considering that you this is gonna be linked to Qfield. I want to make it that way. Keep in mind the column that this setting must be created in is EMPTY. That means there are no current value's that can be set to Unique value's, and the value map is kind of already assigned.

A: first situation:
Use 'unique value' instead of 'value map'.  Already inserted authors will show up.
If you check 'editable' then new values can be added.
second situation:
same as first, but add some default value.
A screenshot wil explain

ps: It is better to update your QGIS to the latest version.


text:
Q: How do I capture SIGINT in Python? I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a Ctrl+C signal, and I'd like to do some cleanup.
In Perl I'd do this:
$SIG{'INT'} = 'exit_gracefully';

sub exit_gracefully {
    print "Caught ^C \n";
    exit (0);
}

How do I do the analogue of this in Python?

A: Register your handler with signal.signal like this:
#!/usr/bin/env python
import signal
import sys

def signal_handler(sig, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()

Code adapted from here.
More documentation on signal can be found here.

A: If you want to ensure that your cleanup process finishes I would add on to Matt J's answer by using a SIG_IGN so that further SIGINT are ignored which will prevent your cleanup from being interrupted.
import signal
import sys

def signal_handler(signum, frame):
    signal.signal(signum, signal.SIG_IGN) # ignore additional signals
    cleanup() # give your process a chance to clean up
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler) # register the signal with the signal handler first
do_stuff()

A: And as a context manager:
import signal

class GracefulInterruptHandler(object):

    def __init__(self, sig=signal.SIGINT):
        self.sig = sig

    def __enter__(self):

        self.interrupted = False
        self.released = False

        self.original_handler = signal.getsignal(self.sig)

        def handler(signum, frame):
            self.release()
            self.interrupted = True

        signal.signal(self.sig, handler)

        return self

    def __exit__(self, type, value, tb):
        self.release()

    def release(self):

        if self.released:
            return False

        signal.signal(self.sig, self.original_handler)

        self.released = True

        return True

To use:
with GracefulInterruptHandler() as h:
    for i in xrange(1000):
        print "..."
        time.sleep(1)
        if h.interrupted:
            print "interrupted!"
            time.sleep(2)
            break

Nested handlers:
with GracefulInterruptHandler() as h1:
    while True:
        print "(1)..."
        time.sleep(1)
        with GracefulInterruptHandler() as h2:
            while True:
                print "\t(2)..."
                time.sleep(1)
                if h2.interrupted:
                    print "\t(2) interrupted!"
                    time.sleep(2)
                    break
        if h1.interrupted:
            print "(1) interrupted!"
            time.sleep(2)
            break

From here: https://gist.github.com/2907502

A: You can use the functions in Python's built-in signal module to set up signal handlers in python. Specifically the signal.signal(signalnum, handler) function is used to register the handler function for signal signalnum.

A: You can handle CTRL+C by catching the KeyboardInterrupt exception. You can implement any clean-up code in the exception handler.

A: From Python's documentation:
import signal
import time

def handler(signum, frame):
    print 'Here you go'

signal.signal(signal.SIGINT, handler)

time.sleep(10) # Press Ctrl+c here

A: thanks for existing answers, but added signal.getsignal()
import signal

# store default handler of signal.SIGINT
default_handler = signal.getsignal(signal.SIGINT)
catch_count = 0

def handler(signum, frame):
    global default_handler, catch_count
    catch_count += 1
    print ('wait:', catch_count)
    if catch_count > 3:
        # recover handler for signal.SIGINT
        signal.signal(signal.SIGINT, default_handler)
        print('expecting KeyboardInterrupt')

signal.signal(signal.SIGINT, handler)
print('Press Ctrl+c here')

while True:
    pass

A: Yet Another Snippet
Referred main as the main function and exit_gracefully as the Ctrl+C handler
if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
    finally:
        exit_gracefully()

A: You can treat it like an exception (KeyboardInterrupt), like any other. Make a new file and run it from your shell with the following contents to see what I mean:
import time, sys

x = 1
while True:
    try:
        print x
        time.sleep(.3)
        x += 1
    except KeyboardInterrupt:
        print "Bye"
        sys.exit()

A: I adapted the code from @udi to support multiple signals (nothing fancy) :
class GracefulInterruptHandler(object):
    def __init__(self, signals=(signal.SIGINT, signal.SIGTERM)):
        self.signals = signals
        self.original_handlers = {}

    def __enter__(self):
        self.interrupted = False
        self.released = False

        for sig in self.signals:
            self.original_handlers[sig] = signal.getsignal(sig)
            signal.signal(sig, self.handler)

        return self

    def handler(self, signum, frame):
        self.release()
        self.interrupted = True

    def __exit__(self, type, value, tb):
        self.release()

    def release(self):
        if self.released:
            return False

        for sig in self.signals:
            signal.signal(sig, self.original_handlers[sig])

        self.released = True
        return True

This code support the keyboard interrupt call (SIGINT) and the SIGTERM (kill <process>)

A: In contrast to Matt J his answer, I use a simple object. This gives me the possibily to parse this handler to all the threads that needs to be stopped securlery.
class SIGINT_handler():
    def __init__(self):
        self.SIGINT = False

    def signal_handler(self, signal, frame):
        print('You pressed Ctrl+C!')
        self.SIGINT = True

handler = SIGINT_handler()
signal.signal(signal.SIGINT, handler.signal_handler)

Elsewhere
while True:
    # task
    if handler.SIGINT:
        break

A: Personally, I couldn't use try/except KeyboardInterrupt because I was using standard socket (IPC) mode which is blocking. So the SIGINT was cueued, but came only after receiving data on the socket.
Setting a signal handler behaves the same.
On the other hand, this only works for an actual terminal. Other starting environments might not accept Ctrl+C, or pre-handle the signal.
Also, there are "Exceptions" and "BaseExceptions" in Python, which differ in the sense that interpreter needs to exit cleanly itself, so some exceptions have a higher priority than others (Exceptions is derived from BaseException)


text:
Q: Is it possible to create an android app which can cast device screen including "negative colors" accessibility feature instead of true colors? I have low vision and use the "negative colors" accessibility feature of android on my devices. I got a Google Chromecast to cast my screen to my TV, but the streaming is in true colors, not the negative colors, no matter what application I use.
Is it possible to create an android app which can cast device screen including "negative colors" accessibility feature instead of true colors? Or is it technically impossible?

A: By "Negative Colors", are you referring to "Color Inversion" or is it something else? Apps don't have control over mirroring/cast screening; it is done at the framework level. If that is not honored by mirroring, then please file a bug.


text:
Q: Golang: response struct having multiple possible types for field I want to send a response from my api with a unified structure for all responses
type formattedResponse struct {
    Status string
    Data []dataStruct
}

type dataStruct struct {
    Name string
    Phone string
}

I want to have Data be able to be different structs and not just the single dataStruct. I can tell that i'm not using this pattern correctly. What is the correct way to accomplish this sort of thing? Is there a way to have a struct field be able to be any type with the same key?

A: I guess this is what you need - you would like to use the same "base" struct with different field types:
package main

type formattedResponse struct {
    Status string
    Data interface{}
}

type dataStruct1 struct {
    Name string
    Phone string
}

type dataStruct2 struct {
    Office string
    Location string
}

func main() {

     // using formattedResponse with dataStruct1

     fr1 := formattedResponse{
           Status: "ok",
     }

     if fr1.Data == nil {
               fr1.Data = make([]dataStruct1, 0)
     }

     fr1.Data = append(fr1.Data.([]dataStruct1), dataStruct1{Name: "n1", Phone: "12345"})

     // using formattedResponse with dataStruct2

     fr2 := formattedResponse{
           Status: "ok",
     }

     if fr2.Data == nil {
               fr2.Data = make([]dataStruct2, 0)
     }

     fr2.Data = append(fr2.Data.([]dataStruct2), dataStruct2{Office: "o2", Location: "Paris"})

}

A: @archaeopteryx what you could do is define the returned Data property as an Interface. See my example below,
type Data interface {
    LogData() string
}

type formattedResponse struct {
    Status string
    Data []Data
}

type userData struct {
    Name string
    Phone string
}

func (u userData) LogData() string {
    fmt.Sprintln("This is some shared function")
}

You'd ideally come up with a function more useful than LogData that can be shared by all returned types but hopefully you get the idea. As long as another struct has the same function(s) within the interface it will implement it, and so satisfy as being part of the returned slice
I hope that makes sense!


text:
Q: Getting parameter names from SOAP request with PHP SOAP extension? Given that the following client.php creates this request XML:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://soap.dev/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <SOAP-ENV:Body>
    <ns1:Test>
      <RequestId xsi:type="xsd:int">1</RequestId>
      <PartnerId xsi:type="xsd:int">99</PartnerId>
    </ns1:Test>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

How do I access the names of the parameters? (RequestId and PartnerId) inside a server.php? The names are clearly there in the payload, but on server side only the values are received (1 and 99)
Sample code follows:
client.php
<?php
$client_params = array(
    'location' => 'http://soap.dev/server.php',
    'uri' => 'http://soap.dev/',
    'trace' => 1
);

$client = new SoapClient(null, $client_params);

try {
    $res = $client->Test(
        new SoapParam(1, 'RequestId'),
        new SoapParam(99, 'PartnerId')
    );

} catch (Exception $Ex) {
    print $Ex->getMessage();
}

var_dump($client->__getLastRequest());
var_dump($client->__getLastResponse());

server.php
class receiver {
    public function __call ($name, $params)
    {
        $args = func_get_args();
        // here $params equals to array(1, 99)
        // I want the names as well.
        return var_export($args, 1);
    }

}

$server_options = array('uri' => 'http://soap.dev/');
$server = new SoapServer(null, $server_options);
$server->setClass('receiver');
$server->handle();

Please note that I can not really change the incoming request format.
Also, I am aware that I could give the names back to parameters by creating a Test function with $RequestId and $PartnerId parameters.
But what I really want to is to get name/value pairs out of incoming request.
So far the only idea I have is to simply parse the XML and this cannot be right.

A: Back when I had this problem I finally decided to go with the proxy function idea - Test function with parameters named ($RequestId and $PartnerId) to give names back to parameters. Its adequate solution, but certainly not the best.
I have not yet lost the hope for finding a better solution though, and here is my best idea so far
<?php
class Receiver {

    private $data;

    public function Test ()
    {
        return var_export($this->data, 1);
    }

    public function int ($xml)
    {
        // receives the following string
        // <PartnerId xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xsd:int">99</PartnerId>
        $element = simplexml_load_string($xml);
        $this->data[$element->getName()] = (string)$element;
    }

}

$Receiver = new Receiver();

$int = array(
    'type_name' => 'int'
    , 'type_ns' => 'http://www.w3.org/2001/XMLSchema'
    , 'from_xml' => array($Receiver, 'int')
);

$server_options = array('uri' => 'http://www.w3.org/2001/XMLSchema', 'typemap' => array($int), 'actor' => 'http://www.w3.org/2001/XMLSchema');
$server = new SoapServer(null, $server_options);
$server->setObject($Receiver);
$server->handle();

It still means parsing XML manually, but one element at a time which is a bit more sane that parsing entire incoming SOAP message.


text:
Q: How do I pass querystring to an httphandler? Passing an id though the querystring to an httphanlder was not so hard in a bindable control like a gridview. I put an imagebutton in the gridview and set its Imageurl Property as such....
ImageUrl='<%#"~\Handlers\ImageHandler.ashx?id=" & Eval("ID")

However, now I am trying to just use a standard Imagebutton control just sitting there on a user control. I call this method I created on the user control:
Public Sub LoadImage()

    Dim sb As New StringBuilder

    sb.Append("~\Handlers\ImageHandler.ashx")
    sb.Append("?imageSourceCode=" & _imageSourceCode.ToString)
    sb.Append("&displayTypeCode=" & _displayTypeCode.ToString)
    sb.Append("&imageData=" & _imageData.ToString)

    imgbtnImage.ImageUrl = sb.ToString

End Sub

...in an attempt to pass some paramters into the httphandler, but once inside, it doesn't see them. The I noticed I had also harded an ImageUrl property on the imagecontrol itself to point to the handler w/o querystring. So, I deleted that and now it fails completely!

A: This may be your problem:
ImageUrl='<%# "~\Handlers\ImageHandler.ashx?id=" & Eval("ID") %>'

A: Try resolving the url before assigning it to the image.
imgbtnImage.ImageUrl = ResolveUrl(sb.ToString)


text:
Q: if (key.equals ("1") || key.equals ("Circle")){ if (key.equals ("1") || key.equals ("Circle")){

how can i make this statement true even if I enter the string "CiRcle" or "circle"? I mean at different cases.

A: You can try as below :
if (key.equals ("1") || key.equalsIgnoreCase("Circle")){

More about equalsIgnoreCase

A: if (key.equals("1") || key.equalsIgnoreCase("Circle")){

A: The general syntax is
public boolean equalsIgnoreCase(String anotherString)
This method returns true if the argument is not null and the Strings are equal, ignoring case; false otherwise.
For your case
if (key.equals("1") || key.equalsIgnoreCase("Circle"))

Doc

A: You can try
if (key.equals ("1") || key.equalsIgnoreCase ("Circle"))

However it seems like you did not have any research or studied String methods in java. I recommend you to look at String topic in java


text:
Q: JetBrains Account connection error: Network is unreachable: connect This Problem shows me when I try to logged in with my student's account.

A: Looks as if you have custom proxy configuration set up in Preferences | Appearance & Behavior | System Settings | HTTP Proxy. Please try removing/changing it - does it help?
If you can't access IDE settings, try resetting them by deleting/renaming the configuration directory: https://www.jetbrains.com/help/pycharm/directories-used-by-the-ide-to-store-settings-caches-plugins-and-logs.html#config-directory


text:
Q: If I want to get a Facebook user's "info" and "posts"...do I need Facebook Connect or Facebook Application? Preferably, I want the least work possible!

A: Your question is a bit odd, because generally the context of where and why you're using the information determines whether you want a Facebook Connect implementation or a Facebook application.
In order to fetch user information from Facebook, you must have a valid session token of some kind.  You cannot get user information without it, and the context of the session token determines what kind of information is available to you.  For example, you can use the API Test Console to try out various API methods, but it will always be from the context of your own Facebook user id, so anything that a user has marked as blocked/private to you won't be available.
With Facebook Connect, you receive a valid token when the user "connects" to your Facebook Connect enabled web site.  With a Facebook application, the token is provided when the user comes to your application inside Facebook.  Once you have the token, you can use it to query the API services and retrieve information about the user.
Each implementation faces different challenges.  For a Facebook Connect site, you have to convince users to come to your web site and "connect" to it using their Facebook accounts.  For a regular app, you have to convince people to add the application to their profile.
With all this, which one will be less work now becomes a subjective question, as it depends on what you want to do with the info and how you're trying to do it.

A: You can use FQL from the demo interface, which allows you to run most queries against your friends. An application is the way to go to scale up on this, though.


text:
Q: Jmeter Connection to http://IP:8080 refused I tested website performance with Jmeter 2.13, I have never used Jmeter before, When I set the number of thread is 500, it is OK, ans when set 750, there are some errors shows below. During the tests, my CPU ,bandwidth, memory,IO are not full.  I have tried other ways ,such as changing maxThread of tomcat7 and so on, but they did not work,  any help is appreciated!
org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.0.160:8080 refused
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:190)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:294)
at org.apache.jmeter.protocol.http.sampler.MeasuringConnectionManager$MeasuredConnection.open(MeasuringConnectionManager.java:107)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:643)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:479)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.executeRequest(HTTPHC4Impl.java:517)
at org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.sample(HTTPHC4Impl.java:331)
at org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy.sample(HTTPSamplerProxy.java:74)
at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1146)
at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1135)
at org.apache.jmeter.threads.JMeterThread.process_sampler(JMeterThread.java:434)
at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:261)
at java.lang.Thread.run(Unknown Source)

Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:127)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:180)
... 14 more

A: There are two possibilities here.

*

*Your server is not able handle the number of incoming connections from the same IP address. Check the size of connection pool and maximum incoming connections. Use some java tool like java melody to check total number of connections. Also check the thread-pool size and max thread settings.

*Or It could be JMeter client issue. Try to run the test from two different load generators and split the load of 750. Client may not be able to establish socket connections for all the 750 users.


text:
Q: Lightning Datatable with wrapperclass How can I use my wrapperclass with a lightning:datatable, Is that possible?
At the moment I use
<apex:pageBlockTable value="{!wrapperList}" var="wl" title="all activities">

to display the result.
CLASS
    public class DokuBox_6 {

    public List<Wrapper> wrapperList {get; set;}
    public String currentRecordId {get; set;}

    public DokuBox_6() {
        currentRecordId = ApexPages.currentPage().getParameters().get('id');

        if(wrapperList == null) {
            wrapperList = new List<Wrapper>();

            for(Task a: [select Id, Subject, CreatedDate, Createdby.Name, Owner.Name, RecordType.Name, Status from Task where WhoId =: currentRecordId AND Subject LIKE 'E-Mail:%']) {
                wrapperList.add(new Wrapper(a, 'E-Mail'));
            }
            for(Task a: [select Id, Subject, CreatedDate, Createdby.Name, Owner.Name, RecordType.Name, Status from Task where WhoId =: currentRecordId AND (NOT Subject LIKE 'E-Mail:%')]) {
                wrapperList.add(new Wrapper(a, 'Aufgabe'));
            }
            for(Event b: [select Id, Subject, CreatedDate, StartDateTime, Createdby.Name, Owner.Name from Event where WhoId =: currentRecordId]) {
                wrapperList.add(new Wrapper(b, 'Termin'));
            }
            for(ContentDocumentLink d: [SELECT Id, ContentDocumentId, ContentDocument.Title, ContentDocument.createdDate, ContentDocument.Createdby.Name, ContentDocument.FileExtension FROM ContentDocumentLink WHERE LinkedEntityId =: currentRecordId AND ContentDocument.FileExtension = 'snote']) {
                wrapperList.add(new Wrapper(d, 'Notiz'));
            }
            for(ContentDocumentLink d: [SELECT Id, ContentDocumentId, ContentDocument.Title, ContentDocument.createdDate, ContentDocument.Createdby.Name, ContentDocument.FileExtension FROM ContentDocumentLink WHERE LinkedEntityId =: currentRecordId AND ContentDocument.FileExtension <> 'snote']) {
                wrapperList.add(new Wrapper(d, 'Datei'));
            }
            wrapperList.sort();
        }
    }

    public class Wrapper implements Comparable {

        private final String objectLabel;
        private final Id id;
        private final String subject;
        private final DateTime createDate;
        private final String Ersteller;
        private final String Typ;
        private final String Status;

        public wrapper(Task t, String oName) {
            objectLabel     = oName;
            id              = t.Id;
            subject         = t.Subject;
            createDate      = t.CreatedDate;
            Ersteller       = t.Owner.Name;
            Typ             = t.RecordType.Name;
            Status          = t.Status;
        }

        public wrapper(Event e, String oName) {
            objectLabel     = oName;
            id              = e.Id;
            subject         = e.Subject;
            createDate      = e.StartDateTime;
            Ersteller       = e.Owner.Name;
        }

        public wrapper(ContentDocumentLink f, String oName) {
            objectLabel     = oName;
            id              = f.ContentDocumentId;
            subject         = f.ContentDocument.Title;
            createDate      = f.ContentDocument.CreatedDate;
            Ersteller       = f.ContentDocument.CreatedBy.Name;
            Typ             = f.ContentDocument.FileExtension;
        }

        public Id getId() {
            return id;
        }

        public String getSubject() {
            return subject;
        }

        public String getTyp() {
            return Typ;
        }

        public DateTime getCreatedDate() {
            return createDate;
        }

        public String getObjectLabel() {
            return objectLabel;
        }

        public String getErsteller() {
            return Ersteller;
        }

        public String getStatus() {
            return Status;
        }

        // Sort in ascending order
        public Integer compareTo(Object compareTo) {
            Wrapper compareToActivity = (Wrapper) compareTo;
            DateTime compareToCreateDate = compareToActivity.getCreatedDate();
            if (createDate > compareToCreateDate) {
                return -1;
            }
            if (createDate < compareToCreateDate) {
                return 1;
            }
            return 0;
        }
    }

}

A: Yes, you can. There are 2 ways you can go about it.
One option is to mark your wrapper class properties as @AuraEnabled and make them public.
public class Wrapper {
    @AuraEnabled
    public String objectLabel;

    @AuraEnabled
    public String id;

    @AuraEnabled
    public String subject;

    @AuraEnabled
    public DateTime createDate;
}

You can then directly bind the list from Apex to the data attribute of lightning-datatable.
import { LightningElement, wire, api } from 'lwc';
import getWrapperData from '@salesforce/apex/DokuBox_6.getWrapperData';

const columns = [
    { label: 'Label', fieldName: 'objectLabel' },
    { label: 'Subject', fieldName: 'subject', type: 'string' },
    { label: 'Created Date', fieldName: 'createDate', type: 'date' },
];

export default class Datatabledemo extends LightningElement {
    @api recordId;

    data = [];
    columns = columns;

    @wire(getWrapperData, {currentRecordId: '$recordId'})
    dataFn({data}){
        this.data = data;
    }
}

<template>
    <lightning-datatable
            key-field="id"
            data={data}
            columns={columns}>
    </lightning-datatable>
</template>

If you dont want to make your wrapper class properties public, you can serialize the list and send it to your component.
@AuraEnabled(cacheable=true)
public static String getWrapperData(String currentRecordId) {
    List<Wrapper> wrapperList = new List<Wrapper>();
    for(Task a: [select Id, Subject, CreatedDate, Createdby.Name, Owner.Name, RecordType.Name, Status from Task where WhoId =: currentRecordId AND Subject LIKE 'E-Mail:%']) {
        wrapperList.add(new Wrapper(a, 'E-Mail'));
    }
    for(Task a: [select Id, Subject, CreatedDate, Createdby.Name, Owner.Name, RecordType.Name, Status from Task where WhoId =: currentRecordId AND (NOT Subject LIKE 'E-Mail:%')]) {
        wrapperList.add(new Wrapper(a, 'Aufgabe'));
    }
    for(Event b: [select Id, Subject, CreatedDate, StartDateTime, Createdby.Name, Owner.Name from Event where WhoId =: currentRecordId]) {
        wrapperList.add(new Wrapper(b, 'Termin'));
    }
    for(ContentDocumentLink d: [SELECT Id, ContentDocumentId, ContentDocument.Title, ContentDocument.createdDate, ContentDocument.Createdby.Name, ContentDocument.FileExtension FROM ContentDocumentLink WHERE LinkedEntityId =: currentRecordId AND ContentDocument.FileExtension = 'snote']) {
        wrapperList.add(new Wrapper(d, 'Notiz'));
    }
    for(ContentDocumentLink d: [SELECT Id, ContentDocumentId, ContentDocument.Title, ContentDocument.createdDate, ContentDocument.Createdby.Name, ContentDocument.FileExtension FROM ContentDocumentLink WHERE LinkedEntityId =: currentRecordId AND ContentDocument.FileExtension <> 'snote']) {
        wrapperList.add(new Wrapper(d, 'Datei'));
    }
    wrapperList.sort();

    return JSON.serialize(wrapperList);
}

Inside your component, you just need to convert the String back to JSON, using JSON.parse.
@wire(getWrapperData)
dataFn({data}){
    if(data){
        this.data = JSON.parse(data);
    }
}


text:
Q: jQuery UI Sortable - saving order when button clicked I have a list with items that should be sorted by the user with jQuery UI Sortable. After the user has chosen his final order of the list he has to click a button "Ready". After the button is clicked, the order should be sent to saveoder.php using serialize and Ajax.
I tried to surround the ajax call with a click event but then there will be a couple of POST-requests done depending on the count of sortable actions of the user. I need only one ajax post request.

$(function() {
 $( "#sortable" ).sortable({
  update: function(event, ui) {
   var order = $(this).sortable('serialize');

   $(document).on("click", "button" , function() { //that doesn't work
    $.ajax({
     data: order,
     type: 'POST',
     url: 'saverank.php'
    });
   });
  }
 }).disableSelection();
});

Item 1

Item 2

Item 3

<button>Ready</button>

A: There is a builtin method for doing this. Refer serialize or toArray
Demo: http://jsfiddle.net/lotusgodkk/GCu2D/539/
JS:
$(function () {
    $("#sortable").sortable({
        update: function (event, ui) {
            var order = $(this).sortable('serialize');

            $(document).on("click", "button", function () { //that doesn't work
                $.ajax({
                    data: order,
                    type: 'POST',
                    url: 'saverank.php'
                });
            });
        }
    }).disableSelection();
    $('button').on('click', function () {
        var r = $("#sortable").sortable("toArray");
        var a = $("#sortable").sortable("serialize", {
            attribute: "id"
        });
        console.log(r, a);
    });
});

A: For single ajax call. Modified from accepted answer

$(function () {
    $("#sortable").sortable({
        update: function (event, ui) {
            var order = $(this).sortable('serialize');
        }
    }).disableSelection();
    $('button').on('click', function () {
        var a = $("#sortable").sortable("serialize", {
            attribute: "id"
        });
        console.log(a);
        $.ajax({
            data: a,
            type: 'POST',
            url: 'saverank.php'
        });
    });
});


text:
Q: Streaming Out Extended ASCII I know that only positive character ASCII values are guaranteed cross platform support.
In Visual Studio 2015, I can do:
cout << '\xBA';

And it prints:

║

When I try that on http://ideone.com I don't print anything.
If I try to directly print this using the literal character:
cout << '║';

Visual Studio gives the warning:

warning C4566: character represented by universal-character-name '\u2551' cannot be represented in the current code page (1252)

And then prints:

?

When this command is run on http://ideone.com I get:

14849425

I've read that wchars may provide a cross platform approach to this. Is that true? Or am I simply out of luck on extended ASCII?

A: There are two separate concepts in play here.
The first one is one of a locale, which is often called "code page" in Microsoft-ese. A locale defines which visual characters are represented by which byte sequence. In your first example, whatever locale your program gets executed as, it shows the "║" character, in response to the byte 0xBA.
Other locales, or code pages, will display different characters for the same bytes. Many locales are multibyte locales, where it can take several bytes to display a single character. In the UTF-8 locale, for example, the same character, ║, takes three bytes to display: 0xE2 0x95 0x91.
The second concept here is one of the source code character set, which comes from the locale in which the source code is edited, before it gets compiled. When you enter the ║ character in your source code, it may get represented, I suppose, either as the 0xBA character, or maybe 0xE2 0x95 0x91 sequence, if your editor uses the UTF-8 locale. The compiler, when it reads the source code, just sees the actual byte sequence. Everything gets reduced to bytes.
Fortunately, all C++ keywords use US-ASCII, so it doesn't matter what character set is used to write C++ code. Until you start using non-Latin characters. Which result in a compiler warning, informing you, basically, that you're using stuff that may or may not work, depending on the eventual locale the resulting program runs in.

A: First, your input source file has its own encoding. Your compiler needs to be able to read this encoding (maybe with the help of flags/settings).
With a simple string, the compiler is free to do what it wants, but it must yield a const char[]. Usually, the compiler keeps the source encoding when it can, so the string stored in your program will have the encoding of your input file. There are cases when the compiler will do a conversion, for example if your file is UTF-16 (you can't fit UTF-16 characters in chars).
When you use '\xBA', you write a raw character, and you chose yourself your encoding, so there is no encoding from the compiler.
When you use '║', the type of '║' is not necessarily char. If the character is not representable as a single byte in the compiler character set, its type will be int. In the case of Visual Studio with the Windows-1252 source file, '║' doesn't fit, so it will be of type int and printed as such by cout <<.
You can force an encoding with prefixes on string literals. u8"" will force UTF-8, u"" UTF-16 and U"" UTF-32. Note that the L"" prefix will give you a wide char wchar_t string, but it's still implementation dependent. Wide chars on Windows are UCS-2 (2 bytes per char), but UTF-32 (4 bytes per char) on linux.
Printing to the console only depends on the type of the variable. cout << is overloaded with all common types, so what it does depends on the type. cout << will usually feed char strings as is to the console (actually stdin), and wcout << will usually feed wchar_t strings as is. Other combinations may have conversions or interpretations (like feeding an int). UTF-8 strings are char strings, so cout << should always feed them correctly.
Next, there is the console itself. A console is a totally independent piece of software. You feed it some bytes, it display them. It doesn't care one bit about your program. It uses its own encoding, and try to print the bytes you fed using this encoding.
The default console encoding on Windows is Code page 850 (not sure if it is always the case). In your case, your file is CP 1252 and your console is CP 850, which is why you can't print '║' directly (CP 1252 doesn't contain '║'), but you can using a raw character. You can change the console encoding on Windows with SetConsoleCP().
On linux, the default encoding is UTF-8, which is more convenient because it support the whole Unicode range. Ideone uses linux, so it will use UTF-8. Note that there is the added layer of HTTP and HTML, but they also use UTF-8 for that.


text:
Q: Set max Date in datapicker field JSP I need to set maximum date in datapicker field. I use jQuery UI
function zerofill(i) {
    return (i < 10 ? '0' : '') + i;
}

$( function() {
    var now = new Date();
    var today = now.getFullYear() + '-' + zerofill(now.getMonth() + 1) + '-' + now.getDate();
    $( "input[id^='datepicker']" ).datepicker({
        dateFormat: "yy-mm-dd",
        maxDate: "0",
        minDate: "-60",
        monthNames: [ "Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Pańdziernik", "Listopad", "Grudzień" ]
    }).val(today);
});

Here I have maxDate: "0" field which work just fine:

but still it is possible to change date by hand in field.
I used
<input class="form-control" type="text" id="datepicker[2]" min="<%=LocalDate.now().minusMonths(2)%>"
  max="<%=LocalDate.now()%>" name="calculationDate">

but it doesn't work as I expected.


text:
Q: Detect changes of a select inside ng-repeat I'm new in Angularjs and i've some problems to detetect changes in my first select inside a ng-repeat. i want to detect changes to update the second select using a function in my controller.

    <select id="field_type" name="type" ng-model="detailDemande.type" ng-options="typeMateriel as typeMateriel.nom for typeMateriel in vm.types | orderBy:'nom' track by typeMateriel.id" >
                        </select>

<select  id="field_article" name="article" ng-model="detailDemande.article" ng-options="article as article.nom for article in vm.articles | orderBy:'nom' track by article.id">
                        <option value=""></option>
                    </select>

Please help
Thanks

A: Assume this is your first select (I've cut down the ng-options just for space):
<select id="field_type" name="type"
  ng-options="typeMateriel in vm.types"
  ng-model="vm.detailDemande.type" ng-change="vm.changeSelect()" />

Then this is your second select:
<select id="field_article" name="article"
  ng-options="article in vm.articles"
  ng-model="vm.detailDemande.article" />

In the first select's html there is the ng-change attribute, pointing at a method in the controller. You can use this to then change what appears in vm.articles:
changeSelect() {
  if (detailDemande.type === 'foo') {
    this.articles = ['new', 'list'];
  }
}


text:
Q: Orthograpic + Perspective projection clipping over each other I have a problem when combining the orthographic projection and the Perspective projection.
I'm drawing a texture over a 3d object:

I guess it has something to do with the clipping values:
camProjection = XMMatrixPerspectiveFovLH(0.4f * 3.14f, (float)SCREEN_WIDTH/SCREEN_HEIGHT, 1.0f, 1000.0f);
camProjection2D = XMMatrixOrthographicOffCenterLH(.0f, SCREEN_WIDTH, SCREEN_HEIGHT, .0f, 0.0f, 1000.0f);

Texture coords: (x, y, z, u, v)
Vertex( 0.0f,  0.0f, -1.0f, 0.0f, 1.0f),
Vertex( 0.0f, 20.0f, -1.0f, 0.0f, 0.0f),
Vertex(20.0f, 20.0f, -1.0f, 1.0f, 0.0f),
Vertex(20.0f,  0.0f, -1.0f, 1.0f, 1.0f),

I hope someone can help me with this problem.
Its not a big problem but its bugging me.

A: You're probably trying to display UI over your rendered scene. The standard way to do this is to render you scene first, then clear your z-buffer before drawing UI elements. This way there will be no z-fighting and interference from objects close to camera.


text:
Q: Allegro 4 text output I'm trying to display the text contained in a text file using Allegro 4, I have no trouble doing it while on the console on C++, but when I try to switch from cout<< to textprintf I get some errors, here's the code of the part I have trouble with:
do{
    char c;
    c=archivo.get();
    textprintf(screen,font,300,300,15,"%s,%d",c,1);
}while(!archivo.eof());
system("pause");
archivo.close();


text:
Q: Fatal Exception on starting activity Android I have created new activity that my MainActivity Should lunch, some why the application is crashing on the start of the new activity (called GamePlayActivity).
Here is the java code:
Intent startGameDrill = new Intent(MainActivity.this, GamePlayActivity.class);
    startActivity(startGameDrill);

Here is the startGameDrill:
package com.simplemathgame;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class GamePlayActivity extends MainActivity {
    int addDrills;
    int subDrils;
    int mulDrills;
    int divDrills;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_play);

        try {
            numberOfAddDrills = (TextView) findViewById(R.id.add_drills_number);
            numberOfSubDrills = (TextView) findViewById(R.id.sub_drills_number);
            numberOfMulDrills = (TextView) findViewById(R.id.mul_drills_number);
            numberOfDivDrills = (TextView) findViewById(R.id.div_drills_number);
            minBoundText = (TextView) findViewById(R.id.min_text);
            maxBoundText = (TextView) findViewById(R.id.max_text);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            Log.w("game","error");
        }

        try {
            addDrills = Integer.parseInt((String) numberOfAddDrills.getText());
            subDrils = Integer.parseInt((String) numberOfSubDrills.getText());
            mulDrills = Integer.parseInt((String) numberOfMulDrills.getText());
            divDrills = Integer.parseInt((String) numberOfDivDrills.getText());
        } catch (NumberFormatException e) {
            Log.w("GameDrills","string to int");
        }
        Log.w("add", "" + addDrills);
        Log.w("add", "" + subDrils);
        Log.w("add", "" + mulDrills);
        Log.w("add", "" + divDrills);
    }

}

Here is the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.simplemathgame"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.simplemathgame.Splash"
            android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.simplemathgame.MainActivity"
            android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
            <intent-filter>
                <action android:name="com.simplemathgame.MainActivity" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <activity
            android:name="com.simplemathgame.GamePlayActivity"
            android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
        </activity>
    </application>

</manifest>

here is the logCat:
12-21 22:05:53.949: D/dalvikvm(610): GC_EXTERNAL_ALLOC freed 42K, 53% free 2546K/5379K, external 1917K/2137K, paused 41ms
12-21 22:06:32.809: D/AndroidRuntime(610): Shutting down VM
12-21 22:06:32.809: W/dalvikvm(610): threadid=1: thread exiting with uncaught exception (group=0x40015560)
12-21 22:06:32.818: E/AndroidRuntime(610): FATAL EXCEPTION: main
12-21 22:06:32.818: E/AndroidRuntime(610): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.simplemathgame/com.simplemathgame.GamePlayActivity}: java.lang.NullPointerException
12-21 22:06:32.818: E/AndroidRuntime(610):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
12-21 22:06:32.818: E/AndroidRuntime(610):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-21 22:06:32.818: E/AndroidRuntime(610):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-21 22:06:32.818: E/AndroidRuntime(610):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-21 22:06:32.818: E/AndroidRuntime(610):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-21 22:06:32.818: E/AndroidRuntime(610):  at android.os.Looper.loop(Looper.java:123)
12-21 22:06:32.818: E/AndroidRuntime(610):  at android.app.ActivityThread.main(ActivityThread.java:3683)
12-21 22:06:32.818: E/AndroidRuntime(610):  at java.lang.reflect.Method.invokeNative(Native Method)
12-21 22:06:32.818: E/AndroidRuntime(610):  at java.lang.reflect.Method.invoke(Method.java:507)
12-21 22:06:32.818: E/AndroidRuntime(610):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-21 22:06:32.818: E/AndroidRuntime(610):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-21 22:06:32.818: E/AndroidRuntime(610):  at dalvik.system.NativeStart.main(Native Method)
12-21 22:06:32.818: E/AndroidRuntime(610): Caused by: java.lang.NullPointerException
12-21 22:06:32.818: E/AndroidRuntime(610):  at com.simplemathgame.GamePlayActivity.onCreate(GamePlayActivity.java:31)
12-21 22:06:32.818: E/AndroidRuntime(610):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-21 22:06:32.818: E/AndroidRuntime(610):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
12-21 22:06:32.818: E/AndroidRuntime(610):  ... 11 more

Here is the layout of the GamePlayActivity:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:background="#000044">
    <TableRow
        android:layout_marginTop="10dp"
        android:gravity="center_vertical" >
        <TextView
            android:textColor="#FFFFFFFF"
            android:textSize="16sp"
            android:textStyle="bold"
            android:text="Addition Drills:"/>
    </TableRow>
</TableLayout>

Why does it crashes?

A: Have a look here:
12-21 22:06:32.818: E/AndroidRuntime(610): Caused by: java.lang.NullPointerException
12-21 22:06:32.818: E/AndroidRuntime(610):  at com.simplemathgame.GamePlayActivity.onCreate(GamePlayActivity.java:31)

Line 31 of GamePlayActivity.java is this line:
addDrills = Integer.parseInt((String) numberOfAddDrills.getText());

Since the only thing on this line that you reference a member or method of is numberOfAddDrills, then it must be null.
Consider that you are checking for exceptions when using findViewById; however, if the view is not found it will just return null, not throw an exception.
Have a look at the activity_game_play.xml you posted; there is no TextView with android:id="@+id/add_drills_number". You need to create it, and the same deal for the other five TextViews.
Oh, and a hint: Don't just catch generic exceptions with } catch (Exception e1) {, especially if you have no intent of reading the logs. I can't tell you how many times people have missed errors from doing this.
If you want to pass values from another layout, you have two options: keep a reference to the View objects (this is a bit silly, don't do this); or pass the data you need from them to your new Activity:
startGameDrill.putExtra("myIntExtra", 5); // For example

Then, in GamePlayActivity.onCreate(), you can fetch it using getIntent()'s extras:
Bundle extras = getIntent().getExtras();
int myIntExtra = extras.getInt("myIntExtra");

Then use that value instead of relying on the view in the previous layout. There is a fuller example in this answer.

A: Follow the stacktrace until you find some references to your classes:
It shows:
12-21 22:06:32.818: E/AndroidRuntime(610): Caused by: java.lang.NullPointerException
12-21 22:06:32.818: E/AndroidRuntime(610):  at com.simplemathgame.GamePlayActivity.onCreate(GamePlayActivity.java:31)

So you are creating a NullPointerException at line 31 in GamePlayActivity.java
Line 31:
addDrills = Integer.parseInt((String) numberOfAddDrills.getText());

so maybe numberOfAddDrills is null?


text:
Q: Keras LSTM error: Input from layer reshape is incompatible with layer lstm Using RapidMiner I want to  implement an LSTM to classify patternes in a time series. Input data is a flat table. My first layer in the Keras operator is a core reshape from exampleset_length x nr_of_attributes to batch x time-steps x features. In the reshape parameter I specifically enter three figures because I want a specific amount of features and time-steps. The only way to achieve this is to specify also batch size, so in total three  figures. But when I add a RNN LSTM layer an error is returned: Input is incompatible with layer lstm expected ndim=n found ndim=n+1. What's wrong?

A: When specifying 'input_shape' for the LSTM layer, you do not include the batch size.
So your 'input_shape' value should be (timesteps, input_dim).
Source: Keras RNN Layer, the parent layer for LSTM


text:
Q: Vue.js : 'v-if' in dynamic child component throws not defined error I have a child component that I am $emiting a v-on:blur event and a v-if condition if on:blur returns an error:
                   <template>
                           <input type="text"
                           class="form-control"
                           id="input-username"
                           name="custid"
                           v-on:blur="$emit('hasValidCustomerId')"
                           v-model="custid"/>

 Error!

                  <template/>

And a Parent Component which has a slide show of child components.:

            <transition name: currentTransition>
                <component
                       v-on:changeSlide="changeSlide"
                       v-on:blur="hasValidCustomerId"
                       :is="slides[currentSlide]">
                </component>
            </transition>

Both click event and the on blur events I am emitting seem fine. But when it hits the v-if, I get an error
 VM17881 vue.js:491 [Vue warn]: Property or method "custidError" is not defined on the instance but referenced during render.

found in

---> <AccountDetails>
       <PasswordFlow>
         <Root>

My javascript:
//////// child component
    var accountDetails =
      {
        template: '#template',
        components: { },
        data: function () {
         return {};
      },
        computed: {},
        methods: {},
      };
//////// parent component
      var passwordFlow =
        {
        template: '#template',
        components: {
            "login": login,
            "account-details": accountDetails,
            "otc-options": otcOptions
        },
        data: function () {
          return {
              slides: ['login', 'account-details', 'otc-options'],
              currentSlide: 0,
              currentTransition: ' '
              custid: '',
              custidError: false //throws error not defined
             };
          },

        computed: {},
        methods: {
              hasValidCustomerId: function () {
              if (this.custid !== "" && !validation_customerid.test(this.custid)) {
              this.custidError = true;
           }
        },
      };

And my VUE instance:
   var vm = new Vue({
        el: "#login-main",
       data: {},
       components: {
           "passwordFlow": passwordFlow,
            },
       computed: {},
       mounted: function () { },
       methods: {}
   });

The error is saying the property in the v-if "custidError " is undefined. However it is defined in the parent. Am I supposed to emit the v-if statement?

A: You should pass your props to the dynamic component as follows :
<component
           v-on:changeSlide="changeSlide"
           v-on:blur="hasValidCustomerId"
         :is="slides[currentSlide]">
          v-bind="{custidError:custidError}"
</component>

In child component define the custidError props:
//////// child component
    var accountDetails =
      {
        template: '#template',
         props:['custidError'],
        components: { },
        data: function () {
         return {};
      },
        computed: {},
        methods: {},
      };


text:
Q: Does Alexa Skill Kit listen on other port of SSL (besides 443) I created a skill from Alexa skill kits on Amazon development. The API endpoint is from my home server running PHP. It works fine but now I have another server running and is listening on port 444 (with SSL). I use same domain name and SSL certificate on this new server (Apache). But now Alexa skill kit doesn't seem to send anything to my API endpoint.
I don't know if the Alexa skill kit only sends request over 443 only or my set up is wrong?
For example, my current working node is: https://myserver.com/api/main.php
My new server: https://myserver.com:444/api/main.php
The reason for this weird 444 port is port 443 is taken on my home public ip (port forwarding). So I need my public IP to forward request to my new server if it sees port 444. I'm new to all this so please excuse all my noob set up here.

A: To my understanding the Alexa service is restricted to using API endpoints with port 443 only. I had come to this conclusion after some testing, then stumbled upon this blog article when searching for answers to this before:
https://freebusy.io/blog/getting-started-with-alexa-app-development-for-amazon-echo-using-dot-net

The Alexa service is strict regarding app endpoints. It will only call
  out using HTTPS on port 443 whether it's calling an app during
  development or deployed to production.
-Stefan at FreeBusy.io

However, you can make requests from a Lambda function without such restrictions and could achieve making requests to both ports on HTTPS or HTTP.
I hope this helps.


text:
Q: Is it a good practice for angular Directive append itself (selector) into the document? I am making a modal dialog with selector:<test-modal> using ng-bootstrap. I originally want to make it as a component. But then it will be like navbar which I need to put it in AppComponent and every page sharing same modal component. The logic seems incorrect.
So I try to make a directive than allow every page can have it own modal. But then I have put the <test-modal> in every component which "may" need modal. So every page no matter will prompt the modal or not will have to include this code. I am not sure if it is normal practice.
Then I find out this page:
https://jasonwatmore.com/post/2018/05/25/angular-6-custom-modal-window-dialog-box
it makes modal as a dynamic directive and will append the <test-modal> to the document html just when it is needed and the directive is being called. Is it the best practice? Thanks in advance.

A: Dynamic adding components or directives is a technique documented in Angular as it offers a way to add component/ directives dynamically, such as the moment we want to use
 not when application is bootstrapping. It's a normal practice in Angular and the document is specified here.
One important thing is that it will not destroy but add new component every time it's triggered which could lower performance of application from time to time. So simply add one or limited number of dynamic components and try to re-use will help to improve performance. In your case, to populating a modal, it should be adding only one component to wrap a modal, then output different message every time it's called.


text:
Q: Php - How can I display time followed my selected value in same input field How can I display date followed by a string selected from the dropdown list in Php? I have 8 department options for a user to select from. Once a department is selected then the user clicks the button. Depending on what department was selected. Department abbreviation needs to show up in the input field followed by time.when that button is pressed the page should issue an AJAX request with the department chosen to another PHP file on the server to get a PO number, formatted like ${DEPT}${Year}${Month}${Day w/ Leading zero}.
I have got the date down so far. but not sure how to include the selected value and date together to output.
`var currentDate = new Date();
    var day = currentDate.getDate();
    var month = currentDate.getMonth() + 1;
    var year = currentDate.getFullYear();

        if(day < 10){
            day = '0' + day
            }

        if (mm < 10){
            month = '0' + month
             }

        document.getElementById("date").innerHTML =("" + day + "/" +
          month + "/" + year + "");`

A: in javascript you can doit like so

   <input type="text" id="show-input">
   <select id="dept">
       <option value="option1">option1</option>
       <option value="option2">option2</option>
   </select>
   <input type="submit" id="save">

then in you main js file
document.querySelector('#save').addEventListener('click', () => {
   const dept = document.querySelector("#dept").value;
   const date = new Date().toDateString(); // you can getDay() or getYear()
   document.querySelector('#show-input').value = dept + date
});


text:
Q: Remove Stop Words From text File i want to remove stop words from my text file and i write the following code for this purpose
 TextWriter tw = new StreamWriter("D:\\output.txt");
 private void button1_Click(object sender, EventArgs e)
        {
            StreamReader reader = new StreamReader("D:\\input1.txt");
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                string[] parts = line.Split(' ');
                string[] stopWord = new string[] { "is", "are", "am","could","will" };
                foreach (string word in stopWord)
                {
                    line = line.Replace(word, "");
                    tw.Write("+"+line);
                }
                tw.Write("\r\n");
            }

but it doesn't show the result in the output file and the output file remain empty.

A: A regular expression might be perfect for the job:
        Regex replacer = new Regex("\b(?:is|are|am|could|will)\b");
        using (TextWriter writer = new StreamWriter("C:\\output.txt"))
        {
            using (StreamReader reader = new StreamReader("C:\\input.txt"))
            {
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    replacer.Replace(line, "");
                    writer.WriteLine(line);
                }
            }
            writer.Flush();
        }

This method will only replace the words with blanks and do nothing with the stopwords if they are part of another word.
Good luck with your quest.

A: The following works as expected for me. However, it's not a good approach because it will remove the stop words even when they are part of a larger word. Also, it doesn't clean up extra spaces between removed words.
string[] stopWord = new string[] { "is", "are", "am","could","will" };

TextWriter writer = new StreamWriter("C:\\output.txt");
StreamReader reader = new StreamReader("C:\\input.txt");

string line;
while ((line = reader.ReadLine()) != null)
{
    foreach (string word in stopWord)
    {
        line = line.Replace(word, "");
    }
    writer.WriteLine(line);
}
reader.Close();
writer.Close();

Also, I recommend using using statements for when you create your streams in order to ensure the files are closed in a timely manner.

A: You should wrap your IO objects in using statements so that they are disposed properly.
using (TextWriter tw = new TextWrite("D:\\output.txt"))
{
    using (StreamReader reader = new StreamReader("D:\\input1.txt"))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            string[] parts = line.Split(' ');
            string[] stopWord = new string[] { "is", "are", "am","could","will" };
            foreach (string word in stopWord)
            {
                line = line.Replace(word, "");
                tw.Write("+"+line);
            }
        }
    }
}

A: Try wrapping StreamWriter and StreamReader in using() {} clauses.
using (TextWriter tw = new StreamWriter(@"D:\output.txt")
{
  ...
}

You may also want to call tw.Flush() at the very end.


text:
Q: Storing iso8601 string stored in ActiveRecord as string or datetime? I'm trying to write a schema for an ActiveRecord object.
I've decided to use iso8601 format throughout my application, including for external api requests.
Should the column be a string or datetime?
Is there any performance impact or distinction between the two?

A: Storing the date in the database as a date or datetime means you can use the date functions like comparing dates in the database. And it gives you the freedom to present the date in whichever format you choose, making it easy to do so if the formatting requirements change in the future, without having to touch the database.
Whereas storing the date in the database as a string removes all these advantages. You no longer can use database date functions. Plus, If you decide to use another format (maybe in a newer version of the API or for mobile apps... etc), you will need to parse the string back into a date/datetime object, which is not very appealing to do.
As a general good practice: the way you store data should be agnostic to the way you present it, when possible.


text:
Q: Normal Force Discrepancy for Wedge Vs. Ramp I have seen a few posts on this subject before, but none have really answered my question.  For clarity, I will refer to the 1st example as a wedge, and the second as a ramp (although both are of course inclined planes). With both examples that I outline below, we will assume no friction, and a massless wedge/ramp for the sake of simplicity.  First, we can begin with the normal force generated from a wedge, for which we know the IMA to be >= 1 provided 45° > theta > 0:

In the case of the wedge, the horizontal force required to maintain equilibrium (F_x) is less than the vertical force applied to the wedge (mg).  In this case (static equilibrium), F_y=mg, therefore F_N=mg/cos(theta).  Intuitively, this makes sense as we would expect the mechanical advantage of the wedge to be greater than unity for angles < 45°, and therefore F_N should be greater than the input force, F_x.
Now, consider the case in which the block is placed on a ramp. There are two reasonable choices for our reference frames - one in which the x axis is parallel to the base of the ramp, and one in which the x axis is parallel to the slope of the ramp.  In this case, the choice of reference frame should not affect the description of the normal force.  In general, it is more advantageous to choose the latter, which is what we have done below:

Shown above is the typical force decomposition that is seen for "ramp" problems, which is similar to the diagram from the wikipedia page on inclined planes, shown below:

In the above "ramp" case, the normal force is given as F_N=mg*cos(theta).  And this is where my quandary lies - for two similar problems, why do we have different results for the normal force?  Which is the correct description of the normal force for both cases?
I feel like I can provide convincing arguments for either case.  I am trying to build both physical intuition, and concrete mathematical evidence of which case is correct.  Any help is greatly appreciated, thank you.


text:
Q: Why is this query returning each student - month pairing individually? SELECT To_Char(registrationdate, 'Month') AS "REGDATE", COUNT(*) AS "NUMSTUDENTS"
FROM registration r
INNER JOIN students s
ON r.studentid = s.studentid
GROUP BY registrationdate
ORDER BY NUMSTUDENTS;

Results are coming back like this:
May         1
April       1
April       1
May         1
April       1
May         1
April       1
May         1

And the expected results are
June                                             213
March                                            258
October                                          291
January                                          325
July                                             328
September                                        333
November                                         359
etc.

I am just trying to get the results to be total students per month, I don't know what I'm missing

A: You are grouping by RegistrationDate, which has a 1-second granularity. As long as no more than one entry occurs per second, you are going to see 1s. To fix, put the same function on it in the GROUP BY that you did in the SELECT:
SELECT To_Char(registrationdate, 'Month') AS "REGDATE", COUNT(*) AS "NUMSTUDENTS"
FROM registration r
INNER JOIN students s
ON r.studentid = s.studentid
GROUP BY To_Char(registrationdate, 'Month')
ORDER BY NUMSTUDENTS;


text:
Q: An extension of line bundles splits locally Consider an extension $0\rightarrow L \overset{\alpha}{\rightarrow} E \overset{\beta}{\rightarrow} L' \rightarrow 0$ of bundles and bundle homomorphisms, where $L$ and $L'$ are line bundles. (Let's assume that all bundles and maps are holomorphic.)
Does it split locally? i.e. is there an open cover $\{U_i\}$ and maps $\sigma_i: L'\vert_{U_i} \rightarrow E\vert_{U_i}$ such that $\beta\circ \sigma_i = \text{id}$?
You could use a common trivialization for $L$, $L'$, and $E$, and then you get an extension of trivial bundles, say $0\rightarrow U\times \mathbb{C} \rightarrow U\times \mathbb{C}^2 \rightarrow U\times \mathbb{C} \rightarrow 0$. So a related question is: do extensions of trivial bundles split locally (or even globally)?
In the smooth case you can use a partition of unity to construct a Hermitian metric, and then you get splitting globally. I was hoping to get this local splitting for vector bundles in any setting, i.e. smooth, holomorphic, algebraic, etc.

A: I'll just shortly elaborate about the algebraic proof.
In fact line bundles are in one-to-one correspondence with locally free sheaves of rank 1.
They are locally given by projective modules (locally free = projective), and then the proof is just a simple algebraic fact that a surjection onto a projective modules splits, which is just the definition of projective.

A: FWIW, an extension $0 \to F \to E \to Q \to 0$ of holomorphic vector bundles splits locally (holomorphically, but not naturally) by your "common trivialization" argument: Pick a local holomorphic frame $\{e_{1},\dots,e_{n}\}$ for $E$ whose first $m$ elements span the fibre of $F$ at some point $p$. Extend to a local frame $\{f_{1},\dots,f_{m}\}$ for $F$, and note that there exist $mn$ (local) holomorphic functions $a_{jk}$ such that $f_{j} = \sum_{k} a_{jk} e_{k}$.
The elements $\{e_{m+1},\dots,e_{n}\}$ induce a frame of $Q$ provided the sum
$$
\operatorname{span}(f_{1},\dots,f_{m}) + \operatorname{span}(e_{m+1},\dots,e_{n})
$$
is direct. This is true in some neighborhood of $p$ by continuity of holomorphic functions.

A: Given a complex manifold $X$ and two locally free sheaves (=vector bundles)  $\mathcal E, \mathcal G$ on $X$, the extensions $0\to \mathcal E\to   \mathcal F \to     \mathcal G    \to 0$ are classified by the complex vector space $H^1(X,\mathcal {Hom}(\mathcal G ,\mathcal E ))$.
The trivial extension $0\to \mathcal E\to   \mathcal E\oplus   \mathcal G\to     \mathcal G    \to 0$ corresponds to the zero element of that vector space.
In particular over  a Stein manifold all extensions are trivial (Theorem B of Cartan-Serre) and even more in particular all  extensions are trivial over a manifold isomorphic to a ball, for example the domain of a chart.
Conclusion
Yes, over holomorphic manifolds  all exact sequences of vector bundles split locally.
And the same proof, mutatis mutandis, shows that this also holds for differential manifolds, complex analytic spaces, algebraic varieties and schemes.
Bibliography
The classification of extensions mentioned above is Proposition 2 of Atiyah's seminal paper Complex analytic connexions in fibre bundles.

A: Question: "In the smooth case you can use a partition of unity to construct a Hermitian metric, and then you get splitting globally. I was hoping to get this local splitting for vector bundles in any setting, i.e. smooth, holomorphic, algebraic, etc."
Answer: If $(X, \mathcal{O}_X)$ is any ringed topological space and
$$\phi: E \rightarrow F \rightarrow 0$$
is a surjection of locally free sheaves on $X$ where $rk(E)=n, rk(F)=m$ and $m\leq n$
let $U_i$ be an open cover where $E,F$ trivialize and let
$$\phi_{U_i}:E_{U_i}\cong \mathcal{O}_{U_i}\{e_1,..,e_n\} \rightarrow F_{U_i}  \cong \mathcal{O}_{U_i}\{f_1,..,f_m\}$$
be the induced map. Choose $\omega_j\in E(U_i)$ with $\phi_{U_i}(\omega_j)=f_j$ and define for $V \subseteq U_i$
$$\psi_{U_i}(V): F(V) \rightarrow F(V)$$
by
$$\psi_{U_i}(V)(\sum_j  a_j f_j)=\sum_j (\omega_j)_{V}e_j.$$
It follows $\psi_{U_i}: F_{U_i}\rightarrow E_{U_i}$ is a local splitting of $\phi_{U_i}$. There is an equality
$$ \phi_{U_i} \circ \psi_{u_i}=Id_{F_{U_i}}.$$
Hence you can construct such local splitting for any ringed topological space $(X, \mathcal{O}_X)$.


text:
Q: is it possible to provide variable arguments to xinetd service? I have created a bash script to listen on specific port (using xinetd), so whenever there is someone connecting to port, then it invokes the script and provides its output to user. But i need to provide dynamic arguments to server, for example when i telnet to server like
telnet myserver 4535

then i should be able to pass an argument like my name "Frank" and it should say
"Hello Frank"

There is a parameter of server-args in xinetd config, but i am not sure that arguments to it can be passed dynamically through the telnet or not.

A: On the initial telnet command line, I doubt you'll be able to put passable arguments.  However, as part of the transactions between the server and client you'll certainly be able to do something like this.


text:
Q: Why am I getting Zlib::DataError? I am posting to a remote server that I do not have control over. The params that are being passed are definitely a factor in the problem but I am having a hard time figuring out why it is failing. It does not look like there is a big enough change to create an error. I have never handled zlib compression directly. Is there a way to get better error output? Example:
This passes:
 {"email" => "a@bc.com"}

This fails:
 {"email" => "a@bd.com"}

Ruby 2.2 / Rails 4
The error:
 #<Zlib::Inflate:0x0000000618ea38 @dictionaries={}>
 #<Zlib::DataError: invalid block type>
 "invalid block type"
[ 0] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:377:in `inflate'",
[ 1] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:377:in `block in inflate_adapter'",
[ 2] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/protocol.rb:411:in `call_block'",
[ 3] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/protocol.rb:402:in `<<'",
[ 4] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/protocol.rb:106:in `read'",
[ 5] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:399:in `read'",
[ 6] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:317:in `read_chunked'",
[ 7] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:281:in `block in read_body_0'",
[ 8] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:260:in `inflater'",
[ 9] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:279:in `read_body_0'",
[10] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:201:in `read_body'",
[11] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:226:in `body'",
[12] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http/response.rb:163:in `reading_body'",
[13] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:1411:in `catch'",
[14] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:1411:in `transport_request'",
[15] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:1384:in `request'",
[16] "/home/pete/.rvm/gems/ruby-2.2.2@umbie/gems/rest-client-1.6.9/lib/restclient/net_http_ext.rb:51:in `request'",
[17] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:1377:in `block in request'",
[18] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:853:in `start'",
[19] "/home/pete/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/net/http.rb:1375:in `request'",
[20] "/home/pete/.rvm/gems/ruby-2.2.2@umbie/gems/rest-client-1.6.9/lib/restclient/net_http_ext.rb:51:in `request'"

Method that throws error in response.rb
 def inflate_adapter(dest)
  if dest.respond_to?(:set_encoding)
    dest.set_encoding(Encoding::ASCII_8BIT)
  elsif dest.respond_to?(:force_encoding)
    dest.force_encoding(Encoding::ASCII_8BIT)
  end
  block = proc do |compressed_chunk|
    @inflate.inflate(compressed_chunk) do |chunk| # This is line 377
      dest << chunk
    end
  end

  Net::ReadAdapter.new(block)
end

3rd party library:
  require 'net/http'
  require 'uri'
  require 'cgi'
  require 'rubygems'
  require 'json'
  module ConnectionHelper
    class Connection
      attr_accessor :practiceid
      attr_reader :token

      def initialize(version, key, secret, practiceid=nil)
        uri = URI.parse('https://api.remote_url.com/')
        @connection = Net::HTTP.new(uri.host, uri.port)
        @connection.use_ssl = true
        # Monkey patch to make Net::HTTP do proper SSL verification.
        # Background reading:
        # http://stackoverflow.com/a/9238221
        # http://blog.spiderlabs.com/2013/06/a-friday-afternoon-troubleshooting-ruby-openssl-its-a-trap.html
        def @connection.proper_ssl_context!
          ssl_context = OpenSSL::SSL::SSLContext.new
          ssl_context.verify_mode = OpenSSL::SSL::VERIFY_PEER
          cert_store = OpenSSL::X509::Store.new
          cert_store.set_default_paths
          ssl_context.cert_store = cert_store
          @ssl_context = ssl_context
        end
        @connection.proper_ssl_context!
        # End monkey patch
        @version = version
        @key = key
        @secret = secret
        @practiceid = practiceid

        authenticate
      end

      def authenticate            # :nodoc:
        auth_paths = {
          'v1' => 'oauth',
          'preview1' => 'oauthpreview',
          'openpreview1' => 'oauthopenpreview',
        }
        request = Net::HTTP::Post.new("/#{auth_paths[@version]}/token")
        request.basic_auth(@key, @secret)
        request.set_form_data({'grant_type' => 'client_credentials'})
        response = @connection.request(request)
        authorization = JSON.parse(response.body)
        @token = authorization['access_token']
      end

      def path_join(*args)        # :nodoc:
        head = '^/+'
        tail = '/+$'
        # add a slash to each slash-trimmed string, grab the non-empty ones, and join them up
        return args.map { |arg| '/' + arg.to_s.gsub(/#{head}|#{tail}/, '') }.select { |x| !x.empty? }.join('')
      end

      def call(request, body, headers, secondcall=false)
        begin
          request.set_form_data(body)
          headers.each {
            |k, v|
            request[k] = v
          }
          request['authorization'] = "Bearer #{@token}"
          response = @connection.request(request)

          if response.code == '401' && !secondcall
            authenticate
            return call(request, body, headers, secondcall=true)
          end
          return JSON.parse(response.body)
        rescue Exception => e
          puts e.message
        end
      end

      def POST(path, parameters=nil, headers=nil)
        url = path
        parameters ||= {}
        headers ||= {}
        request = Net::HTTP::Post.new(path_join(@version, @practiceid, url))
        return call(request, parameters, headers)
      end

    private :authenticate, :path_join, :call
    end
  end

Update
I am able to get a valid response from the web view API tester when it fails. I have posted a good and bad response below. It would seem that there is a validation error on the remote servers end and for some reason their response can not be parsed by zlib.
Bad response:
 #Header
 Content-Type: application/json
 Date: Wed, 22 Jun 2016 19:39:59 GMT
 Nncoection: close
 Pragma: No-cache
 Server: Apache
 Vary: Accept-Encoding
 X-Mashery-Message-Id: 524sd54sd-21sd-s5d4-89ds-54sd54sd4s5d4
 X-Mashery-Responder: some_site.com
 Transfer-Encoding: chunked
 Connection: keep-alive

 #Body
 {
  "fields": ["email", "mobilephone", "workphone", "zip"],
  "error": "Data for one or more of the fields listed above are required to successfully create or find a patient record. Note: invalid phone numbers are ignored."
 }

Good Response:
 #Header
 Cache-Control: no-cache, no-store
 Content-Type: application/json
 Date: Wed, 22 Jun 2016 19:41:19 GMT
 Expires: Mon, 06 Jan 1975 16:00:00 GMT
 Nncoection: close
 Pragma: No-cache
 Server: Apache
 Vary: Accept-Encoding
 X-Mashery-Message-Id: s5ad4as5d-5s4d-5s4d-3545-s5d4s5d453s4d
 X-Mashery-Responder: some_site.com
 Content-Length: 22
 Connection: keep-alive

 #Body
 [{
   "personid": "4131"
 }]

I do not know if it matters but there is no "accept-encoding" and it defaults to: "gzip;q=1.0,deflate;q=0.6,identity;q=0.3".

A: The net/http did not know how to handle the response. The solution was to set the request 'accept-encoding' to 'identity'.
    request.set_form_data(body)
    headers.each {
      |k, v|
      request[k] = v
    }

    request["User-Agent"] = "Mozilla/5.0"
    request["accept-encoding"] = "identity"
    request['authorization'] = "Bearer #{@token}"