Use the regular expression feature of Oracle to find all movies whose titles include three or more words

Question: What code should I use to only show titles with three or more words.
So far I have used
SELECT  title
FROM movie
WHERE REGEXP_LIKE (title, '\s+( )')

or would this code work? So far it has but is there another way?
SELECT  title
FROM movie
WHERE REGEXP_LIKE (title, '(\s[A-Z]*){2}')

Comment: What did you try so far?
Answer: Don't use regex! Instead return movies whose name has at least 2 spaces:
SELECT  title
FROM movie
WHERE title LIKE '% % %'

Comment: I doubt a `! ? .` is a string containing three words, so I added some more options to my answer.
Comment: @RyszardCzech I strongly doubt any such edge case exists. Can you find even one such case?
Comment: Yes, I can and do find a lot of such cases. You can't imagine what mess people keep in their databases.
Comment: within the domain of movie titles? Can you name one?
Comment: @RyszardCzech you took my question too literally. I meant "Can you find even one such case *of any commercially released movie, and if so tell us here in a comment*".
Comment: Guys, I meant what I said. Our customers literally keep any junk among what they think should be some specific content. Better safe than sorry.
Comment: The OP doesn't define "word".  I think that interpreted a symbol such as `'?'` separated by spaces as a valid word is a *very* reasonable interpretation of the question.  After all, a solution using regular expressions wouldn't be checking strings against a dictionary of allowed words, so it also has its assumptions and limitations.
Comment: I suppose if the title had been wrongly entered with additional spaces, such as `'Star  Wars'` or `'Mad Max '` then a regex could avoid counting it. But if there are serious data quality issues then you won't get a reliable result whatever approach you use. Like @Bohemian I doubt there are any movie titles containing a punctuation character as a separate word, though, so I wouldn't personally worry about `! ? .`
Comment: Actually now I think about it, I've seen `! ? .` and it's rubbish.
Answer: Depending on what you mean by a word, use
WHERE REGEXP_LIKE (title, '\S+(\s+\S+){2}')

Or,
WHERE REGEXP_LIKE (title, '\w+(\W+\w+){2}')

Or,
WHERE REGEXP_LIKE (title, '[[:alpha:]]+(\s+[[:alpha:]]+){2}')

Where:

\S+  - word is non-whitespaces
\w+ - word contains letters, digits and underscores
\s+ - whitespaces
[[:alpha:]]+ -  word contains letters
{2} - two repetitions.


Racing wheel controllers for XBox 360

Question: I'd like to pick up a racing wheel for the Xbox 360 (bonus points if it supports PC and/or PS3 as well), but I can't find any that seem to be still distributed. Logitech's and Mad Catz's models are discontinued and I can't find even the original Microsoft one either.
Are there particular flaws with the controllers that their respective manufacturers stopped making them? Am I just going to open myself to a world of frustration if I pick one up from eBay or Craigslist?
And while I'm on the subject, are there any wheels still in production today that I missed? I'm in Canada, but not opposed to buying controllers from other parts of the world so long as they're compatible with North American consoles.
Comment: I'm not sure how this meets the criteria for a shopping recommendation; this is the epitome of what we want and expertise we can bring.  It doesn't want us to recommend a product, but specifically detail aspects everyone can look for when making their own choices.
Answer: This is an old question but for everybody looking for an answer right now this would be my answer:
If you are a bit handy whith electronics you likely find GIMX (http://blog.gimx.fr/) useful.
From their website:

GIMX stands for Game Input MultipleXer or Game Input MatriX. The purpose of this free software is to control a video game console with a computer (e.g. a PC or a Raspberry Pi). It works with the PS3, the Xbox 360, the PS4 and the Xbox One.
  It operates:

over bluetooth: works with GNU/Linux (PS3, PS4) only. A compatible
  bluetooth dongle is required.
over usb: works with GNU/Linux and Windows (PS3, PS4, 360, XOne). A USB adapter is required.

The application gets data from the peripherals (mice, keyboards and joysticks) and sends controls to the game console over bluetooth or usb. Other controls such as gesture or voice are possible through the use of external software that emulate peripherals.

Whith GIMX you are able to emulate game controllers. Just find a (second hand) wheel of your taste. Though Logitech Wheels are best supported including some with force feedback (http://blog.gimx.fr/gimx-force-feedback-wheel-support-in-action/)
I just managed to make my 14 year old Microsoft Sidewinder Wheel working with my sons PS4! Though the force feedback is not working (yet?).
Answer: If you are serious about racing take a look at Fanatec wheels. They are more on expensive side but praised by many for their build quality and force feedback (look for reviews on youtube). They also work on all platforms (except some models).
Answer: You can try to look for Thrustmaster's lineup of products. Some of the basic level without FFB are below 100 euros, while the entry level FFB wheels are below 200 euros.

Racing wheel controllers for XBox 360


Django Admin Page broken links

Question: I am deploying a Django app using uwsgi.
The app is deployed under SERVER_URL:PORT.
Using a proxy server, the app can be accessed also via EXTERNAL_WEB_SITE/MY_APP_NAME.
When using the admin page, under: EXTERNAL_WEB_SITE/MY_APP_NAME/ADMIN/, I can see the correct models. But, the links in the admin page that direct to the models themselves direct to: EXTERNAL_WEB_SITE/ADMIN/MAIN_PACKAGE/SELECTED_MODEL/. That is - the MY_APP_NAME won't pass in the link provided.
I suppose this is because in the server itself the app is deployed with no app name, just under a specific port.
In order to solve it, I tried defining FORCE_SCRIPT_NAME=MY_APP_NAME in settings.py. This gives me good links. BUT - when trying to modify an object and save it - under EXTERNAL_WEB_SITE/MY_APP_NAME/ADMIN/MAIN_PACKAGE/SELECTED_MODEL/ITEM/ - after hitting Save I am linked to EXTERNAL_WEB_SITE/MY_APP_NAME/MY_APP_NAME/ADMIN/MAIN_PACKAGE/SELECTED_MODEL/ITEM/ - that is - I get MY_APP_NAME twice.
Does anyone know how to solve this issue?
Answer: you need to pass SCRIPT_NAME env variable with your request from proxy server
alternatively you could have two instances running one with FORCE_SCRIPT_NAME set and second without
uwsgi have a nice option, that you can deploy your app on two ports or (even better) set env variable depending on headers or paths
[uwsgi]
route = ^(/MY_APP_NAME)/ addvar:SCRIPT_NAME=$1

Django Admin Page broken links


When adding an air return to the basement for the sake of habitable space, what considerations should I be making?

Question: I am currently planning to create a finished office space in my basement. I understand that habitable spaces require service from both supply and return air. The house, ~2000sqft over 2 habitable floors, is served by two main return air grates, one upstairs in the ceiling of the landing area, one downstairs in the wall in the kitchen.
My assumption going into making plans for air supply and return for the habitable space in the basement is that the current central air system was not specced or balanced for additional air return, however I am not totally sure if this is the case. Can an air return simply be added without worries of unbalancing the system too terribly?
Additionally, how should I go about calculating the size of the return ducting for the habitable space? The current proposed plans have the habitable space at around 140sqft. I have initially opted to have the return grate be a 10" x 10" to 6" duct. However I am unsure if this will constitute enough airflow to be satisfactory to the space.
Thanks in advance.
Answer: Use the rest of the house as a guide. Add up the floor areas (example 1400 square feet) and add up all the return grille openings (example 7 grilles with total 14 sq ft,)  In this example there is 1 sq ft return grille area per 100 sq ft floor area. So in this example your basement office return grille would be 1.4 square feet. A 6-inch round duct would be the minimum size.
Comment: So my current habitable space is 2000sqft with two return grilles of 2.75sqft total area each (5.5 total). So I'm looking at a 2.75 sqft return grille, which would roughly be 16" x 16".
Comment: Check your math ... you say your new space is 140 sq ft. Also look for hidden return air grilles.


Restkit Dynamic Mapping for optional attribute

Question: I am getting a json document like this from a ws:
<code>{
   ...
   error=true,
   errorMsg="xyz",
   errorCode="1234"
}
</code>
But these attributes are optional so sometimes they are present and sometime they are not.
I added a dynamic mapping for reading only error - only if error is set to true
either:
<code>[dynamicMapping addMatcher:[RKObjectMappingMatcher matcherWithKeyPath:@"error" expectedValue:[NSNumber numberWithInt:1] objectMapping:errorMapping]];
</code>
or
<code>[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
        if ([[representation valueForKey:@"error"] isEqualToNumber:[NSNumber numberWithInt:1]]) {
            return errorMapping;
        }

        return nil;
    }];
</code>
Everything is working fine if error=true but if the error attributes are missing I get a warning:
<code>restkit.object_mapping:RKMapperOperation.m:98 Adding mapping error: Could not find an object mapping for keyPath: '<null>'
</code>
I just want to get rid of the warning. What is the best practice for this problem? How do I mark the attribute as optional?
Comment: Are you using this and another mapping?
Comment: Hi, yes I use the same mapping ("errorMapping") for server errors with status code RKStatusCodeClassServerError = 500. So if an error occurs on the server the server send the error msg in a json format.
Comment: I mean how is your success scenario handled? Usually your dynamic mapping would check the status and then either return the error mapping or the success mapping.
Comment: A success would be if either error=false or no error attributes are specified. Error=false with a message would be a warning for which I may also add an object and add another dynamic mapping.
Answer: To remove the warning, you need to complete your mapping configuration, because currently you're only giving it information for half of the scenarios. The warning is just that, a warning. It may be that it is intended functionality, that's why it isn't an assertion.
So, you're handling the error situation, simply add another check, something like:
<code>[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
    NSNumber *errorNumber = [representation valueForKey:@"error"];

    if (errorNumber == nil) {
        return successMapping;
    } else if ([errorNumber isEqualToNumber:[NSNumber numberWithInt:1]]) {
        return errorMapping;
    }

    return warningMapping;
}];
</code>
Also, you aren't limited to checking just the 'error' parameter. You can check any other key and value in the response, both for existence and for value.
Comment: the problem is that I registered a success mapping for the key path "people" so my success json may look like this: {people:[..],error=false,...} The error dynamic mapping is therefore registered for keypath nil


Why audio recording in background on iOS not working?

Question: I'm trying to make my audio recorder work in the background on iOS.
I tried setting the background mode "audio" to prevent my app from being suspended when it enters background mode, but that doesn't seem to work. I did that by following Implementing Long-Running Background Tasks > Playing and Recording Background Audio, which states that

You enable audio support from the Background modes section of the
  Capabilities tab in your Xcode project. (You can also enable this
  support by including the UIBackgroundModes key with the audio value in
  your app's Info.plist file.)

The problem is that when my app goes to background, only about one second of further audio is recorded. The app seems to be suspended thereafter. I test this on Simulator by simulating a home button press.
What can I do to make the app record in the background?
Comment: Have you tried this on a device? An audio playing app exhibits the same symptoms on the simulator
Answer: An audio playing app on the simulator exhibits the same symptoms as you described for your recording app. In general, background tasks don't behave in the same way on the simulator and on devices.
Try testing the App on a device.
Comment: thanks, your assumption is correct and it's that simple. Recording in the background works perfectly on a device with no change of the code while it does not work in simulator.
Comment: As of iOS 11.0 Beta 3 (included in Xcode 9.0 Beta 3) backgrounded tasks should be suspended, so the behavior you see in the simulator should better match what you see on device now.


How const reference bound to rvalue

Question: I have seen quite a few FAQ posts about binding const reference to rvalue.
Some said it's because system generates a temporary object for reference to bind to, and some said it's just an abstract system rule, it may not really doing this. So which side should I follow? Could someone kindly explain the true mechanism about binding const reference to a rvalue or just simply find me a relevant and confirm accurate link. Many thanks in advance!!
Comment: The point is, that's how the *language* says it must work. What's going on "under the hood" will be different in different cases, even from the same compiler. The point is, you shouldn't need to care. You could always check the generated assembly, but that's a pain.
Comment: Well, [pretty much *everything* you know about C++ is "just an abstract system rule"](http://en.cppreference.com/w/cpp/language/as_if).
Comment: @BoBTFish Oh it means you support the second point right? But some high rep people seems very confirm about the first point according to the way they explain it..
Comment: Thanks for the efforts and the links!!
Answer: Both are correct. You have to understand that C++ is an abstraction. The code that your computer executes looks nothing like it.
When you bind a temporary to a const reference, you could imagine various C++ mechanisms to represent how your compiler's making that work. Or you could just accept that it does make that work, and that your compiler is a black box whose internals you do not need to reason about. The two are indistinguishable, for all intents and purposes. That's the whole point of constructing models.
If you really, really, really want to know how your specific compiler is implementing a specific piece of code under certain circumstances, you will have to become an expert on that compiler's source code. This is an incredibly advanced topic, and typically there are only a handful of people in the world who understand what a compiler is doing inside. It's generally not worth the time and investment required to become one of them.1
1 Although I'm sure they'd be extremely grateful for the extra help! They'll eventually need to "pass the torch", after all.
Comment: Thanks for the efforts. I will just follow your idea then:-)
Comment: @Des1gnWizard: Which one? ;)
Answer: Herb Sutter writted a nice article about const reference to rvalue, here is the link.

How const reference bound to rvalue


vim using up 100% CPU, can't kill it

Question: Every so often (about once a month), my vim starts eating resources like crazy, and I'm unable to kill it. Here's an example:

I ran:
kill 13799

To no effect. I would like to know:
1) Could be vim going haywire due to something else? I use it to write code in and it's usually when the code is running that I get an issue.
2) If not, why would vim do this?
3) How can I kill it? Currently, I have to reboot every time.
Thanks )
Comment: `kill -9 $(pidof vim)`
Comment: It would be hard to figure out the reason, are you editing some very large files? Did you copy/paste some text by mistake while in command mode (This can run the commands which may need a while process)? When you run the code, is it modifying some larger files that you have open in vim while you have `autoread` enabled? Do you have lots of plugins installed? etc.
Comment: Maybe clearing `vim cache` in `~/.viminfo` fix
 it: https://stackoverflow.com/questions/2816719/clear-certain-criteria-from-viminfo-file
Comment: Thanks for the comments. I'll try clear cache and kill -9 next time. @Dan maybe plugins are the issue yea, I have quite a few.
Answer: kill is quite polite by default, it raises the SIGTERM signal. With this, the application is expected to see and handle the signal (eg quit) but that is completely up to the application to be able and willing.
You can see here that vim is "running" —that's what the R means— and that means it's likely too busy to intercept and process the signal. If it's been doing this a while, you may have stumbled on a bug.
Either which way, if you want to forcibly nuke it, you can use other signals. SIGKILL is a popular choice.
kill -9 13799

It cannot be ignored as it interrupts the current process (with some run-state exceptions, like zombie or other uninterruptible states).
This is an extremely high-level look at this. Take a look at man 7 signal to zoom in.

vim using up 100% CPU, can't kill it


Python sched module to enqueue delayed tasks in quart or flask

Question: I want to schedule a task to run after a delay in my quart/flask application whenever a certain query is made.  I'm hoping to use the sched module so there are fewer external dependencies, but I'm having difficulty understanding how to set up the scheduler.  Below is my attempt so far (quart/Quart can be replaced with flask/Flask and the async keyword can be dropped to convert it to a flask app):
from quart import Quart
import sched, time, threading

app = Quart(__name__)
scheduler = sched.scheduler(time.time, time.sleep)
scheduler_thread = threading.Thread(target = scheduler.run)
scheduler_thread.start()

def do_task(message):
    print(f'{int(time.time())} From do_task, running {message}')

@app.route('/')
async def index():
    do_task("Immediate task")
    # Schedule a task after a 5 second delay with priority 1
    scheduler.enter(5, 1, do_task, argument=("Scheduled task",))
    return '
Hello World!
'

The goal is that whenever I query the app, it will add an event to the scheduler, and the scheduler will execute it once the delay has elapsed.
E.g. if I do curl http://127.0.0.1:5000/ one time then I would expect roughly the following to be printed:
1651519374 From do_task, running Immediate task
1651519379 From do_task, running Scheduled task

And if I run it again a few seconds later, then again I would expect something like:
1651519415 From do_task, running Immediate task
1651519420 From do_task, running Scheduled task

And if I run it three times, three seconds apart each time, then I would expect something like:
1651519500 From do_task, running Immediate task
1651519503 From do_task, running Immediate task
1651519505 From do_task, running Scheduled task
1651519506 From do_task, running Immediate task
1651519508 From do_task, running Scheduled task
1651519511 From do_task, running Scheduled task

However, what I am getting is just the Immediate task is run, and the Scheduled task never runs.
I've tried some permutations, like:
from quart import Quart
import sched, time, threading

app = Quart(__name__)
scheduler = sched.scheduler(time.time, time.sleep)
scheduler_thread = threading.Thread(target = scheduler.run)

def do_task(message):
    print(f'{int(time.time())} From do_task, running {message}')

@app.route('/')
async def index():
    do_task("Immediate task")
    scheduler.enter(5, 1, do_task, argument=("Scheduled task",))
    scheduler_thread.start()
    return '
Hello World!
'

In this case, the first time I query it prints what I expect:
1651521193 From do_task, running Scheduled task
1651521202 From do_task, running Immediate task

But the second time fails with RuntimeError: threads can only be started once
What am I missing?
Answer: Well, it looks like quart has a feature that does this in another way, and I think it's doing what I need:
from quart import Quart
import time

app = Quart(__name__)

def do_task(message, delay=0):
    time.sleep(delay)
    print(f'{int(time.time())} From do_task, running {message}')

@app.route('/')
async def index():
    do_task("Immediate task")
    app.add_background_task(do_task, "Scheduled task", delay=10)
    return '
Hello World!
'


Convert a JSON Response into an Array of Objects

Question: I checked tons of SO Questions about this but I wasn´t able to solve it for my case. So I make a get call from an API:
axios.get("https://ddragon.leagueoflegends.com/cdn/9.2.1/data/en_US/champion.json").then(response => {

    console.log(response.data)
    response.data.forEach(entry => {

    })
})

the response.data has what I want but in weird format like
XXX: { ... }, KKK: { ... }, JJJ: {...}
But I need it as a simple Array of Objects.
the response.data.forEach is also undefined for some reason
Comment: Then it's an object, not an array. `.forEach` is an **Array** prototype, **not** an object one. If you want to loop that response, you need to do something like this: `Object.keys(response.data).forEach(k => console.log(response.data[k]))`
Comment: is `response.data`
 undefined?
Comment: @briosheje No it has the data I need but in the format mentioned above
Comment: Possible duplicate of [How do I loop through or enumerate a JavaScript object?](https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object)
Answer: Looks like you just need the values of the dictionary, however, you need to not only access the data of the response, but the 'data' of the actual response data itself.
const data = Object.values(response.data['data']);

Comment: The link in OPs question – https://ddragon.leagueoflegends.com/cdn/9.2.1/data/en_US/champion.json
Comment: Well there's your answer, we were thinking the `response.data` was the data containing each 'champion'. You need to use `response.data['data']` / `response.data.data` instead.
Comment: @Callam Thank you now it works, usually im not that stupid in terms of JS but never had todo with JSON yet, will defenetly read myself into it for the future.
Comment: Minor note: You loose the first-level keys this way.
Comment: First level keys seem to be in the nested data
Comment: How do you know that? The OP doesn't indicate they are.
Comment: Hey thanks so far, but in the forEach If i try to console log the entry I still get the weird format of `key: {....}` instead of just `{}`
Comment: What do you get when you `console.log(Object.values(response.data)[0])`?
Comment: @Callam `champion`
Comment: aaand `console.log(Object.values(response.data['data'])[0])`?
Comment: @Callam then I get the first entry of the data object
Answer: For accessing key-level as well:
Object.keys(response.data).forEach(k => {
   console.log('key is', k);
   console.log('value is', response.data[k]);
});

About why it was not working: you're trying to loop over an object. However, regular javascript objects do not have a forEach prototype, while arrays does.
Answer:

fetch("https://ddragon.leagueoflegends.com/cdn/9.2.1/data/en_US/champion.json")
  .then(response => response.json())
  .then(({ data }) => {
    const result = [];
    Object.keys(data).forEach(key => {
      result.push(data[key])
    })
    console.log(result)
  })
Answer: Another one that converts the object to an Array while preserving the key names.
FWIW I doubt you wanna go this route, but it's a way to turn your Object to an Array whilst keeping the key names.

const res = {XXX: { foo: 'bar' }, KKK: {foo: 'bar' } }
const arr = Object.keys(res).map(key => ({ ...res[key], key }))

console.log(arr)
Answer: Since it's an object that gets returned, use Object.entries

Object.entries(response.data).forEach(([k, v]) => console.log(k,v));


Why does Istanbul / tap code coverage report a switch statement as not covered when each conditional path is covered?

Question: In a node.js application I have a class with a getter that contains a large switch statement, same as this but larger with unreleased-product-specific values instead of a, b, c, 1, 2, 3 etc:
Class SomeClass () {
  constructor (someVar) {
    this.someProp = someVar
  }
  get someGetter () {
    switch (this.someProp) {
      case 'a':
      case 'b':
        return 1

      case 'c':
      case 'd':
      case 'e':
        return 2

      case 'f':
        return 3

      case undefined:
        return null

      default:
        return 0
    }
  }
}

I then have a test case structured like this, that reaches each of the possible paths:
const expectedResults = new Map(Object.entries({
  a: 1,
  c: 2,
  f: 3,
  null: null,
  z: 0
}))

for (const [testCase, expected] of expectedResults) {
  const someInstance = new SomeClass(testCase)
  t.equal(someInstance.someGetter, expected)
}

t.end()

This gave me coverage on all of the possible paths and no red flags in the node tap coverage report.
Hover, I get one (yellow) uncovered line, which is the line of the switch statement itself: line 6 in the example code, the line:
switch (this.someProp) {

I've tried adding redundant breaks after each return, but these are then (correctly!) flagged as uncovered (because they're unreachable).
I thought maybe it's complaining because it has a test for, for example, 'a' in the path that returns 1 but not 'b' in the same path. But if that's the problem I don't understand why it's flagging the switch statement itself, not those specific lines.
Comment: I've edited the title to be a grammatical question. And it's encouraged to post answers to your own questions if you have them: it shares knowledge with other people searching on the same problem in future, while keeping open the possibility of someone posting an even better answer. See https://stackoverflow.com/help/self-answer
Comment: What's the question? And you already have the answer? Are you asking something here?
Answer: The uncovered line notice disappeared when I had the tests cover every possible case:, not just every path.
Since there were many, many cases in my real world code, and all of the return paths are tested as being correct, rather than extending the expectedResults map massively, I created another, simpler test condition which took a simple array of every case and simply made sure that each one was recognised (wasn't falling back to the default value). Like:
const allCases = ['a', 'b', 'c', 'd', 'e', 'f']

for (const testCase of allCases) {
  const someInstance = new SomeClass(testCase)
  t.notEqual(someInstance.someGetter, 0)
}

By comparing against the default fallback value, there's at least some value to this test, it's not purely there to meet 100% coverage: it makes sure no possible cases in the switch get deleted in future etc (e.g. if the switch statement is reordered or modified).


Passing a value to WTForms field with Jinja2

Question: This is probably super simple.  But I'm using WTForms and want to set the value of a field to a variable I pull from the database.  But instead of displaying the dynamic variable, it's displaying the variable name.
<code>{{ form.question.label }}
{{ form.question(value="{{ q.question }}") }}

{{ form.slug.label }}
{{ form.slug(value="{{ q.slug }}") }}
</code>
So in the field it says "{{ q.question }}" instead of something like "What is the meaning of life?".
Is there a way to display nested variables in Jinja?  Or is there some other way I need to go about this?  Any help is appreciated!
Comment: I think you are looking for `{{ form.slug(value = q.slug) }}`.  You have already told Jinja to parse whatever is inside the first `{{ }}`.
Answer: take out the double quotes and the template tags.
<code>{{ form.question(value=q.question) }}
</code>
and the same for slug
Comment: Hey that's what this is for.  Don't waste time with the small stuff.  Go forth, make awesome webapps.


Arzela-Ascoli Counter Example?

Question: I am taking my second undergraduate analysis course, our text book is N.L. Carothers "Real Analysis". This question is my own after reading the chapter "The Space of Continuous Functions" and the section "Equicontinuity"
First some preliminaries:

Arzela-Ascoli Theorem. Let $X$ be any compact set. For $A\subset C(X)$, $A$ is compact iff $A$ is closed, bounded, and equicontinuous.

The set $A$ is closed if for any convergent sequence $(f_n)_{n\in\mathbb{N}}$ we have that the limit of $f_n$ is an element of A.
The set $A$ is bounded if for all $f$ in $A$ we have $||f||=sup_{x\in X}{f(x)} = M\in \mathbb{R}$ exists for all $x$ in $X$.
The set $A$ is equicontinuous if for every $\epsilon >0$ there is a $\delta>0$ such that for all $f$ in the set $A$ and for all $x, y$ in $X$, $d(x,y)<\delta$ implies that $|f(x)-f(y)| < \epsilon$.
The set A is compact if every sequence in $A$ has a subsequence that converges in $A$.
Here is my question:
There is this famous problem called the 3-body problem. I don't know if you have heard of it but there is a simulation here.
Each of the functions that generate a path given some starting position are in the space $C([a,b] \times [c,d])$. Let $A$ be the set of all possible functions in the three body problem. It seems to me that $A$ is closed, bounded and equicontinuous but not compact since $f$ depends so heavily on the initial position of the planet. Does this contradict the theorem?
Answer: For any physical model involving force, it only makes sense to think of compact sets, especially for gravitational problem (as the force decreases radially, and eventually becomes negligible).
Now to get more technical. Arzela-Ascoli is certainly correct, and has been verified and used for some time now. In addition, the formulation in the textbook is not the best. Arzela-Ascoli tells us when subspaces of general metric spaces (typically function spaces) are compact, since metric spaces are Hausdorff, compact subsets are closed. Knowing this means you have less work to do, you don't need to show the space is closed. Arzela-Ascoli would tell us $A$ is compact and that guarantees that $A$ is closed.
The conditions for a subspace of a metric space to be compact is that it is uniformly bounded and equicontinuous.
Let $A$ be the set of functions which satisfy your requirements.
We know that $f \in C([a,b] \times [c,d])$ is bounded because of the Extreme Value Theorem, so every function in $A$ is bounded, but nothing would indicate a priori that the functions are uniformly bounded. In fact, without an explicit description of $A$ we cannot say much about what functions live in the space. Equicontinuity can fail as well.
To summarize, without having an explicit description of the functions that make up $A\subset C([a,b] \times [c,d])$, we cannot verify equicontinuity or uniform boundedness. In addition, the functions that we choose are purely because they fit a model, there is nothing in the physical world that forces $A$ to be compact, and whatever $A$ is, it will not violate Arzela-Ascoli.
Finally, if $A$ is open (not closed), then by contrapositive, you right away know that $A$ is not compact, and the space $C(X)$ where $X$ is a compact set is itself, not compact.
Comment: I was thinking about this recently and you are right, I didn't provide an explicit description of the functions that make up $A$. I don't know if this makes sense, but can you think of the set of all functions that are a solution to a set of differential equations as a set $A \subset C[a,b]$?
Comment: Unfortunately, that is not generally possible! For starters, the solution to the differential equation itself need not be continuous, and hence not in the set, such solutions are called weak solutions. Even if we restrict ourselves to strong solutions (i.e. smooth functions), consider the following: since $A$ is a subspace, it has a vector space basis (Schauder basis, since $A$ has uncountable dimension), this basis will allow you to express all solutions as a linear combination, but in general you cannot write down an explicit basis for any arbitrary vector space.
Comment: Oh interesting. I wasn't expecting that. For example the differential equation $\frac{dv}{dt}=9.8-0.196v$ has solutions of the form $v(t)=50 + ce^{-0.196t}$. So take $a_n=1/n$ and let $A={0}\cup {a_n}$. Let $c \in A$ Then $v_n(t)=50+ce^{-0.196t}$. Let t vary in $[0,1]$. The sequence of functions is a set, is that set compact? Yes I think so.
Comment: $A=0 \cup a_n$ is compact, because it is the union of two compact sets. However, as you defined it, $A$ is a sequence of real numbers, not a sequence of functions. $c$ is just either $0$ or $1/n$ for some $n$. in addition, for $v_n(t)$ you have defined one function, there is no $n$ on the RHS, however, if you defined it as $v_n(t):[0,1]\rightarrow \mathbb{R}$, with $v_n(t)=50+c_n e^{-0.196t}$ the sequence is uniformly bounded by 50, but not equicontinuous, (take $c_0$ and another function and see there is no way to choose an appropriate $\delta$

Arzela-Ascoli Counter Example?


Does radiation have any effects besides lowering maximum health?

Question: In FO3 radiation functioned by essentially adding negative perks, which lowered your SPECIAL scores, or affected other stats.  In FO4, radiation just seems to limit your maximum health until removed.  Are there any other effects besides this in FO4?
Answer: In Fallout 4, unless you take certain perks like Ghoulish, radiation simply reduces your maximum health. It has no other effects. The rate appears to be 1% of your health decreased per 10 RADs.
Comment: Well, there are also the [Ghoulish perks](http://fallout.wikia.com/wiki/Ghoulish), which makes radiation heal you... but also reduce your maximum health.  Not a particularly useful set of perks as far as I'm concerned, but it does add a different effect for radiation, strictly speaking.


FirebaseRecyclerAdapter doesn't recognize first layout as a position

Question: My Title is kind of hard to understand but basically when I add items into my database is should display it in a RecyclerView. Now in my RecyclerView I have two layouts but the problem is the first item of my database goes behind my first item in my other layout. So if I have 3 items in my database, it shows only 2 items from the database and the first item hides behind my first item in the RecyclerView which is a different layout that does not use the database at all.
This is my code:
 FirebaseRecyclerOptions<Event> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<Event>()
            .setQuery(query1, Event.class).build();
    AccAdapter = new FirebaseRecyclerAdapter<Event, RecyclerView.ViewHolder>(firebaseRecyclerOptions){

        final static int TYPE_HEADER = 0;
        final static int TYPE_ITEM = 1;

        @Override
        public int getItemViewType(int position) {
            if (position == 0) return TYPE_HEADER;
            return TYPE_ITEM;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            if (viewType == TYPE_HEADER){
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.recycler_view_row_add_items,
                        parent, false);
                return new ProdudctHolder3(view);
            } else {
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.recycler_view_row_acc,
                        parent, false);
                return new ProductHolder2(view);
            }
        }

        @Override
        protected void onBindViewHolder(final RecyclerView.ViewHolder holder, int position, final Event model) {
            if (holder instanceof ProdudctHolder3){
                ((ProdudctHolder3) holder).addBackground.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(getActivity(), AccAddItems.class ));
                    }
                });
            } else{

                final ProductHolder2 productHolder2 = (ProductHolder2) holder;

                productHolder2.mName.setText(model.getName());
                productHolder2.view.setBackgroundResource(getBackgroundDrawable(Integer.valueOf(model.getProductAmount())));
                productHolder2.mbackground.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        dialog = new Dialog(getActivity());
                        dialog.setContentView(R.layout.popup_edit_product);

                        SeekBar amountSeekBar = dialog.findViewById(R.id.amountSeekBar);
                        amountSeekBar.setMax(100);
                        amountSeekBar.setProgress(Integer.valueOf(model.getProductAmount()));
                        amountSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                            @Override
                            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                                progress = i;
                            }

                            @Override
                            public void onStartTrackingTouch(SeekBar seekBar) {

                            }

                            @Override
                            public void onStopTrackingTouch(SeekBar seekBar) {
                                getRef(holder.getAdapterPosition()).child("productAmount").setValue(String.valueOf(progress));
                                dialog.dismiss();

                            }
                        });

                        dialog.show();

                    }
                });

                productHolder2.mbackground.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
                        final PopupMenu popupMenu = new PopupMenu(getActivity(), productHolder2.mbackground);

                        popupMenu.inflate(R.menu.menu_acc);
                        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(MenuItem menuItem) {
                                switch (menuItem.getItemId()){
                                    case R.id.deleteProduct:
                                        getRef(productHolder2.getAdapterPosition()).removeValue();
                                        popupMenu.dismiss();
                                        return true;

                                    default:
                                        return false;
                                }
                            }
                        });

                        popupMenu.show();

                        return true;
                    }
                });

            }
        }

    };

    mAccRecyclerViewRef.setAdapter(AccAdapter);

My two Product Holders
private class ProdudctHolder3 extends  RecyclerView.ViewHolder{
    private RelativeLayout addBackground;

    public ProdudctHolder3(View itemView) {
        super(itemView);
        addBackground = itemView.findViewById(R.id.mBackground2);
    }
}

private class ProductHolder2 extends RecyclerView.ViewHolder{

    private TextView mName;
    private RelativeLayout mbackground;
    private View view;

    public ProductHolder2(View itemView) {
        super(itemView);

        mName = itemView.findViewById(R.id.ItemName);
        mbackground = itemView.findViewById(R.id.mBackground1);
        view = itemView.findViewById(R.id.amountIndicator);

    }
}

Comment: Still havnt solved it someone pls help. I don't understand why I've looked at this for hours already
Comment: would you mind sharing your layout xml files?
Comment: can you please paste xml code?
Comment: I've updated it!
Answer: The ideal solution would have been to set two adapters on a single RecyclerView but unfortunatelly this is not possible.
However, you can make a single custom Adapter that handles two types of items. I will explain this by getting an example.
Let's assume you need to display objects of two types, humans and aliens. Your objects require completely different layouts and completely different ViewHolders. Please see the below code for the ViewHolders:
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static class HumanViewHolder extends RecyclerView.ViewHolder {
        public HumanViewHolder(View itemView) {
            super(itemView);

            //Prepare your ViewHolder
        }

        public void bind(Human human) {

            //Display your human object
        }
    }

    private static class AlienViewHolder extends RecyclerView.ViewHolder {
        public AlienViewHolder(View itemView) {
            super(itemView);

            //Prepare your ViewHolder
        }

        public void bind(Alien alien) {

            //Display your alien object
        }
    }
}

First you need to add two different constants to your adapter representing both type of views:
private static final int ITEM_TYPE_HUMAN;
private static final int ITEM_TYPE_ALIEN;

To keep things simple, let's also assume you store your objects in a list:
private List<Object> items = new ArrayList<>();

public MyAdapter(List<Object> items) {
    this.items.addAll(items);

    //Other stuff if needed
}

Now, the first you need to do, is to implement getItemViewType() method:
@Override
public int getItemViewType(int position) {
    if (items.get(position) instanceof Human) {
        return ITEM_TYPE_HUMAN;
    } else {
        return ITEM_TYPE_ALIEN;
    }
}

Second, you need to use the item type inside the onCreateViewHolder() method like this:
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)  {
    LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());

    if (viewType == ITEM_TYPE_HUMAN) {
        View view = layoutInflater.inflate(R.layout.item_human, parent, false);

        return new HumanViewHolder(view);
    } else {
        View view = layoutInflater.inflate(R.layout.item_alien, parent, false);

        return new AlienViewHolder(view);
    }
}

In the end, you just need to bind the proper view holder like this:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
    Object item = items.get(position);

    if (viewHolder instanceof HumanViewHolder) {
        ((HumanViewHolder) viewHolder).bind((Human) item);
    } else {
        ((AlienViewHolder) viewHolder).bind((Alien) item);
    }
}

Comment: Hey the problem with this is the onCreateViewHolder. Using FirebaseRecyclerAdapter I cannot return a different ViewHolder as suggested above.
Comment: In this case, do it directly in your holder class. The same principle apllies, right?
Comment: and thats what I have. Check my code for the ProductHolder class I prepare my Viewholder based on viewType value
Comment: Have you tried to use that if statement but only with a single TextView?
Comment: what do you mean? sorry
Comment: I mean to use only one TExtView instead of all those views (mbackground, addBackground), just to see if it works.
Comment: It works the problem is that, lets say for example I have 2 items in my database, it only shows 1 item from the database and another one which is the default button that should always be there.
Comment: This doesn't seem to work as I cannot use two ViewHolders in RecyclerViewAdapter
Comment: You can have as many holders as you want but you can use only one at a time. So you can inflate either one or the other layout, according to the type of the object, right?
Comment: right. But how would I let the adapter know to move the position to +1 so that part of the data is not hidden
Comment: You don't need to tel the adapter to move to the next position, you only need to use the corresponding holder according to the type of object it is. With other words, while creating each `item view` for the the `RecyclerView` by getting the data from the adapter, each item view should have a different layout according to the type of data the adapter provides. There is nothing more that you need to do. Is it ok now?
Comment: I know the problem still persists even though I have done that.
Comment: It seems that there is another problem which I cannot see using only the code you have shared. Maybe you can share somehow your changed code to take a closer look.
Comment: I just pasted the whole code instead so taht you can see
Comment: Seeing your code, I can say that you haven't tried to use the idea from my answer. You keept your idea and tried to adapt which I can see that it doesn't work at all. It's to broad so I can answer in a comment but what can I say to you is to try to do the exact things that I showed you in my aswer starting from scratch and do things one step after another. Keep in mind that you cannot using [two differenty queries](https://stackoverflow.com/questions/50592325/is-there-a-way-to-paginate-queries-by-combining-query-cursors-using-firestorerec).
Comment: Also don't try to hide view by seetting the visibility to `GONE` because that view will fall on the remaing place.
Comment: I've updated it to match yours, also the question, and the same problem still persists. If I delete my item the first layout is also removed. It's like whatever position it is on firebase it takes the first layout. Therefore you cannot see the first item
Answer: Why use the Firebase Recycler Adapter when you could easily make a custom one? If I understood well you want an item to be fixed at position 0 (header) while others will be added below the first one, right? If so, here is a solution I like to use:
public interface ViewType {
    public int getViewType();
}

public interface ViewTypeDelegateAdapter {
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent);
    public void onBindViewHolder(RecyclerView.ViewHolder holder, ViewType item);
}

public class ViewTypes {
    public static int HEADER = 0
    public static int ITEM = 1
}

public class ProductDelegateAdapter implements ViewTypeDelegateAdapter {

    private int resID;
    private Context context;

    public ProductDelegateAdapter(int resID, Context context) {
        this.resID = resID;
        this.context = context;
    }

    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {
        return new ProductHolder(LayoutInflater.from(parent.context).inflate(resID, parent, false));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, ViewType item) {
        (holder as ProductHolder).bind("test");
    }

    class ProductHolder extends RecyclerView.ViewHolder {

        public ProductHolder(View view) {
            super(view);
        }

        public void bind(String test) {

        }

    }

}

public class HeaderDelegateAdapter implements ViewTypeDelegateAdapter {

    private int resID;
    private Context context;

    public ProductDelegateAdapter(int resID, Context context) {
        this.resID = resID;
        this.context = context;
    }

    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) {
        return new HeaderHolder(LayoutInflater.from(parent.context).inflate(resID, parent, false));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, ViewType item) {
        (holder as HeaderHolder).bind("test");
    }

    class HeaderHolder extends RecyclerView.ViewHolder {

        public HeaderHolder(View view) {
            super(view);
        }

        public void bind(String test) {

        }

    }

}

public class AccAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private Context context;
    private List<ViewType> items;
    private SparseArrayCompat<ViewTypeDelegateAdapter> delegateAdapters;
    private ViewType headerItem;

    public AccAdapter(Context context) {
        this.context = context;
        this.items = new ArrayList();
        this.delegateAdapters = new SparseArrayCompat();
        this.headerItem = new ViewType() {
            @Override
            public int getViewType() {
                return ViewTypes.HEADER;
            }
        };

        this.items.add(this.headerItem);
        this.delegateAdapters.put(ViewTypes.HEADER, HeaderDelegateAdapter(R.id.test, this.context));
        this.delegateAdapters.put(ViewTypes.ITEM, ProductDelegateAdapter(R.id.test, this.context));
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, Int viewType) {
        return delegateAdapters.get(viewType).onCreateViewHolder(parent);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, Int position) {
        delegateAdapters.get(getItemViewType(position)).onBindViewHolder(holder, items[position])
    }

    @Override
    public Int getItemViewType(Int position) {
        return items.get(position).getViewType();
    }

    @Override
    public Int getItemCount() {
        return items.getSize();
    }

    public void add(ViewType viewType) {
        val initPosition = this.items.size - 1
        this.items.add(item)
        notifyItemRangeChanged(initPosition, this.items.size + 1)
    }

}

public class Event implements ViewType {

    private String id;

    @Override
    public int getViewType() {
        return ViewTypes.ITEM;
    }

}

Excuse me for some syntax errors, I've translated to Java from Kotlin to help you. Hope it helps!
Comment: Im sorry but the reason I used FirebaseRecyclerAdapter was so that it updates   data in realtime with other benefits as well.
Comment: You can easily make that happen without using the FirebaseRecyclerAdapter. You can make the structure this way and then register a listener to your Firebase node and then just call the add method from the "main adapter". Much more clean and concise.
Comment: is there a way to possibly solve this problem with firebaserecyclerAdapter


Fourier Transform of a Gaussian Function in the Complex Domain - is it trivial?

Question: I want to calculate $$f(q)=\int_{-\infty}^\infty G(r)p(r)e^{iqr} dr$$ with complex $q$.
I know the Fourier transform of $p(r)$ for complex $q$. I.e. $f_{p}(q)=\int_{-\infty}^\infty p(r)e^{iqr} dr$ is solved.
and G(r) is a Gaussian function $$G(r)=e^{-ar^2}$$
I want to use the convolution theorem to solve this problem and thus need the Fourier transform of $G(r)$.
I know that for real $q$, the Fourier transform of a Gaussian is another Gaussian. My central question is: is this still valid if $q$ is complex?
Wikipedia seems to hint that the answer may not be trivial:
https://www.wikiwand.com/en/Fourier_transform#/Complex_domain

"Depending on the properties of f, this might not converge off the
  real axis at all, or it might converge to a complex analytic function
  for all values of ξ = σ + iτ, or something in between"

and the explanation following that quote goes over my head. Despite searching I have yet to confirm this key detail.
So, please help me!: Is it true that the Fourier transform of a Gaussian function is still
 $$f_{g}(q)=\int_{-\infty}^\infty e^{-ar^2} e^{iqr} dr = \sqrt{\pi/a} e^{-\pi^2 q^2 /a}$$ for complex $q$?
Thank you
Comment: Hint: try plugging in $q=-iax^2$. Does this converge?
Comment: Okay, so there's a singularity when $q=-iar$? (my mistake there with the notation by the way, not yours. I've updated it to remove the stray $x$). Am I going to need to get out my complex analysis notes from 10 years ago and try to find out if it's removable?
Comment: Note that $q$ is a constant, but $r$ variable being integrated against.
Comment: I'm still not sure I'm getting it!
Comment: I think this post answers the question: https://math.stackexchange.com/questions/1864480/complex-frequency-shifting-in-fourier-transform
Comment: I have just posted my answer, which I think works. I get the impression you had something simpler in mind though, so please go ahead and correct me if I am unnecessarily over-complicating it! Or if you don't have the time, then thank you for your attempts to push me in the right direction.
Comment: I expected a suitable choice of q would make the integral not converge, likely due to thinking that you can set q with some r dependence for some reason. This doesn't turn out to be the case though.
Answer: Okay I think I figured this out with the help of this post:
Complex Frequency Shifting in Fourier Transform
I want to confirm that
$$f_{g}(q)=\int_{-\infty}^\infty e^{-ar^2} e^{iqr} dr = \sqrt{\pi/a} e^{-\pi^2 q^2 /a}$$
or otherwise find a similar solution, when $q$ is complex.
if $q=x+iy$
$$f_{g}(q)=\int_{-\infty}^\infty e^{-ar^2} e^{i(x+iy)r} dr$$
or
$$f_{g}(q)=\int_{-\infty}^\infty e^{-ar^2} e^{-yr} e^{ixr}  dr$$
Using the convolution theorem, this is equivalent to
$$f_{g}(q)=(\int_{-\infty}^\infty e^{-ar^2} e^{ixr}  dr) \circledast (\int_{-\infty}^\infty e^{-yr} e^{ixr}  dr)$$
Which since the LHS is a Gaussian and the RHS is a plane wave is
$$f_{g}(q)=((\sqrt{\pi/a} e^{-\pi^2 x^2 /a}) \circledast(c \delta(x-y)))(x)$$
where c is some constant that may or may not exist, and which I am currently too tired to properly think about.
Then because the delta function is kind of like the identity function of convolution (something I vaguely remember from DSP - apologies if that is not rigourously true...), the convolution just scales the Gaussian by $c$ and shifts it by $y$... so the answer is
$$f_{g}(q)=c(\sqrt{\pi/a}) e^{-\pi^2 (x-y)^2 /a}$$
So the effect of complex q is just to scale and shift the resulting Gaussian.
I'm not 100% confident, and I suspect there's a simpler answer. I'd appreciate anyone jumping in to correct me if so!


Changing datatype and removing commas from a number

Question: I am trying to remove commas from number which has been entered as a string and change it's data type to integer for analysis purposes
0      1,741,147
1          1,755
2         95,532
3        216,022
4        208,134

Above is the Pandas series('Active Cases') that I am working with whose data type is Object. I want to remove the commas and change the data type to int64. I have tried doing it in the following way but it is not working:
df['Active Cases'].replace(',','')
df['Active Cases'].astype(np.int64)

Answer: You can use pandas.Series.str.replace then use pandas.Series.astype.
df['Active Cases'] = df['Active Cases'].str.replace(',', '').astype(int)
print(df['Active Cases'])

0    1741147
1       1755
2      95532
3     216022
4     208134
Name: Active Cases, dtype: int64

Answer: The operation is not inplace, you need assign the result back
df['Active Cases'] = df['Active Cases'].replace(',','').astype(np.int64)

If you want to make the replace more robust, like also replace possible spaces after comma, you can do Series.str.replace
df['Active Cases'] = df['Active Cases'].str.replace(', *', '', regex=True).astype(np.int64)

I would recommend do pd.to_numeric instead to avoid possible error
df['Active Cases'] = pd.to_numeric(df['Active Cases'].str.replace(', *', '', regex=True), errors='coerce')


Get the property in vbscropy to get the path

Question: Here is my code:
Option Explicit
Dim fso, s , i

Set fso = CreateObject("Scripting.FilesystemObject")
MsgBox "1"
s = Session.Property("TARGETDIR")
MsgBox "2"
i = Session.Property ("INSTALLDIR")
MsgBox "3"
MsgBox s & "\CopyDuringInstallation.txt"

fso.CopyFile s & "\CopyDuringInstallation.txt", i
MsgBox "4"

I am having trouble with the varaible s. Which property should I use to make a universal path?
All i want to know is the property which can concatenate the path as shown in the code after msgbox 3.
Thank You
Comment: Yes, ASP is VBScript, but OP uses Session. In plain VBScript there is no such object.
Comment: Thank you Lanny.. one more thing i ma using this in install shield. And i want to concatenate the CopyDuringInstallation.txt file with the address stored in varable s. Is there any other property apart from TARGETDIR
Comment: I Changed the variable name but it dint make any difference to the execution. can you help as to how to join both the paths so that it can be used universally.
Comment: What do you mean with "used universally"? Is it that you want a UNC path? Or a URL? Or something else?
Comment: By universally i meant that if anybody else installs the program the variable s should give the file source address automatically.
Answer: The CopyFile method requires that the second argument also specifies a file name:
fso.CopyFile s & "\CopyDuringInstallation.txt", i & "\CopyDuringInstallation.txt"

I would advise to use more descriptive variable names, like targetDir instead of i.
Comment: Consider using  `fso.BuildPath( s, "file.txt")` instead of `s & "\file.txt"`. The `BuildPath` method inserts an additional path separator between the existing path and the name, only if necessary.


label in kivy doesn't update in while loop

Question: I'm trying to make a timer that updates a label to see the current amount of time remaining. I have a button that when you press should start the 2 min timer. For some reason the label doesn't update. Is there something wrong with the way I am doing this?
Here is my code:
import time

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label

Builder.load_string("""
#:import sla kivy.adapters.simplelistadapter
#:import label kivy.uix.label
<ListItemButton>:
    selected_color: 0, 0, 1, 1
    deselected_color: 0, 0, 0, 1

<MenuScreen>:
    FloatLayout:
        #cols: 2
        #rows: 2
        size: 800,480
        Label:
            id: output
            text: "0 min 0 s"
            font_size: 60
            size_hint: None, None
            size: 400, 100
            pos: 200,425
        Button:
            id: statheader
            text: "2 min"
            font_size: 40
            size_hint: None, None
            size: 600,100
            pos: 150,800
            background_color: 0,0,1,1
            on_press: root.startTimer(int(2))

""")

class MenuScreen(Screen):
    tww = 0
    def startTimer(self, what):
        self.tww = what*60
        while self.tww > 0:
            minute = self.tww/60
            print(minute)
            second = self.tww - minute*60
            print(second)
            self.ids.output.text = str(minute) + " min " + str(second) + " s"
            self.tww -= 1
            time.sleep(1)

sm = ScreenManager()
menu_screen = MenuScreen(name='menu')
sm.add_widget(menu_screen)

class TestApp(App):

    def build(self):
        return sm

if __name__ == '__main__':
    TestApp().run()

Is there something else that self.ids.output.text should be?
Answer: Kivy's graphics can't update until your while loop finishes - during the loop, only the content of the loop is run (repeatedly), and Kivy's normal functions are blocked.
You should instead use Clock.schedule_interval to run computations every frame without blocking other functions, or run your while loop in a thread.
Comment: Bummer. Thanks for the answer


What is the format of /proc/[pid]/sched file? What is option avg_per_cpu in it?

Question: I'm wondering if there is some documentation for /proc/[pid]/sched file in linux? this is not present in man proc. I need to understand what are the different field in there and what is avg_per_cpu field.
Answer: Do you know how to program C?  Then head to: The Linux source code search and type anything you've ever wanted to know about Linux but were afraid to ask!
If you don't know how to program C then please, don't do it!  (whatever it is you're trying to do)  ;-)


How to fix selector on this combination bath tap/shower setup?

Question: I have a combination tap/shower setup for my bath that looks like this:

The lever in the middle can be rotated left or right to choose between whether the water comes out the tap or out of the showerhead. Recently it has come loose and will just rotate left/right without doing anything. With a bit of jiggling you can get the mechanism to engage and it will function. I'm assuming that there is a loose screw or similar that could be tightened to fix the lever back in place but I can't figure out how I would be able to access such a screw.
While I doubt anyone will be familiar with this exact model, I assume there a few a standard ways for this to work. Where should I start trying to dismantle it? I am in Germany in case that is relevant to the answer.
Answer:
The porcelain handle might unscrew showing more options to get inside the diverter valve.

It might just need to come off to be out of the way.
It might not unscrew and may come off as you complete the following steps.

At the pivot point of that handle, there appears to be a porcelain covered button with gold trim.

COVER YOUR DRAIN SO YOU DON'T LOOSE PARTS
Gently prying behind that gold trim should pop this button off revealing a screw behind it. A strong fingernail is probably sufficient to pop the button off, if not, use a plastic screwdriver, old credit card or similar to avoid scratching the finish. If you don't have something plastic, carefully use a small flat blade screwdriver to pry.
Unscrewing that will allow further disassembly.
Take a lot of pics (better: have someone take them for you) as you disassemble so you can remember how to reassemble it.

Once you've got it disassembled, if you're not sure what's failing or how to fix it, please feel free to ask a new question about that portion of the process.
Comment: Glad you got it figured out @JackAidley! Your follow up question is an excellent opportunity to hit the ["Ask Question" button](https://diy.stackexchange.com/questions/ask). Down here, nobody will find your question or the answer. It deserves to get attention of its own.
Comment: You can also search the site (or the internet in general) for questions on how to keep a screw from coming loose.
Comment: The handle does indeed unscrew although it revealed nothing useful. However after a little wiggling the whole thing fell off and looking inside revealed a brass screw at the end under the gold/porcelain cap which appeared to hold the assembly in place but was currently inaccessible.
Comment: The cap was firmly stuck in place though so I spent some time trying to pry it off and applied a little WD40 whereupon it loosened up enough for me to realise that it was actually screwed in place rather than being a press fit. Once that was done it was easy enough to refit and tighten the screw and it's all working well again. However I assume it will loosen itself over time since presumably the repeated left/right rotations worked the screw loose. Anything I can do to secure the screw more firmly?
Comment: I didn't think it was worth a question of its own, but perhaps it is.


Why does C# make the caller provide the actual parameter value for a method that has an optional parameter?

Question: The last section of this blog explains the what: http://lostechies.com/jimmybogard/2010/05/18/caveats-of-c-4-0-optional-parameters/
But I am still wondering about the why.
I recently came across the default parameter of Scala.
In Scala it's the callee who provides the actual value for a parameter that has a default value.
So all the callers don't have to be recompiled to use an updated default parameter value.
If Scala can do it, I guess C# could have done it too.
So, why? Why did they design it to be error prone?
Edit:
Error prone might be too strong a word, so my question is more like this:
Why is it designed in a way that versioning of the default parameter could not affect the callers?
Comment: Why do you consider this error prone?  If I am consuming your assembly with a default value of 1, I have written all of my unit tests and validated my functionality with that value.  If the default is changed to 2 underneath me, my app could function incorrectly with that value.
Comment: But you provide the value only if you don't want the default one.Please provide a Scala and a C# example side by side
Comment: sorry, i was not being clear enough, I meant in the compiled result, in CIL and bytecode. In C# compiled CIL, the default value comes from the caller. In Scala compiled bytecode, the default value comes from the callee, which avoids the versioning issue described in the blog link
Comment: like you said, your app could function incorrectly with that value, that's why i said it's error prone
Answer: From the words of Eric Lippert himself:

That is, they believe that the default value is somehow "baked in" to
the callee.
In fact, the default value is baked in to the caller; the code on the
callee side is untouched and the caller becomes
M("{0}", false);
A consequence of this fact is that if you change the
default value of a library method without recompiling the callers of
that library, the callers don't change their behaviour just because
the default changed. If you ship a new version of method M that
changes the default to true it doesn't matter to those callers. Until
a caller of M with one argument is recompiled it will always pass
false.
That could be a good thing. Changing a default from false to true is a
breaking change, and one could argue that existing callers should be
insulated from that breaking change. [emphasis mine]
This is a fairly serious versioning issue, and one of the main reasons
why we pushed back for so long on adding default arguments to C#. The
lesson here is to think carefully about the scenario with the long
term in mind. If you suspect that you will be changing a default value
and you want the callers to pick up the change without recompilation,
don't use a default value in the argument list; make two overloads,
where the one with fewer parameters calls the other.

Source: Optional argument corner cases, part four (full series)
As to why this is different in Scala: perhaps there are technical constraints in C# that don't exist there. If you look through the 4 posts on optional arguments you'll notice that they have many cornercases to keep in mind.
If it isn't a technical constraint it might very well have been a managerial one. As has been often indicated:

Here's how we designed C# 4.
First we made a list of every possible feature we could think of
adding to the language.
Then we bucketed the features into "this is bad, we must never do it",
"this is awesome, we have to do it", and "this is good but let's not
do it this time".
Then we looked at how much budget we had to design, implement, test,
document, ship and maintain the "gotta have" features and discovered
that we were 100% over budget.
So we moved a bunch of stuff from the "gotta have" bucket to the "nice
to have" bucket.
Every minute we spend designing, implementing, testing, documenting or
maintaining nice feature X is a minute we can't spend on awesome
features A, B, C, D, E, F and G. We have to ruthlessly prioritize so
that we only do the best possible features. Indexed properties would
be nice, but nice isn't anywhere even close to good enough to actually
get implemented.
Comment: I don't think Scala would have any problems with the corner cases. Scala does caller modification as well but it encodes a method call to  a public compiler generated method in the callee's package. If C# had done this, there may have been some awkwardness interoperating with other .NET languages and tools that may show public members by default. Meanwhile, Scala default parameters are not accessible from Java (well, the compiler generated methods are public but there is no compiler support to insert the ugly calls for you).


SQL Server identity column incrementing without insert

Question: I have a C# console app which is using a stored procedure to insert rows into a SQL Server database. Currently the database has about 1m rows, however the ID column is up at 26m!
On the last successful insert the ID went from 16m to 26m. The app runs multiple threads in parallel so there is a chance it could be trying to insert two things at the same time.
Is there anything other than a transaction rollback that would cause the identity column to increment without adding a row?
It seems unlikely that there were 10 million times that two threads tried to write a conflicting row at the same time.
I'm using a temporary table variable which is populated by passing XML into the stored proc:
<code>-- insert data if it doesn-t already exist
insert into DataStore (DataText, DataSourceID)
select distinct td.dataText, td.dataSource
  from @tempData td
 where not exists ( select 'x'
                      from DataStore ds
                     where ds.DataText = td.dataText );
</code>
Comment: You have a race condition there. That pattern will not work under concurrency [as illustrated here](http://stackoverflow.com/questions/3407857/only-inserting-a-row-if-its-not-already-there)
Comment: Does `DataText` have a unique constraint on it? Maybe you did actually encounter a whole load of rollbacks.
Comment: `DataText` doesn't have a constraint, but another column `DateCreated` (populated by default value of `getdate()`) does have one.
Comment: (but `DateCreated` isn't a unique constraint I forgot to mention)
Answer: What can leave gaps?

DELETEs
Explicit rollbacks
Constraint violations (= implied rollback)
SET IDENTITY_INSERT
Replication without NOT FOR REPLICATION clause
DBCC CHECKIDENT (edit: as per Oleg Dok's answer)
...

I'd also check the increment value using IDENT_INCR in case it is really is 5 million or such
Comment: @finoutlook: added more ideas
Comment: Increment is 1, never doing any deletes on the table. I'll take a look at constraints.
Answer: Inserted and deleted record increments identity counter,
as mentioned by @gbn - Rollbacks and c-violations also, but there is two more options:

SET IDENTITY_INSERT
DBCC CHECKIDENT(..., RESEED)
Comment: I added DBCC CHECKIDENT to my answer, forgot about that one. Cheers


NextSibling with class not working

Question: This is my code and it's not alerting anything and nor is it returning anything good :(
the first part works fine
but afterwords it doesnt :( i cant seem to figure out what the problem is..
   this.getNextItem = function(o) {
// given
 playlist item, find next
 and then

  if (o.nextElementSibling) {
      o = o.nextElementSibling;
    }
    else {

      o = o.nextSibling;

  }

    while (o && o.className !== 'playerr') {
       if (o.nextElementSibling) {
             o = o.nextElementSibling;

             } else {

                o = o.nextSibling;

             }

       }

   if(o){ if (o.className !== 'playerr') { //nodeName.toLowerCase()

          return null;
    } else {
         alert(o.className);
          alert(o.getElementsByTagName('a')[0]);
      return o.getElementsByTagName('a')[0];
    }}

  };

if you want to see the full context its http://beastdrops.com then run page("content2") in consol to get to the new "player"
forward the song to the end then when its about to change to the next one it will not... :( thats what this script has to do
Comment: You're not running any tests to see if `o` is an object. `while (o && o.getAttribute('class') !== 'playerr') {` ...and... `if (o) {if (o.getAttribute('class') !== 'playerr') { ... } else { ... } }`
Comment: does the sibling of the element `o` passed as a parameter have a `class` attribute? (i.e. always?)
Comment: ...also, use `o.className` instead of `.getAttribute("class")`
Comment: ...and indent your code evenly. It's sort of a mess right now.
Comment: it doesnt have a class always going to update the code: how it looks currently
Comment: If it doesn't have a class, why are you testing for its class? Anyway, the issue is likely the lack of tests for `o`. You should be checking your developer console for errors. Here's an updated version of the code. http://jsfiddle.net/Y4CtM/
Comment: You've really got to learn to indent your code cleanly. No one wants to read code that looks like that.
Comment: how should it look?
im sorry for beeing messy but i got used to seeing code as such
Comment: @KolosFeriFazekas - try pasting your code in here: http://jsbeautifier.org/ to see what nice, compact, readable code that many people are used to looks like.
Comment: thanks! The script still doesnt work :( if you want to see the full context its http://beastdrops.com then run page("content2") in consol to get to the new "player" forward the song to the end then when its about to change to the next one it will not... :( thats what this script has to do
Answer: OK, per your comments, it looks like you want to do nextByClass() so here's a version that does that:
function hasClass(elem, cls) {
    var str = " " + elem.className + " ";
    var testCls = " " + cls + " ";
    return(str.indexOf(testCls) != -1) ;
}

function nextByClass(node, cls) {
    while (node = node.nextSibling) {
        if (hasClass(node, cls)) {
            return node;
        }
    }
    return null;
}

Working demo: http://jsfiddle.net/jfriend00/3L9FL/
You could use this to find the next item on the same level with the desired class like this:
// assumes you pass it the node for the starting

// returns first link in next
 with the desired classor null if none
this.getNextItem = function(node) {
    node = nextByClass(node, "playerr");
    if (node) {
        return node.getElementsByTagName('a')[0];
    }
    return null;
}

Older version of answer superceded by clarification in comments:
Per the comments in your code, it looks like given an element that is an
 tag, you just want to find the next
 on the same level.  If that's the case, here's a very simple function that finds the next sibling of the same tagName:
// gets the next sibling with the same tagName as the starting point
// returns null if none found
function nextByTag(node) {
    var tag = node.tagName;
    while (node = node.nextSibling) {
        if (node.tagName === tag) {
            return node;
        }
    }
    return null;
}

You could use this to find the first descendant link in the next
 like this:
// assumes you pass it the node for the starting

// returns first link in next
 or null if none
this.getNextItem = function(node) {
    node = nextByTag(node);
    if (node) {
        return node.getElementsByTagName('a')[0];
    }
    return null;
}

Comment: it doesnt seem to work for :( in my case since the main problem is that the next node is not good for me only about the 6th with the class of playerr :( if you want to see the full code http://beastdrops.com and in console run page("content2")
there press play after waiting abit (its a bit buggy) and then go to the end of the music and then it the getNextItem will try to run..
its ment to start playing the music below it
Comment: @KolosFeriFazekas - OK.  Per your clarification, I've added a version to the beginning of the answer that works by class name.
Comment: http://jsfiddle.net/D9JhW/1/ it seems like next sibling doesnt go ahead of some divs and other tags:S
Comment: @KolosFeriFazekas - your HTML in that jsFiddle is pretty messed up and completely unreadable too (horrible indentation).  You can't just insert an `` tag in the middle of some `` tags.  An `` needs to be in the correct container (a ``, ``, or ``) and only have other `` tags as siblings. When you've made your HTML into legal HTML, then you will have to describe what you're really trying to do because your current structure can't be searched with nextSibling at all.  I don't know what you're trying to accomplish.  From what element do you want to find what?
Comment: @KolosFeriFazekas - You perhaps don't understand what `nextSibling` actually does.  It finds the next tag with the same immediate parent at the same level of the hierarchy.  It does not go beyond that.

NextSibling with class not working


Does the Magic stat affect all magic or only offensive spells?

Question: From "The Ultimate Strategy Guide" FAQ:

Magic (Mag):
Magic is used to power up the magic that a character can use. This includes summons as well as regular magic and enemy skills. The higher your Mag, the higher damage you'll hit with magic.

I can't tell if it affects healing and protection too, or just offensive spells.
Does the Magic stat affect all magic? Or just offensive spells?
Answer: Yes, Magic affects healing. The formula to calculate how much you heal with Cure is:

6 * (Magic + Level) + 22 * Power

So the higher the Magic stat, the more HP that character will heal with a given Cure spell.
Source
Comment: this is only a partial answer
Comment: What do you think would make the answer more complete?
Comment: the question was about all other spells rather than offensive, not just cure.
Answer: Each type of magic has it's own formula (offensive, defensive, healing).
MAt = Magic Attack
MDf = Magic Defense
Offensive:

The Magical Formula for Base Damage is defined as such:
Base Damage = 6 * (MAt + Lvl)

Defensive:

Ability Power and the Defense Stat are factored in at the same time,
  just like the Physical formula:
Damage = [(Power * (512 - MDf) * Base Damage) / (16 * 512)]

Healing:

The Cure formula is very similar to the Magical Formula, and starts
  off in a similar way.
Base Damage = 6 * (MAt + Lvl)
Damage = Base Damage + 22 * Power

Other formulas can be found in the FAQ linked in the source.
Source
(Starts at 3.4.2  Magical)


Google form sync with Fusion Table fails if \ (backslash) is present

Question: I am using this google script to transfer data from google web form to fusion table.
http://fusion-tables-api-samples.googlecode.com/svn/trunk/FusionTablesFormSync/src/formsync.js
This works perfectly well, except in cases when any field of my webform includes \  character, and script results in "Exception: Invalid query: Parse error near...."
Example of Web form input field data:-
10^{23}\;atoms
Is it possible to fix (where?) in the script, which probably builds malformed query to fusion table?
Answer: I just committed a new version of the script that fixes the unescaped backslashes, as well as correcting the timestamp format so Fusion Tables knows what to do with it.
Comment: There seems something not quite right with this new script. The web form input goes missing and not stored in excel as well.      Please confirm if this has been tested.
Comment: Yes, I tested it multiple ways before posting the update. Are you seeing any errors in the Apps Script log?
Comment: Thanks. This is working now. I had 2 "on submit form" triggers, which for some reasons was preventing fusion table update.


Was it standard practice in decades past to connect hot conductors with crimp devices?

Question: Yesterday, the modem and desk lamp in my home office started flashing.  I thought the power strip was failing.  When I touched the outlet to unplug the power strip, the outlet was hot to touch!!!
I immediately shut the power off and upon examination of the outlet, a copper crimp had been used to pigtail off two black wires.  The insulation on the wires and electrical tape had melted and the crimp fell to the floor when I removed the outlet.
This is the second time this has happened.  We were fortunate to find this before major damage. The first time I had an electrician inspect the first incident and he made the repair.  This one, I rewired with wire nuts and electrical tape.  Now I plan to inspect EVERY outlet to remove these crimps.
Question:
House was built in 1978 in central CA.  Was this normal procedure back then?  If so, with new technology and gadgets, is that causing the failure of the crimps.  Thank you.  Bk.
Comment: Yeah, they were experimental in the 70s, including **with aluminum wire** so watch for that too.  You gotta figure, like backstabs (or any jab-and-forget connection) today, they *knew at the time* the crimps were hokey, and were making a conscious choice to be cheap.
Comment: Most stranded wire is crimped to lugs and when splicing large cables crimps are standard. In some areas grounds are still required to be iriversable crimps so yes crimps were used and still are today.
Comment: My house, built in 1965 in California has crimps on copper wire and there have been no issues. Just an comment that they don't always fail.
Comment: The crimps are on the ground wires too, and look to be intact with no problems.   The problem is with the crimps on the hot wire(s).  Thank you both!
Comment: I would not expect crimps on grounds to be an issue, as they should never be carrying any current. What concerns me is the note on the hots. FYI... I would also expect you to see this on the neutrals where they are joined but more concerned about the use you are potentially placing on the circuit. Also advise you take the time to secure a breaker and check all plates/switches. Make notes of condition of each.
Comment: Is this all copper wiring, or is there aluminum present?  Also, what type of crimp terminal fell apart? Can you get us some photos of the crimps?
Answer: Somewhere between the practice of soldering / taping and the use of wire nuts, Barrel crimps were used to make joints in smaller wire.
If they are done properly they should last a lifetime. Just as any other compression type lug lasts. Millions of ring/fork type lugs are sold and used every year without incident unless they are not crimped tight enough. Then they can heat causing expansion and contraction and eventual failure.
Inspecting the electrical system for more failures would be prudent but I wouldn't rush to replace every joint in the house. If the wires are tight and there is no sign of excessive heating of the joint then they outlast us all.
Good luck and stay safe!
Answer: Crimps are NOT (necessarily) a bad thing. Yes it was standard practice and is still done in certain situations. However, in residential jobs it is not what is typically done today.
The more important points are:

Are you maxing out the current draw on the line? Just because a run can support 15A does not make it wise to draw 14A 24/7.
Are you actually cycling current? Drawing 10A then 0A then 10A then 0A is more of an issue in the long run.
As @Harper touched on, is your wiring all copper or is there aluminum involved?

There are specific code driven requirements when aluminum wiring exists. Pigtailing to copper with dielectric grease helping to prevent oxidization is a common approach and then wired to outlets, gfci's, and switches.
When stranded wire is mixed with solid wire it is also imperative to ensure the pigtial is put together correctly, and often secured with electrical tape even though it does not solve the problem of #1 or #2 above.
Given your experience thus far, and the age of your home, it is possible all 3 are happening. Ask your electrician for a recommendation. ESPECIALLY since you have now had this happen twice, it's certainly worth it to fix the issues you are having.
Doing an assessment on all 3 points will give you peace of mind.
Comment: thank you all.  All wiring is Copper.  I did find the crimps on the neutral wire also.  The crimp fell off and out at both ends.  I will try and take a picture of it and if I find another like it and post it
Comment: Yes, it sounds like the crimp was probably deployed incompetently. The heat was due to insufficient pressure holding the wires together. Loose connections=heat and possible fire. I would be a little concerned about the rest of the house.
Comment: So #3 is off the list, and so is a whole mess along with it. @ArchOSX makes a good point, heck, its possible a helper who worked with the contractor or electrician was new to the work, or used the wrong tool or used the tool the wrong way. It makes more sense than a crimped copper copper falling apart unexplicably.


Merging git branches to master using Jenkins

Question: I want to create a modular process which will merge the "devel" branch upon each successful build to the master branch, and it will also create a tag.
Is there any way to do it using Jenkins and Git plugin rather than writing code.
If yes, is there any option to provide Git plugin the repository URL as a parameter, so it will be as modular as possible.
The job that I want to create will be performing only the merge (git merge --no-commit -X theirs) operation and it will create a tag (the tag name will be provided as a parameter as well).This job will be triggered by other jobs.
Answer: You can try use post-build action Git Publish and provide to it's fields build parameters you have as a variables (for example $REPO_URL, if you have parameterized build with variable $REPO_URL or have Env Injection plugin with this variable).


Need a Delphi component/library that allows me to encrypt/decrypt some text using RSA

Question: I need a component or library (as simple as possible, and no DLLs would be great) to encrypt a text, decrypt another, using public keys generated by OpenSSL.
I thought I'd use LockBox (the new version, v3), but according to other users here it's not as good as the old version, and more importantly, cannot use keys from other libraries. (see OpenSSL's PEM file and Lockbox3 interoperability)
I'm using Delphi 7. Any suggestions?
Comment: Why "No DLL"? Using openssl's DLL will give you an openssl interoperability easily. You can pack the dll into installer of your application.
Answer: We use Lockbox 2 in Delphi 2010 and it works great. I guess it should also work with Delphi 7. Here's a code sample:
<code>unit LBRSA;

interface

uses
  LbCipher,
  LbRSA,
  LbString,
  LbUtils;

  function DecryptRSA(const CipherText: String): String; overload; overload;
  function DecryptRSA(const CipherText, Exponent, Modulus: String): String; overload;

implemention

function EncryptRSA(const ClearText, Exponent, Modulus: String): String;
var
  RSA: TLbRSA;
begin
  RSA := TLbRSA.Create(nil);
  try
    RSA.PublicKey.ExponentAsString := Exponent;
    RSA.PublicKey.ModulusAsString := Modulus;

    Result := RSA.EncryptStringW(ClearText);
  finally
    FreeAndNil(RSA);
  end;
end;

function DecryptRSA(const CipherText, Exponent, Modulus: String): String;
var
  RSA: TLbRSA;
begin
  RSA := TLbRSA.Create(nil);
  try
    RSA.PrivateKey.ExponentAsString := Exponent;
    RSA.PrivateKey.ModulusAsString := Modulus;

    Result := RSA.DecryptStringW(CipherText);
  finally
    FreeAndNil(RSA);
  end;
end;

end.
</code>
Lockbox includes a demo app that lets you generate the public and private keys.
Answer: Our SecureBlackbox will do the job. Delphi 7 is supported. Certificates and keys in PEM format are supported as well (if you have raw RSA key encoded in PEM, you will need to write a couple of lines of code to unwrap it, and X.509 certificates are loaded from PEM with one function call).
Answer: Here is a manual, how to import libeay32.dll from openssl into delphi:
http://www.disi.unige.it/person/FerranteM/delphiopenssl/
They have file encrypt/decrypt using RSA:
http://www.disi.unige.it/person/FerranteM/delphiopenssl/RSAEncrypt.html


How does trustworthiness with NPCs work?

Question: In light of Raven Dreamer's answer to Why can I sometimes take half of a shops items while the oher half is considered stealing?, how does one get people to like the player-character? In other words, get their disposition higher (towards the player-character) and get them to allow the player-character to take their stuff?
Edit: While rereading kotekzot's answer, I wondered how (easy it is) to affect a relationship negatively.
Edit 2: Then I realized that I was focusing solely on take vs. steal when I could be asking about what else that trustworthiness (as I'll call it instead of relationship) affects. If it is felt that this edit broadens too much; that what trustworthiness affects deserves its own question, this question can be changed back.
Answer: The only legit way to increase an NPC's disposition toward you is to complete quests for them (or somebody close to them, in a few cases). Not all quests will increase disposition and not all NPCs will have a quest for you.
You can also use setrelationshiprank player 1 in console to befriended the targeted NPC. Read more about console commands.


How hungry will I get from a boat trip?

Question: I am planning to make a large expedition with my boat. Does travelling by boat reduce my food bar? If so, how much (compared to walking/swimming)? And does this actually depend on the difficulty? I am playing on 'easy'.
Answer: Boating does not inspire hunger.  You can use it to cross thousands of blocks (meters) without any need for food.  On the other hand, you can only cross 133 blocks per haunch of meat by swimming (0.015 hunger/block) and 200 blocks walking (0.01).
Difficulty only affects hunger as to what happens when you're starving.  Your health drops on easy until it hits 5 hearts, normal drops to 1/2 heart, and on hard you die.

How hungry will I get from a boat trip?


Cannot import python file inside another python file in the same subfolder

Question:
I have a file called blog/urls.py inside which I am importing a function from blog/views.py called allblogs
Even if I write import .views or import views I get the error ModuleNotFoundError: No module named 'views' even though both files are in the same folder. How do I resolve this ?

Answer: the search path must be located in sys.path.
see https://realpython.com/absolute-vs-relative-python-imports/
to list your current directory, use os.curdir; you can then compare to see if it is in the system path
import os
os.curdir
import sys
for p in sys.path:
   print(p);

Comment: What if the folder path is in sys.path but I cannot import the file
Comment: The name of the folder I am working in is in sys.path and I am able to import other files from that folder I just cannot import that file for some reason
Comment: This is true for other projects I am working on too
Answer: In django,you need to add this to your setting.py:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

Then you could use import view.xxxx
This will make you more convenient every time you want to import the module.


Multi-dimensional ndarray set operations

Question: I have the need to run the set difference of two potentially large multidimensional numpy.ndarrays.
My tests have proven unsuccessful trying to extend the numpy.setdiff1d to work for multidimensional arrays without throwing the following TypeError:
TypeError: Cannot change data-type for object array.

The data in these arrays is a long and a string.
I have the two following arrays:
A = [[0L 'a']
     [2L 'c']
     [1L 'b']
     [3L 'b']
     [0L 'd']]

B = [[1L 'b']
     [0L 'a']
     [4L 'b']]

The expected result is the set difference S = A - B which are the pairs ((0,d), (2,c), (3,b)).
Answer: Use a structured array as long as the shape along which you're doing set comparisons is 1d (here it is, since you have an effective 1d array of pairs):
A = np.array([(0L, 'a'),
              (2L, 'c'),
              (1L, 'b'),
              (3L, 'b'),
              (0L, 'd')], dtype=[('n', long), ('l', 'S1')])

B = np.array([(1L, 'b'),
              (0L, 'a'),
              (4L, 'b')], dtype=[('n', long), ('l', 'S1')])

S = np.setdiff1d(A, B)

>>> S
array([(2L, 'c'), (3L, 'b'), (0L, 'd')],
      dtype=[('n', '<i8'), ('l', 'S1')])

Comment: This looks like the correct way to do so, but I cannot change the array dtype like you mentioned. My np.arrays are returned from the Pandas .values() method. The dtype of those are object. I am trying to convert them to your suggested dtype using .astype but i am getting the following type error: expected a readable buffer object. Any ideas?
Comment: Ah, yes sometimes converting certain arrays into structured arrays can be tricky.  Take a look at `np.core.rec.fromarrays`.  Also, there may be a pandas solution so you don't have to conver to numpy.
Answer: You can use Python's set operations here:
In [66]: s = set(tuple(x) for x in A).difference(tuple(x) for x in B)

In [67]: np.array(list(s))
Out[67]:
array([['0', 'd'],
       ['2', 'c'],
       ['3', 'b']],
      dtype='|S1')


Do experience gain items on your pet affect your character in Torchlight?

Question: In Torchlight there are wearable rings that boost experience gain by a percentage. If I equip my pet with one of these rings, will this increase the experience gain of my player?
Comment: I don't *think* so. I know that if you give your pet +Magic Find items, they will benefit from the magic find only when they kill things (as opposed to you killing them. Your pet has magic find = to your magic find + any magic find items worn by the pet.
Comment: So your magic find affects your pets? The same mechanic would be useless with experience gain but because it's implemented there's a chance they've implemented something experience related.
Comment: exactly. But the way it would work is, if you have a +3% xp ring, and your pet has a +2% xp ring, you would get 103% XP, and your pet would get 105% (all of your xp%, + it's own). However, since pets don't accrue experience, this is irrelevant.
Comment: @Raven Dreamer: Until anyone can prove you wrong that sounds like an answer to me. The thing is it's difficult to test with 2% and 3%. I can't figure it out myself but I'm more convinced that your point about Magic Find applies to experience gain as well.
Answer: It is unlikely that your pet's +%xp affects your own.
Looking at the similar stat of +% magic find, I know that if you give your pet +Magic Find items, they will benefit from the magic find only when they kill things (as opposed to you killing them. Your pet has magic find = to your magic find + any magic find items worn by the pet.
But the way this concept would work for XP is, if you have a +3% xp ring, and your pet has a +2% xp ring, you would get 103% XP, and your pet would get 105% (all of your xp%, + it's own). However, since pets don't accrue experience, this is irrelevant.
Comment: I will go through the effort of testing this when I feel like grinding Torchlight again. In the meantime thanks for your input :)
Answer: There was a change in Patch 1.2 that sheds some light on this:

Magic find takes the max value between you and your pet when pets or pet minions make a kill.

If your pet's trinkets give a total 2% magic find boost, and your own equipment has a total 3% magic find boost, then you will only receive a 3% find rate boost.
I think the meaning of the change is that pre-patch pets and minions would have had their own drop rate that applied whenever they made a kill. The change simplifies the situation, so you don't need to have drop rate boosts for yourself and your pet.
However, it isn't clear if this applies to experience as well.
Comment: If it applied to experience, experience gain would only be maximal if my pet made the kill, and even then it would only apply to my pet. I'm more interested in my character.


Need VBA code that retrieves sumproduct of particular rows and columns

Question: I'm wondering if someone can write me a VBA Code that retrieves the "sumproduct" of particular cells and columns. Here I have a screenshot of what I'm requesting.

To explain what the code does: it finds particular text that matches the words "ABC TOT", "EFG TOT", and "XYZ TOT" in Column A PAIRED WITH a particular text matching the words "THIS TITLE" in a particular column (I'm using Column C for this example) and retrieves the "total sum" of those paired words. So it will mean:
"ABC TOT" = 6
"EFG TOT" = 9
"XYZ TOT" = 6
Which means: 6 + 9 + 6 = 21
"21" is the resulting answer that I want input into a new cell. I can't just do C5 + C10 + C15 because this is a spreadsheet with hundreds of rows & columns and the location of all the numbers change every day. One day the numbers in C5 are going to end up in H7 (etc.) and that will be a problem. So this is why I need VBA Code to automate the task for me and retrieve the resulting answer based on specific row and column text alone. I made a diagram below that you can copy/paste.
       NOTTHISTITLE THISTITLE NOTTHISTITLE
A                 0         1            0
B                 1         0            4
C                 2         5            1
ABC TOT           3         6            5

E                 0         0            1
F                 2         2            1
G                 2         7            0
EFG TOT           4         9            2

X                 1         3            4
Y                 0         1            0
Z                 1         2            3
XYZ TOT           2         6            7

Comment: SO is not a code writing service.
Answer: This should do the trick by calling it either directly as a formula in Excel =SumOnCondition(A1, "THISTITLE", "ABC TOT", "EFG TOT", "XYZ TOT") or calling it from a Sub in VBA. Note you can specify an unlimited number of rows to match at the end of the function call.
Function SumOnCondition(StartCell As Range, ColumnName As String, ParamArray RowNames() As Variant) As Double

    Dim ColumnFound As Boolean
    Dim ColumnNr As Long
    ColumnNr = 0
    ' Find the column number for ColumnName
    Do While Not (ColumnFound)
        ColumnNr = ColumnNr + 1
        If StartCell.Offset(0, ColumnNr - 1).Value = ColumnName Then
            ColumnFound = True
        End If
    Loop

    ' Add all the matching RowNames
    Dim RowFound As Boolean
    Dim RowNr As Long
    RowNr = 1
    Dim RowName As Variant
    For Each RowName In RowNames
        Do While Not (RowFound)
            RowNr = RowNr + 1
            If StartCell.Offset(RowNr - 1, 0).Value = RowName Then
                RowFound = True
                SumOnCondition = SumOnCondition + StartCell.Offset(RowNr - 1, ColumnNr - 1)
            End If
        Loop

        ' reset to defaults:
        RowFound = False
        RowNr = 1
    Next RowName

End Function

Usage:
1. You can call this function from a cell in your workbook:

2. You can call this function from another Sub:
Sub RunSumOnCondition()

    ActiveCell.Value = SumOnCondition(Range("A1"), "THISTITLE", "ABC TOT", "EFG TOT", "XYZ TOT")

End Sub